inline void ParseAuthNameAndPassword(StrPtrLen *codedStrPtr, StrPtrLen* namePtr, StrPtrLen* passwordPtr)
 {
    
    if (!codedStrPtr || (codedStrPtr->Len >= kAuthNameAndPasswordBuffSize) ) 
    {   return; 
    }
    
    StrPtrLen   codedLineStr;
    StrPtrLen   nameAndPassword;
    memset(decodedLine,0,kAuthNameAndPasswordBuffSize);
    memset(codedLine,0,kAuthNameAndPasswordBuffSize);
    
    memcpy (codedLine,codedStrPtr->Ptr,codedStrPtr->Len);
    codedLineStr.Set((char*) codedLine, codedStrPtr->Len);  
    (void) Base64decode(decodedLine, codedLineStr.Ptr);
    
    nameAndPassword.Set((char*) decodedLine, strlen(decodedLine));
    StringParser parsedNameAndPassword(&nameAndPassword);
    
    parsedNameAndPassword.ConsumeUntil(namePtr,':');            
    parsedNameAndPassword.ConsumeLength(NULL, 1);

    // password can have whitespace, so read until the end of the line, not just until whitespace
    parsedNameAndPassword.ConsumeUntil(passwordPtr, StringParser::sEOLMask);
    
    namePtr->Ptr[namePtr->Len]= 0;
    passwordPtr->Ptr[passwordPtr->Len]= 0;
    
    //qtss_printf("decoded nameAndPassword="******"decoded name="); PRINT_STR(namePtr); 
    //qtss_printf("decoded password="); PRINT_STR(passwordPtr); 

    return;
};
Exemple #2
0
int CACrypto::decodeBase64(const char* input,
                           char* output,
                           int outputBufferLength)
{
    CCAssert(Base64decode_len(input) <= outputBufferLength, "CACrypto::decodeBase64() - outputBufferLength too small");
    return Base64decode(output, input);
}
LUA_STRING Crypto::encodingBase64Lua(bool isDecoding,
                                       const char* input,
                                       int inputLength)
{
    LuaStack* stack = LuaEngine::getInstance()->getLuaStack();
    stack->clean();

    int bufferSize = isDecoding ? Base64decode_len(input) : Base64encode_len(inputLength);
    char *buffer = bufferSize ? (char*)malloc(bufferSize) : NULL;
    int size = 0;

    if (buffer)
    {
        size = isDecoding ? Base64decode(buffer, input) : Base64encode(buffer, input, inputLength);
    }
    if (size)
    {
        stack->pushString(buffer, size);
    }
    else
    {
        stack->pushNil();
    }
    if (buffer)
    {
        free(buffer);
    }
    return 1;
}
Exemple #4
0
int main () {

    char *B64Text = "HUIfTQsPAh9PE048GmllH0kcDk4TAQsHThsBFkU2AB4BSWQgVB0dQzNTTmVSBgBHVBwNRU0HBAxTEjwMHghJGgkRTxRMIRpHKwAFHUdZEQQJAGQmB1MANxYGDBoXQR0BUlQwXwAgEwoFR0$";
    char *buf = malloc(Base64decode_len(B64Text));

    Base64decode(buf, B64Text);
    RepeatedXorAnalysis(buf, Base64decode_len(B64Text) - 1);
}
Exemple #5
0
/* Decodes binary data from a file. */
static c4snet_data_t *C4SNetDecode(FILE *file)
{
  c4snet_data_t *c = SNetMemAlloc(sizeof(c4snet_data_t));

  Base64decodeDataType(file, (int*) &c->vtype);
  Base64decode(file, &c->size, sizeof(int));
  Base64decodeDataType(file, (int*) &c->type);

  c->ref_count = 1;

  if(c->vtype == VTYPE_array) {
    c->data.ptr = MemAlloc(AllocatedSpace(c));
    Base64decode(file, c->data.ptr, AllocatedSpace(c));
  } else {
    Base64decode(file, &c->data, C4SNetSizeof(c));
  }

  return c;
}
Exemple #6
0
int main(int argc, char** argv) {

  const char encoded[300] = "eyJWZXIiOjEsICJJRCI6MSwgIlRzdGFtcCI6MTQ0MzcwMDkxNSwgIlJzdGF0ZSI6Ik9OIiwgIlZzdGF0ZSI6Ik9QRU4iLCAiR3N0YXRlIjoiT0siLCAiVDEiOjU0LCAiVDIiOjI5LCAiVDMiOjE0LCAiVDQiOjI1LCAiS1ciOjAuMywgIktXSCI6MC4wLCAiSExtaW4iOjAuMCwgIkhMdG90YWwiOjAuMCwgIkNMbWluIjowLjAsICJDTHRvdGFsIjowLjB9";
  char decode[300];


  printf("%s\n", encoded);

  Base64decode(decode, "eyJWZXIiOjEsICJJRCI6MSwgIlRzdGFtcCI6MTQ0MzcwMDkxNSwgIlJzdGF0ZSI6Ik9OIiwgIlZzdGF0ZSI6Ik9QRU4iLCAiR3N0YXRlIjoiT0siLCAiVDEiOjU0LCAiVDIiOjI5LCAiVDMiOjE0LCAiVDQiOjI1LCAiS1ciOjAuMywgIktXSCI6MC4wLCAiSExtaW4iOjAuMCwgIkhMdG90YWwiOjAuMCwgIkNMbWluIjowLjAsICJDTHRvdGFsIjowLjB9");

    printf("%s\n", decode);

  return 0;
}
Exemple #7
0
/*
 * Signature: ([B)[B
 */
