Example #1
0
Domain::DataKey DEKPool::generate_new_data_key() {
    Domain::DataKey data_key;
    std::string encoded_dek;
    std::string master_key = CardCrypter::assemble_master_key(config_, session_);
    AESCrypter aes_crypter(master_key);
    while (true) {
        std::string dek_value = generate_random_bytes(32);
        try {
            encoded_dek = encode_base64(aes_crypter.encrypt(dek_value));
            auto count = Yb::query<Domain::DataKey>(session_)
                    .filter_by(Domain::DataKey::c.dek_crypted == encoded_dek)
                    .count();
            if (!count)
                break;
        } catch(AESBlockSizeException &exc) {
            std::cout << exc.what() << std::endl;
        }
    }
    data_key.dek_crypted = encoded_dek;
    data_key.start_ts = Yb::now();
    data_key.finish_ts = Yb::dt_make(2020, 12, 31);
    data_key.counter = 0;
    data_key.save(session_);
    session_.flush();
    return data_key;
}
Example #2
0
static char *get_auth_header(Port_T P, char *auth, int l) {
        char *b64;
        char buf[STRLEN];
        char *username = NULL;
        char *password = NULL;

        if (P->url_request) {
                URL_T U = P->url_request->url;
                if (U) {
                        username = U->user;
                        password = U->password;
                }
        }

        if (! (username && password))
                return auth;

        snprintf(buf, STRLEN, "%s:%s", username, password);
        if (! (b64 = encode_base64(strlen(buf), (unsigned char *)buf)) )
                return auth;

        snprintf(auth, l, "Authorization: Basic %s\r\n", b64);
        FREE(b64);

        return auth;
}
Example #3
0
int main (int argc, char **argv){
  char *message=NULL;
  char *presence=NULL;
  char *subscription=NULL;
  char *base64=NULL;
  char *clear=NULL;
  char *roster=NULL;
  char *sroster=NULL;
  char *sha=NULL;
  foo = (jabberID*) createJabberID("[email protected]/cjabber");
  if(!foo) return 1;
  printf("foo->user: %s, foo->server: %s, foo->resource: %s, foo->full: %s\n",foo->user,foo->server,foo->resource,foo->full);
  message=createMessage("Hello cruel world!","[email protected]/muh","[email protected]/cjabber",0,"foobar",create_sha_hash("foobarblubb", 11));
  printf("%s",message);
  presence=createPresenceMsg(2,"away from keyboard","[email protected]/input", "[email protected]/bla", 23);
  printf("%s",presence);
  subscription=createSubscriptionMsg(1,NULL,NULL);
  printf("%s",subscription);
  roster=requestRoster("[email protected]/cjabber", "roster_1");
  printf("%s",roster);
  sroster=setRoster("[email protected]/cjabber", "roster_2", "[email protected]/input", "mouse", "device", SUB_SUBSCRIBED);
  printf("%s",sroster);
  base64=encode_base64("This book is just for you in order to give you alternatives, alternatives to nothin' precise. Alternatives are necessary to form yours and other lifes. Alternatives are present everyday, but not overwhelming like you. It's hard to understand why I like you, but as easy as I can say: It's just youl. Will you be my valentine?");
  printf("base64: %s\n",base64);
  clear=decode_base64(base64);
  printf("clear: %s\n",clear);
  sha=create_sha_hash("foobarblubb", 11);
  printf("sha: %s\n",sha);

  return 0;
}
Example #4
0
char *
bits_save (BITS *bits)
{
    int
        block_nbr;                      /*  Bitstring block number           */
    word
        comp_size;                      /*  Size of compressed block         */
    BITBLOCK
        *block_ptr;                     /*  Points to bitstring block        */
    byte
        *buffer = NULL,                 /*  Stream buffer                    */
        *position;                      /*  Current position in the stream   */
    long
        size;
    char
        *encoded = NULL;

    ASSERT (bits);

    size = calculate_buffer_size (bits);
    buffer = mem_alloc (size);
    if (buffer)
      {
        position = buffer;
        /*  Write bitstring header to stream                                 */
        *((int *)position) = bits-> block_count;
        position += sizeof (bits-> block_count);

        *((dbyte *)position) = bits-> free_list;
        position += sizeof (bits-> free_list);

        /*  Write bitstring blocks to stream                                 */
        for (block_nbr = 0; block_nbr < bits-> block_count; block_nbr++)
          {
            block_ptr = bits-> block [block_nbr];
            comp_size = compress_block (block_ptr-> block.data,
                                    compressed, (word)BIT_DATASIZE);

            *((dbyte *)position) = block_ptr-> right;
            position += sizeof (block_ptr-> right);

            *((int *)position) = block_ptr-> size;
            position += sizeof (block_ptr-> size);

            *((word *)position) = comp_size;
            position += sizeof (word);
            memcpy (position, compressed, comp_size);
            position += comp_size;
          }
        /* Encode binary buffer in base64                                    */
        encoded = mem_alloc ((long)((double) size * 1.5) + 2);
        if (encoded)
            encode_base64 (buffer, encoded, size);

        mem_free (buffer);
      }
    return (encoded);
}
Example #5
0
void tempodb_build_query(tempodb_config *config, char *buffer, const size_t buffer_size, const char *verb, const char *path, const char *payload) {
  char access_credentials[ACCESS_KEY_SIZE*2 + 2];
  char *encoded_credentials;
  snprintf(access_credentials, strlen(config->access_key) + strlen(config->access_secret) + 2, "%s:%s", config->access_key, config->access_secret);
  encoded_credentials = encode_base64(strlen(access_credentials), (unsigned char *)access_credentials);

  snprintf(buffer, buffer_size, "%s %s HTTP/1.0\r\nAuthorization: Basic %s\r\nUser-Agent: tempodb-embedded-c/1.0.1\r\nHost: %s\r\nContent-Length: %lu\r\nContent-Type: application/json\r\n\r\n%s", verb, path, encoded_credentials, DOMAIN, (unsigned long)strlen(payload), payload);
  free(encoded_credentials);
}
int
brutus(const char *login, const char *name_file, const char *ip)
{

	FILE* file = NULL;
	char *passwd = malloc(50 * sizeof(char));
	char *search = NULL;
	char buff[50];


	file = fopen(name_file, "r");

	if ( file == NULL ) {
		fprintf(stderr, "open file <%s> failed\n", name_file);
		free(passwd);
		return -1;
	}

	printf("** open file successfull\n");
	printf("** strat scan .. CTRL+C for stop\n\n");


	while ( fgets(buff, 50, file) ) {

		search = strtok(buff, "\n");
		
		sprintf(passwd, "%s:%s", login, search);

		if ( encode_base64(&passwd) == -1 ) {
			free(passwd);
			return -1;
		}


		printf("** passwd encoded : %s\n",passwd);


		if ( test_passwd(passwd, ip) == 0 ) {
			printf("**Passwd find\n");
			printf("\tlogin : %s\n\tpasswd : %s\n\n", login , search);
			free(passwd);
			return 0;
		}


		memset(buff, 0, sizeof(buff));
		memset(passwd, 0, strlen(passwd));

	}

	free(passwd);
	return -1;
}
NtripStream::NtripStream(const std::string& address, uint16_t port,
                         const std::string& mountpoint, const std::string& user,
                         const std::string& passwd, uint32_t timeout_s)
    : _mountpoint(mountpoint),
      _write_data_prefix("GET /" + mountpoint +
                         " HTTP/1.0\r\n"
                         "User-Agent: NTRIP gnss_driver/0.0\r\n"
                         "accept: */* \r\n\r\n"),

      _login_data("GET /" + mountpoint +
                  " HTTP/1.0\r\n"
                  "User-Agent: NTRIP gnss_driver/0.0\r\n"
                  "accept: */* \r\n"
                  "Authorization: Basic " +
                  encode_base64(user + ":" + passwd) + "\r\n\r\n"),
      _timeout_s(timeout_s),
      _tcp_stream(new TcpStream(address.c_str(), port, 0, false)) {}