static jbyteArray Base64Decode(JNIEnv *env, jobject thiz, jbyteArray ba)
{
	char * data = (*env)->GetByteArrayElements(env, ba, 0);
//	int len = (*env)->GetArrayLength(env, ba);
	unsigned long deDataLen;
	char* deData = (char*)malloc(BUFFER_LEN);
	deDataLen = Base64decode(deData,data);

	jbyteArray jarrRV =(*env)->NewByteArray(env,deDataLen);

	(*env)->SetByteArrayRegion(env,jarrRV, 0,deDataLen, deData);

	(*env)->ReleaseByteArrayElements(env,ba,data,0);
	free(deData);
	return jarrRV;
}
Exemple #8
0
 fzBuffer Data::B64Decode(const char *input, fzUInt inLength)
 {
     FZ_ASSERT(input, "Input pointer cannot be NULL");
     FZ_ASSERT(inLength > 0, "Input data length cannot be 0.");
     
     //should be enough to store 6-bit buffers in 8-bit buffers
     fzUInt outputSize = Base64decode_len(input);
     char *output = new(std::nothrow) char[outputSize];
     
     if( output ) {
         Base64decode(output, input);
         return fzBuffer(output, outputSize);
         
     }else{
         FZLOGERROR("Base64: error allocating memory.");
         return fzBuffer::empty();
     }
 }
inline Bool16 OSXAuthenticate(StrPtrLen *keyStrPtr)
{
#if __MacOSX__
//  Authorization: AuthRef QWxhZGRpbjpvcGVuIHNlc2FtZQ==
    Bool16 result = false;
    
    if (keyStrPtr == NULL || keyStrPtr->Len  == 0)
        return result;
    
    char *encodedKey = keyStrPtr->GetAsCString();
    OSCharArrayDeleter encodedKeyDeleter(encodedKey);

    char *decodedKey = NEW char[Base64decode_len(encodedKey) + 1];
    OSCharArrayDeleter decodedKeyDeleter(decodedKey);

    (void) Base64decode(decodedKey, encodedKey);

    AuthorizationExternalForm  *receivedExtFormPtr = (AuthorizationExternalForm  *) decodedKey;
    AuthorizationRef  receivedAuthorization;
    OSStatus status = AuthorizationCreateFromExternalForm(receivedExtFormPtr, &receivedAuthorization);

    if (status != errAuthorizationSuccess) 
        return result;
        
    status = AuthorizationCopyRights(receivedAuthorization, &sRightSet, kAuthorizationEmptyEnvironment, kAuthorizationFlagExtendRights , NULL);
    if (status == errAuthorizationSuccess)
    {
        result = true;
    }

    AuthorizationFree(receivedAuthorization, kAuthorizationFlagDestroyRights);

    return result;

#else

    return false;

#endif

}
Exemple #10
0
QTSS_Error RTSPRequest::ParseBasicHeader(StringParser *inParsedAuthLinePtr)
{
    QTSS_Error  theErr = QTSS_NoErr;
    fAuthScheme = qtssAuthBasic;

    StrPtrLen authWord;
    
    inParsedAuthLinePtr->ConsumeWhitespace();
    inParsedAuthLinePtr->ConsumeUntilWhitespace(&authWord);
    if (0 == authWord.Len ) 
        return theErr;
        
    char* encodedStr = authWord.GetAsCString();
    OSCharArrayDeleter encodedStrDeleter(encodedStr);   
    
    char *decodedAuthWord = NEW char[Base64decode_len(encodedStr) + 1];
    OSCharArrayDeleter decodedAuthWordDeleter(decodedAuthWord);

    (void) Base64decode(decodedAuthWord, encodedStr);
    
    StrPtrLen   nameAndPassword;    
    nameAndPassword.Set(decodedAuthWord, ::strlen(decodedAuthWord));
    
    StrPtrLen   name("");
    StrPtrLen   password("");
    StringParser parsedNameAndPassword(&nameAndPassword);

    parsedNameAndPassword.ConsumeUntil(&name,':');          
    parsedNameAndPassword.ConsumeLength(NULL, 1);
    parsedNameAndPassword.GetThruEOL(&password);
        

    // Set the qtssRTSPReqUserName and qtssRTSPReqUserPassword attributes in the Request object
    (void) this->SetValue(qtssRTSPReqUserName, 0,  name.Ptr , name.Len, QTSSDictionary::kDontObeyReadOnly);
    (void) this->SetValue(qtssRTSPReqUserPassword, 0,  password.Ptr , password.Len, QTSSDictionary::kDontObeyReadOnly);

    // Also set the qtssUserName attribute in the qtssRTSPReqUserProfile object attribute of the Request Object
    (void) fUserProfile.SetValue(qtssUserName, 0, name.Ptr, name.Len, QTSSDictionary::kDontObeyReadOnly);
    
    return theErr;
}
Exemple #11
0
/*
 * Signature: ([B)[B
 */