char * do_hash( char * sec_ws_key )
{
#if 0
  strcpy( sec_ws_key, "wTfhMBsUmc9/v6RWgzmLiw==" ); 
  /* expected: TyRLRl5fE8awKtbv4EQl5GSWfcE= */
#endif

  SHA1Context sha;
  SHA1Reset( &sha );

  char * combined = (char *)calloc( 1 + strlen( sec_ws_key ) + strlen( GUID ), sizeof( char ) );
  sprintf( combined, "%s%s", sec_ws_key, GUID );
  printf( "HASHING: [%s]\n", combined );

  SHA1Input( &sha, (const unsigned char *)combined, strlen( combined ) );

  if ( SHA1Result( &sha ) )
  {
    char * result = (char *)calloc( 128, sizeof( char ) );
    result[0] = '\0';

    int i, j;
    for ( i = 0, j = 0 ; i < 5 ; i++ )
    {
      int k;
      char mini[16];
      sprintf( mini, "%08X", sha.Message_Digest[i] );  /* e.g. 99AABBCC */
      for ( k = 0 ; k < 8 ; k += 2 )
      {
        result[j++] = hex_to_digit( mini[k] ) * 16 + hex_to_digit( mini[k+1] );
      }
    }

    int output_length = 28;
    char * x = encode_base64( 20, (unsigned char *)result );
    strncpy( result, x, output_length );
    result[ output_length ] = '\0';
    return result;
  }
  else
  {
    printf( "Error performing do_hash() function\n" );
    return (char *)NULL;
  }
}
Example #9
0
void FlatMessageIO::xmlExportContent(
	ExportContext& context) const {

	context.beginContent();

	// convert message to base64
	ASSERT(m_message);
	ssize_t flatSize = m_message->FlattenedSize();
	ASSERT(flatSize);
	char* flatData = new char[flatSize];
	status_t err = m_message->Flatten(flatData, flatSize);
	ASSERT(err == B_OK);
	
	// make plenty of room for encoded content (encode_base64 adds newlines)
	ssize_t base64Size = ((flatSize * 3) / 2);
	char* base64Data = new char[base64Size];
	ssize_t base64Used = encode_base64(base64Data, flatData, flatSize);
	base64Data[base64Used] = '\0';
	
	// write the data

	const char* pos = base64Data;
	while(*pos) {
		ssize_t chunk = 0;
		const char* nextBreak = strchr(pos, '\n');
		if(!nextBreak)
			chunk = strlen(pos);
		else
			chunk = nextBreak - pos;

		context.writeString(context.indentString());
		context.writeString(pos, chunk);
		context.writeString("\n");
		
		pos += chunk;
		if(*pos == '\n')
			++pos;
	}
	
	// clean up
	delete [] flatData;
	delete [] base64Data;
}
Example #10
0
int ucloud_uhost_set_str_param(ucloud_http_params_t *param, ucloud_uhost_param_mask_t *mask, const char *val)
{
	if (param == NULL || mask == NULL || val == NULL)
	{
		return UCLOUDE_INVALID_PARAM;
	}

	if (mask->region) ucloud_http_params_add(param, "Region", val);
	if (mask->image_id) ucloud_http_params_add(param, "ImageId", val);
	if (mask->name) ucloud_http_params_add(param, "Name", val);
	if (mask->password)
	{
		char base64_passwd[128] = {0};
		encode_base64((uint8_t*)base64_passwd, (uint8_t*)val, strlen(val));
		ucloud_http_params_add(param, "Password", base64_passwd);
	}
	if (mask->key_pair) ucloud_http_params_add(param, "KeyPair", val);
	return UCLOUDE_OK;
}
Example #11
0
int _tmain(int argc, _TCHAR* argv[])
{
	char hex[BUFFER_SIZE];
	char b64Enc[BUFFER_SIZE];
	char md5Hex[BUFFER_SIZE];
	char md5B64[BUFFER_SIZE];
	char sha1Hex[BUFFER_SIZE];
	char sha1B64[BUFFER_SIZE];

	if ( argc < 2 ){
		printf("usage: CreateMD5Hash <string>\n");
		exit(-1);
	}

	BYTE *str = (BYTE*)argv[1];
	size_t strSize = strlen(argv[1]);

	size_t hexSize		= encode_hex(str, strSize, hex, sizeof(hex));
	size_t b64EncSize	= encode_base64(str, strSize, b64Enc, sizeof(b64Enc));
	size_t md5HexSize	= md5_hex(str, strSize, md5Hex, sizeof(md5Hex));
	size_t md5B64Size	= md5_base64(str, strSize, md5B64, sizeof(md5B64));
	size_t sha1HexSize	= sha1_hex(str, strSize, sha1Hex, sizeof(sha1Hex));
	size_t sha1B64Size	= sha1_base64(str, strSize, sha1B64, sizeof(sha1B64));

	printf(
		"'%s':%d\n"
		"  Hex:\t\t'%s':%d\n"
		"  B64:\t\t'%s':%d\n"
		"  MD5Hex:\t'%s':%d\n"
		"  MD5B64:\t'%s':%d\n"
		"  SHA1Hex:\t'%s':%d\n"
		"  SHA1B64:\t'%s':%d\n",
		str, strSize,
		hex,		hexSize,
		b64Enc,		b64EncSize,
		md5Hex,		md5HexSize,
		md5B64,		md5B64Size,
		sha1Hex,	sha1HexSize,
		sha1B64,	sha1B64Size
	);

	return 0;
}
Example #12
0
void SMTP_auth(T S, const char *username, const char *password) {
    ASSERT(S);
    ASSERT(username);
    ASSERT(password);
    char buffer[STRLEN] = {};
    // PLAIN has precedence
    if (S->flags & MTA_AuthPlain) {
        int len = snprintf(buffer, STRLEN, "%c%s%c%s", '\0', username, '\0', password);
        char *b64 = encode_base64(len, (unsigned char *)buffer);
        TRY
        {
            _send(S, "AUTH PLAIN %s\r\n", b64);
            _receive(S, 235, NULL);
        }
        FINALLY
        {
            FREE(b64);
        }
        END_TRY;
    } else if (S->flags & MTA_AuthLogin) {
/*
* Encoded App SSOToken needs to be sent in
* requester attribute in SessionRequest.
*/
void AgentProfileService::setEncodedAgentSSOToken(std::string appSSOToken) {
    char* encodedAppSSOTokenString = NULL;
    string tmpTokenString = "token:";
    tmpTokenString.append(appSSOToken);
    encodedAppSSOTokenString = (char *)
        malloc(((tmpTokenString.size() * 4/3 + 1)/4 + 1)*4 + 4);

    if(encodedAppSSOTokenString != NULL) {
        encode_base64(tmpTokenString.c_str(),
                  tmpTokenString.size(),
                  encodedAppSSOTokenString);
        encodedAgentSSOToken = encodedAppSSOTokenString;
    } else {
        encodedAgentSSOToken = "";
    }

    if(encodedAppSSOTokenString != NULL) {
       free(encodedAppSSOTokenString);
    }
}
zframe_t* zwshandshake_get_response(zwshandshake_t *self)
{
	const char * sec_websocket_key_name = "sec-websocket-key";
	const char * magic_string = "258EAFA5-E914-47DA-95CA-C5AB0DC85B11";

	char * key = (char *)zhash_lookup(self->header_fields, sec_websocket_key_name);

	int len = strlen(key) + strlen(magic_string);

	char plain[150];

	strcpy(plain, key);
	strcat(plain, magic_string);

	zdigest_t* digest = zdigest_new();
	zdigest_update(digest, (byte *) plain, len);
	
	byte* hash = zdigest_data(digest);
		
	char accept_key[150];

	int accept_key_len = encode_base64(hash, zdigest_size(digest), accept_key, 150);

	int response_len = strlen("HTTP/1.1 101 Switching Protocols\r\n"
		"Upgrade: websocket\r\n"
		"Connection: Upgrade\r\n"
		"Sec-WebSocket-Accept: \r\n"
		"Sec-WebSocket-Protocol: WSNetMQ\r\n\r\n") + accept_key_len;

	char* response = (char *)zmalloc(sizeof(char) * (response_len+1));
	
	strcpy(response, "HTTP/1.1 101 Switching Protocols\r\n"
		"Upgrade: websocket\r\n"
		"Connection: Upgrade\r\n"
		"Sec-WebSocket-Accept: ");
	strncat(response, accept_key, accept_key_len);
	strcat(response, "\r\nSec-WebSocket-Protocol: WSNetMQ\r\n\r\n");	

	return zframe_new(response, response_len);
}
Example #15
0
File: db_sql.c Project: po1vo/aide
void sql_write_byte_base64(byte*data,size_t len,char* s,int i )
{
  char* tmpstr=NULL;
  int retval=0;
  
  tmpstr=encode_base64(data,len);
  if(i){
    strcat(s,",");
  }
  
  strcat(s,"'");
  
  if(tmpstr){
    strcat(s,tmpstr);
    free(tmpstr);
  }else {
    /* Do nothing.. */
  }
  
  strcat(s,"'");
  return;
}
Example #16
0
int ucloud_uhost_set_reinstall_param(ucloud_http_params_t *param, ucloud_uhost_reinstall_param_mask_t *mask, const char *val)
{
	if (param == NULL || mask == NULL)
	{
		return UCLOUDE_INVALID_PARAM;
	}
	if (mask->password && val)
	{
		char base64_passwd[128] = {0};
		encode_base64((uint8_t*)base64_passwd, (uint8_t*)val, strlen(val));
		ucloud_http_params_add(param, "Password", base64_passwd);
	}
	if (mask->image_id && val)
	{
		ucloud_http_params_add(param, "ImageId", val);
	}
	if (mask->reserve_disk && val)
	{
		ucloud_http_params_add(param, "ReserveDisk", val);
	}
	return UCLOUDE_OK;
}
Example #17
0
File: db_sql.c Project: po1vo/aide
void sql_write_time_base64(time_t data,char* s,int i){
  static char* ptr=NULL;
  char* tmpstr=NULL;
  int retval=0;
  
  if(i!=0){
    strcat(s,",");
  }
  
  if(data==0){
    strcat(s,"''");
    return;
  }


  ptr=(char*)malloc(sizeof(char)*TIMEBUFSIZE);
  if (ptr==NULL) {
    error(0,"\nCannot allocate memory..\n");
    abort();
  }
  
  memset((void*)ptr,0,sizeof(char)*TIMEBUFSIZE);

  sprintf(ptr,"%li",data);


  tmpstr=encode_base64(ptr,strlen(ptr));
  strcat(s,"'");
  strcat(s,tmpstr);
  strcat(s,"'");

  free(tmpstr);
  free(ptr);
  
  return;
  
}
Example #18
0
_EXPORT ssize_t utf8_to_rfc2047 (char **bufp, ssize_t length, uint32 charset, char encoding) {
	struct word {
		BString	originalWord;
		BString	convertedWord;
		bool	needsEncoding;

		// Convert the word from UTF-8 to the desired character set.  The
		// converted version also includes the escape codes to return to ASCII
		// mode, if relevant.  Also note if it uses unprintable characters,
		// which means it will need that special encoding treatment later.
		void ConvertWordToCharset (uint32 charset) {
			int32 state = 0;
			int32 originalLength = originalWord.Length();
			int32 convertedLength = originalLength * 5 + 1;
			char *convertedBuffer = convertedWord.LockBuffer (convertedLength);
			mail_convert_from_utf8 (charset, originalWord.String(),
				&originalLength, convertedBuffer, &convertedLength, &state);
			for (int i = 0; i < convertedLength; i++) {
				if ((convertedBuffer[i] & (1 << 7)) ||
					(convertedBuffer[i] >= 0 && convertedBuffer[i] < 32)) {
					needsEncoding = true;
					break;
				}
			}
			convertedWord.UnlockBuffer (convertedLength);
		};
	};
	struct word *currentWord;
	BList words;

	// Break the header into words.  White space characters (including tabs and
	// newlines) separate the words.  Each word includes any space before it as
	// part of the word.  Actually, quotes and other special characters
	// (",()<>@) are treated as separate words of their own so that they don't
	// get encoded (because MIME headers get the quotes parsed before character
	// set unconversion is done).  The reader is supposed to ignore all white
	// space between encoded words, which can be inserted so that older mail
	// parsers don't have overly long line length problems.

	const char *source = *bufp;
	const char *bufEnd = *bufp + length;
	const char *specialChars = "\"()<>@,";

	while (source < bufEnd) {
		currentWord = new struct word;
		currentWord->needsEncoding = false;

		int wordEnd = 0;

		// Include leading spaces as part of the word.
		while (source + wordEnd < bufEnd && isspace (source[wordEnd]))
			wordEnd++;

		if (source + wordEnd < bufEnd &&
			strchr (specialChars, source[wordEnd]) != NULL) {
			// Got a quote mark or other special character, which is treated as
			// a word in itself since it shouldn't be encoded, which would hide
			// it from the mail system.
			wordEnd++;
		} else {
			// Find the end of the word.  Leave wordEnd pointing just after the
			// last character in the word.
			while (source + wordEnd < bufEnd) {
				if (isspace(source[wordEnd]) ||
					strchr (specialChars, source[wordEnd]) != NULL)
					break;
				if (wordEnd > 51 /* Makes Base64 ISO-2022-JP "word" a multiple of 4 bytes */ &&
					0xC0 == (0xC0 & (unsigned int) source[wordEnd])) {
					// No English words are that long (46 is the longest),
					// break up what is likely Asian text (which has no spaces)
					// at the start of the next non-ASCII UTF-8 character (high
					// two bits are both ones).  Note that two encoded words in
					// a row get joined together, even if there is a space
					// between them in the final output text, according to the
					// standard.  Next word will also be conveniently get
					// encoded due to the 0xC0 test.
					currentWord->needsEncoding = true;
					break;
				}
				wordEnd++;
			}
		}
		currentWord->originalWord.SetTo (source, wordEnd);
		currentWord->ConvertWordToCharset (charset);
		words.AddItem(currentWord);
		source += wordEnd;
	}

	// Combine adjacent words which contain unprintable text so that the
	// overhead of switching back and forth between regular text and specially
	// encoded text is reduced.  However, the combined word must be shorter
	// than the maximum of 75 bytes, including character set specification and
	// all those delimiters (worst case 22 bytes of overhead).

	struct word *run;

	for (int32 i = 0; (currentWord = (struct word *) words.ItemAt (i)) != NULL; i++) {
		if (!currentWord->needsEncoding)
			continue; // No need to combine unencoded words.
		for (int32 g = i+1; (run = (struct word *) words.ItemAt (g)) != NULL; g++) {
			if (!run->needsEncoding)
				break; // Don't want to combine encoded and unencoded words.
			if ((currentWord->convertedWord.Length() + run->convertedWord.Length() <= 53)) {
				currentWord->originalWord.Append (run->originalWord);
				currentWord->ConvertWordToCharset (charset);
				words.RemoveItem(g);
				delete run;
				g--;
			} else // Can't merge this word, result would be too long.
				break;
		}
	}

	// Combine the encoded and unencoded words into one line, doing the
	// quoted-printable or base64 encoding.  Insert an extra space between
	// words which are both encoded to make word wrapping easier, since there
	// is normally none, and you're allowed to insert space (the receiver
	// throws it away if it is between encoded words).

	BString rfc2047;
	bool	previousWordNeededEncoding = false;

	const char *charset_dec = "none-bug";
	for (int32 i = 0; mail_charsets[i].charset != NULL; i++) {
		if (mail_charsets[i].flavor == charset) {
			charset_dec = mail_charsets[i].charset;
			break;
		}
	}

	while ((currentWord = (struct word *)words.RemoveItem(0L)) != NULL) {
		if ((encoding != quoted_printable && encoding != base64) ||
		!currentWord->needsEncoding) {
			rfc2047.Append (currentWord->convertedWord);
		} else {
			// This word needs encoding.  Try to insert a space between it and
			// the previous word.
			if (previousWordNeededEncoding)
				rfc2047 << ' '; // Can insert as many spaces as you want between encoded words.
			else {
				// Previous word is not encoded, spaces are significant.  Try
				// to move a space from the start of this word to be outside of
				// the encoded text, so that there is a bit of space between
				// this word and the previous one to enhance word wrapping
				// chances later on.
				if (currentWord->originalWord.Length() > 1 &&
					isspace (currentWord->originalWord[0])) {
					rfc2047 << currentWord->originalWord[0];
					currentWord->originalWord.Remove (0 /* offset */, 1 /* length */);
					currentWord->ConvertWordToCharset (charset);
				}
			}

			char *encoded = NULL;
			ssize_t encoded_len = 0;
			int32 convertedLength = currentWord->convertedWord.Length ();
			const char *convertedBuffer = currentWord->convertedWord.String ();

			switch (encoding) {
				case quoted_printable:
					encoded = (char *) malloc (convertedLength * 3);
					encoded_len = encode_qp (encoded, convertedBuffer, convertedLength, true /* headerMode */);
					break;
				case base64:
					encoded = (char *) malloc (convertedLength * 2);
					encoded_len = encode_base64 (encoded, convertedBuffer, convertedLength, true /* headerMode */);
					break;
				default: // Unknown encoding type, shouldn't happen.
					encoded = (char *) convertedBuffer;
					encoded_len = convertedLength;
					break;
			}

			rfc2047 << "=?" << charset_dec << '?' << encoding << '?';
			rfc2047.Append (encoded, encoded_len);
			rfc2047 << "?=";

			if (encoding == quoted_printable || encoding == base64)
				free(encoded);
		}
		previousWordNeededEncoding = currentWord->needsEncoding;
		delete currentWord;
	}

	free(*bufp);

	ssize_t finalLength = rfc2047.Length ();
	*bufp = (char *) (malloc (finalLength + 1));
	memcpy (*bufp, rfc2047.String(), finalLength);
	(*bufp)[finalLength] = 0;

	return finalLength;
}
Example #19
0
static int oauth2_authenticate(mailsmtp * session, int type, const char * auth_user,
                               const char * access_token)
{
    int r;
    char command[SMTP_STRING_SIZE];
    char * ptr;
    char * full_auth_string;
    char * full_auth_string_b64;
    int auth_user_len;
    int access_token_len;
    int full_auth_string_len;
    int res;

    full_auth_string = NULL;
    full_auth_string_b64 = NULL;

    /* Build client response string */
    auth_user_len = strlen(auth_user);
    access_token_len = strlen(access_token);
    full_auth_string_len = 5 + auth_user_len + 1 + 12 + access_token_len + 2;
    full_auth_string = malloc(full_auth_string_len + 1);
    if (full_auth_string == NULL) {
        res = MAILSMTP_ERROR_MEMORY;
        goto free;
    }

    ptr = memcpy(full_auth_string, "user="******"\1auth=Bearer ", 13);
    ptr = memcpy(ptr + 13, access_token, access_token_len);
    ptr = memcpy(ptr + access_token_len, "\1\1\0", 3);

    /* Convert to base64 */
    full_auth_string_b64 = encode_base64(full_auth_string, full_auth_string_len);
    if (full_auth_string_b64 == NULL) {
        res = MAILSMTP_ERROR_MEMORY;
        goto free;
    }

    switch (type) {
    case XOAUTH2_TYPE_GMAIL:
    default:
    {
        snprintf(command, SMTP_STRING_SIZE, "AUTH XOAUTH2 ");
        r = mailsmtp_send_command(session, command);
        if (r == -1) {
            res = MAILSMTP_ERROR_STREAM;
            goto free;
        }
        r = mailsmtp_send_command(session, full_auth_string_b64);
        if (r == -1) {
            res = MAILSMTP_ERROR_STREAM;
            goto free;
        }
        snprintf(command, SMTP_STRING_SIZE, "\r\n");
        r = mailsmtp_send_command(session, command);
        if (r == -1) {
            res = MAILSMTP_ERROR_STREAM;
            goto free;
        }
        break;
    }
    case XOAUTH2_TYPE_OUTLOOK_COM:
        snprintf(command, SMTP_STRING_SIZE, "AUTH XOAUTH2\r\n");
        r = mailsmtp_send_command(session, command);
        if (r == -1) {
            res = MAILSMTP_ERROR_STREAM;
            goto free;
        }
        break;
    }

    r = mailsmtp_read_response(session);
    switch (r) {
    case 220:
    case 235:
        res = MAILSMTP_NO_ERROR;
        goto free;

    case 334:
        /* AUTH in progress */

        switch (type) {
        case XOAUTH2_TYPE_GMAIL:
        default:
        {
            /* There's probably an error, send an empty line as acknowledgement. */
            snprintf(command, SMTP_STRING_SIZE, "\r\n");
            r = mailsmtp_send_command(session, command);
            if (r == -1) {
                res = MAILSMTP_ERROR_STREAM;
                goto free;
            }
            break;
        }
        case XOAUTH2_TYPE_OUTLOOK_COM:
        {
            r = mailsmtp_send_command(session, full_auth_string_b64);
            if (r == -1) {
                res = MAILSMTP_ERROR_STREAM;
                goto free;
            }
            snprintf(command, SMTP_STRING_SIZE, "\r\n");
            r = mailsmtp_send_command(session, command);
            if (r == -1) {
                res = MAILSMTP_ERROR_STREAM;
                goto free;
            }
            break;
        }
        }

        r = mailsmtp_read_response(session);
        switch (r) {
        case 535:
            res = MAILSMTP_ERROR_AUTH_LOGIN;
            goto free;

        case 220:
        case 235:
            res = MAILSMTP_NO_ERROR;
            goto free;

        default:
            res = MAILSMTP_ERROR_UNEXPECTED_CODE;
            goto free;
        }
        break;

    default:
        res = MAILSMTP_ERROR_UNEXPECTED_CODE;
        goto free;
    }

free:
    free(full_auth_string);
    free(full_auth_string_b64);
    return res;
}
Example #20
0
int sendmail_main(int argc UNUSED_PARAM, char **argv)
{
	char *opt_connect = opt_connect;
	char *opt_from = NULL;
	char *s;
	llist_t *list = NULL;
	char *host = sane_address(safe_gethostname());
	unsigned nheaders = 0;
	int code;
	enum {
		HDR_OTHER = 0,
		HDR_TOCC,
		HDR_BCC,
	} last_hdr = 0;
	int check_hdr;
	int has_to = 0;

	enum {
	//--- standard options
		OPT_t = 1 << 0,         // read message for recipients, append them to those on cmdline
		OPT_f = 1 << 1,         // sender address
		OPT_o = 1 << 2,         // various options. -oi IMPLIED! others are IGNORED!
		OPT_i = 1 << 3,         // IMPLIED!
	//--- BB specific options
		OPT_w = 1 << 4,         // network timeout
		OPT_H = 1 << 5,         // use external connection helper
		OPT_S = 1 << 6,         // specify connection string
		OPT_a = 1 << 7,         // authentication tokens
		OPT_v = 1 << 8,         // verbosity
	};

	// init global variables
	INIT_G();

	// save initial stdin since body is piped!
	xdup2(STDIN_FILENO, 3);
	G.fp0 = xfdopen_for_read(3);

	// parse options
	// -v is a counter, -H and -S are mutually exclusive, -a is a list
	opt_complementary = "vv:w+:H--S:S--H:a::";
	// N.B. since -H and -S are mutually exclusive they do not interfere in opt_connect
	// -a is for ssmtp (http://downloads.openwrt.org/people/nico/man/man8/ssmtp.8.html) compatibility,
	// it is still under development.
	opts = getopt32(argv, "tf:o:iw:H:S:a::v", &opt_from, NULL,
			&timeout, &opt_connect, &opt_connect, &list, &verbose);
	//argc -= optind;
	argv += optind;

	// process -a[upm]<token> options
	if ((opts & OPT_a) && !list)
		bb_show_usage();
	while (list) {
		char *a = (char *) llist_pop(&list);
		if ('u' == a[0])
			G.user = xstrdup(a+1);
		if ('p' == a[0])
			G.pass = xstrdup(a+1);
		// N.B. we support only AUTH LOGIN so far
		//if ('m' == a[0])
		//	G.method = xstrdup(a+1);
	}
	// N.B. list == NULL here
	//bb_info_msg("OPT[%x] AU[%s], AP[%s], AM[%s], ARGV[%s]", opts, au, ap, am, *argv);

	// connect to server

	// connection helper ordered? ->
	if (opts & OPT_H) {
		const char *args[] = { "sh", "-c", opt_connect, NULL };
		// plug it in
		launch_helper(args);
		// Now:
		// our stdout will go to helper's stdin,
		// helper's stdout will be available on our stdin.

		// Wait for initial server message.
		// If helper (such as openssl) invokes STARTTLS, the initial 220
		// is swallowed by helper (and not repeated after TLS is initiated).
		// We will send NOOP cmd to server and check the response.
		// We should get 220+250 on plain connection, 250 on STARTTLSed session.
		//
		// The problem here is some servers delay initial 220 message,
		// and consider client to be a spammer if it starts sending cmds
		// before 220 reached it. The code below is unsafe in this regard:
		// in non-STARTTLSed case, we potentially send NOOP before 220
		// is sent by server.
		// Ideas? (--delay SECS opt? --assume-starttls-helper opt?)
		code = smtp_check("NOOP", -1);
		if (code == 220)
			// we got 220 - this is not STARTTLSed connection,
			// eat 250 response to our NOOP
			smtp_check(NULL, 250);
		else
		if (code != 250)
			bb_error_msg_and_die("SMTP init failed");
	} else {
		// vanilla connection
		int fd;
		// host[:port] not explicitly specified? -> use $SMTPHOST
		// no $SMTPHOST? -> use localhost
		if (!(opts & OPT_S)) {
			opt_connect = getenv("SMTPHOST");
			if (!opt_connect)
				opt_connect = (char *)"127.0.0.1";
		}
		// do connect
		fd = create_and_connect_stream_or_die(opt_connect, 25);
		// and make ourselves a simple IO filter
		xmove_fd(fd, STDIN_FILENO);
		xdup2(STDIN_FILENO, STDOUT_FILENO);

		// Wait for initial server 220 message
		smtp_check(NULL, 220);
	}

	// we should start with modern EHLO
	if (250 != smtp_checkp("EHLO %s", host, -1))
		smtp_checkp("HELO %s", host, 250);

	// perform authentication
	if (opts & OPT_a) {
		smtp_check("AUTH LOGIN", 334);
		// we must read credentials unless they are given via -a[up] options
		if (!G.user || !G.pass)
			get_cred_or_die(4);
		encode_base64(NULL, G.user, NULL);
		smtp_check("", 334);
		encode_base64(NULL, G.pass, NULL);
		smtp_check("", 235);
	}

	// set sender
	// N.B. we have here a very loosely defined algorythm
	// since sendmail historically offers no means to specify secrets on cmdline.
	// 1) server can require no authentication ->
	//	we must just provide a (possibly fake) reply address.
	// 2) server can require AUTH ->
	//	we must provide valid username and password along with a (possibly fake) reply address.
	//	For the sake of security username and password are to be read either from console or from a secured file.
	//	Since reading from console may defeat usability, the solution is either to read from a predefined
	//	file descriptor (e.g. 4), or again from a secured file.

	// got no sender address? use auth name, then UID username as a last resort
	if (!opt_from) {
		opt_from = xasprintf("%s@%s",
		                     G.user ? G.user : xuid2uname(getuid()),
		                     xgethostbyname(host)->h_name);
	}
	free(host);

	smtp_checkp("MAIL FROM:<%s>", opt_from, 250);

	// process message

	// read recipients from message and add them to those given on cmdline.
	// this means we scan stdin for To:, Cc:, Bcc: lines until an empty line
	// and then use the rest of stdin as message body
	code = 0; // set "analyze headers" mode
	while ((s = xmalloc_fgetline(G.fp0)) != NULL) {
 dump:
		// put message lines doubling leading dots
		if (code) {
			// escape leading dots
			// N.B. this feature is implied even if no -i (-oi) switch given
			// N.B. we need to escape the leading dot regardless of
			// whether it is single or not character on the line
			if ('.' == s[0] /*&& '\0' == s[1] */)
				bb_putchar('.');
			// dump read line
			send_r_n(s);
			free(s);
			continue;
		}

		// analyze headers
		// To: or Cc: headers add recipients
		check_hdr = (0 == strncasecmp("To:", s, 3));
		has_to |= check_hdr;
		if (opts & OPT_t) {
			if (check_hdr || 0 == strncasecmp("Bcc:" + 1, s, 3)) {
				rcptto_list(s+3);
				last_hdr = HDR_TOCC;
				goto addheader;
			}
			// Bcc: header adds blind copy (hidden) recipient
			if (0 == strncasecmp("Bcc:", s, 4)) {
				rcptto_list(s+4);
				free(s);
				last_hdr = HDR_BCC;
				continue; // N.B. Bcc: vanishes from headers!
			}
		}
		check_hdr = (list && isspace(s[0]));
		if (strchr(s, ':') || check_hdr) {
			// other headers go verbatim
			// N.B. RFC2822 2.2.3 "Long Header Fields" allows for headers to occupy several lines.
			// Continuation is denoted by prefixing additional lines with whitespace(s).
			// Thanks (stefan.seyfried at googlemail.com) for pointing this out.
			if (check_hdr && last_hdr != HDR_OTHER) {
				rcptto_list(s+1);
				if (last_hdr == HDR_BCC)
					continue;
					// N.B. Bcc: vanishes from headers!
			} else {
				last_hdr = HDR_OTHER;
			}
 addheader:
			// N.B. we allow MAX_HEADERS generic headers at most to prevent attacks
			if (MAX_HEADERS && ++nheaders >= MAX_HEADERS)
				goto bail;
			llist_add_to_end(&list, s);
		} else {
			// a line without ":" (an empty line too, by definition) doesn't look like a valid header
			// so stop "analyze headers" mode
 reenter:
			// put recipients specified on cmdline
			check_hdr = 1;
			while (*argv) {
				char *t = sane_address(*argv);
				rcptto(t);
				//if (MAX_HEADERS && ++nheaders >= MAX_HEADERS)
				//	goto bail;
				if (!has_to) {
					const char *hdr;

					if (check_hdr && argv[1])
						hdr = "To: %s,";
					else if (check_hdr)
						hdr = "To: %s";
					else if (argv[1])
						hdr = "To: %s," + 3;
					else
						hdr = "To: %s" + 3;
					llist_add_to_end(&list,
							xasprintf(hdr, t));
					check_hdr = 0;
				}
				argv++;
			}
			// enter "put message" mode
			// N.B. DATA fails iff no recipients were accepted (or even provided)
			// in this case just bail out gracefully
			if (354 != smtp_check("DATA", -1))
				goto bail;
			// dump the headers
			while (list) {
				send_r_n((char *) llist_pop(&list));
			}
			// stop analyzing headers
			code++;
			// N.B. !s means: we read nothing, and nothing to be read in the future.
			// just dump empty line and break the loop
			if (!s) {
				send_r_n("");
				break;
			}
			// go dump message body
			// N.B. "s" already contains the first non-header line, so pretend we read it from input
			goto dump;
		}
	}
	// odd case: we didn't stop "analyze headers" mode -> message body is empty. Reenter the loop
	// N.B. after reenter code will be > 0
	if (!code)
		goto reenter;

	// finalize the message
	smtp_check(".", 250);
 bail:
	// ... and say goodbye
	smtp_check("QUIT", 221);
	// cleanup
	if (ENABLE_FEATURE_CLEAN_UP)
		fclose(G.fp0);

	return EXIT_SUCCESS;
}
Example #21
0
am_status_t
BaseService::doRequest(const ServiceInfo& service,
		       const BodyChunk& headerPrefix,
		       const std::string& uriParameters,
		       const Http::CookieList& cookieList,
		       const BodyChunk& headerSuffix,
		       const BodyChunkList& bodyChunkList,
		       Http::Response& response,
		       std::size_t initialBufferLen,
		       const std::string &cert_nick_name,
		       const ServerInfo** serverInfo) const
{
    am_status_t status = AM_SERVICE_NOT_AVAILABLE;
    std::size_t dataLen = 0;
    // Create a temporary buffer for the Content-Line header
    // the extra '2' is for the <CR><LF> at the end.  The
    // sizeof the CONTENT_LENGTH_HDR includes space for the
    // terminating NUL.
    char contentLine[sizeof(CONTENT_LENGTH_HDR) +
		     (sizeof(dataLen) * DIGITS_PER_BYTE) + 2];
    std::size_t contentLineLen;

    for (unsigned int i = 0; i < bodyChunkList.size(); ++i) {
	dataLen += bodyChunkList[i].data.size();
    }

    contentLineLen = snprintf(contentLine, sizeof(contentLine), "%s%d\r\n",
			      CONTENT_LENGTH_HDR, dataLen);
    if (sizeof(contentLine) > contentLineLen) {
	BodyChunk contentLineChunk(contentLine, contentLineLen);
	ServiceInfo::const_iterator iter;

	for (iter = service.begin(); iter != service.end(); ++iter) {
            ServerInfo svrInfo = ServerInfo((const ServerInfo&)(*iter));
	    if (!svrInfo.isHealthy(poll_primary_server)) {
		Log::log(logModule, Log::LOG_WARNING,
			"BaseService::doRequest(): "
			"Server is unavailable: %s.",
			svrInfo.getURL().c_str());
		continue;
	    } else {
		Log::log(logModule, Log::LOG_DEBUG,
			"BaseService::doRequest(): Using server: %s.",
			iter->getURL().c_str());
            }

            Http::HeaderList headerList, proxyHeaderList;
            Http::Cookie hostHeader("Host", svrInfo.getHost());
            headerList.push_back(hostHeader);

            if (useProxy) {
                proxyHeaderList.push_back(hostHeader);
                // Override (temporarily) server credentials if using proxy
                svrInfo.setHost(proxyHost);
                svrInfo.setPort(proxyPort);
                // We don't use SSL for initial proxy connection
		svrInfo.setUseSSL(false);
                Log::log(logModule, Log::LOG_DEBUG,
                         "BaseService::doRequest(): Using proxy: %s:%d",
                         proxyHost.c_str(),proxyPort);
                // Add Proxy-Authorization header if user defined
                if (useProxyAuth) {
                    // allocate enough for a base64-encoded digest
                    int authSize = proxyUser.size() + 
                                   proxyPassword.size() + 1;
                    // 11 extra bytes for prefix and terminator
                    char * digest = (char *)malloc(authSize * 4/3 + 11);
                    strcpy(digest, "Basic ");
                    encode_base64((proxyUser + ":" + proxyPassword).c_str(),
                                   authSize,(digest + 6));
                    Log::log(logModule, Log::LOG_MAX_DEBUG,
                         "BaseService::doRequest(): Using proxy auth as: %s",
                         proxyUser.c_str());
                    hostHeader = Http::Cookie("Proxy-Authorization", digest);
                    proxyHeaderList.push_back(hostHeader);
                    free(digest);
                }
            }

            // retry to connect to server before marking it as down.
            // making the number of attempts configurable may have a negative
            // side effect on performance, if the the value is a high number.
            int retryAttempts = 3;
            int retryCount = 0;
            while(retryCount < retryAttempts) {
                retryCount++;
	        try {
                    Connection conn(svrInfo, certDBPasswd,
                      (cert_nick_name.size()>0)?cert_nick_name:certNickName,
                         alwaysTrustServerCert);
		    const char *operation = "sending to";
                    // in case proxy is defined and target URL is HTTPS, 
                    // establish an SSL tunnel first send 
                    // CONNECT host:port string
                    if (useProxy && iter->useSSL()) {
                        SECStatus   secStatus = SECFailure;
                        // All the other parameters would be empty for a 
                        // proxy CONNECT
                        Http::CookieList emptyCookieList;
                        BodyChunk emptyChunk;
                        BodyChunkList emptyChunkList;

                        // Add a Keep-alive header since we're using HTTP/1.0
                        hostHeader = Http::Cookie("Connection", 
                                                  "Keep-Alive\r\n");
                        proxyHeaderList.push_back(hostHeader);
                        status = sendRequest(conn, 
                                        BodyChunk(std::string("CONNECT ")), 
                                        iter->getHost() + ":" +
					Utils::toString(iter->getPort()), 
                                        std::string(""), proxyHeaderList, 
                                        emptyCookieList, emptyChunk, 
                                        emptyChunk, emptyChunkList);
                        if (status == AM_SUCCESS) {
                            // Retrieve proxie's response if tunnel 
                            // established
                            (void) response.readAndIgnore(logModule, conn);
                            // Secure the tunnel now by upgrading the socket
                            PRFileDesc *sock = conn.secureSocket(
                                                  certDBPasswd, 
                                                  (cert_nick_name.size()>0)?
                                            cert_nick_name:certNickName, 
				            alwaysTrustServerCert, NULL);
                            if (sock != static_cast<PRFileDesc *>(NULL)) {
                                secStatus = SSL_SetURL(sock, 
                                                  iter->getHost().c_str());
                            }
                        }

                        if (status != AM_SUCCESS || SECSuccess != secStatus){
                            Log::log(logModule, Log::LOG_ERROR,
                                "BaseService::doRequest(): could not "
				"establish a secure proxy tunnel");
                            // Can't continue and mark server as down as 
                            // it was a  proxy failure
                            return AM_FAILURE;
                        }
                    }

		    if(Log::isLevelEnabled(logModule, Log::LOG_MAX_DEBUG)) {
		        std::string commString;
		        for(std::size_t i = 0; i<bodyChunkList.size(); ++i) {
			    if(!bodyChunkList[i].secure) {
			        commString.append(bodyChunkList[i].data);
			    } else {
			        commString.append("<secure data>");
			    }
		        }
		        for(std::size_t commPos = commString.find("%");
		    	    commPos != std::string::npos &&
			    commPos < commString.size();
			    commPos = commString.find("%", commPos)) {
			    commString.replace(commPos, 1, "%%");
			    commPos += 2;
		        }
		        Log::log(logModule, Log::LOG_MAX_DEBUG,
			     commString.c_str());
		    }

                    std::string requestString = iter->getURI();
                    /*
                     * In case the following request would go to a proxy
                     * we need to use full URL and special headers.
                     * If the resource is HTTPS, we're not posting our
                     * request to the proxy, but to the server 
                     * through proxy tunnel
                     */

                    if (useProxy && !(iter->useSSL())) {
                        requestString = iter->getURL();
                        headerList = proxyHeaderList;
                    }
		    status = sendRequest(conn, headerPrefix, requestString,
				     uriParameters, headerList, cookieList,
				     contentLineChunk, headerSuffix,
				     bodyChunkList);
		    if (AM_SUCCESS == status) {
		        operation = "receiving from";
		        status = response.readAndParse(logModule, conn,
						   initialBufferLen);
		        if (AM_SUCCESS == status) {
			    Log::log(logModule, Log::LOG_MAX_DEBUG, "%.*s",
				 response.getBodyLen(), response.getBodyPtr());
		        }
		    }

		    if (AM_NSPR_ERROR == status) {
		        PRErrorCode nspr_code = PR_GetError();
		        Log::log(logModule, Log::LOG_ALWAYS,
			     "BaseService::doRequest() NSPR failure while "
			     "%s %s, error = %s", operation,
			     (*iter).toString().c_str(), 
			     PR_ErrorToName(nspr_code));
		    }
		
		    if (AM_SUCCESS == status) {
		        if(serverInfo != NULL) *serverInfo = &(*iter);
		            break;
		    } else {
                        if(retryCount < retryAttempts) {
                            continue;
                        } else {
                           Log::log(logModule, Log::LOG_DEBUG,
                               "BaseService::doRequest() Invoking markSeverDown");
                           svrInfo.markServerDown(poll_primary_server);
                        }
		    }
	        } catch (const NSPRException& exc) {
		    Log::log(logModule, Log::LOG_DEBUG,
			 "BaseService::doRequest() caught %s: %s called by %s "
			 "returned %s", exc.what(), exc.getNsprMethod(),
			 exc.getThrowingMethod(), 
			 PR_ErrorToName(exc.getErrorCode()));

                   if(retryCount < retryAttempts) {
		       status = AM_NSPR_ERROR;
                       continue;
                    } else {
                       Log::log(logModule, Log::LOG_DEBUG,
                           "BaseService::doRequest() Invoking markSeverDown");
                       svrInfo.markServerDown(poll_primary_server);
		       status = AM_NSPR_ERROR;
                    }
	        }
            } //end of while

            if (AM_SUCCESS == status) {
               if(serverInfo != NULL) *serverInfo = &(*iter);
                    break;
            }
            if (status = AM_NSPR_ERROR) {
               continue;
            }

	} // end of for
    } else {
	status = AM_BUFFER_TOO_SMALL;
    }

    return status;
}
Example #22
0
size_t
FileUploader::sendFilePart(unsigned int offset, unsigned int size)
{
	if(fileOpened)
	{
		char *pFilePart = (char*)malloc(size);
		Element* pElement = new Element();
		pElement->name = L"part";
	
		Attribute fileNameAttribute;
		Attribute filePartStartAttribute;
		Attribute filePartEndAttribute;
		Attribute filePartEncoding;

		fileNameAttribute.name = L"name";
		fileNameAttribute.value = fileName.c_str();
		filePartStartAttribute.name = L"part-start";
		filePartStartAttribute.value = boost::lexical_cast<wstring>(offset);
		filePartEncoding.name = L"encoding";
		filePartEncoding.value = L"base64";

		pElement->attributes.push_back(fileNameAttribute);
		pElement->attributes.push_back(filePartStartAttribute);
		pElement->attributes.push_back(filePartEncoding);
		

		/* Seek to offset and read size bytes */
		//printf("size: %i\n", size);
		//printf("offset: %i\n", offset);
		int err = fseek(pFileStream, offset, 0);
		//printf("fseel: %i\n", err);
		size_t bytesRead = fread(pFilePart , sizeof(char), size, pFileStream);
		//printf("bytesRead: %i\n", bytesRead);
		//printf("fread error: %i\n", ferror(pFileStream));
		filePartEndAttribute.name = L"part-end";
		int end = offset + bytesRead;
		filePartEndAttribute.value = boost::lexical_cast<wstring>(end);
		pElement->attributes.push_back(filePartEndAttribute);

		/* Encode the data just read in base64 and append to XML element */
		size_t encodedLength = 0;
		char* pEncodedFilePart = encode_base64(pFilePart, bytesRead, &encodedLength);
		pElement->data = pEncodedFilePart;
		pElement->dataLength = encodedLength;

		/* Send the XML element to the server */
		//printf("feof: %i\n", feof(pFileStream));
		if(bytesRead > 0)
		{
			server->sendXMLElement(pElement);
		}

		/* Cleanup */
		free(pEncodedFilePart);
		free(pFilePart);
		delete pElement;
		if(feof(pFileStream) > 0)
		{
			return 0;
		} else {
			return bytesRead;
		}
	}
	return 0;
}
Example #23
0
int mailimap_oauth2_authenticate_send(mailimap * session,
                                      const char * auth_user,
                                      const char * access_token)
{
  int r;
  char * ptr;
  char * full_auth_string;
  char * full_auth_string_b64;
  int auth_user_len;
  int access_token_len;
  int full_auth_string_len;
  int res;
  
  full_auth_string = NULL;
  full_auth_string_b64 = NULL;
  
  /* Build client response string */
  auth_user_len = strlen(auth_user);
  access_token_len = strlen(access_token);
  full_auth_string_len = 5 + auth_user_len + 1 + 12 + access_token_len + 2;
  full_auth_string = malloc(full_auth_string_len + 1);
  if (full_auth_string == NULL) {
    res = MAILIMAP_ERROR_MEMORY;
    goto free;
  }
  
  ptr = memcpy(full_auth_string, "user="******"\1auth=Bearer ", 13);
  ptr = memcpy(ptr + 13, access_token, access_token_len);
  ptr = memcpy(ptr + access_token_len, "\1\1\0", 3);
  
  /* Convert to base64 */
  full_auth_string_b64 = encode_base64(full_auth_string, full_auth_string_len);
  if (full_auth_string_b64 == NULL) {
    res = MAILIMAP_ERROR_MEMORY;
    goto free;
  }
  
  r = mailimap_token_send(session->imap_stream, "AUTHENTICATE");
  if (r != MAILIMAP_NO_ERROR) {
    res = r;
    goto free;
  }
  r = mailimap_space_send(session->imap_stream);
  if (r != MAILIMAP_NO_ERROR) {
    res = r;
    goto free;
  }
  r = mailimap_token_send(session->imap_stream, "XOAUTH2");
  if (r != MAILIMAP_NO_ERROR) {
    res = r;
    goto free;
  }
  r = mailimap_space_send(session->imap_stream);
  if (r != MAILIMAP_NO_ERROR) {
    res = r;
    goto free;
  }
  r = mailimap_astring_send(session->imap_stream, full_auth_string_b64);
  if (r != MAILIMAP_NO_ERROR) {
    res = r;
    goto free;
  }
  
  res = MAILIMAP_NO_ERROR;
  
 free:
  free(full_auth_string);
  free(full_auth_string_b64);
  return res;
}
Example #24
0
// Handles compiling the Apple-Challenge, HWID, and Server IP Address
// Into the response the airplay client is expecting.
int buildAppleResponse(struct connection *pConn, unsigned char *pIpBin, unsigned int pIpBinLen, char *pHWID)
{
  // Find Apple-Challenge
  char *tResponse = NULL;

  int tFoundSize = 0;
  char* tFound = getFromHeader(pConn->recv.data, "Apple-Challenge", &tFoundSize);
  if(tFound != NULL)
  {
    char tTrim[tFoundSize + 2];
    getTrimmed(tFound, tFoundSize, TRUE, TRUE, tTrim);
    slog(LOG_DEBUG_VV, "HeaderChallenge:  [%s] len: %d  sizeFound: %d\n", tTrim, strlen(tTrim), tFoundSize);
    int tChallengeDecodeSize = 16;
    char *tChallenge = decode_base64((unsigned char *)tTrim, tFoundSize, &tChallengeDecodeSize);
    slog(LOG_DEBUG_VV, "Challenge Decode size: %d  expected 16\n", tChallengeDecodeSize);

    int tCurSize = 0;
    unsigned char tChalResp[38];

    memcpy(tChalResp, tChallenge, tChallengeDecodeSize);
    tCurSize += tChallengeDecodeSize;
    
    memcpy(tChalResp+tCurSize, pIpBin, pIpBinLen);
    tCurSize += pIpBinLen;

    memcpy(tChalResp+tCurSize, pHWID, HWID_SIZE);
    tCurSize += HWID_SIZE;

    int tPad = 32 - tCurSize;
    if (tPad > 0)
    {
      memset(tChalResp+tCurSize, 0, tPad);
      tCurSize += tPad;
    }

    char *tTmp = encode_base64((unsigned char *)tChalResp, tCurSize);
    slog(LOG_DEBUG_VV, "Full sig: %s\n", tTmp);
    free(tTmp);

    // RSA Encrypt
    RSA *rsa = loadKey();  // Free RSA
    int tSize = RSA_size(rsa);
    unsigned char tTo[tSize];
    RSA_private_encrypt(tCurSize, (unsigned char *)tChalResp, tTo, rsa, RSA_PKCS1_PADDING);
    
    // Wrap RSA Encrypted binary in Base64 encoding
    tResponse = encode_base64(tTo, tSize);
    int tLen = strlen(tResponse);
    while(tLen > 1 && tResponse[tLen-1] == '=')
    {
      tResponse[tLen-1] = '\0';
    }
    free(tChallenge);
    RSA_free(rsa);
  }

  if(tResponse != NULL)
  {
    // Append to current response
    addToShairBuffer(&(pConn->resp), "Apple-Response: ");
    addToShairBuffer(&(pConn->resp), tResponse);
    addToShairBuffer(&(pConn->resp), "\r\n");
    free(tResponse);
    return TRUE;
  }
  return FALSE;
}
Example #25
0
/* Read ossec config */
int config_read(HWND hwnd)
{
    char *tmp_str;
    char *delim = " - ";

    /* Clear config */
    config_clear();

    /* Get OSSEC status */
    if (CheckServiceRunning()) {
        config_inst.status = ST_RUNNING;
    } else {
        config_inst.status = ST_STOPPED;
    }

    /* Get version/install date */
    config_inst.version = cat_file(VERSION_FILE, NULL);
    if (config_inst.version) {
        config_inst.install_date = strstr(config_inst.version, delim);
        if (config_inst.install_date) {
            *config_inst.install_date = '\0';
            config_inst.install_date += strlen(delim);
        }
    }

    /* Get number of messages sent */
    tmp_str = cat_file(SENDER_FILE, NULL);
    if (tmp_str) {
        unsigned long int tmp_val = 0;
        char *to_free = tmp_str;

        tmp_val = atol(tmp_str);
        if (tmp_val) {
            config_inst.msg_sent = tmp_val * 9999;

            tmp_str = strchr(tmp_str, ':');
            if (tmp_str) {
                tmp_str++;
                tmp_val = atol(tmp_str);
                config_inst.msg_sent += tmp_val;
            }
        }

        free(to_free);
    }

    /* Get agent ID, name and IP */
    tmp_str = cat_file(AUTH_FILE, NULL);
    if (tmp_str) {
        /* Get base 64 */
        config_inst.key = encode_base64(strlen(tmp_str), tmp_str);
        if (config_inst.key == NULL) {
            config_inst.key = FL_NOKEY;
        }

        /* Get ID */
        config_inst.agentid = tmp_str;

        tmp_str = strchr(tmp_str, ' ');
        if (tmp_str) {
            *tmp_str = '\0';
            tmp_str++;

            /* Get name */
            config_inst.agentname = tmp_str;
            tmp_str = strchr(tmp_str, ' ');
            if (tmp_str) {
                *tmp_str = '\0';
                tmp_str++;

                /* Get IP */
                config_inst.agentip = tmp_str;

                tmp_str = strchr(tmp_str, ' ');
                if (tmp_str) {
                    *tmp_str = '\0';
                }
            }
        }
    }

    if (config_inst.agentip == NULL) {
        config_inst.agentid = strdup(ST_NOTSET);
        config_inst.agentname = strdup("Auth key not imported.");
        config_inst.agentip = ST_NOTSET;

        config_inst.status = ST_MISSING_IMPORT;
    }

    /* Get server IP */
    if (!get_ossec_server()) {
        if (strcmp(config_inst.status, ST_MISSING_IMPORT) == 0) {
            config_inst.status = ST_MISSING_ALL;
        } else {
            config_inst.status = ST_MISSING_SERVER;
        }
    }

    return (0);
}
Example #26
0
int main (int argc, char *argv [])
{
    char
        *feedback,
        read_buffer    [LINE_MAX+1];
    byte
        decoded_buffer [LINE_MAX+1],
        encoded_buffer [LINE_MAX+1];
    size_t
        return_size;
    FILE
        *file;

    memset (read_buffer,    0, LINE_MAX+1);
    memset (encoded_buffer, 0, LINE_MAX+1);
    memset (decoded_buffer, 0, LINE_MAX+1);

    if (argc > 1)
      {
        file = file_open (argv[1], 'r');
        if (file != NULL)
          {
            while (file_read (file, read_buffer) == TRUE)
              {
                printf ("Read    : %s\n", read_buffer);

                /*  Encode the buffer                                        */
                return_size = encode_base64 ((byte *) read_buffer, 
                                             encoded_buffer,
                                             strlen (read_buffer));
                printf ("Encoded : %s\n", encoded_buffer);

                /*  Decode the buffer                                        */
                decode_base64 (encoded_buffer, decoded_buffer, return_size);
                printf ("Decoded : %s\n\n", decoded_buffer);

                /*  Test if error                                            */
                if (strcmp (read_buffer, (char *) decoded_buffer) != 0)
                  {
                    printf ("Error : decoded is not same as read\n");
                    break;
                  }
                /*  Reset the buffers                                        */
                memset (decoded_buffer, 0, LINE_MAX+1);
                memset (encoded_buffer, 0, LINE_MAX+1);
              }
            file_close (file);
          }
      }
    printf ("Test encode quoted string\n");
    printf ("encoding this string: %s\n", TEST_FRENCH);
    feedback = encode_quoted_string (NULL, 0, TEST_FRENCH, "ISO-8859-1");
    if (feedback)
      {
        printf ("Result: %s\n", feedback);
        mem_free (feedback);
      }
    feedback = encode_mimeb_string (NULL, 0, TEST_FRENCH, "iso-2220-jp");
    if (feedback)
      {
        printf ("Result: %s\n", feedback);
        mem_free (feedback);
      }
    return (EXIT_SUCCESS);
}
Example #27
0
std::ostream& operator<<(std::ostream& output, const base64& argument)
{
    output << encode_base64(argument.value_);
    return output;
}
Example #28
0
/* extract base64 for a specific agent */
int k_extract(char *cmdextract)
{
    FILE *fp;
    char *user_input;
    char *b64_enc;
    char line_read[FILE_SIZE +1];
    char n_id[USER_SIZE +1];


    if(cmdextract)
    {
        user_input = cmdextract;

        if(!IDExist(user_input))
        {
            printf(NO_ID, user_input);
            exit(1);
        }
    }

    else
    {
        if(!print_agents(0, 0, 0))
        {
            printf(NO_AGENT);
            printf(PRESS_ENTER);
            read_from_user();
            return(0);
        }

        do
        {
            printf(EXTRACT_KEY);
            fflush(stdout);
            user_input = read_from_user();

            /* quit */
            if(strcmp(user_input, QUIT) == 0)
                return(0);

            if(!IDExist(user_input))
                printf(NO_ID, user_input);

        } while(!IDExist(user_input));
    }


    /* Trying to open the auth file */
    fp = fopen(AUTH_FILE, "r");
    if(!fp)
    {
        ErrorExit(FOPEN_ERROR, ARGV0, AUTH_FILE);
    }

    fsetpos(fp, &fp_pos);

    memset(n_id, '\0', USER_SIZE +1);
    strncpy(n_id, user_input, USER_SIZE -1);


    if(fgets(line_read, FILE_SIZE, fp) == NULL)
    {
        printf(ERROR_KEYS);
        fclose(fp);
        exit(1);
    }
    chomp(line_read);


    b64_enc = encode_base64(strlen(line_read),line_read);
    if(b64_enc == NULL)
    {
        printf(EXTRACT_ERROR);
        fclose(fp);
        exit(1);
    }

    printf(EXTRACT_MSG, n_id, b64_enc);
    if(!cmdextract)
    {
        printf("\n" PRESS_ENTER);
        read_from_user();
    }

    free(b64_enc);
    fclose(fp);

    return(0);
}
Example #29
0
_EXPORT ssize_t encode_base64__local_abi(char *out, char *in, off_t length) {
	return encode_base64(out,in,length,0 /* headerMode */);
}
Example #30
0
int makemime_main(int argc UNUSED_PARAM, char **argv)
{
	llist_t *opt_headers = NULL, *l;
	const char *opt_output;
#define boundary opt_output

	enum {
		OPT_c = 1 << 0,         // Content-Type:
		OPT_e = 1 << 1,         // Content-Transfer-Encoding. Ignored. Assumed base64
		OPT_o = 1 << 2,         // output to
		OPT_C = 1 << 3,         // charset
		OPT_N = 1 << 4,         // COMPAT
		OPT_a = 1 << 5,         // additional headers
		OPT_m = 1 << 6,         // COMPAT
		OPT_j = 1 << 7,         // COMPAT
	};

	INIT_G();

	// parse options
	opt_complementary = "a::";
	opts = getopt32(argv,
		"c:e:o:C:N:a:m:j:",
		&G.content_type, NULL, &opt_output, &G.opt_charset, NULL, &opt_headers, NULL, NULL
	);
	//argc -= optind;
	argv += optind;

	// respect -o output
	if (opts & OPT_o)
		freopen(opt_output, "w", stdout);

	// no files given on command line? -> use stdin
	if (!*argv)
		*--argv = (char *)"-";

	// put additional headers
	for (l = opt_headers; l; l = l->link)
		puts(l->data);

	// make a random string -- it will delimit message parts
	srand(monotonic_us());
	boundary = xasprintf("%d-%d-%d", rand(), rand(), rand());

	// put multipart header
	printf(
		"Mime-Version: 1.0\n"
		"Content-Type: multipart/mixed; boundary=\"%s\"\n"
		, boundary
	);

	// put attachments
	while (*argv) {
		printf(
			"\n--%s\n"
			"Content-Type: %s; charset=%s\n"
			"Content-Disposition: inline; filename=\"%s\"\n"
			"Content-Transfer-Encoding: base64\n"
			, boundary
			, G.content_type
			, G.opt_charset
			, bb_get_last_path_component_strip(*argv)
		);
		encode_base64(*argv++, (const char *)stdin, "");
	}

	// put multipart footer
	printf("\n--%s--\n" "\n", boundary);

	return EXIT_SUCCESS;
#undef boundary
}