static jbyteArray Decrypto(JNIEnv *env, jobject thiz, jbyteArray ba, jint tp)
{
//	monstartup("libjcryptoc.so");
//	LOGPOS();
	char * data = (*env)->GetByteArrayElements(env, ba, 0);
//	int len = (*env)->GetArrayLength(env, ba);

	unsigned long deDataLen;
	char* deData = (char*)malloc(CIPHER_BUFFER_LEN);
	deDataLen = Base64decode(deData,data);

	char * key;
	if(tp == 1){
		key = PASS;
	}else if(tp == 2){
		key = UPASS;
	}else{
		key = NPASS;
	}

	int plainBufferLen;
	void * plainBuffer = malloc(BUFFER_LEN);

	plainBufferLen = MGDecryptor(deData, deDataLen, key, strlen(key), plainBuffer);
	free(deData);



	jbyteArray jarrRV =(*env)->NewByteArray(env,plainBufferLen);

	(*env)->SetByteArrayRegion(env,jarrRV, 0,plainBufferLen, plainBuffer);
	free(plainBuffer);

	(*env)->ReleaseByteArrayElements(env,ba,data,0);

//	setenv("CPUPROFILE", "/sdcard/gmon.out", 1);
//	moncleanup();
	return jarrRV;
}
 extern "C" int Base64Decode(void* byteDataDest, const char* base64Src)
 {
     return Base64decode((char*) byteDataDest, base64Src);
 }
Exemple #13
0
void
nc_otoc_start(nc_opts *opts, int pair_raw_sock)
{
  int shell_fd_sock;
  int pair_fd_sock;

  fd_set readfds;
  int maxfds;
  char time_str[NOW_STR_LEN];

  enum {init, none,
	text_sent, text_received,
	pkey_sent, pkey_received} last_action = init;

  shell_fd_sock = fileno(stdin);
  pair_fd_sock = nc_utils_get_rec_sockfd(pair_raw_sock);
  maxfds = pair_fd_sock + 1;

  /* --- start of sending public key --- */
  if(opts->secure) {

    char *msg = NULL;
    char *msg_type = OTOC_MTYPE_PKEY;
    char *msg_body = NULL;

    /* --- start of encoding public key --- */
    const char *plain_pkey = (const char*) my_publickey;
    int plain_pkey_len = crypto_box_PUBLICKEYBYTES;
    char encoded_pkey[Base64encode_len(plain_pkey_len)];
    Base64encode(encoded_pkey, plain_pkey, plain_pkey_len);
    nc_log_writef("debug", "encode my public key: %s", encoded_pkey);
    /* --- end of encoding public key --- */

    msg_body = encoded_pkey;
    nc_json_make_otoc_msg(&msg_type, &msg_body, plain_pkey_len, &msg);
    nn_send(pair_raw_sock, msg, strlen(msg), 0);
    nc_log_writef("debug", "one to one chat sent public key: %s", msg);
    last_action = pkey_sent;
    
  }
  /* --- end of sending public key --- */
  
  /* --- start of shel command registration --- */
  nc_otoc_register_cmd("/help", func_cmd_help);
  nc_otoc_register_cmd("/leave", func_cmd_leave);
  /* --- end of shell commmand registration --- */

  for(;;) {

    switch(last_action) {
    case init:
    case pkey_sent:
      fprintf(stdout,
	      ">> Entering (room code %d) ...\n",
	      pair_raw_sock);
      fprintf(stdout, ">>> ");
      fflush(stdout); 
      break;
    case text_received: 
      fprintf(stdout, ">>> ");
      fflush(stdout); 
      break;
    case text_sent: 
      fprintf(stdout, ">>> "); 
      fflush(stdout); 
      break;
    case none:
      fprintf(stdout, ">>> ");
      fflush(stdout);
      break;
    case pkey_received:
      break;
    }

    FD_ZERO(&readfds);
    FD_SET(pair_fd_sock, &readfds);
    FD_SET(shell_fd_sock, &readfds);

    select(maxfds, &readfds, NULL, NULL, NULL);

    if(FD_ISSET(shell_fd_sock, &readfds)) {      

      char *buf = NULL;
      size_t buf_sz = 1024;
      int i;

      nc_utils_now_str(time_str);      
      getline(&buf, &buf_sz, stdin);

      if(buf[0] == '\n') {
	
	last_action = none;

      } else if(buf[0] == '/') {

	nc_utils_del_new_line(buf);
	for(i = 0; i < cmd_current_code; i++) {
	  
	  if(strstr(buf, cmds[i].name)) {

	    if(cmds[i].func(buf) < 0) {
	      return;
	    }

	    break;
	  }
	}

	last_action = none;

      } else {

	if(opts->secure) {

	  /* --- make ciphermsg with key pairs --- */
	  int ciphermsg_len = crypto_box_MACBYTES + strlen(buf);
	  unsigned char nonce[crypto_box_NONCEBYTES];
	  unsigned char ciphermsg[ciphermsg_len];

	  /* @TODO: use random nonce */
	  //randombytes_buf(nonce, sizeof nonce);
	  memset(nonce, '\0', sizeof nonce);
	  
	  crypto_box_easy(ciphermsg, (const unsigned char*) buf,
	  		  strlen(buf), nonce,
	  		  peers_publickey[pair_raw_sock], my_secretkey);

	  /* --- make msg encoded with base64  --- */
	  const char *plain_ciphermsg = (const char*) ciphermsg;
	  int plain_ciphermsg_len = ciphermsg_len;
	  int encoded_ciphermsg_len = Base64encode_len(plain_ciphermsg_len);
	  char encoded_ciphermsg[encoded_ciphermsg_len];

	  Base64encode(encoded_ciphermsg, plain_ciphermsg, plain_ciphermsg_len);
	  nc_log_writef("debug", "encode ciphermsg: %s", encoded_ciphermsg);

	  /* --- serialize msg with json --- */
	  char *msg = NULL;
	  char *msg_type = OTOC_MTYPE_STXT;
	  char *msg_body = NULL;

	  msg_body = encoded_ciphermsg;
	  nc_json_make_otoc_msg(&msg_type, &msg_body, strlen(buf), &msg);
	  nc_log_writef("debug", "serialize encoded ciphermsg: %s", msg);
	  
	  /* --- send msg --- */
	  nn_send(pair_raw_sock, msg, strlen(msg), 0);

	} else {

	  char *msg = NULL;
	  char *msg_type = OTOC_MTYPE_RTXT;

	  nc_json_make_otoc_msg(&msg_type, &buf, strlen(buf), &msg);
	  nn_send(pair_raw_sock, msg, strlen(msg), 0);
	  fprintf(stdout, "[%s] >>> %s", time_str, buf);
	  fflush(stdout);
	  nc_utils_del_new_line(buf);
	  nc_log_writef("debug", "one to one chat sent: %s", buf);
	  nc_utils_empty_string(buf);
	  last_action = text_sent;

	}

      }
      
    } else if(FD_ISSET(pair_fd_sock, &readfds)) {

      char *buf = NULL;
      char *msg_body = NULL;
      char *msg_type = NULL;
      int original_msg_body_len;
      
      nn_recv(pair_raw_sock, &buf, NN_MSG, 0);
      nc_json_extract_otoc_msg(&buf, &msg_type, &original_msg_body_len, &msg_body);

      nc_utils_del_new_line(buf);
      nc_log_writef("debug", "one to one chat received: %s", msg_type);
      nn_freemsg(buf);
      
      if(strncmp(msg_type, OTOC_MTYPE_PKEY, OTOC_MTYPE_LEN) == 0) {

	/* public key message */

	/* --- start of decoding public key --- */
	int plain_pkey_len = Base64decode_len(msg_body);
	char plain_pkey[plain_pkey_len];

	Base64decode(plain_pkey, (const char*) msg_body);
	strncpy(peers_publickey[pair_raw_sock], plain_pkey, crypto_box_PUBLICKEYBYTES);
	nc_log_writef("debug", "decoded peer's public key was stored.");
	/* --- end of decoding public key --- */
	
	last_action = pkey_received;
	
      } else if(strncmp(msg_type, OTOC_MTYPE_RTXT, OTOC_MTYPE_LEN) == 0) {

	/* raw text message */

	nc_utils_now_str(time_str);
	fprintf(stdout, "\r[%s] <<< %s", time_str, msg_body);
	fflush(stdout);
	last_action = text_received;

      } else if(strncmp(msg_type, OTOC_MTYPE_STXT, OTOC_MTYPE_LEN) == 0) {

	/* secure text message */

	if(!opts->secure) {

	  char *alert =
	    "\r[%s] <<< { ... encrypted message ... }\n"
	    "==========================================\n"
	    "Your peer uses NanoChat undre secure mode.\n"
	    "Use -s flag to see his encrypted messages.\n"
	    "==========================================\n";

	  nc_utils_now_str(time_str);
	  fprintf(stdout, alert, time_str);
	  fflush(stdout);
	  last_action = text_received;

	} else {

	  /* --- decode  secure msg body --- */
	  int plain_ciphermsg_len = Base64decode_len(msg_body);
	  char plain_ciphermsg[plain_ciphermsg_len];

	  Base64decode(plain_ciphermsg, (const char*) msg_body);

	  /* --- decrypt ciphermsg --- */

	  int decrypted_len = original_msg_body_len;
	  int ciphermsg_len = crypto_box_MACBYTES + decrypted_len;
	  unsigned char decrypted[decrypted_len];
	  unsigned char nonce[crypto_box_NONCEBYTES];
	  memset(nonce, '\0', sizeof nonce);

	  crypto_box_open_easy(decrypted, plain_ciphermsg, ciphermsg_len, nonce,
			       peers_publickey[pair_raw_sock], my_secretkey);

	  /* --- show decrypted msg body --- */

	  decrypted[original_msg_body_len] = '\0';
	
	  nc_utils_now_str(time_str);
	  fprintf(stdout, "\r[%s] <<< %s", time_str, decrypted);
	  fflush(stdout);
	  last_action = text_received;

	}
      }
    }
    
  }

}
static bool CreateDictionaryFromXMLRecursive(char *data, int size, CFMutableDictionaryRef *dict,
        char *key)
{

    if (size == 0) return true;

    xml_token tok;
    char *buf = data;
    int bytesleft = size, closeindex;
    bool bClosed, bAllocatedKey = false;

    while (bytesleft) {

        // skip whitespace
        if (isspace(buf[0])) {
            buf++;
            bytesleft--;
            continue;
        }

        bClosed = false;
        closeindex = -1;

        // get XML token
        if (!GetNextToken(&buf, &bytesleft, &tok, &bClosed)) {

            if (bAllocatedKey) free(key);

            return false;
        }

        // closed XML token?
        if (bClosed) {

            if (key == NULL) continue;

            if (*dict == NULL) {

                if (bAllocatedKey) free(key);

                return false;
            }

            CFBooleanRef value = NULL;

            if (!strcasecmp(tok.id, "true")) {
                value = kCFBooleanTrue;
            }
            else if (!strcasecmp(tok.id, "false")) {
                value = kCFBooleanFalse;
            }

            if (value != NULL) {
                CFStringRef cfkey = CFStringCreateWithCString(kCFAllocatorDefault,
                                    key, kCFStringEncodingUTF8);

                if (bAllocatedKey) {
                    free(key);
                    key = NULL;
                    bAllocatedKey = false;
                }

                if (cfkey == NULL) {
                    return false;
                }

                CFDictionaryAddValue(*dict, cfkey, value);
            }
            else if (bAllocatedKey) {
                free(key);
                key = NULL;
                bAllocatedKey = false;
            }

            continue;
        }

        // check for token types we know about
        if (!strcasecmp(tok.id, "key")) {

            if (bAllocatedKey) free(key);

            if (*dict == NULL) return false;

            closeindex = PIGetIndexOfClosingTag(buf, bytesleft, "key");

            if (closeindex == -1) return false;

            key = (char*)malloc(closeindex+1);
            strncpy(key, buf, closeindex);
            key[closeindex] = 0;
            StripWhitespace(&key);
#ifdef DEBUG
            printf("key = %s\n", key);
#endif

            // empty keys are not allowed
            if (strlen(key) == 0) {
                free(key);
                return false;
            }

            bAllocatedKey = true;
            buf += closeindex + 6;
            bytesleft -= closeindex + 6;
        }
        else if (!strcasecmp(tok.id, "dict")) {

            if (key == NULL) {

                if (*dict != NULL) return false;

                closeindex = PIGetIndexOfClosingTag(buf, bytesleft, "dict");

                if (closeindex == -1) {
                    return false;
                }

                *dict = CFDictionaryCreateMutable(kCFAllocatorDefault, 0,
                                                  &kCFTypeDictionaryKeyCallBacks,
                                                  &kCFTypeDictionaryValueCallBacks);

                if (*dict == NULL) {
                    return false;
                }

                if (!CreateDictionaryFromXMLRecursive(buf, closeindex, dict, NULL)) {
                    CFRelease(*dict);
                    return false;
                }

                return true;
            }
            else if (*dict != NULL) {
                closeindex = PIGetIndexOfClosingTag(buf, bytesleft, "dict");

                if (closeindex == -1) {

                    if (bAllocatedKey) free(key);

                    return false;
                }

                CFMutableDictionaryRef dict2 = CFDictionaryCreateMutable(kCFAllocatorDefault, 0,
                                               &kCFTypeDictionaryKeyCallBacks,
                                               &kCFTypeDictionaryValueCallBacks);

                if (dict2 == NULL) {

                    if (bAllocatedKey) free(key);

                    return false;
                }

                if (!CreateDictionaryFromXMLRecursive(buf, closeindex, &dict2, NULL)) {

                    if (bAllocatedKey) free(key);

                    CFRelease(dict2);
                    return false;
                }

                CFStringRef cfkey = CFStringCreateWithCString(kCFAllocatorDefault,
                                    key, kCFStringEncodingUTF8);

                if (bAllocatedKey) {
                    free(key);
                    key = NULL;
                    bAllocatedKey = false;
                }

                if (cfkey == NULL) {
                    CFRelease(dict2);
                    return false;
                }

                CFDictionaryAddValue(*dict, cfkey, dict2);

                buf += closeindex + 7;
                bytesleft -= closeindex + 7;
            }
            else {

                if (bAllocatedKey) free(key);

                return false;
            }

        }
        else if (!strcasecmp(tok.id, "data")) {

            if ( (key == NULL) || (*dict == NULL) ) return false;

            closeindex = PIGetIndexOfClosingTag(buf, bytesleft, "data");

            if (closeindex == -1) {

                if (bAllocatedKey) free(key);

                return false;
            }

            CFStringRef cfkey = CFStringCreateWithCString(kCFAllocatorDefault,
                                key, kCFStringEncodingUTF8);

            if (bAllocatedKey) {
                free(key);
                key = NULL;
                bAllocatedKey = false;
            }

            if (cfkey == NULL) {
                return false;
            }

            char *value = (char*)malloc(closeindex+1);
            strncpy(value, buf, closeindex);
            value[closeindex] = 0;
            StripWhitespace(&value);

            if (strlen(value) > 0) {
                // Base64 decode the data
                int decodelen = Base64decode_len(value);

                if (decodelen > 0) {
                    char *decodedval = (char*)malloc(decodelen);
                    Base64decode(decodedval, value);
                    free(value);
                    value = decodedval;
                }

            }

            CFDataRef cfvalue = CFDataCreate(kCFAllocatorDefault, (const UInt8*)value, strlen(value));
            free(value);

            if (cfvalue == NULL) {
                return false;
            }

            CFDictionaryAddValue(*dict, cfkey, cfvalue);

            buf += closeindex + 7;
            bytesleft -= closeindex + 7;
        }
        else if (!strcasecmp(tok.id, "string")) {

            if ( (key == NULL) || (*dict == NULL) ) return false;

            closeindex = PIGetIndexOfClosingTag(buf, bytesleft, "string");

            if (closeindex == -1) {

                if (bAllocatedKey) free(key);

                return false;
            }

            CFStringRef cfkey = CFStringCreateWithCString(kCFAllocatorDefault,
                                key, kCFStringEncodingUTF8);

            if (bAllocatedKey) {
                free(key);
                key = NULL;
                bAllocatedKey = false;
            }

            if (cfkey == NULL) {
                return false;
            }

            char *value = (char*)malloc(closeindex+1);
            strncpy(value, buf, closeindex);
            value[closeindex] = 0;
            StripWhitespace(&value);
#ifdef DEBUG
            printf("string = %s\n", value);
#endif

            CFStringRef cfvalue = CFStringCreateWithCString(kCFAllocatorDefault,
                                  value, kCFStringEncodingUTF8);
            free(value);

            if (cfvalue == NULL) {
                return false;
            }

            CFDictionaryAddValue(*dict, cfkey, cfvalue);

            buf += closeindex + 9;
            bytesleft -= closeindex + 9;
        }
        else if (!strcasecmp(tok.id, "?xml") || !strcasecmp(tok.id, "!DOCTYPE") ||
                 !strcasecmp(tok.id, "plist")) {
            // Ignore
        }
        else {

            // unknown token -- just skip it
            if (bAllocatedKey) {
                free(key);
                key = NULL;
                bAllocatedKey = false;
            }

            closeindex = PIGetIndexOfClosingTag(buf, bytesleft, tok.id);

            if (closeindex == -1) {
                return false;
            }

            buf += closeindex + strlen(tok.id) + 3;
            bytesleft -= closeindex + strlen(tok.id) + 3;
        }

    }

    if (bAllocatedKey) free(key);

    return true;
}
Exemple #15
0
void* SomeAwesomeThings(void* Param){
	Client* theClient = (Client*)Param;
	char* message = (char*)malloc(4086);
	char sendMessage[4086];
	char encrypt[4086];
	char* receiver;
	char* tmp;
	char* ender;
	char* err;
	Client* ClientCounter;
	int msgSize;
	int usernameSet = 0;
	int nameLength;
	int sub_msg_len;
	int encrypt_len;

	//RC4 component
	RC4Container RC4key;
	int iter1;
	int iter2;
	RC4key.iter1 = &iter1;
	RC4key.iter2 = &iter2;
	int RC4KeySet = 0;
	//
	unsigned char hash_out[SHA_DIGEST_LENGTH + 1];
	char hash_string[SHA_DIGEST_LENGTH * 2 + 1];
	int iterator;
	memset(sendMessage, '\0', sizeof(sendMessage));
	err = (char*) malloc(130);

	//    if((msgSize = read(theClient->sockfd, message, sizeof(message) - 1)) > 0){
	//        message[msgSize] = '\0';
	//        int nameLength = strstr(message, "\r\n.\r\n") - message;
	//        for(msgSize = 0; msgSize < nameLength; msgSize++){
	//            theClient->Name[msgSize] = message[msgSize];
	//        }
	//        theClient->Name[nameLength] = '\0';
	//        printf("%s has connected\n", theClient->Name);
	//    }


	while((msgSize = read(theClient->sockfd, message, 4086 - 1)) > 0){

		message[msgSize] = '\0';
		sub_msg_len = 0;
		while((ender = strstr(message, "\r\n.\r\n")) != NULL){
			//            *ender = '\0';
			sub_msg_len += ender - message + 5;
			if(sub_msg_len > msgSize)
				break;

			//            printf("%s\n", message);
			//Do things here
			tmp = strstr(message, "\r\n");
			*tmp = '\0';
			printf("%s\n", message);
			if(strcmp(message, "Mode: Public") == 0){

				tmp = tmp + 2;
				nameLength = strstr(tmp, "\r\n.\r\n") - tmp + 5;
				sprintf(sendMessage,"%s\r\nUser: %s\r\n", message, theClient->Name);
				strncat(sendMessage, tmp, nameLength);

				for(ClientCounter = head; ClientCounter != NULL; ClientCounter = ClientCounter->Next){
					if(ClientCounter == theClient) continue;
					write(ClientCounter->sockfd, sendMessage, sizeof(sendMessage));
				}
			}
			else if((strcmp(message, "Mode: Private") == 0) || (strcmp(message, "Mode: InitPriv") == 0) || (strcmp(message, "Mode: AccPriv") == 0) ){

				tmp = tmp + 2;
				tmp = strstr(tmp, " ") + 1;
				receiver = tmp;
				tmp = strstr(tmp, "\r\n");
				*tmp = '\0';
				tmp = tmp + 2;
				nameLength = strstr(tmp, "\r\n.\r\n") - tmp + 5;

				sprintf(sendMessage,"%s\r\nUser: %s\r\n", message, theClient->Name);
				strncat(sendMessage, tmp, nameLength);

				for(ClientCounter = head; ClientCounter != NULL; ClientCounter = ClientCounter->Next){
					if(strcmp(receiver, ClientCounter->Name) == 0){
						write(ClientCounter->sockfd, sendMessage, sizeof(sendMessage));
						break;
					}
				}
			}
			else if(strcmp(message, "Mode: GetList") == 0){
				sprintf(sendMessage, "Mode: List\r\n");
				for(ClientCounter = head; ClientCounter != NULL; ClientCounter = ClientCounter->Next){
					if(ClientCounter == theClient)continue;
					strcat(sendMessage, ClientCounter->Name);
					strcat(sendMessage, "\r\n");
				}
				strcat(sendMessage, "\r\n.\r\n");

				write(theClient->sockfd, sendMessage, sizeof(sendMessage));
			}
			else if(strcmp(message, "Mode: Username") == 0){
				tmp = tmp + 2;
				if(usernameSet == 0){
					if(RC4KeySet == 1){
						printf("Setting username\n");
						nameLength = strstr(tmp, "\r\n.\r\n") - tmp;
						char* decode;
						int decode_len = Base64decode(tmp, (unsigned char**)&decode, nameLength);
						encrypt_len = RC4Crypt(decode_len, (unsigned char*)decode, (unsigned char*)encrypt, &RC4key);

						free(decode);

						tmp = strstr(encrypt, "\r\n.,\r\n");
						nameLength = tmp - encrypt;
						*tmp = '\0';
						tmp = tmp + 6;

						if(CheckHashValidation(nameLength, (unsigned char*)encrypt, tmp) == 1){
							for(msgSize = 0; msgSize < nameLength; msgSize++){
								theClient->Name[msgSize] = *(encrypt + msgSize);
							}
							theClient->Name[nameLength] = '\0';
							printf("%s\n", theClient->Name);
							usernameSet++;
						}
					}
				}
			}
			else if(strcmp(message, "Mode: GetCA") == 0){
				sprintf(sendMessage, "Mode: ServCA\r\n");
				strcat(sendMessage, public_key);
				strcat(sendMessage, "\r\n.\r\n");

				write(theClient->sockfd, sendMessage, sizeof(sendMessage));
			}
			else if(strcmp(message, "Mode: SetPubKey") == 0){
				tmp = tmp + 2;
				nameLength = strstr(tmp, "\r\n.\r\n") - tmp;
				if(RC4KeySet == 1){
					char* decoded;
					int decoded_len = Base64decode(tmp, (unsigned char**)&decoded, nameLength);
					encrypt_len = RC4Crypt(decoded_len, (unsigned char*)decoded, (unsigned char*)encrypt, &RC4key);
					free(decoded);
					encrypt[encrypt_len] = '\0';
					tmp = strstr(encrypt, "\r\n.,\r\n");
					nameLength = tmp - encrypt;
					*tmp = '\0';
					tmp = tmp + 6;
					if(CheckHashValidation(nameLength, (unsigned char*)encrypt, tmp) == 1){
						for(iterator = 0; iterator < nameLength; iterator++){
							*(theClient->public_key + iterator) = *(encrypt + iterator);
						}
						*(theClient->public_key + nameLength) = '\0';
					}
					else{
						//TODO: Return some error
						printf("Failed to set public key\n");
						sprintf(sendMessage, "Mode: FailPubKey\r\n.\r\n");
						write(theClient->sockfd, sendMessage, sizeof(sendMessage));
					}
				}
			}
			else if(strcmp(message, "Mode: SetRC4Key") == 0){
				if(RC4KeySet == 0){
					tmp = tmp + 2;
					nameLength = strstr(tmp, "\r\n.\r\n") - tmp;
					char* decoded;
					int dedoded_len = Base64decode(tmp, (unsigned char**)&decoded, nameLength);
					if((encrypt_len = private_decrypt((unsigned char*)decoded, dedoded_len, (unsigned char*)private_key, (unsigned char*)encrypt, RSA_PKCS1_OAEP_PADDING)) == -1){
						ERR_load_crypto_strings();
						ERR_error_string(ERR_get_error(), err);
						fprintf(stderr, "Error decrypting message: %s\n", err);
						sprintf(sendMessage, "Mode: FailRC4Key\r\n.\r\n");
						write(theClient->sockfd, sendMessage, sizeof(sendMessage));
					}
					else{
						tmp = strstr(encrypt, "\r\n.,\r\n");
						nameLength = tmp - encrypt;
						*tmp = '\0';
						tmp = tmp + 6;
						//TODO: Check if hash of encrypt is the same with tmp
						if(CheckHashValidation(nameLength, (unsigned char*)encrypt, tmp) == 1){
							initRC4key(&RC4key, encrypt, nameLength);
							RC4KeySet = 1;
						}
						else{
							sprintf(sendMessage, "Mode: FailRC4Key\r\n.\r\n");
							write(theClient->sockfd, sendMessage, sizeof(sendMessage));
						}
					}
					free(decoded);
				}
			}
			else if(strcmp(message, "Mode: GetPubKey") == 0){
				tmp = tmp + 2;
				tmp = strstr(tmp, " ") + 1;
				receiver = tmp;
				tmp = strstr(tmp, "\r\n");
				*tmp = '\0';
				for(ClientCounter = head; ClientCounter != NULL; ClientCounter = ClientCounter->Next){
					if(strcmp(receiver, ClientCounter->Name) == 0)
						break;
				}
				if(ClientCounter != NULL){
					if(ClientCounter->public_key[0] != '\0' && RC4KeySet == 1){
						SHA1((unsigned char*)ClientCounter->public_key, strlen(ClientCounter->public_key), (unsigned char*)hash_out);
						for(iterator = 0; iterator < SHA_DIGEST_LENGTH; iterator++){
							sprintf(&hash_string[iterator * 2], "%02x", (unsigned int)hash_out[iterator]);
						}
						sprintf(sendMessage, "%s\r\n.,\r\n%s", ClientCounter->public_key, hash_string);
						encrypt_len = RC4Crypt(strlen(sendMessage), (unsigned char*)sendMessage, (unsigned char*)encrypt, &RC4key);
						encrypt[encrypt_len] = '\0';
						char* encoded;
						int encoded_len = Base64encode(encrypt, encrypt_len, &encoded);
						encoded[encoded_len] = '\0';
						sprintf(sendMessage, "Mode: ClientPubKey\r\nUser: %s\r\n%s\r\n.\r\n", ClientCounter->Name, encoded);
						free(encoded);
						printf("%s\n", sendMessage);
						printf("%s\n", ClientCounter->public_key);
						write(theClient->sockfd, sendMessage, sizeof(sendMessage));
					}
					else{
						sprintf(sendMessage, "Mode: FailPubKey\r\nUser: %s\r\n.\r\n", ClientCounter->Name);
					}
				}
			}

			*ender = '\0';
			ender += 5;
			message = ender;
		}
	}

	printf("%s has been disconnected\n", theClient->Name);
	if(theClient == head){
		head = theClient->Next;
		if(head != NULL)head->Previous = NULL;
		else tail = NULL;
	}
	else{
		theClient->Previous->Next = theClient->Next;
		if(theClient == tail){
			tail = theClient->Previous;
		}
	}
	if(theClient->keypair != NULL)
		RSA_free(theClient->keypair);
	free(theClient);

	return NULL;
}
Exemple #16
0
/**
 * Calculate the real key from master key, encrypted data key
 */
static int key_calculate_real(fcgienc_crypt * fc)
{
	int i;
	ssize_t len;
	unsigned char mkhex[32], ivhex[16];
	char decodebuf[KEY_SIZE];
	int decodelen;
	unsigned char keystr[KEY_SIZE];
	char *keyencbase64;

	if (!fc)
		return -1;

	keyencbase64 = fc->encryptedDataKey;

	// string -> hex of master key 
	memset(mkhex, 0, 32);
	len = strlen(fc->masterKey)&0xFFFFFFFE;
	for (i=0; i<len; i+=2)
	{
		char c[3];
		if (i>=64)
			break;
		c[0] = fc->masterKey[i];
		c[1] = fc->masterKey[i+1];
		c[2] = 0;
		sscanf(c, "%x", (unsigned int *)&mkhex[i/2]);
	}

	if ((i<64) && (len < strlen(fc->masterKey)))
	{
		char c[3];
		c[0] = fc->masterKey[len];
		c[1] = '0';
		c[2] = 0;
		sscanf(c, "%x", (unsigned int *)&mkhex[i/2]);
	}

	// string -> hex of data key
	memset(ivhex, 0, 16);
	len = strlen(fc->initializationVector)&0xFFFFFFFE;
	for (i=0; i<len; i+=2)
	{
		char c[3];
		if (i>=32)
			break;
		c[0] = fc->initializationVector[i];
		c[1] = fc->initializationVector[i+1];
		c[2] = 0;
		sscanf(c, "%x", (unsigned int *)&ivhex[i/2]);
	}
	if ((i<32) && (len < strlen(fc->initializationVector)))
	{
		char c[3];
		c[0] = fc->initializationVector[len];
		c[1] = '0';
		c[2] = 0;
		sscanf(c, "%x", (unsigned int *)&ivhex[i/2]);
	}

	// decode base64
	decodelen = Base64decode(decodebuf, keyencbase64);

	// decrypt key
	memset(keystr, 0, KEY_SIZE);
	len = DecryptAesCBC((unsigned char *)decodebuf, decodelen, keystr, mkhex, ivhex);

	if (len < 0)
	{
		log_keythread("KEY-THREAD - AES-CBC decryption failed with key %s", fc->dataKeyId);
		return -1;
	}

	// store into variable
	memcpy(fc->dataKey, keystr, len);
	fc->dataKey[len] = 0;
	fc->dataKeyLength = len;

	return 0;
}