void CHttpPush::DoHttpPush() { std::string httpUrl = ""; std::string httpData = ""; std::string httpHeaders = ""; int httpMethodInt = 0; int httpAuthInt = 0; std::string httpAuthBasicLogin = ""; std::string httpAuthBasicPassword = ""; m_sql.GetPreferencesVar("HttpMethod", httpMethodInt); m_sql.GetPreferencesVar("HttpAuth", httpAuthInt); m_sql.GetPreferencesVar("HttpAuthBasicLogin", httpAuthBasicLogin); m_sql.GetPreferencesVar("HttpAuthBasicPassword", httpAuthBasicPassword); int httpDebugActiveInt = 0; bool httpDebugActive = false; m_sql.GetPreferencesVar("HttpDebug", httpDebugActiveInt); if (httpDebugActiveInt == 1) { httpDebugActive = true; } std::vector<std::vector<std::string> > result; result = m_sql.safe_query( "SELECT A.DeviceID, A.DelimitedValue, B.ID, B.Type, B.SubType, B.nValue, B.sValue, A.TargetType, A.TargetVariable, A.TargetDeviceID, A.TargetProperty, A.IncludeUnit, B.SwitchType, strftime('%%s', B.LastUpdate), B.Name FROM HttpLink as A, DeviceStatus as B " "WHERE (A.DeviceID == '%" PRIu64 "' AND A.Enabled = '1' AND A.DeviceID==B.ID)", m_DeviceRowIdx); if (!result.empty()) { std::string sendValue; std::vector<std::vector<std::string> >::const_iterator itt; for (itt = result.begin(); itt != result.end(); ++itt) { m_sql.GetPreferencesVar("HttpUrl", httpUrl); m_sql.GetPreferencesVar("HttpData", httpData); m_sql.GetPreferencesVar("HttpHeaders", httpHeaders); if (httpUrl == "") return; std::vector<std::string> sd = *itt; //unsigned int deviceId = atoi(sd[0].c_str()); std::string sdeviceId = sd[0].c_str(); std::string ldelpos = sd[1].c_str(); int delpos = atoi(sd[1].c_str()); int dType = atoi(sd[3].c_str()); int dSubType = atoi(sd[4].c_str()); int nValue = atoi(sd[5].c_str()); std::string sValue = sd[6].c_str(); //int targetType = atoi(sd[7].c_str()); std::string targetVariable = sd[8].c_str(); //int targetDeviceID = atoi(sd[9].c_str()); //std::string targetProperty = sd[10].c_str(); int includeUnit = atoi(sd[11].c_str()); int metertype = atoi(sd[12].c_str()); int lastUpdate = atoi(sd[13].c_str()); std::string ltargetVariable = sd[8].c_str(); std::string ltargetDeviceId = sd[9].c_str(); std::string lname = sd[14].c_str(); sendValue = sValue; unsigned long tzoffset = get_tzoffset(); #ifdef WIN32 unsigned __int64 localTime = lastUpdate; unsigned __int64 localTimeUtc = lastUpdate - tzoffset; #else unsigned long long int localTime = lastUpdate; unsigned long long int localTimeUtc = lastUpdate - tzoffset; #endif char szLocalTime[21]; sprintf(szLocalTime, "%llu", localTime); char szLocalTimeUtc[21]; sprintf(szLocalTimeUtc, "%llu", localTimeUtc); char szLocalTimeMs[21]; sprintf(szLocalTimeMs, "%llu", localTime * 1000); char szLocalTimeUtcMs[21]; sprintf(szLocalTimeUtcMs, "%llu", localTimeUtc * 1000); std::string llastUpdate = get_lastUpdate(localTimeUtc); // Replace keywords /* %v : Value %t0 : Timestamp (epoc time localtime) %t1 : Timestamp (epoc ms localtime) %t2 : Timestamp (epoc time UTC) %t3 : Timestamp (epoc ms UTC) %t4 : Timestamp : "2015-01-29T21:50:44Z" %D : Target Device id %V : Target Variable %u : Unit %n : Device name %T0 : Type %T1 : SubType %h : hostname %idx : 'Original device' id (idx) */ std::string lunit = getUnit(delpos, metertype); std::string lType = RFX_Type_Desc(dType, 1); std::string lSubType = RFX_Type_SubType_Desc(dType, dSubType); char hostname[256]; gethostname(hostname, sizeof(hostname)); std::vector<std::string> strarray; if (sendValue.find(";") != std::string::npos) { StringSplit(sendValue, ";", strarray); if (int(strarray.size()) >= delpos && delpos > 0) { std::string rawsendValue = strarray[delpos - 1].c_str(); sendValue = ProcessSendValue(rawsendValue, delpos, nValue, false, dType, dSubType, metertype); } } else { sendValue = ProcessSendValue(sendValue, delpos, nValue, false, dType, dSubType, metertype); } ltargetDeviceId += "_"; ltargetDeviceId += ldelpos; replaceAll(httpUrl, "%v", sendValue); replaceAll(httpUrl, "%u", includeUnit ? lunit : ""); replaceAll(httpUrl, "%D", ltargetDeviceId); replaceAll(httpUrl, "%V", ltargetVariable); replaceAll(httpUrl, "%t0", std::string(szLocalTime)); replaceAll(httpUrl, "%t1", std::string(szLocalTimeMs)); replaceAll(httpUrl, "%t2", std::string(szLocalTimeUtc)); replaceAll(httpUrl, "%t3", std::string(szLocalTimeUtcMs)); replaceAll(httpUrl, "%t4", llastUpdate); replaceAll(httpUrl, "%n", lname); replaceAll(httpUrl, "%T0", lType); replaceAll(httpUrl, "%T1", lSubType); replaceAll(httpUrl, "%h", std::string(hostname)); replaceAll(httpUrl, "%idx", sdeviceId); replaceAll(httpData, "%v", sendValue); replaceAll(httpData, "%u", includeUnit ? lunit : ""); replaceAll(httpData, "%D", ltargetDeviceId); replaceAll(httpData, "%V", ltargetVariable); replaceAll(httpData, "%t0", std::string(szLocalTime)); replaceAll(httpData, "%t1", std::string(szLocalTimeMs)); replaceAll(httpData, "%t2", std::string(szLocalTimeUtc)); replaceAll(httpData, "%t3", std::string(szLocalTimeUtcMs)); replaceAll(httpData, "%t4", llastUpdate); replaceAll(httpData, "%n", lname); replaceAll(httpData, "%T0", lType); replaceAll(httpData, "%T1", lSubType); replaceAll(httpData, "%h", std::string(hostname)); replaceAll(httpData, "%idx", sdeviceId); if (sendValue != "") { std::string sResult; std::vector<std::string> ExtraHeaders; if (httpAuthInt == 1) { // BASIC authentication std::stringstream sstr; sstr << httpAuthBasicLogin << ":" << httpAuthBasicPassword; std::string m_AccessToken = base64_encode((const unsigned char *)(sstr.str().c_str()), strlen(sstr.str().c_str())); ExtraHeaders.push_back("Authorization:Basic " + m_AccessToken); } sendValue = CURLEncode::URLEncode(sendValue); // data if (httpDebugActive) { _log.Log(LOG_NORM, "HttpLink: sending global variable %s with value: %s", targetVariable.c_str(), sendValue.c_str()); } if (httpMethodInt == 0) { // GET if (!HTTPClient::GET(httpUrl, ExtraHeaders, sResult, true)) { _log.Log(LOG_ERROR, "HttpLink: Error sending data to http with GET!"); } } else if (httpMethodInt == 1) { // POST if (httpHeaders.size() > 0) { // Add additional headers std::vector<std::string> ExtraHeaders2; StringSplit(httpHeaders, "\r\n", ExtraHeaders2); for (size_t i = 0; i < ExtraHeaders2.size(); i++) { ExtraHeaders.push_back(ExtraHeaders2[i]); } } if (!HTTPClient::POST(httpUrl, httpData, ExtraHeaders, sResult, true, true)) { _log.Log(LOG_ERROR, "HttpLink: Error sending data to http with POST!"); } } else if (httpMethodInt == 2) { // PUT if (!HTTPClient::PUT(httpUrl, httpData, ExtraHeaders, sResult, true)) { _log.Log(LOG_ERROR, "HttpLink: Error sending data to http with PUT!"); } } // debug if (httpDebugActive) { _log.Log(LOG_NORM, "HttpLink: response %s", sResult.c_str()); } } } } }
std::string PWHash::computePassword(std::string password, std::string site){ std::string tmpString = sha256(password + site); const unsigned char * constStr = reinterpret_cast<const unsigned char *> (tmpString.c_str()); return base64_encode(constStr, tmpString.length()); }
int main (void) { const char *in = "abcdefghijklmnop"; const char *b64in = "YWJjZGVmZw=="; char out[255]; size_t len; bool ok; char *p; memset (out, 0x42, sizeof (out)); base64_encode (in, 0, out, 0); ASSERT (out[0] == '\x42'); memset (out, 0x42, sizeof (out)); base64_encode (in, 1, out, 1); ASSERT (memcmp (out, "YQ==", 1) == 0); memset (out, 0x42, sizeof (out)); base64_encode (in, 1, out, 2); ASSERT (memcmp (out, "YQ==", 2) == 0); memset (out, 0x42, sizeof (out)); base64_encode (in, 1, out, 3); ASSERT (memcmp (out, "YQ==", 3) == 0); memset (out, 0x42, sizeof (out)); base64_encode (in, 1, out, 4); ASSERT (memcmp (out, "YQ==", 4) == 0); memset (out, 0x42, sizeof (out)); base64_encode (in, 1, out, 8); ASSERT (memcmp (out, "YQ==", 4) == 0); memset (out, 0x42, sizeof (out)); base64_encode (in, 2, out, 4); ASSERT (memcmp (out, "YWI=", 4) == 0); memset (out, 0x42, sizeof (out)); base64_encode (in, 3, out, 4); ASSERT (memcmp (out, "YWJj", 4) == 0); memset (out, 0x42, sizeof (out)); base64_encode (in, 4, out, 5); ASSERT (memcmp (out, "YWJjZA==", 5) == 0); memset (out, 0x42, sizeof (out)); base64_encode (in, 4, out, 100); ASSERT (memcmp (out, "YWJjZA==", 6) == 0); /* Decode. */ memset (out, 0x42, sizeof (out)); len = 0; ok = base64_decode (b64in, 4, out, &len); ASSERT (ok); ASSERT (len == 0); memset (out, 0x42, sizeof (out)); len = 1; ok = base64_decode (b64in, 4, out, &len); ASSERT (ok); ASSERT (len == 1); ASSERT (memcmp (out, "abcdefg", 1) == 0); memset (out, 0x42, sizeof (out)); len = 2; ok = base64_decode (b64in, 4, out, &len); ASSERT (ok); ASSERT (len == 2); ASSERT (memcmp (out, "abcdefg", 2) == 0); memset (out, 0x42, sizeof (out)); len = 3; ok = base64_decode (b64in, 4, out, &len); ASSERT (ok); ASSERT (len == 3); ASSERT (memcmp (out, "abcdefg", 3) == 0); memset (out, 0x42, sizeof (out)); len = 4; ok = base64_decode (b64in, 4, out, &len); ASSERT (ok); ASSERT (len == 3); ASSERT (memcmp (out, "abcdefg", 3) == 0); memset (out, 0x42, sizeof (out)); len = 100; ok = base64_decode (b64in, strlen (b64in), out, &len); ASSERT (ok); ASSERT (len == 7); ASSERT (memcmp (out, "abcdefg", 7) == 0); /* Allocating encode */ len = base64_encode_alloc (in, strlen (in), &p); ASSERT (len == 24); ASSERT (strcmp (p, "YWJjZGVmZ2hpamtsbW5vcA==") == 0); free (p); len = base64_encode_alloc (in, SIZE_MAX - 5, &p); ASSERT (len == 0); /* Decode context function */ { struct base64_decode_context ctx; base64_decode_ctx_init (&ctx); len = sizeof (out); ok = base64_decode_ctx (&ctx, b64in, strlen (b64in), out, &len); ASSERT (ok); ASSERT (len == 7); ASSERT (memcmp (out, "abcdefg", len) == 0); } /* Allocating decode context function */ ok = base64_decode_alloc_ctx (NULL, b64in, strlen (b64in), &p, &len); ASSERT (ok); ASSERT (len == 7); ASSERT (memcmp (out, "abcdefg", len) == 0); free (p); { struct base64_decode_context ctx; const char *newlineb64 = "YWJjZG\nVmZ2hp\namtsbW5vcA=="; base64_decode_ctx_init (&ctx); ok = base64_decode_alloc_ctx (&ctx, newlineb64, strlen (newlineb64), &p, &len); ASSERT (ok); ASSERT (len == strlen (in)); ASSERT (memcmp (p, in, len) == 0); free (p); } { struct base64_decode_context ctx; base64_decode_ctx_init (&ctx); ok = base64_decode_alloc_ctx (&ctx, "YW\nJjZGVmZ2hp", 13, &p, &len); ASSERT (ok); ASSERT (len == 9); ASSERT (memcmp (p, "abcdefghi", len) == 0); free (p); base64_decode_ctx_init (&ctx); ok = base64_decode_alloc_ctx (&ctx, "YW\n", 3, &p, &len); ASSERT (ok); ASSERT (len == 0); free (p); ok = base64_decode_alloc_ctx (&ctx, "JjZGVmZ2", 8, &p, &len); ASSERT (ok); ASSERT (len == 6); ASSERT (memcmp (p, "abcdef", len) == 0); free (p); ok = base64_decode_alloc_ctx (&ctx, "hp", 2, &p, &len); ASSERT (ok); ASSERT (len == 3); ASSERT (memcmp (p, "ghi", len) == 0); free (p); ok = base64_decode_alloc_ctx (&ctx, "", 0, &p, &len); ASSERT (ok); free (p); } { struct base64_decode_context ctx; const char *newlineb64 = "\n\n\n\n\n"; base64_decode_ctx_init (&ctx); ok = base64_decode_alloc_ctx (&ctx, newlineb64, strlen (newlineb64), &p, &len); ASSERT (ok); ASSERT (len == 0); free (p); } ok = base64_decode_alloc_ctx (NULL, " ! ", 3, &p, &len); ASSERT (!ok); ok = base64_decode_alloc_ctx (NULL, "abc\ndef", 7, &p, &len); ASSERT (!ok); ok = base64_decode_alloc_ctx (NULL, "aa", 2, &p, &len); ASSERT (!ok); ok = base64_decode_alloc_ctx (NULL, "aa=", 3, &p, &len); ASSERT (!ok); ok = base64_decode_alloc_ctx (NULL, "aax", 3, &p, &len); ASSERT (!ok); ok = base64_decode_alloc_ctx (NULL, "aa=X", 4, &p, &len); ASSERT (!ok); ok = base64_decode_alloc_ctx (NULL, "aa=X", 4, &p, &len); ASSERT (!ok); ok = base64_decode_alloc_ctx (NULL, "aax=X", 5, &p, &len); ASSERT (!ok); return 0; }
} } dhFreeString(pszTag); dhFreeString(pszSerial); } NEXT(wmiMediaItem); SAFE_RELEASE(colMedia); SAFE_RELEASE(colCPU); SAFE_RELEASE(wmiSvc); std::string encoded = base64_encode(reinterpret_cast<const unsigned char*>(uniqueIdentifier.c_str()), uniqueIdentifier.length()); dhUninitialize(TRUE); return (encoded.substr(0, length)); } HRESULT dhShowException(PDH_EXCEPTION pException) { WCHAR szMessage[512]; dhFormatExceptionW(pException, szMessage, ARRAYSIZE(szMessage), FALSE); #ifdef ERROR_DIALOGS MessageBoxW(g_ExceptionOptions.hwnd, szMessage, g_ExceptionOptions.szAppName,
int authEmail(const int socketFd, const unsigned char *mailAddr, const unsigned char *mailPasswd) { int outSize = 0, stringLen; char readData[SMTP_MTU] = {0}; char writeData[SMTP_MTU] = {0}; char userName[MAX_EMAIL_LEN] = {0}; char userPasswd[MAX_EMAIL_LEN] = {0}; memset(&readData, 0, SMTP_MTU); safeRead(socketFd, readData, SMTP_MTU); SMTP_Print6("[%s][%d]recv: %s\r\n", __FILE__, __LINE__, readData); /* Send: EHLO */ safeWrite(socketFd, "EHLO Here\r\n", strlen("EHLO Here\r\n")); /* Recv: EHLO */ memset(&readData, 0, SMTP_MTU); safeRead(socketFd, readData, SMTP_MTU); SMTP_Print6("[%s][%d]recv: %s\r\n", __FILE__, __LINE__, readData); recvStatus(readData); /* Send: AUTH LOGIN */ safeWrite(socketFd, "AUTH LOGIN\r\n", strlen("AUTH LOGIN\r\n")); /* Recv: AUTH LOGIN */ memset(&readData, 0, SMTP_MTU); safeRead(socketFd, readData, SMTP_MTU); SMTP_Print6("[%s][%d]recv: %s\r\n", __FILE__, __LINE__, readData); recvStatus(readData); /* Send: username */ memset(&userName, 0, MAX_EMAIL_LEN); memset(&writeData, 0, SMTP_MTU); stringCut((unsigned char*)mailAddr, NULL, "@", userName); outSize = BASE64_SIZE(strlen(userName)); base64_encode(writeData, outSize, userName, strlen(userName)); strcat(writeData, "\r\n"); safeWrite(socketFd, writeData, strlen(writeData)); /* Recv: username */ memset(&readData, 0, SMTP_MTU); safeRead(socketFd, readData, SMTP_MTU); SMTP_Print6("[%s][%d]recv: %s\r\n", __FILE__, __LINE__, readData); recvStatus(readData); /* Send: passwd */ memset(&userPasswd, 0, MAX_EMAIL_LEN); strcpy(userPasswd, mailPasswd); memset(&writeData, 0, SMTP_MTU); outSize = BASE64_SIZE(strlen(userPasswd)); base64_encode(writeData, outSize, userPasswd, strlen(userPasswd)); strcat(writeData, "\r\n"); safeWrite(socketFd, writeData, strlen(writeData)); /* Recv: passwd */ memset(&readData, 0, SMTP_MTU); safeRead(socketFd, readData, SMTP_MTU); SMTP_Print6("[%s][%d]recv: %s\r\n", __FILE__, __LINE__, readData); recvStatus(readData); return 0; }
gss_client_response *authenticate_gss_server_step(gss_server_state *state, const char *auth_data) { OM_uint32 maj_stat; OM_uint32 min_stat; gss_buffer_desc input_token = GSS_C_EMPTY_BUFFER; gss_buffer_desc output_token = GSS_C_EMPTY_BUFFER; int ret = AUTH_GSS_CONTINUE; gss_client_response *response = NULL; // Always clear out the old response if (state->response != NULL) { free(state->response); state->response = NULL; } // we don't need to check the authentication token if S4U2Self protocol // transition was done, because we already have the client credentials. if (state->client_creds == GSS_C_NO_CREDENTIAL) { if (auth_data && *auth_data) { int len; input_token.value = base64_decode(auth_data, &len); input_token.length = len; } else { response = calloc(1, sizeof(gss_client_response)); if(response == NULL) die1("Memory allocation failed"); response->message = strdup("No auth_data value in request from client"); response->return_code = AUTH_GSS_ERROR; goto end; } maj_stat = gss_accept_sec_context(&min_stat, &state->context, state->server_creds, &input_token, GSS_C_NO_CHANNEL_BINDINGS, &state->client_name, NULL, &output_token, NULL, NULL, &state->client_creds); if (GSS_ERROR(maj_stat)) { response = gss_error(__func__, "gss_accept_sec_context", maj_stat, min_stat); response->return_code = AUTH_GSS_ERROR; goto end; } // Grab the server response to send back to the client if (output_token.length) { state->response = base64_encode((const unsigned char *)output_token.value, output_token.length); maj_stat = gss_release_buffer(&min_stat, &output_token); } } // Get the user name maj_stat = gss_display_name(&min_stat, state->client_name, &output_token, NULL); if (GSS_ERROR(maj_stat)) { response = gss_error(__func__, "gss_display_name", maj_stat, min_stat); response->return_code = AUTH_GSS_ERROR; goto end; } state->username = (char *)malloc(output_token.length + 1); strncpy(state->username, (char*) output_token.value, output_token.length); state->username[output_token.length] = 0; // Get the target name if no server creds were supplied if (state->server_creds == GSS_C_NO_CREDENTIAL) { gss_name_t target_name = GSS_C_NO_NAME; maj_stat = gss_inquire_context(&min_stat, state->context, NULL, &target_name, NULL, NULL, NULL, NULL, NULL); if (GSS_ERROR(maj_stat)) { response = gss_error(__func__, "gss_inquire_context", maj_stat, min_stat); response->return_code = AUTH_GSS_ERROR; goto end; } maj_stat = gss_display_name(&min_stat, target_name, &output_token, NULL); if (GSS_ERROR(maj_stat)) { response = gss_error(__func__, "gss_display_name", maj_stat, min_stat); response->return_code = AUTH_GSS_ERROR; goto end; } state->targetname = (char *)malloc(output_token.length + 1); strncpy(state->targetname, (char*) output_token.value, output_token.length); state->targetname[output_token.length] = 0; } if (state->constrained_delegation && state->client_creds != GSS_C_NO_CREDENTIAL) { if ((response = store_gss_creds(state)) != NULL) { goto end; } } ret = AUTH_GSS_COMPLETE; end: if (output_token.length) gss_release_buffer(&min_stat, &output_token); if (input_token.value) free(input_token.value); if(response == NULL) { response = calloc(1, sizeof(gss_client_response)); if(response == NULL) die1("Memory allocation failed"); response->return_code = ret; } // Return the response return response; }
xt_status sasl_pkt_challenge( struct xt_node *node, gpointer data ) { struct im_connection *ic = data; struct jabber_data *jd = ic->proto_data; struct xt_node *reply_pkt = NULL; char *nonce = NULL, *realm = NULL, *cnonce = NULL; unsigned char cnonce_bin[30]; char *digest_uri = NULL; char *dec = NULL; char *s = NULL, *reply = NULL; xt_status ret = XT_ABORT; if( node->text_len == 0 ) goto error; dec = frombase64( node->text ); if( jd->flags & JFLAG_SASL_FB ) { /* New-style Facebook OAauth2 support. Instead of sending a refresh token, they just send an access token that should never expire. */ GSList *p_in = NULL, *p_out = NULL; char time[33]; oauth_params_parse( &p_in, dec ); oauth_params_add( &p_out, "nonce", oauth_params_get( &p_in, "nonce" ) ); oauth_params_add( &p_out, "method", oauth_params_get( &p_in, "method" ) ); oauth_params_free( &p_in ); g_snprintf( time, sizeof( time ), "%lld", (long long) ( gettime() * 1000 ) ); oauth_params_add( &p_out, "call_id", time ); oauth_params_add( &p_out, "api_key", oauth2_service_facebook.consumer_key ); oauth_params_add( &p_out, "v", "1.0" ); oauth_params_add( &p_out, "format", "XML" ); oauth_params_add( &p_out, "access_token", jd->oauth2_access_token ); reply = oauth_params_string( p_out ); oauth_params_free( &p_out ); } else if( !( s = sasl_get_part( dec, "rspauth" ) ) ) { /* See RFC 2831 for for information. */ md5_state_t A1, A2, H; md5_byte_t A1r[16], A2r[16], Hr[16]; char A1h[33], A2h[33], Hh[33]; int i; nonce = sasl_get_part( dec, "nonce" ); realm = sasl_get_part( dec, "realm" ); if( !nonce ) goto error; /* Jabber.Org considers the realm part optional and doesn't specify one. Oh well, actually they're right, but still, don't know if this is right... */ if( !realm ) realm = g_strdup( jd->server ); random_bytes( cnonce_bin, sizeof( cnonce_bin ) ); cnonce = base64_encode( cnonce_bin, sizeof( cnonce_bin ) ); digest_uri = g_strdup_printf( "%s/%s", "xmpp", jd->server ); /* Generate the MD5 hash of username:realm:password, I decided to call it H. */ md5_init( &H ); s = g_strdup_printf( "%s:%s:%s", jd->username, realm, ic->acc->pass ); md5_append( &H, (unsigned char *) s, strlen( s ) ); g_free( s ); md5_finish( &H, Hr ); /* Now generate the hex. MD5 hash of H:nonce:cnonce, called A1. */ md5_init( &A1 ); s = g_strdup_printf( ":%s:%s", nonce, cnonce ); md5_append( &A1, Hr, 16 ); md5_append( &A1, (unsigned char *) s, strlen( s ) ); g_free( s ); md5_finish( &A1, A1r ); for( i = 0; i < 16; i ++ ) sprintf( A1h + i * 2, "%02x", A1r[i] ); /* A2... */ md5_init( &A2 ); s = g_strdup_printf( "%s:%s", "AUTHENTICATE", digest_uri ); md5_append( &A2, (unsigned char *) s, strlen( s ) ); g_free( s ); md5_finish( &A2, A2r ); for( i = 0; i < 16; i ++ ) sprintf( A2h + i * 2, "%02x", A2r[i] ); /* Final result: A1:nonce:00000001:cnonce:auth:A2. Let's reuse H for it. */ md5_init( &H ); s = g_strdup_printf( "%s:%s:%s:%s:%s:%s", A1h, nonce, "00000001", cnonce, "auth", A2h ); md5_append( &H, (unsigned char *) s, strlen( s ) ); g_free( s ); md5_finish( &H, Hr ); for( i = 0; i < 16; i ++ ) sprintf( Hh + i * 2, "%02x", Hr[i] ); /* Now build the SASL response string: */ reply = g_strdup_printf( "username=\"%s\",realm=\"%s\",nonce=\"%s\",cnonce=\"%s\"," "nc=%08x,qop=auth,digest-uri=\"%s\",response=%s,charset=%s", jd->username, realm, nonce, cnonce, 1, digest_uri, Hh, "utf-8" ); } else { /* We found rspauth, but don't really care... */ } s = reply ? tobase64( reply ) : NULL; reply_pkt = xt_new_node( "response", s, NULL ); xt_add_attr( reply_pkt, "xmlns", XMLNS_SASL ); if( !jabber_write_packet( ic, reply_pkt ) ) goto silent_error; ret = XT_HANDLED; goto silent_error; error: imcb_error( ic, "Incorrect SASL challenge received" ); imc_logout( ic, FALSE ); silent_error: g_free( digest_uri ); g_free( cnonce ); g_free( nonce ); g_free( reply ); g_free( realm ); g_free( dec ); g_free( s ); xt_free_node( reply_pkt ); return ret; }
/** Convert a buffer to a string using base64 encoding. \param bytes Pointer to buffer to encode. \return Encoded buffer. */ inline std::string base64_encode(std::vector<uint8_t> const& bytes) { return base64_encode(bytes.data(), bytes.size()); }
void StringEncode(char *buf, char *str, int size) { int base64_encode(const unsigned char *in, unsigned long len,unsigned char *out); base64_encode((unsigned char *)str, size,(unsigned char *)buf); }
json_t* authRequest(Parameters& params, std::string url, std::string request, std::string options) { // nonce struct timeval tv; gettimeofday(&tv, NULL); unsigned long long nonce = (tv.tv_sec * 1000.0) + (tv.tv_usec * 0.001) + 0.5; // check if options parameter is empty std::ostringstream oss; if (options.empty()) { oss << "{\"request\":\"/v1/" << request << "\",\"nonce\":\"" << nonce << "\"}"; } else { oss << "{\"request\":\"/v1/" << request << "\",\"nonce\":\"" << nonce << "\", " << options << "}"; } std::string tmpPayload = base64_encode(reinterpret_cast<const unsigned char*>(oss.str().c_str()), oss.str().length()); oss.clear(); oss.str(""); oss << "X-GEMINI-PAYLOAD:" << tmpPayload; std::string payload; payload = oss.str(); oss.clear(); oss.str(""); // build the signature unsigned char* digest; // Using sha384 hash engine digest = HMAC(EVP_sha384(), params.geminiSecret.c_str(), strlen(params.geminiSecret.c_str()), (unsigned char*)tmpPayload.c_str(), strlen(tmpPayload.c_str()), NULL, NULL); char mdString[SHA384_DIGEST_LENGTH+100]; // FIXME +100 for (int i = 0; i < SHA384_DIGEST_LENGTH; ++i) { sprintf(&mdString[i*2], "%02x", (unsigned int)digest[i]); } oss.clear(); oss.str(""); oss << "X-GEMINI-SIGNATURE:" << mdString; // cURL headers struct curl_slist *headers = NULL; std::string api = "X-GEMINI-APIKEY:" + std::string(params.geminiApi); headers = curl_slist_append(headers, api.c_str()); headers = curl_slist_append(headers, payload.c_str()); headers = curl_slist_append(headers, oss.str().c_str()); // cURL request CURLcode resCurl; // curl = curl_easy_init(); if (params.curl) { std::string readBuffer; curl_easy_setopt(params.curl, CURLOPT_POST, 1L); // curl_easy_setopt(params.curl, CURLOPT_VERBOSE, 1L); curl_easy_setopt(params.curl, CURLOPT_HTTPHEADER, headers); curl_easy_setopt(params.curl, CURLOPT_POSTFIELDS, ""); curl_easy_setopt(params.curl, CURLOPT_SSL_VERIFYPEER, 0L); curl_easy_setopt(params.curl, CURLOPT_WRITEFUNCTION, WriteCallback); curl_easy_setopt(params.curl, CURLOPT_WRITEDATA, &readBuffer); curl_easy_setopt(params.curl, CURLOPT_URL, url.c_str()); curl_easy_setopt(params.curl, CURLOPT_CONNECTTIMEOUT, 10L); resCurl = curl_easy_perform(params.curl); json_t *root; json_error_t error; while (resCurl != CURLE_OK) { *params.logFile << "<Gemini> Error with cURL. Retry in 2 sec..." << std::endl; sleep(2.0); readBuffer = ""; resCurl = curl_easy_perform(params.curl); } root = json_loads(readBuffer.c_str(), 0, &error); while (!root) { *params.logFile << "<Gemini> Error with JSON:\n" << error.text << std::endl; *params.logFile << "<Gemini> Buffer:\n" << readBuffer.c_str() << std::endl; *params.logFile << "<Gemini> Retrying..." << std::endl; sleep(2.0); readBuffer = ""; resCurl = curl_easy_perform(params.curl); while (resCurl != CURLE_OK) { *params.logFile << "<Gemini> Error with cURL. Retry in 2 sec..." << std::endl; sleep(2.0); readBuffer = ""; resCurl = curl_easy_perform(params.curl); } root = json_loads(readBuffer.c_str(), 0, &error); } curl_slist_free_all(headers); curl_easy_reset(params.curl); return root; } else { *params.logFile << "<Gemini> Error with cURL init." << std::endl; return NULL; } }
void dib_img_writer(const char *contents, FILE *out, drawingStates *states, PU_BITMAPINFOHEADER BmiSrc, const unsigned char *BmpSrc, size_t size, bool assign_mono_colors_from_dc) { char *b64Bmp = NULL; size_t b64s; char *tmp = NULL; // Handle simple cases first, no treatment needed for them switch (BmiSrc->biCompression) { case U_BI_JPEG: b64Bmp = base64_encode(BmpSrc, size, &b64s); fprintf(out, "xlink:href=\"data:image/jpg;base64,"); break; case U_BI_PNG: b64Bmp = base64_encode(BmpSrc, size, &b64s); fprintf(out, "xlink:href=\"data:image/png;base64,"); break; } if (b64Bmp != NULL) { fprintf(out, "%s\" ", b64Bmp); free(b64Bmp); return; } // more complexe treatment, with conversion to png RGBBitmap convert_in; convert_in.size = size; convert_in.width = BmiSrc->biWidth; convert_in.height = BmiSrc->biHeight; convert_in.pixels = (RGBPixel *)BmpSrc; convert_in.bytewidth = BmiSrc->biWidth * 3; convert_in.bytes_per_pixel = 3; RGBBitmap convert_out; convert_out.pixels = NULL; const U_RGBQUAD *ct = NULL; U_RGBQUAD monoCt[2]; uint32_t width, height, colortype, numCt, invert; char *rgba_px = NULL; int dibparams; char *in; size_t img_size; RGBABitmap convert_inpng; // In any cases after that, we get a png blob fprintf(out, "xlink:href=\"data:image/png;base64,"); switch (BmiSrc->biCompression) { case U_BI_RLE8: convert_out = rle8ToRGB8(convert_in); break; case U_BI_RLE4: convert_out = rle4ToRGB(convert_in); break; } if (convert_out.pixels != NULL) { in = (char *)convert_out.pixels; img_size = convert_out.size; } else { in = (char *)convert_in.pixels; img_size = convert_in.size; } dibparams = e2s_get_DIB_params((PU_BITMAPINFO)BmiSrc, (const U_RGBQUAD **)&ct, &numCt, &width, &height, &colortype, &invert); // if enable to read header, then exit if (dibparams || width > MAX_BMP_WIDTH || height > MAX_BMP_HEIGHT) { free(convert_out.pixels); states->Error = true; return; } // check that what we will read in the DIB_to_RGBA conversion is actually // there size_t offset_check = (size_t)((float)width * (float)height * get_pixel_size(colortype)); if (((in + img_size) < in + offset_check)) { free(convert_out.pixels); states->Error = true; return; } if (colortype == U_BCBM_MONOCHROME) { if (assign_mono_colors_from_dc) { monoCt[0].Red = states->currentDeviceContext.text_red; monoCt[0].Green = states->currentDeviceContext.text_green; monoCt[0].Blue = states->currentDeviceContext.text_blue; monoCt[0].Reserved = 0xff; monoCt[1].Red = states->currentDeviceContext.bk_red; monoCt[1].Green = states->currentDeviceContext.bk_green; monoCt[1].Blue = states->currentDeviceContext.bk_blue; monoCt[1].Reserved = 0xff; // states->currentDeviceContext.bk_mode ? 0xff : 0; ct = monoCt; } } DIB_to_RGBA(in, ct, numCt, &rgba_px, width, height, colortype, numCt, invert); if (rgba_px != NULL) { convert_inpng.size = width * 4 * height; convert_inpng.width = width; convert_inpng.height = height; convert_inpng.pixels = (RGBAPixel *)rgba_px; convert_inpng.bytewidth = BmiSrc->biWidth * 3; convert_inpng.bytes_per_pixel = 3; rgb2png(&convert_inpng, &b64Bmp, &b64s); tmp = (char *)b64Bmp; b64Bmp = base64_encode((unsigned char *)b64Bmp, b64s, &b64s); free(convert_out.pixels); free(tmp); free(rgba_px); } if (b64Bmp != NULL) { fprintf(out, "%s\" ", b64Bmp); free(b64Bmp); } else { // transparent 5x5 px png fprintf(out, "iVBORw0KGgoAAAANSUhEUgAAAAUAAAAFCAYAAACNbyblAAAABGdBTUEAA" "LGPC/xhBQAAAAZiS0dEAP8A/wD/" "oL2nkwAAAAlwSFlzAAALEwAACxMBAJqcGAAAAAd0SU1FB+" "ABFREtOJX7FAkAAAAIdEVYdENvbW1lbnQA9syWvwAAAAxJREFUCNdjYKA" "TAAAAaQABwB3y+AAAAABJRU5ErkJggg==\" "); } }
static int check_oauth(void) { const char server_name[33] = "blackdow.carleon.gov"; size_t i_hmacs,i_shas,i_encs; const char long_term_password[33] = "HGkj32KJGiuy098sdfaqbNjOiaz71923"; size_t ltp_output_length=0; const char* base64encoded_ltp = base64_encode((const unsigned char *)long_term_password, strlen(long_term_password), <p_output_length); const char mac_key[33] = "ZksjpweoixXmvn67534m"; const size_t mac_key_length=strlen(mac_key); const uint64_t token_timestamp = (uint64_t)(92470300704768LL); const uint32_t token_lifetime = 3600; const char kid[33] = "2783466234"; const turn_time_t key_timestamp = 1234567890; const turn_time_t key_lifetime = 3600; const char aead_nonce[OAUTH_AEAD_NONCE_SIZE+1] = "h4j3k2l2n4b5"; for (i_hmacs = 0; hmacs[i_hmacs]; ++i_hmacs) { for (i_shas = 0; shas[i_shas]; ++i_shas) { for (i_encs = 0; encs[i_encs]; ++i_encs) { printf("oauth token %s:%s:%s:",hmacs[i_hmacs],shas[i_shas],encs[i_encs]); if(print_extra) printf("\n"); oauth_token ot; ot.enc_block.key_length = (uint16_t)mac_key_length; STRCPY(ot.enc_block.mac_key,mac_key); ot.enc_block.timestamp = token_timestamp; ot.enc_block.lifetime = token_lifetime; oauth_token dot; ns_bzero((&dot),sizeof(dot)); oauth_key key; ns_bzero(&key,sizeof(key)); { oauth_key_data okd; ns_bzero(&okd,sizeof(okd)); { oauth_key_data_raw okdr; ns_bzero(&okdr,sizeof(okdr)); STRCPY(okdr.kid,kid); STRCPY(okdr.ikm_key,base64encoded_ltp); STRCPY(okdr.as_rs_alg, encs[i_encs]); STRCPY(okdr.auth_alg, hmacs[i_hmacs]); STRCPY(okdr.hkdf_hash_func, shas[i_shas]); okdr.timestamp = key_timestamp; okdr.lifetime = key_lifetime; convert_oauth_key_data_raw(&okdr, &okd); char err_msg[1025] = "\0"; size_t err_msg_size = sizeof(err_msg) - 1; if (convert_oauth_key_data(&okd, &key, err_msg, err_msg_size) < 0) { fprintf(stderr, "%s\n", err_msg); return -1; } } } if(print_extra) { print_field5769("AS-RS",key.as_rs_key,key.as_rs_key_size); print_field5769("AUTH",key.auth_key,key.auth_key_size); } { encoded_oauth_token etoken; ns_bzero(&etoken,sizeof(etoken)); if (encode_oauth_token((const u08bits *) server_name, &etoken, &key, &ot, (const u08bits*)aead_nonce) < 0) { fprintf(stderr, "%s: cannot encode oauth token\n", __FUNCTION__); return -1; } if(print_extra) { print_field5769("encoded token",etoken.token,etoken.size); } if (decode_oauth_token((const u08bits *) server_name, &etoken, &key, &dot) < 0) { fprintf(stderr, "%s: cannot decode oauth token\n", __FUNCTION__); return -1; } } if (strcmp((char*) ot.enc_block.mac_key, (char*) dot.enc_block.mac_key)) { fprintf(stderr, "%s: wrong mac key: %s, must be %s\n", __FUNCTION__, (char*) dot.enc_block.mac_key, (char*) ot.enc_block.mac_key); return -1; } if (ot.enc_block.key_length != dot.enc_block.key_length) { fprintf(stderr, "%s: wrong key length: %d, must be %d\n", __FUNCTION__, (int) dot.enc_block.key_length, (int) ot.enc_block.key_length); return -1; } if (ot.enc_block.timestamp != dot.enc_block.timestamp) { fprintf(stderr, "%s: wrong timestamp: %llu, must be %llu\n", __FUNCTION__, (unsigned long long) dot.enc_block.timestamp, (unsigned long long) ot.enc_block.timestamp); return -1; } if (ot.enc_block.lifetime != dot.enc_block.lifetime) { fprintf(stderr, "%s: wrong lifetime: %lu, must be %lu\n", __FUNCTION__, (unsigned long) dot.enc_block.lifetime, (unsigned long) ot.enc_block.lifetime); return -1; } printf("OK\n"); } } } return 0; }
int32_t mail_responder(uint32_t socket) { #ifdef DEBUG printf("Entering MAIL subroutine\n"); #endif /*DEBUG*/ //Allocate general variables //Allocate primary buffers and counters char source_account_buffer[ROUTING_FIELD_SIZE] = {0}; int32_t source_account_length = 0; char source_domain_buffer[ROUTING_FIELD_SIZE] = {0}; int32_t source_domain_length = 0; char dest_account_buffer[ROUTING_FIELD_SIZE] = {0}; int32_t dest_account_length = 0; char dest_domain_buffer[ROUTING_FIELD_SIZE] = {0}; int32_t dest_domain_length = 0; uint32_t version = 0; uint32_t attachment_count = 0; uint64_t message_length = 0; uint64_t log_length = 0; //Generate unique file from current time and current FD //Get time with nanosecond resolution (or so they say) struct timespec time_for_file; clock_gettime(CLOCK_REALTIME, &time_for_file); //Mix time with FD and hash //We are hashing two ints and a long, so char meat_and_potatoes[24] = {0}; //memset(meat_and_potatoes, 0, sizeof(meat_and_potatoes)); memcpy(meat_and_potatoes, &time_for_file.tv_sec, sizeof(time_for_file.tv_sec)); memcpy(meat_and_potatoes+sizeof(time_for_file.tv_sec), &socket, sizeof(socket)); memcpy(meat_and_potatoes+sizeof(time_for_file.tv_sec)+sizeof(socket), &time_for_file.tv_nsec, sizeof(time_for_file.tv_nsec)); unsigned char hash[64]; //64 bytes because hash has a fixed size output crypto_generichash(hash, sizeof(hash), (const unsigned char *)meat_and_potatoes, sizeof(meat_and_potatoes),NULL, 0); //Get file ready to write //TODO needs to be /mail/user/unique_file_name char unique_file_name[129] = {0}; //char base64_username[341] = {0}; char unique_file_location[522] = {0}; //TODO Need to check if user is part of this domain. If not the file location should be some temporary storage. //unique_file_name_length is not currently used. Should be fine. uint32_t unique_file_name_length = base64_encode((char *)hash, sizeof(hash), unique_file_name, sizeof(unique_file_name), (char *)filesystem_safe_base64_string, 64); if (unique_file_name_length<=0) { perror("base64_encode. unique_file_name failed to be created"); print_to_log("base64_encode failed to create a unique_file_name.", LOG_ERR); return -1; } //uint32_t base64_username_length = base64_encode((char *)dest_account_buffer, strlen(dest_account_buffer), base64_username, strlen(base64_username), (char *)filesystem_safe_base64_string, 64); //Read primary routing and processing information //First read in fixed length fields if (read_n_bytes(socket, (unsigned char *)&version, 4)!=4) { perror("read_n_bytes version"); print_to_log("Read error while reading crypto type", LOG_ERR); return -1; } if (read_n_bytes(socket, (unsigned char *)&attachment_count, 4)!=4) { perror("read_n_bytes attachment_count"); print_to_log("Read error while reading attachment count", LOG_ERR); return -1; } if (read_n_bytes(socket, (unsigned char *)&log_length, 8)!=8) { perror("read_n_bytes log_length"); print_to_log("Read error while reading message length", LOG_ERR); return -1; } if (read_n_bytes(socket, (unsigned char *)&message_length, 8)!=8) { perror("read_n_bytes message_length"); print_to_log("Read error while reading message length", LOG_ERR); return -1; } //Read in account and domain info if ((dest_account_length=read_until(socket, (unsigned char *)dest_account_buffer, sizeof(dest_account_buffer), '\0'))<0) { perror("read_until"); print_to_log("Read error while reading dest_account_buffer", LOG_ERR); return -1; } if (snprintf(unique_file_location, sizeof(unique_file_location), "%s%s%s%s", "/mail/", dest_account_buffer, "/" , unique_file_name)<0) { perror("snprintf"); print_to_log("snprintf failed to create a new file string. Cannot write message out",LOG_ERR); return -1; } write_to_file((char *)&version, 4, unique_file_location); version = be32toh(version); write_to_file((char *)&attachment_count, 4, unique_file_location); attachment_count = be32toh(attachment_count); write_to_file((char *)&log_length, 8, unique_file_location); log_length = be64toh(log_length); write_to_file((char *)&message_length, 8, unique_file_location); message_length = be64toh(message_length); #ifdef DEBUG printf("Writing mail to %s\n", unique_file_location); printf("Log length = %ld\n", log_length); printf("Version = %d\n", version); printf("Attachment count = %d\n", attachment_count); printf("Message length = %ld\n", message_length); #endif /*DEBUG*/ write_to_file(dest_account_buffer, dest_account_length, unique_file_location); #ifdef DEBUG printf("dest_account_length = %d\n", dest_account_length); #endif /*DEBUG*/ if ((dest_domain_length=read_until(socket, (unsigned char *)dest_domain_buffer, sizeof(dest_domain_buffer), '\0'))<0) { perror("read_until"); print_to_log("Read error while reading dest_domain_buffer", LOG_ERR); return -1; } write_to_file(dest_domain_buffer, dest_domain_length, unique_file_location); #ifdef DEBUG printf("dest_domain_length = %d\n", dest_domain_length); #endif /*DEBUG*/ //Check if this is the destination if((strcmp(dest_domain_buffer, home_domain)!=0)&&(forward==0)) { //Send delivery failure, close connection, clean up and return. unsigned char signature_of_DELIVERYFAILURE[crypto_sign_BYTES] = {0}; unsigned char write_buffer[sizeof(network_crypto_version)+sizeof(server_public_key)+sizeof(signature_of_DELIVERYFAILURE)+2]; crypto_sign_detached(signature_of_DELIVERYFAILURE, NULL, signature_of_DELIVERYFAILURE, sizeof(signature_of_DELIVERYFAILURE), server_private_key); memcpy(write_buffer, &network_crypto_version, sizeof(network_crypto_version)); memcpy(write_buffer+sizeof(network_crypto_version), cmtp_reply_DELIVERYFAILURE, sizeof(cmtp_reply_DELIVERYFAILURE)); memcpy(write_buffer+sizeof(network_crypto_version)+sizeof(cmtp_reply_DELIVERYFAILURE), &signature_of_DELIVERYFAILURE, sizeof(signature_of_DELIVERYFAILURE)); memcpy(write_buffer+sizeof(network_crypto_version)+sizeof(cmtp_reply_DELIVERYFAILURE)+sizeof(signature_of_DELIVERYFAILURE), &termination_char, sizeof(termination_char)); write(socket, write_buffer, sizeof(write_buffer)); } if ((source_account_length=read_until(socket, (unsigned char *)source_account_buffer, sizeof(source_account_buffer), '\0'))<0) { perror("read_until"); print_to_log("Read error while reading source_account_buffer", LOG_ERR); return -1; } write_to_file(source_account_buffer, source_account_length, unique_file_location); #ifdef DEBUG printf("source_account_length = %d\n", source_account_length); #endif /*DEBUG*/ if ((source_domain_length=read_until(socket, (unsigned char *)source_domain_buffer, sizeof(source_domain_buffer), '\0'))<0) { perror("read_until"); print_to_log("Read error while reading source_domain_buffer", LOG_ERR); return -1; } write_to_file(source_domain_buffer, source_domain_length, unique_file_location); #ifdef DEBUG printf("source_domain_length = %d\n", source_domain_length); #endif /*DEBUG*/ //This completes the read of the header //uint64_t numeric_message_length = be64toh(*(uint64_t*)(&(message_length[0]))); //uint64_t numeric_log_length = be64toh(*(uint64_t*)(&(log_length[0]))); char temp_byte[1] = {0}; //Read log for (uint64_t i = 0; i<log_length; i++) { if (read(socket, temp_byte, 1)<1) { print_to_log("read error while reading message body", LOG_ERR); perror("read"); return -1; } write_to_file(temp_byte, 1, unique_file_location); } //Read message body for (uint64_t i = 0; i<message_length; i++) { if (read(socket, temp_byte, 1)<1) { print_to_log("read error while reading message body", LOG_ERR); perror("read"); return -1; } write_to_file(temp_byte, 1, unique_file_location); } #ifdef DEBUG printf("Message body finished. Moving to attachment handling.\n"); #endif /*DEBUG*/ //Read for attachment //uint32_t numeric_attachment_count = be32toh(*(uint32_t*)(&(attachment_count[0]))); temp_byte[0] = 0; for (uint64_t i = 0; i<attachment_count; i++) { if (read(socket, temp_byte, 1)<1) { print_to_log("read error while reading message body", LOG_ERR); perror("read"); return -1; } write_to_file(temp_byte, 1, unique_file_location); } #ifdef DEBUG printf("Mail destin for %s\n", dest_domain_buffer); printf("Server domain is %s\n", home_domain); #endif /*DEBUG*/ //Destination cases if ((memcmp(dest_domain_buffer, home_domain, dest_domain_length)==0)&&(memcmp(dest_account_buffer,"",1))==0) { #ifdef DEBUG printf("Devlivered mail is for server. Begin processing.\n"); #endif /*DEBUG*/ print_to_log("Mail has arrived for the server. Processing.",LOG_INFO); //Destination is this domain and for the server } else if ((memcmp(dest_domain_buffer, home_domain, dest_domain_length)==0)) { #ifdef DEBUG printf("Devlivered mail is for a user on this domain. Store.\n"); #endif /*DEBUG*/ print_to_log("Mail has arrived for a user on this domain. Storing.",LOG_INFO); //Destination is for a user at this domain } else { #ifdef DEBUG printf("Devlivered mail is not destined for this domain. Forward to %s\n", dest_domain_buffer); #endif /*DEBUG*/ print_to_log("Mail has arrived for another domain. Forwarding.",LOG_INFO); forwardMessage(unique_file_location, dest_domain_buffer); //Destination is on the web. Forward message. } #ifdef DEBUG printf("Mail section complete. Returning to mail loop.\n"); #endif /*DEBUG*/ return 0; }
/* subscription_first_event -- send format/queue event that is automatically * sent on a new subscription. */ static int subscription_first_event(struct subscription *s) { /* * Actually, utf-8 is the default, but it doesn't hurt to specify it. * * APStatus is apparently a bit set, * 0x1 = configuration change (but is always set?) * 0x10 = ap is locked * * Per UPnP spec, we send out the last value of each variable, even * for WLANEvent, whatever it was. */ char *wlan_event; struct wpabuf *buf; int ap_status = 1; /* TODO: add 0x10 if access point is locked */ const char *head = "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n" "<e:propertyset xmlns:e=\"urn:schemas-upnp-org:event-1-0\">\n"; const char *tail = "</e:propertyset>\n"; char txt[10]; int ret; if (s->sm->wlanevent == NULL) { /* * There has been no events before the subscription. However, * UPnP device architecture specification requires all the * evented variables to be included, so generate a dummy event * for this particular case using a WSC_ACK and all-zeros * nonces. The ER (UPnP control point) will ignore this, but at * least it will learn that WLANEvent variable will be used in * event notifications in the future. */ struct wpabuf *msg; wpa_printf(MSG_DEBUG, "WPS UPnP: Use a fake WSC_ACK as the " "initial WLANEvent"); msg = build_fake_wsc_ack(); if (msg) { s->sm->wlanevent = (char *) base64_encode(wpabuf_head(msg), wpabuf_len(msg), NULL); wpabuf_free(msg); } } wlan_event = s->sm->wlanevent; if (wlan_event == NULL || *wlan_event == '\0') { wpa_printf(MSG_DEBUG, "WPS UPnP: WLANEvent not known for " "initial event message"); wlan_event = ""; } buf = wpabuf_alloc(500 + os_strlen(wlan_event)); if (buf == NULL) return -1; wpabuf_put_str(buf, head); wpabuf_put_property(buf, "STAStatus", "1"); os_snprintf(txt, sizeof(txt), "%d", ap_status); wpabuf_put_property(buf, "APStatus", txt); if (*wlan_event) wpabuf_put_property(buf, "WLANEvent", wlan_event); wpabuf_put_str(buf, tail); ret = event_add(s, buf, 0); if (ret) { wpabuf_free(buf); return ret; } wpabuf_free(buf); return 0; }
gss_client_response *authenticate_gss_client_step(gss_client_state* state, const char* challenge) { OM_uint32 maj_stat; OM_uint32 min_stat; gss_buffer_desc input_token = GSS_C_EMPTY_BUFFER; gss_buffer_desc output_token = GSS_C_EMPTY_BUFFER; int ret = AUTH_GSS_CONTINUE; gss_client_response *response = NULL; gss_cred_id_t gss_cred = GSS_C_NO_CREDENTIAL; // Always clear out the old response if (state->response != NULL) { free(state->response); state->response = NULL; } // If there is a challenge (data from the server) we need to give it to GSS if (challenge && *challenge) { int len; input_token.value = base64_decode(challenge, &len); input_token.length = len; } if (state->credentials_cache) { response = init_gss_creds(state->credentials_cache, &gss_cred); if (response) { goto end; } } // Do GSSAPI step maj_stat = gss_init_sec_context(&min_stat, gss_cred, &state->context, state->server_name, GSS_C_NO_OID, (OM_uint32)state->gss_flags, 0, GSS_C_NO_CHANNEL_BINDINGS, &input_token, NULL, &output_token, NULL, NULL); if ((maj_stat != GSS_S_COMPLETE) && (maj_stat != GSS_S_CONTINUE_NEEDED)) { response = gss_error(__func__, "gss_init_sec_context", maj_stat, min_stat); response->return_code = AUTH_GSS_ERROR; goto end; } ret = (maj_stat == GSS_S_COMPLETE) ? AUTH_GSS_COMPLETE : AUTH_GSS_CONTINUE; // Grab the client response to send back to the server if(output_token.length) { state->response = base64_encode((const unsigned char *)output_token.value, output_token.length); maj_stat = gss_release_buffer(&min_stat, &output_token); } // Try to get the user name if we have completed all GSS operations if (ret == AUTH_GSS_COMPLETE) { gss_name_t gssuser = GSS_C_NO_NAME; maj_stat = gss_inquire_context(&min_stat, state->context, &gssuser, NULL, NULL, NULL, NULL, NULL, NULL); if(GSS_ERROR(maj_stat)) { response = gss_error(__func__, "gss_inquire_context", maj_stat, min_stat); response->return_code = AUTH_GSS_ERROR; goto end; } gss_buffer_desc name_token; name_token.length = 0; maj_stat = gss_display_name(&min_stat, gssuser, &name_token, NULL); if(GSS_ERROR(maj_stat)) { if(name_token.value) gss_release_buffer(&min_stat, &name_token); gss_release_name(&min_stat, &gssuser); response = gss_error(__func__, "gss_display_name", maj_stat, min_stat); response->return_code = AUTH_GSS_ERROR; goto end; } else { state->username = (char *)malloc(name_token.length + 1); if(state->username == NULL) die1("Memory allocation failed"); strncpy(state->username, (char*) name_token.value, name_token.length); state->username[name_token.length] = 0; gss_release_buffer(&min_stat, &name_token); gss_release_name(&min_stat, &gssuser); } } end: if (gss_cred != GSS_C_NO_CREDENTIAL) gss_release_cred(&min_stat, &gss_cred); if(output_token.value) gss_release_buffer(&min_stat, &output_token); if(input_token.value) free(input_token.value); if(response == NULL) { response = calloc(1, sizeof(gss_client_response)); if(response == NULL) die1("Memory allocation failed"); response->return_code = ret; } // Return the response return response; }
/*++ * @method: Client::getSignature * * @description: this method calculates HMAC-SHA1 signature of OAuth header * * @input: eType - HTTP request type * rawUrl - raw url of the HTTP request * rawKeyValuePairs - key-value pairs containing OAuth headers and HTTP data * * @output: oAuthSignature - base64 and url encoded signature * * @remarks: internal method * *--*/ bool Client::getSignature( const Http::RequestType eType, const std::string& rawUrl, const KeyValuePairs& rawKeyValuePairs, std::string& oAuthSignature ) { std::string rawParams; std::string paramsSeperator; std::string sigBase; /* Initially empty signature */ oAuthSignature.assign( "" ); /* Build a string using key-value pairs */ paramsSeperator = "&"; getStringFromOAuthKeyValuePairs( rawKeyValuePairs, rawParams, paramsSeperator ); /* Start constructing base signature string. Refer http://dev.twitter.com/auth#intro */ switch( eType ) { case Http::Head: { sigBase.assign( "HEAD&" ); } break; case Http::Get: { sigBase.assign( "GET&" ); } break; case Http::Post: { sigBase.assign( "POST&" ); } break; case Http::Delete: { sigBase.assign( "DELETE&" ); } break; case Http::Put: { sigBase.assign( "PUT&" ); } break; default: { return false; } break; } sigBase.append( PercentEncode( rawUrl ) ); sigBase.append( "&" ); sigBase.append( PercentEncode( rawParams ) ); /* Now, hash the signature base string using HMAC_SHA1 class */ CHMAC_SHA1 objHMACSHA1; std::string secretSigningKey; unsigned char strDigest[Defaults::BUFFSIZE_LARGE]; memset( strDigest, 0, Defaults::BUFFSIZE_LARGE ); /* Signing key is composed of consumer_secret&token_secret */ secretSigningKey.assign( PercentEncode(mConsumer->secret()) ); secretSigningKey.append( "&" ); if( mToken && mToken->secret().length() ) { secretSigningKey.append( PercentEncode(mToken->secret()) ); } objHMACSHA1.HMAC_SHA1( (unsigned char*)sigBase.c_str(), sigBase.length(), (unsigned char*)secretSigningKey.c_str(), secretSigningKey.length(), strDigest ); /* Do a base64 encode of signature */ std::string base64Str = base64_encode( strDigest, 20 /* SHA 1 digest is 160 bits */ ); /* Do an url encode */ oAuthSignature = PercentEncode( base64Str ); return ( oAuthSignature.length() ) ? true : false; }
gss_client_response *authenticate_gss_client_wrap(gss_client_state* state, const char* challenge, const char* user) { OM_uint32 maj_stat; OM_uint32 min_stat; gss_buffer_desc input_token = GSS_C_EMPTY_BUFFER; gss_buffer_desc output_token = GSS_C_EMPTY_BUFFER; int ret = AUTH_GSS_CONTINUE; gss_client_response *response = NULL; char buf[4096], server_conf_flags; unsigned long buf_size; // Always clear out the old response if(state->response != NULL) { free(state->response); state->response = NULL; } if(challenge && *challenge) { int len; input_token.value = base64_decode(challenge, &len); input_token.length = len; } if(user) { // get bufsize server_conf_flags = ((char*) input_token.value)[0]; ((char*) input_token.value)[0] = 0; buf_size = ntohl(*((long *) input_token.value)); free(input_token.value); #ifdef PRINTFS printf("User: %s, %c%c%c\n", user, server_conf_flags & GSS_AUTH_P_NONE ? 'N' : '-', server_conf_flags & GSS_AUTH_P_INTEGRITY ? 'I' : '-', server_conf_flags & GSS_AUTH_P_PRIVACY ? 'P' : '-'); printf("Maximum GSS token size is %ld\n", buf_size); #endif // agree to terms (hack!) buf_size = htonl(buf_size); // not relevant without integrity/privacy memcpy(buf, &buf_size, 4); buf[0] = GSS_AUTH_P_NONE; // server decides if principal can log in as user strncpy(buf + 4, user, sizeof(buf) - 4); input_token.value = buf; input_token.length = 4 + strlen(user); } // Do GSSAPI wrap maj_stat = gss_wrap(&min_stat, state->context, 0, GSS_C_QOP_DEFAULT, &input_token, NULL, &output_token); if (maj_stat != GSS_S_COMPLETE) { response = gss_error(__func__, "gss_wrap", maj_stat, min_stat); response->return_code = AUTH_GSS_ERROR; goto end; } else ret = AUTH_GSS_COMPLETE; // Grab the client response to send back to the server if (output_token.length) { state->response = base64_encode((const unsigned char *)output_token.value, output_token.length);; gss_release_buffer(&min_stat, &output_token); } end: if (output_token.value) gss_release_buffer(&min_stat, &output_token); if(response == NULL) { response = calloc(1, sizeof(gss_client_response)); if(response == NULL) die1("Memory allocation failed"); response->return_code = ret; } // Return the response return response; }
/** Generate a new certificate for our loaded or generated keys, and write it * to disk. Return 0 on success, nonzero on failure. */ static int generate_certificate(void) { char buf[8192]; time_t now = time(NULL); struct tm tm; char published[ISO_TIME_LEN+1]; char expires[ISO_TIME_LEN+1]; char id_digest[DIGEST_LEN]; char fingerprint[FINGERPRINT_LEN+1]; char *ident = key_to_string(identity_key); char *signing = key_to_string(signing_key); FILE *f; size_t signed_len; char digest[DIGEST_LEN]; char signature[1024]; /* handles up to 8192-bit keys. */ int r; get_fingerprint(identity_key, fingerprint); get_digest(identity_key, id_digest); tor_localtime_r(&now, &tm); tm.tm_mon += months_lifetime; format_iso_time(published, now); format_iso_time(expires, mktime(&tm)); tor_snprintf(buf, sizeof(buf), "dir-key-certificate-version 3" "%s%s" "\nfingerprint %s\n" "dir-key-published %s\n" "dir-key-expires %s\n" "dir-identity-key\n%s" "dir-signing-key\n%s" "dir-key-crosscert\n" "-----BEGIN ID SIGNATURE-----\n", address?"\ndir-address ":"", address?address:"", fingerprint, published, expires, ident, signing ); tor_free(ident); tor_free(signing); /* Append a cross-certification */ r = RSA_private_encrypt(DIGEST_LEN, (unsigned char*)id_digest, (unsigned char*)signature, EVP_PKEY_get1_RSA(signing_key), RSA_PKCS1_PADDING); signed_len = strlen(buf); base64_encode(buf+signed_len, sizeof(buf)-signed_len, signature, r); strlcat(buf, "-----END ID SIGNATURE-----\n" "dir-key-certification\n", sizeof(buf)); signed_len = strlen(buf); SHA1((const unsigned char*)buf,signed_len,(unsigned char*)digest); r = RSA_private_encrypt(DIGEST_LEN, (unsigned char*)digest, (unsigned char*)signature, EVP_PKEY_get1_RSA(identity_key), RSA_PKCS1_PADDING); strlcat(buf, "-----BEGIN SIGNATURE-----\n", sizeof(buf)); signed_len = strlen(buf); base64_encode(buf+signed_len, sizeof(buf)-signed_len, signature, r); strlcat(buf, "-----END SIGNATURE-----\n", sizeof(buf)); if (!(f = fopen(certificate_file, "w"))) { log_err(LD_GENERAL, "Couldn't open %s for writing: %s", certificate_file, strerror(errno)); return 1; } if (fputs(buf, f) < 0) { log_err(LD_GENERAL, "Couldn't write to %s: %s", certificate_file, strerror(errno)); fclose(f); return 1; } fclose(f); return 0; }
void load_auto_pickup(bool bCharacter) { std::ifstream fin; std::string sFile = FILENAMES["autopickup"]; if (bCharacter) { sFile = world_generator->active_world->world_path + "/" + base64_encode(g->u.name) + ".apu.txt"; } bool legacy_autopickup_loaded = false; fin.open(sFile.c_str()); if(!fin.is_open()) { if( !bCharacter ) { fin.open(FILENAMES["legacy_autopickup"].c_str()); } if( !fin.is_open() ) { assure_dir_exist(FILENAMES["config_dir"]); create_default_auto_pickup(bCharacter); fin.open(sFile.c_str()); } else { legacy_autopickup_loaded = true; } if(!fin.is_open()) { DebugLog( D_ERROR, DC_ALL ) << "Could neither read nor create " << sFile; return; } } vAutoPickupRules[(bCharacter) ? APU_CHARACTER : APU_GLOBAL].clear(); std::string sLine; while(!fin.eof()) { getline(fin, sLine); if(sLine != "" && sLine[0] != '#') { int iNum = std::count(sLine.begin(), sLine.end(), ';'); if(iNum != 2) { DebugLog( D_ERROR, DC_ALL ) << "Bad Rule: " << sLine; } else { std::string sRule = ""; bool bActive = true; bool bExclude = false; size_t iPos = 0; int iCol = 1; do { iPos = sLine.find(";"); std::string sTemp = (iPos == std::string::npos) ? sLine : sLine.substr(0, iPos); if (iCol == 1) { sRule = sTemp; } else if (iCol == 2) { bActive = (sTemp == "T" || sTemp == "True") ? true : false; } else if (iCol == 3) { bExclude = (sTemp == "T" || sTemp == "True") ? true : false; } iCol++; if (iPos != std::string::npos) { sLine = sLine.substr(iPos + 1, sLine.size()); } } while(iPos != std::string::npos); vAutoPickupRules[(bCharacter) ? APU_CHARACTER : APU_GLOBAL].push_back(cPickupRules(sRule, bActive, bExclude)); } } } fin.close(); merge_vector(); createPickupRules(); if( legacy_autopickup_loaded ) { assure_dir_exist(FILENAMES["config_dir"]); save_auto_pickup( bCharacter ); } }
static int base2json(heim_object_t obj, struct twojson *j) { heim_tid_t type; int first = 0; char *str; if (obj == NULL) { if (j->flags & HEIM_JSON_F_CNULL2JSNULL) { obj = heim_null_create(); } else if (j->flags & HEIM_JSON_F_NO_C_NULL) { return EINVAL; } else { indent(j); j->out(j->ctx, "<NULL>\n"); /* This is NOT valid JSON! */ return 0; } } type = heim_get_tid(obj); switch (type) { case HEIM_TID_ARRAY: indent(j); j->out(j->ctx, "[\n"); j->indent++; first = j->first; j->first = 1; heim_array_iterate_f(obj, j, array2json); j->indent--; if (!j->first) j->out(j->ctx, "\n"); indent(j); j->out(j->ctx, "]\n"); j->first = first; break; case HEIM_TID_DICT: indent(j); j->out(j->ctx, "{\n"); j->indent++; first = j->first; j->first = 1; heim_dict_iterate_f(obj, j, dict2json); j->indent--; if (!j->first) j->out(j->ctx, "\n"); indent(j); j->out(j->ctx, "}\n"); j->first = first; break; case HEIM_TID_STRING: indent(j); j->out(j->ctx, "\""); str = heim_string_copy_utf8(obj); j->out(j->ctx, str); free(str); j->out(j->ctx, "\""); break; case HEIM_TID_DATA: { heim_dict_t d; heim_string_t v; char *b64 = NULL; int ret; if (j->flags & HEIM_JSON_F_NO_DATA) return EINVAL; /* JSON doesn't do binary */ ret = base64_encode(heim_data_get_bytes(obj), (int)heim_data_get_length(obj), &b64); if (ret < 0 || b64 == NULL) return ENOMEM; if (j->flags & HEIM_JSON_F_NO_DATA_DICT) { indent(j); j->out(j->ctx, "\""); j->out(j->ctx, b64); /* base64-encode; hope there's no aliasing */ j->out(j->ctx, "\""); free(b64); } else { /* * JSON has no way to represent binary data, therefore the * following is a Heimdal-specific convention. * * We encode binary data as a dict with a single very magic * key with a base64-encoded value. The magic key includes * a uuid, so we're not likely to alias accidentally. */ d = heim_dict_create(2); if (d == NULL) { free(b64); return ENOMEM; } v = heim_string_create(b64); free(b64); if (v == NULL) { heim_release(d); return ENOMEM; } ret = heim_dict_set_value(d, heim_tid_data_uuid_key, v); heim_release(v); if (ret) { heim_release(d); return ENOMEM; } ret = base2json(d, j); heim_release(d); if (ret) return ret; } break; } case HEIM_TID_NUMBER: { char num[32]; indent(j); snprintf(num, sizeof (num), "%d", heim_number_get_int(obj)); j->out(j->ctx, num); break; } case HEIM_TID_NULL: indent(j); j->out(j->ctx, "null"); break; case HEIM_TID_BOOL: indent(j); j->out(j->ctx, heim_bool_val(obj) ? "true" : "false"); break; default: return 1; } return 0; }
xt_status sasl_pkt_mechanisms( struct xt_node *node, gpointer data ) { struct im_connection *ic = data; struct jabber_data *jd = ic->proto_data; struct xt_node *c, *reply; char *s; int sup_plain = 0, sup_digest = 0, sup_gtalk = 0, sup_fb = 0, sup_ms = 0; int want_oauth = FALSE; GString *mechs; if( !sasl_supported( ic ) ) { /* Should abort this now, since we should already be doing IQ authentication. Strange things happen when you try to do both... */ imcb_log( ic, "XMPP 1.0 non-compliant server seems to support SASL, please report this as a BitlBee bug!" ); return XT_HANDLED; } s = xt_find_attr( node, "xmlns" ); if( !s || strcmp( s, XMLNS_SASL ) != 0 ) { imcb_log( ic, "Stream error while authenticating" ); imc_logout( ic, FALSE ); return XT_ABORT; } mechs = g_string_new( "" ); c = node->children; while( ( c = xt_find_node( c, "mechanism" ) ) ) { if( c->text && g_strcasecmp( c->text, "PLAIN" ) == 0 ) sup_plain = 1; else if( c->text && g_strcasecmp( c->text, "DIGEST-MD5" ) == 0 ) sup_digest = 1; else if( c->text && g_strcasecmp( c->text, "X-OAUTH2" ) == 0 ) sup_gtalk = 1; else if( c->text && g_strcasecmp( c->text, "X-FACEBOOK-PLATFORM" ) == 0 ) sup_fb = 1; else if( c->text && g_strcasecmp( c->text, "X-MESSENGER-OAUTH2" ) == 0 ) sup_ms = 1; if( c->text ) g_string_append_printf( mechs, " %s", c->text ); c = c->next; } if( !sup_plain && !sup_digest ) { if( !sup_gtalk && !sup_fb && !sup_ms ) imcb_error( ic, "This server requires OAuth " "(supported schemes:%s)", mechs->str ); else imcb_error( ic, "BitlBee does not support any of the offered SASL " "authentication schemes:%s", mechs->str ); imc_logout( ic, FALSE ); g_string_free( mechs, TRUE ); return XT_ABORT; } g_string_free( mechs, TRUE ); reply = xt_new_node( "auth", NULL, NULL ); xt_add_attr( reply, "xmlns", XMLNS_SASL ); want_oauth = set_getbool( &ic->acc->set, "oauth" ); if( sup_gtalk && want_oauth ) { int len; /* X-OAUTH2 is, not *the* standard OAuth2 SASL/XMPP implementation. It's currently used by GTalk and vaguely documented on http://code.google.com/apis/cloudprint/docs/rawxmpp.html . */ xt_add_attr( reply, "mechanism", "X-OAUTH2" ); len = strlen( jd->username ) + strlen( jd->oauth2_access_token ) + 2; s = g_malloc( len + 1 ); s[0] = 0; strcpy( s + 1, jd->username ); strcpy( s + 2 + strlen( jd->username ), jd->oauth2_access_token ); reply->text = base64_encode( (unsigned char *)s, len ); reply->text_len = strlen( reply->text ); g_free( s ); } else if( sup_ms && want_oauth ) { xt_add_attr( reply, "mechanism", "X-MESSENGER-OAUTH2" ); reply->text = g_strdup( jd->oauth2_access_token ); reply->text_len = strlen( jd->oauth2_access_token ); } else if( sup_fb && want_oauth ) { xt_add_attr( reply, "mechanism", "X-FACEBOOK-PLATFORM" ); jd->flags |= JFLAG_SASL_FB; } else if( want_oauth ) { imcb_error( ic, "OAuth requested, but not supported by server" ); imc_logout( ic, FALSE ); xt_free_node( reply ); return XT_ABORT; } else if( sup_digest ) { xt_add_attr( reply, "mechanism", "DIGEST-MD5" ); /* The rest will be done later, when we receive a <challenge/>. */ } else if( sup_plain ) { int len; xt_add_attr( reply, "mechanism", "PLAIN" ); /* With SASL PLAIN in XMPP, the text should be b64(\0user\0pass) */ len = strlen( jd->username ) + strlen( ic->acc->pass ) + 2; s = g_malloc( len + 1 ); s[0] = 0; strcpy( s + 1, jd->username ); strcpy( s + 2 + strlen( jd->username ), ic->acc->pass ); reply->text = base64_encode( (unsigned char *)s, len ); reply->text_len = strlen( reply->text ); g_free( s ); } if( reply && !jabber_write_packet( ic, reply ) ) { xt_free_node( reply ); return XT_ABORT; } xt_free_node( reply ); /* To prevent classic authentication from happening. */ jd->flags |= JFLAG_STREAM_STARTED; return XT_HANDLED; }
/*++ * @method: oAuth::getSignature * * @description: this method calculates HMAC-SHA1 signature of OAuth header * * @input: eType - HTTP request type * rawUrl - raw url of the HTTP request * rawKeyValuePairs - key-value pairs containing OAuth headers and HTTP data * * @output: oAuthSignature - base64 and url encoded signature * * @remarks: internal method * *--*/ bool oAuth::getSignature( const eOAuthHttpRequestType eType, const std::string& rawUrl, const oAuthKeyValuePairs& rawKeyValuePairs, std::string& oAuthSignature ) { std::string rawParams; std::string paramsSeperator; std::string sigBase; /* Initially empty signature */ oAuthSignature = ""; /* Build a string using key-value pairs */ paramsSeperator = "&"; getStringFromOAuthKeyValuePairs( rawKeyValuePairs, rawParams, paramsSeperator ); /* Start constructing base signature string. Refer http://dev.twitter.com/auth#intro */ switch( eType ) { case eOAuthHttpGet: { sigBase.assign( "GET&" ); } break; case eOAuthHttpPost: { sigBase.assign( "POST&" ); } break; case eOAuthHttpDelete: { sigBase.assign( "DELETE&" ); } break; default: { return false; } break; } sigBase.append( urlencode( rawUrl ) ); sigBase.append( "&" ); sigBase.append( urlencode( rawParams ) ); /* Now, hash the signature base string using HMAC_SHA1 class */ CHMAC_SHA1 objHMACSHA1; std::string secretSigningKey; unsigned char strDigest[oAuthLibDefaults::OAUTHLIB_BUFFSIZE_LARGE]; memset( strDigest, 0, oAuthLibDefaults::OAUTHLIB_BUFFSIZE_LARGE ); /* Signing key is composed of consumer_secret&token_secret */ secretSigningKey.assign( m_consumerSecret ); secretSigningKey.append( "&" ); if( m_oAuthTokenSecret.length() ) { secretSigningKey.append( m_oAuthTokenSecret ); } objHMACSHA1.HMAC_SHA1( (unsigned char*)sigBase.c_str(), sigBase.length(), (unsigned char*)secretSigningKey.c_str(), secretSigningKey.length(), strDigest ); /* Do a base64 encode of signature */ std::string base64Str = base64_encode( strDigest, 20 /* SHA 1 digest is 160 bits */ ); /* Do an url encode */ oAuthSignature = urlencode( base64Str ); return !oAuthSignature.empty(); }
/* * Called by mgmt to queue packet out to UART. */ static int nmgr_uart_out(struct nmgr_transport *nt, struct os_mbuf *m) { struct nmgr_uart_state *nus = (struct nmgr_uart_state *)nt; struct os_mbuf_pkthdr *mpkt; struct os_mbuf *n; char tmp_buf[12]; uint16_t crc; char *dst; int off; int boff; int slen; int sr; int rc; int last; int tx_sz; assert(OS_MBUF_IS_PKTHDR(m)); mpkt = OS_MBUF_PKTHDR(m); off = 0; crc = CRC16_INITIAL_CRC; for (n = m; n; n = SLIST_NEXT(n, om_next)) { crc = crc16_ccitt(crc, n->om_data, n->om_len); } crc = htons(crc); dst = os_mbuf_extend(m, sizeof(crc)); if (!dst) { goto err; } memcpy(dst, &crc, sizeof(crc)); n = os_msys_get(SHELL_NLIP_MAX_FRAME, 0); if (!n || OS_MBUF_TRAILINGSPACE(n) < 32) { goto err; } while (off < mpkt->omp_len) { tx_sz = 2; dst = os_mbuf_extend(n, 2); if (off == 0) { *(uint16_t *)dst = htons(SHELL_NLIP_PKT); *(uint16_t *)tmp_buf = htons(mpkt->omp_len); boff = 2; } else { *(uint16_t *)dst = htons(SHELL_NLIP_DATA); boff = 0; } while (off < mpkt->omp_len) { slen = mpkt->omp_len - off; last = 1; if (slen > sizeof(tmp_buf) + boff) { slen = sizeof(tmp_buf) - boff; last = 0; } if (tx_sz + BASE64_ENCODE_SIZE(slen + boff) >= 124) { break; } rc = os_mbuf_copydata(m, off, slen, tmp_buf + boff); assert(rc == 0); off += slen; slen += boff; dst = os_mbuf_extend(n, BASE64_ENCODE_SIZE(slen)); if (!dst) { goto err; } tx_sz += base64_encode(tmp_buf, slen, dst, last); boff = 0; } if (os_mbuf_append(n, "\n", 1)) { goto err; } } os_mbuf_free_chain(m); OS_ENTER_CRITICAL(sr); if (!nus->nus_tx) { nus->nus_tx = n; uart_start_tx(nus->nus_dev); } else { os_mbuf_concat(nus->nus_tx, n); } OS_EXIT_CRITICAL(sr); return 0; err: os_mbuf_free_chain(m); os_mbuf_free_chain(n); return -1; }
/** * @func sendemail * @brief send email in blocking-mode * @param smtpServer * @param body */ void send_email(char *smtpServer, char *body, char *from_addr, char* from_passwd, char* to_qq) { int sockfd = 0; struct sockaddr_in their_addr = {0}; char buf[1500] = {0}; char rbuf[1500] = {0}; char login[128] = {0}; char pass[128] = {0}; struct hostent *host = NULL; // 取得主机IP地址 if((host = gethostbyname(smtpServer))==NULL){ fprintf(stderr,"Gethostname error, %s\n", strerror(errno)); exit(1); } memset(&their_addr, 0, sizeof(their_addr)); their_addr.sin_family = AF_INET; their_addr.sin_port = htons(25); their_addr.sin_addr = *((struct in_addr *)host->h_addr); sockfd = socket(PF_INET, SOCK_STREAM, 0); if(sockfd < 0){ xyprintf(0, "STMP_ERROR:%s %d -- Open sockfd(TCP ) error!", __FILE__, __LINE__); return ; } if(connect(sockfd, (struct sockaddr *)&their_addr, sizeof(struct sockaddr)) < 0){ close(sockfd); xyprintf(0, "STMP_ERROR:%s %d -- Connect sockfd(TCP ) error!", __FILE__, __LINE__); return ; } memset(rbuf, 0, 1500); if(recv(sockfd, rbuf, 1500, 0) == 0){ close(sockfd); xyprintf(0, "STMP_ERROR:%s %d -- "); return ; } memset(buf, 0, 1500); /* EHLO */ sprintf(buf, "EHLO abcdefg-PC\r\n"); send(sockfd, buf, strlen(buf), 0); xyprintf(0, " --> %s", buf); memset(rbuf, 0, 1500); recv(sockfd, rbuf, 1500, 0); xyprintf(0, " <-- %s", rbuf); memset(buf, 0, 1500); /*AUTH LOGIN */ sprintf(buf, "AUTH LOGIN\r\n"); send(sockfd, buf, strlen(buf), 0); xyprintf(0, " --> %s", buf); memset(rbuf, 0, 1500); recv(sockfd, rbuf, 1500, 0); xyprintf(0, " <-- %s", rbuf); memset(buf, 0, 1500); /* USER */ sprintf(buf, "%s", from_addr); memset(login, 0, 128); base64_encode(buf, strlen(buf), login, 128); /* base64 */ xyprintf(0, " --> %s", buf); sprintf(buf, "%s\r\n", login); send(sockfd, buf, strlen(buf), 0); xyprintf(0, " --> %s", buf); memset(rbuf, 0, 1500); recv(sockfd, rbuf, 1500, 0); xyprintf(0, " <-- %s", rbuf); /* PASSWORD */ memset(buf, 0, 1500); sprintf(buf, "%s", from_passwd); memset(pass, 0, 128); base64_encode(buf, strlen(buf), pass, 128); memset(buf, 0, 1500); xyprintf(0, " --> %s", buf); sprintf(buf, "%s\r\n", pass); send(sockfd, buf, strlen(buf), 0); xyprintf(0, " --> %s", buf); memset(rbuf, 0, 1500); recv(sockfd, rbuf, 1500, 0); xyprintf(0, " <-- %s", rbuf); memset(buf, 0, 1500); /* MAIL FROM */ sprintf(buf, "MAIL FROM: <%s>\r\n", from_addr); send(sockfd, buf, strlen(buf), 0); xyprintf(0, " --> %s", buf); memset(rbuf, 0, 1500); recv(sockfd, rbuf, 1500, 0); xyprintf(0, " <-- %s", rbuf); /* rcpt to 第一个收件人 */ sprintf(buf, "RCPT TO:<*****@*****.**>\r\n", to_qq); send(sockfd, buf, strlen(buf), 0); xyprintf(0, " --> %s", buf); memset(rbuf, 0, 1500); recv(sockfd, rbuf, 1500, 0); xyprintf(0, " <-- %s", rbuf); /* DATA email connext ready */ sprintf(buf, "DATA\r\n"); send(sockfd, buf, strlen(buf), 0); xyprintf(0, " --> %s", buf); memset(rbuf, 0, 1500); recv(sockfd, rbuf, 1500, 0); xyprintf(0, " <-- %s", rbuf); /* send email connext \r\n.\r\n end*/ send(sockfd, body, strlen(body), 0); //xyprintf(0, " --> %s", body); memset(rbuf, 0, 1500); recv(sockfd, rbuf, 1500, 0); xyprintf(0, " <-- %s", rbuf); /* QUIT */ sprintf(buf, "QUIT\r\n"); send(sockfd, buf, strlen(buf), 0); xyprintf(0, " --> %s", buf); memset(rbuf, 0, 1500); recv(sockfd, rbuf, 1500, 0); xyprintf(0, " <-- %s", rbuf); close(sockfd); return ; }
/* static attachmemt size */ int mailAttachment(unsigned char **mail, const unsigned char *filePath) { FILE *fp = NULL; int fileSize, base64Size, headerSize, len; char *attach = NULL, *base64Attach = NULL, *attachHeader = NULL; char fileName[MAX_EMAIL_LEN] = {0}; const char *contentType = "Content-Type: application/octet-stream"; const char *contentEncode = "Content-Transfer-Encoding: base64"; const char *contentDes = "Content-Disposition: attachment"; fp = fopen(filePath, "rb"); if (NULL == fp) { perror("open..."); return -1; } fseek(fp, 0, SEEK_END); fileSize = ftell(fp); if (0 > fileSize) { perror("ftell...\n"); return -1; } rewind(fp); attach = calloc(fileSize, 1); if (NULL == attach) { perror("malloc..."); return -1; } headerSize = strlen(contentType)+strlen(contentEncode)+strlen(contentDes)+200; attachHeader = calloc(headerSize, 1); if (NULL == attach) { perror("malloc..."); return -1; } /* attachment header */ stringCut(filePath, "/", NULL, fileName); sprintf(attachHeader, "%s;name=\"%s\"\r\n%s\r\n%s;filename=\"%s\"\r\n\r\n", contentType, fileName, contentEncode, contentDes, fileName); base64Size = BASE64_SIZE(fileSize); base64Attach = calloc(base64Size, 1); if (NULL == base64Attach) { perror("malloc..."); return -1; } len = fread(attach, sizeof(char), fileSize, fp); SMTP_Print6("[%s][%d] %s size = %d, base64Size = %d \r\n",__FILE__, __LINE__, filePath, fileSize, base64Size); /* attachment transform to base64 */ base64_encode(base64Attach, base64Size, attach, fileSize); free(attach); *mail = realloc(*mail, strlen(*mail)+headerSize+base64Size+1); if (NULL == *mail) { perror("realloc...\n"); /* what should I do? */ return -1; } strcat(*mail, attachHeader); strcat(*mail, base64Attach); free(attachHeader); free(base64Attach); return fileSize; }
int main(int argc, char **argv) { int port = 0; int messagenumber = 5; char local_addr[256]; int c; int mclient = 1; char peer_address[129] = "\0"; int peer_port = PEER_DEFAULT_PORT; char rest_api_separator = ':'; int use_null_cipher=0; set_logfile("stdout"); set_execdir(); set_system_parameters(0); ns_bzero(local_addr, sizeof(local_addr)); while ((c = getopt(argc, argv, "a:d:p:l:n:L:m:e:r:u:w:i:k:z:W:C:E:F:o:bZvsyhcxXgtTSAPDNOUMRIGBJ")) != -1) { switch (c){ case 'J': { oauth = 1; oauth_key_data okd_array[3]; convert_oauth_key_data_raw(&okdr_array[0], &okd_array[0]); convert_oauth_key_data_raw(&okdr_array[1], &okd_array[1]); convert_oauth_key_data_raw(&okdr_array[2], &okd_array[2]); char err_msg[1025] = "\0"; size_t err_msg_size = sizeof(err_msg) - 1; if (convert_oauth_key_data(&okd_array[0], &okey_array[0], err_msg, err_msg_size) < 0) { fprintf(stderr, "%s\n", err_msg); exit(-1); } if (convert_oauth_key_data(&okd_array[1], &okey_array[1], err_msg, err_msg_size) < 0) { fprintf(stderr, "%s\n", err_msg); exit(-1); } if (convert_oauth_key_data(&okd_array[2], &okey_array[2], err_msg, err_msg_size) < 0) { fprintf(stderr, "%s\n", err_msg); exit(-1); } } break; case 'a': bps = (band_limit_t)strtoul(optarg,NULL,10); break; case 'o': STRCPY(origin,optarg); break; case 'B': random_disconnect = 1; break; case 'G': extra_requests = 1; break; case 'F': STRCPY(cipher_suite,optarg); break; case 'I': no_permissions = 1; break; case 'M': mobility = 1; break; case 'E': { char* fn = find_config_file(optarg,1); if(!fn) { fprintf(stderr,"ERROR: file %s not found\n",optarg); exit(-1); } STRCPY(ca_cert_file,fn); } break; case 'O': dos = 1; break; case 'C': rest_api_separator=*optarg; break; case 'D': mandatory_channel_padding = 1; break; case 'N': negative_test = 1; break; case 'R': negative_protocol_test = 1; break; case 'z': RTP_PACKET_INTERVAL = atoi(optarg); break; case 'Z': dual_allocation = 1; break; case 'u': STRCPY(g_uname, optarg); break; case 'w': STRCPY(g_upwd, optarg); break; case 'g': dont_fragment = 1; break; case 'd': STRCPY(client_ifname, optarg); break; case 'x': default_address_family = STUN_ATTRIBUTE_REQUESTED_ADDRESS_FAMILY_VALUE_IPV6; break; case 'X': default_address_family = STUN_ATTRIBUTE_REQUESTED_ADDRESS_FAMILY_VALUE_IPV4; break; case 'l': clmessage_length = atoi(optarg); break; case 's': do_not_use_channel = 1; break; case 'n': messagenumber = atoi(optarg); break; case 'p': port = atoi(optarg); break; case 'L': STRCPY(local_addr, optarg); break; case 'e': STRCPY(peer_address, optarg); break; case 'r': peer_port = atoi(optarg); break; case 'v': clnet_verbose = TURN_VERBOSE_NORMAL; break; case 'h': hang_on = 1; break; case 'c': no_rtcp = 1; break; case 'm': mclient = atoi(optarg); break; case 'y': c2c = 1; break; case 't': use_tcp = 1; break; case 'b': use_sctp = 1; use_tcp = 1; break; case 'P': passive_tcp = 1; /* implies 'T': */ /* no break */ case 'T': relay_transport = STUN_ATTRIBUTE_TRANSPORT_TCP_VALUE; break; case 'U': use_null_cipher = 1; /* implies 'S' */ /* no break */ case 'S': use_secure = 1; break; case 'W': g_use_auth_secret_with_timestamp = 1; STRCPY(g_auth_secret,optarg); break; case 'i': { char* fn = find_config_file(optarg,1); if(!fn) { fprintf(stderr,"ERROR: file %s not found\n",optarg); exit(-1); } STRCPY(cert_file,fn); free(fn); } break; case 'k': { char* fn = find_config_file(optarg,1); if(!fn) { fprintf(stderr,"ERROR: file %s not found\n",optarg); exit(-1); } STRCPY(pkey_file,fn); free(fn); } break; default: fprintf(stderr, "%s\n", Usage); exit(1); } } if(dual_allocation) { no_rtcp = 1; } if(g_use_auth_secret_with_timestamp) { { char new_uname[1025]; const unsigned long exp_time = 3600 * 24; /* one day */ if(g_uname[0]) { snprintf(new_uname,sizeof(new_uname),"%lu%c%s",(unsigned long)time(NULL) + exp_time,rest_api_separator, (char*)g_uname); } else { snprintf(new_uname,sizeof(new_uname),"%lu", (unsigned long)time(NULL) + exp_time); } STRCPY(g_uname,new_uname); } { u08bits hmac[MAXSHASIZE]; unsigned int hmac_len; switch(shatype) { case SHATYPE_SHA256: hmac_len = SHA256SIZEBYTES; break; case SHATYPE_SHA384: hmac_len = SHA384SIZEBYTES; break; case SHATYPE_SHA512: hmac_len = SHA512SIZEBYTES; break; default: hmac_len = SHA1SIZEBYTES; }; hmac[0]=0; if(stun_calculate_hmac(g_uname, strlen((char*)g_uname), (u08bits*)g_auth_secret, strlen(g_auth_secret), hmac, &hmac_len, shatype)>=0) { size_t pwd_length = 0; char *pwd = base64_encode(hmac,hmac_len,&pwd_length); if(pwd) { if(pwd_length>0) { ns_bcopy(pwd,g_upwd,pwd_length); g_upwd[pwd_length]=0; } } free(pwd); } } } if(is_TCP_relay()) { dont_fragment = 0; no_rtcp = 1; c2c = 1; use_tcp = 1; do_not_use_channel = 1; } if(port == 0) { if(use_secure) port = DEFAULT_STUN_TLS_PORT; else port = DEFAULT_STUN_PORT; } if (clmessage_length < (int) sizeof(message_info)) clmessage_length = (int) sizeof(message_info); const int max_header = 100; if(clmessage_length > (int)(STUN_BUFFER_SIZE-max_header)) { fprintf(stderr,"Message length was corrected to %d\n",(STUN_BUFFER_SIZE-max_header)); clmessage_length = (int)(STUN_BUFFER_SIZE-max_header); } if (optind >= argc) { fprintf(stderr, "%s\n", Usage); exit(-1); } if (!c2c) { if (make_ioa_addr((const u08bits*) peer_address, peer_port, &peer_addr) < 0) { return -1; } if(peer_addr.ss.sa_family == AF_INET6) { default_address_family = STUN_ATTRIBUTE_REQUESTED_ADDRESS_FAMILY_VALUE_IPV6; } else if(peer_addr.ss.sa_family == AF_INET) { default_address_family = STUN_ATTRIBUTE_REQUESTED_ADDRESS_FAMILY_VALUE_IPV4; } } /* SSL Init ==>> */ if(use_secure) { SSL_load_error_strings(); OpenSSL_add_ssl_algorithms(); const char *csuite = "ALL"; //"AES256-SHA" "DH" if(use_null_cipher) csuite = "eNULL"; else if(cipher_suite[0]) csuite=cipher_suite; if(use_tcp) { root_tls_ctx[root_tls_ctx_num] = SSL_CTX_new(SSLv23_client_method()); SSL_CTX_set_cipher_list(root_tls_ctx[root_tls_ctx_num], csuite); root_tls_ctx_num++; root_tls_ctx[root_tls_ctx_num] = SSL_CTX_new(TLSv1_client_method()); SSL_CTX_set_cipher_list(root_tls_ctx[root_tls_ctx_num], csuite); root_tls_ctx_num++; #if TLSv1_1_SUPPORTED root_tls_ctx[root_tls_ctx_num] = SSL_CTX_new(TLSv1_1_client_method()); SSL_CTX_set_cipher_list(root_tls_ctx[root_tls_ctx_num], csuite); root_tls_ctx_num++; #if TLSv1_2_SUPPORTED root_tls_ctx[root_tls_ctx_num] = SSL_CTX_new(TLSv1_2_client_method()); SSL_CTX_set_cipher_list(root_tls_ctx[root_tls_ctx_num], csuite); root_tls_ctx_num++; #endif #endif } else { #if !DTLS_SUPPORTED fprintf(stderr,"ERROR: DTLS is not supported.\n"); exit(-1); #else if(OPENSSL_VERSION_NUMBER < 0x10000000L) { TURN_LOG_FUNC(TURN_LOG_LEVEL_WARNING, "WARNING: OpenSSL version is rather old, DTLS may not be working correctly.\n"); } root_tls_ctx[root_tls_ctx_num] = SSL_CTX_new(DTLSv1_client_method()); SSL_CTX_set_cipher_list(root_tls_ctx[root_tls_ctx_num], csuite); root_tls_ctx_num++; #if DTLSv1_2_SUPPORTED root_tls_ctx[root_tls_ctx_num] = SSL_CTX_new(DTLSv1_2_client_method()); SSL_CTX_set_cipher_list(root_tls_ctx[root_tls_ctx_num], csuite); root_tls_ctx_num++; #endif #endif } int sslind = 0; for(sslind = 0; sslind<root_tls_ctx_num; sslind++) { if(cert_file[0]) { if (!SSL_CTX_use_certificate_chain_file(root_tls_ctx[sslind], cert_file)) { TURN_LOG_FUNC(TURN_LOG_LEVEL_ERROR, "\nERROR: no certificate found!\n"); exit(-1); } } if (!SSL_CTX_use_PrivateKey_file(root_tls_ctx[sslind], pkey_file, SSL_FILETYPE_PEM)) { TURN_LOG_FUNC(TURN_LOG_LEVEL_ERROR, "\nERROR: no private key found!\n"); exit(-1); } if(cert_file[0]) { if (!SSL_CTX_check_private_key(root_tls_ctx[sslind])) { TURN_LOG_FUNC(TURN_LOG_LEVEL_ERROR, "\nERROR: invalid private key!\n"); exit(-1); } } if (ca_cert_file[0]) { if (!SSL_CTX_load_verify_locations(root_tls_ctx[sslind], ca_cert_file, NULL )) { TURN_LOG_FUNC(TURN_LOG_LEVEL_ERROR, "ERROR: cannot load CA from file: %s\n", ca_cert_file); } /* Set to require peer (client) certificate verification */ SSL_CTX_set_verify(root_tls_ctx[sslind], SSL_VERIFY_PEER, NULL ); /* Set the verification depth to 9 */ SSL_CTX_set_verify_depth(root_tls_ctx[sslind], 9); } else { SSL_CTX_set_verify(root_tls_ctx[sslind], SSL_VERIFY_NONE, NULL ); } if(!use_tcp) SSL_CTX_set_read_ahead(root_tls_ctx[sslind], 1); } } start_mclient(argv[optind], port, client_ifname, local_addr, messagenumber, mclient); return 0; }
DECLARE_TEST( base64, encode_decode ) { char test_string[2048]; char test_data[1024]; char verify_data[1024]; unsigned int written; char prev_value; char guard_value; for( written = 0; written < 1024; written += 8 ) *(uint64_t*)( test_data + written ) = random64(); //Test encode/decode zero/one blocks { written = base64_encode( test_data, test_string, 1, 1 ); EXPECT_EQ( written, 1 ); EXPECT_EQ( test_string[0], 0 ); guard_value = test_data[0]; written = base64_decode( test_string, test_data, 0, 1 ); EXPECT_EQ( written, 0 ); EXPECT_EQ( guard_value, test_data[0] ); guard_value = test_data[0]; written = base64_decode( test_string, test_data, 1, 1 ); EXPECT_EQ( written, 0 ); EXPECT_EQ( guard_value, test_data[0] ); written = base64_encode( test_data, test_string, 1, 0 ); EXPECT_EQ( written, 5 ); EXPECT_EQ( test_string[2], '=' ); EXPECT_EQ( test_string[3], '=' ); EXPECT_EQ( test_string[4], 0 ); prev_value = test_data[0]; guard_value = test_data[1]; test_data[0] = ~prev_value; written = base64_decode( test_string, test_data, 4, 1 ); EXPECT_EQ( written, 1 ); EXPECT_EQ( prev_value, test_data[0] ); EXPECT_EQ( guard_value, test_data[1] ); prev_value = test_data[0]; guard_value = test_data[1]; test_data[0] = ~prev_value; written = base64_decode( test_string, test_data, 0, 0 ); EXPECT_EQ( written, 1 ); EXPECT_EQ( prev_value, test_data[0] ); EXPECT_EQ( guard_value, test_data[1] ); } //Test encode/decode larger blocks { written = base64_encode( test_data, test_string, 32, 8 ); EXPECT_EQ( written, 5 ); EXPECT_EQ( test_string[4], 0 ); prev_value = test_string[0]; test_string[0] = ~test_string[0]; written = base64_encode( test_data, test_string, 32, 9 ); EXPECT_EQ( written, 9 ); EXPECT_EQ( test_string[8], 0 ); EXPECT_EQ( test_string[0], prev_value ); prev_value = test_string[0]; test_string[0] = ~test_string[0]; written = base64_encode( test_data, test_string, 32, 10 ); EXPECT_EQ( written, 9 ); EXPECT_EQ( test_string[8], 0 ); EXPECT_EQ( test_string[0], prev_value ); prev_value = test_string[0]; test_string[0] = ~test_string[0]; written = base64_encode( test_data, test_string, 31, 45 ); EXPECT_EQ( written, 45 ); EXPECT_EQ( test_string[44], 0 ); EXPECT_EQ( test_string[0], prev_value ); prev_value = test_string[0]; test_string[0] = ~test_string[0]; written = base64_encode( test_data, test_string, 32, 45 ); EXPECT_EQ( written, 45 ); EXPECT_EQ( test_string[44], 0 ); EXPECT_EQ( test_string[0], prev_value ); prev_value = test_string[0]; test_string[0] = ~test_string[0]; written = base64_encode( test_data, test_string, 33, 45 ); EXPECT_EQ( written, 45 ); EXPECT_EQ( test_string[44], 0 ); EXPECT_EQ( test_string[0], prev_value ); prev_value = test_string[0]; test_string[0] = ~test_string[0]; written = base64_encode( test_data, test_string, 32, 64 ); EXPECT_EQ( written, 45 ); EXPECT_EQ( test_string[44], 0 ); EXPECT_EQ( test_string[0], prev_value ); prev_value = test_string[0]; test_string[0] = ~test_string[0]; written = base64_encode( test_data, test_string, 31, 0 ); EXPECT_EQ( written, 45 ); EXPECT_EQ( test_string[44], 0 ); EXPECT_EQ( test_string[0], prev_value ); memset( verify_data, 0, 1024 ); written = base64_decode( test_string, verify_data, 44, 0 ); EXPECT_EQ( written, 31 ); EXPECT_EQ( memcmp( test_data, verify_data, written ), 0 ); prev_value = test_string[0]; test_string[0] = ~test_string[0]; written = base64_encode( test_data, test_string, 32, 0 ); EXPECT_EQ( written, 45 ); EXPECT_EQ( test_string[44], 0 ); EXPECT_EQ( test_string[0], prev_value ); memset( verify_data, 0, 1024 ); written = base64_decode( test_string, verify_data, 44, 0 ); EXPECT_EQ( written, 32 ); EXPECT_EQ( memcmp( test_data, verify_data, written ), 0 ); prev_value = test_string[0]; test_string[0] = ~test_string[0]; written = base64_encode( test_data, test_string, 33, 0 ); EXPECT_EQ( written, 45 ); EXPECT_EQ( test_string[44], 0 ); EXPECT_EQ( test_string[0], prev_value ); memset( verify_data, 0, 1024 ); written = base64_decode( test_string, verify_data, 44, 0 ); EXPECT_EQ( written, 33 ); EXPECT_EQ( memcmp( test_data, verify_data, written ), 0 ); memset( verify_data, 0, 1024 ); written = base64_decode( test_string, verify_data, 44, 33 ); EXPECT_EQ( written, 33 ); EXPECT_EQ( memcmp( test_data, verify_data, written ), 0 ); memset( verify_data, 0, 1024 ); written = base64_decode( test_string, verify_data, 44, 7 ); EXPECT_EQ( written, 7 ); EXPECT_EQ( memcmp( test_data, verify_data, written ), 0 ); memset( verify_data, 0, 1024 ); written = base64_decode( test_string, verify_data, 8, 33 ); EXPECT_EQ( written, 6 ); EXPECT_EQ( memcmp( test_data, verify_data, written ), 0 ); memset( verify_data, 0, 1024 ); written = base64_decode( test_string, verify_data, 0, 33 ); EXPECT_EQ( written, 33 ); EXPECT_EQ( memcmp( test_data, verify_data, written ), 0 ); memset( verify_data, 0, 1024 ); written = base64_decode( test_string, verify_data, 0, 0 ); EXPECT_EQ( written, 33 ); EXPECT_EQ( memcmp( test_data, verify_data, written ), 0 ); prev_value = test_string[5]; test_string[0] = ~test_string[0]; written = base64_encode( test_data, test_string, 1024, 0 ); EXPECT_EQ( written, 1369 ); EXPECT_EQ( test_string[1368], 0 ); EXPECT_EQ( test_string[5], prev_value ); memset( verify_data, 0, 1024 ); written = base64_decode( test_string, verify_data, 1369, 0 ); EXPECT_EQ( written, 1024 ); EXPECT_EQ( memcmp( test_data, verify_data, written ), 0 ); memset( verify_data, 0, 1024 ); written = base64_decode( test_string, verify_data, 1368, 1024 ); EXPECT_EQ( written, 1024 ); EXPECT_EQ( memcmp( test_data, verify_data, written ), 0 ); memset( verify_data, 0, 1024 ); written = base64_decode( test_string, verify_data, 982, 519 ); EXPECT_EQ( written, 519 ); EXPECT_EQ( memcmp( test_data, verify_data, written ), 0 ); memset( verify_data, 0, 1024 ); written = base64_decode( test_string, verify_data, 378, 985 ); EXPECT_EQ( written, 283 ); EXPECT_EQ( memcmp( test_data, verify_data, written ), 0 ); memset( verify_data, 0, 1024 ); written = base64_decode( test_string, verify_data, 0, 1024 ); EXPECT_EQ( written, 1024 ); EXPECT_EQ( memcmp( test_data, verify_data, written ), 0 ); memset( verify_data, 0, 1024 ); written = base64_decode( test_string, verify_data, 0, 0 ); EXPECT_EQ( written, 1024 ); EXPECT_EQ( memcmp( test_data, verify_data, written ), 0 ); } return 0; }
bool CPacket::SearchItem(vector<string>& vStrSearchList, unsigned char* pData, long int lStartAddress, long int lMemorySize, bool bExtraSearch) { bool bSearchResult = false; vector<string>::iterator itr; for(itr = vStrSearchList.begin(); itr < vStrSearchList.end(); itr++) { // 원본 키워드를 얻어온다 string strKeyword = *itr; cout << " [*] TRY TO SEARCH [" << strKeyword << "] " << endl; // ASCII, UNICODE 문자로 변환한다 int nKeywordSize = strKeyword.size(); unsigned char* pStrKeyword = (unsigned char*) malloc(nKeywordSize); unsigned char* pUniKeyword = (unsigned char*) malloc(nKeywordSize * 2); memset(pStrKeyword, 0x00, nKeywordSize ); memset(pUniKeyword, 0x00, nKeywordSize*2); memcpy(pStrKeyword, strKeyword.c_str(), nKeywordSize); for(int i = 0; i < nKeywordSize; i++) pUniKeyword[i*2] = strKeyword[i]; // SEARCHING for String Keyword for(long int i = 0; i < lMemorySize; i++) { if(memcmp(pData+i, pStrKeyword, nKeywordSize) == 0) { //DisplayMemoryData(pData, lStartAddress, i, m_nDisplayMemLineCount, SEARCH_TYPE_STRING); bSearchResult = true; } } // SEARCHING for UNICODE Keyword for(long int i = 0; i < lMemorySize; i++) { if(memcmp(pData+i, pUniKeyword, nKeywordSize * 2) == 0) { //DisplayMemoryData(pData, lStartAddress, i, m_nDisplayMemLineCount, SEARCH_TYPE_UNICODE); bSearchResult = true; } } // EXTRA SEARCH if( bExtraSearch == true ) { // SEARCHING for STRING to BASE64 Keyword string strSTRBase64Keyword = base64_encode(pStrKeyword, nKeywordSize); for(int i = 0; i < lMemorySize; i++) { if(memcmp(pData+i, strSTRBase64Keyword.c_str(), strSTRBase64Keyword.size()) == 0) { //DisplayMemoryData(pData, lStartAddress, i, m_nDisplayMemLineCount, SEARCH_TYPE_BASE64); } } // SEARCHING for UNICODE to BASE64 Keyword string strUNIBase64Keyword = base64_encode(pUniKeyword, nKeywordSize*2); for(int i = 0; i < lMemorySize; i++) { if(memcmp(pData+i, strUNIBase64Keyword.c_str(), strUNIBase64Keyword.size()) == 0) { //DisplayMemoryData(pData, lStartAddress, i, m_nDisplayMemLineCount, SEARCH_TYPE_BASE64); } } // SEARCHING for STRING to MD5 Keyword md5_state_t state; md5_byte_t digest[16]; char hex_output[16*2 + 1]; md5_init(&state); md5_append(&state, (const md5_byte_t*)pStrKeyword, nKeywordSize); md5_finish(&state, digest); //for (int di = 0; di < 16; ++di) //sprintf(hex_output + di * 2, "%02x", digest[di]); //cout << "md5 : " << string(hex_output) << endl; for(int i = 0; i < lMemorySize; i++) { if(memcmp(pData+i, digest, 16) == 0) { //DisplayMemoryData(pData, lStartAddress, i, m_nDisplayMemLineCount, SEARCH_TYPE_BASE64); } } } free(pStrKeyword); free(pUniKeyword); } return bSearchResult; }
int libdc_driver_extract(dev_handle_t abstract, void * buffer, uint32_t size, divedata_callback_fn_t cb, void * userdata) { libdc_device_t dev = (libdc_device_t)(abstract); if (dev == NULL) { errno = EINVAL; return -1; } unsigned char * dive_data; unsigned char * token_data; uint32_t pos = 0; size_t ndives; size_t dlen; size_t tlen; if (size < sizeof(size_t)) { dev->errcode = DRIVER_ERR_INVALID; dev->errmsg = "Invalid or corrupt data in smart_transfer"; return -1; } while (pos < size) { // Extract the Dive Data from the Buffer if (size - pos < sizeof(size_t)) { dev->errcode = DRIVER_ERR_INVALID; dev->errmsg = "Length of dive extends past end of received data in libdc_driver_extract"; return -1; } memcpy(& dlen, buffer + pos, sizeof(size_t)); pos += sizeof(size_t); if (size - pos < dlen) { dev->errcode = DRIVER_ERR_INVALID; dev->errmsg = "Length of dive extends past end of received data in libdc_driver_extract"; return -1; } dive_data = buffer + pos; pos += dlen; if (size - pos < sizeof(size_t)) { dev->errcode = DRIVER_ERR_INVALID; dev->errmsg = "Length of dive extends past end of received data in libdc_driver_extract"; return -1; } memcpy(& tlen, buffer + pos, sizeof(size_t)); pos += sizeof(size_t); if (size - pos < tlen) { dev->errcode = DRIVER_ERR_INVALID; dev->errmsg = "Length of dive extends past end of received data in libdc_driver_extract"; return -1; } token_data = buffer + pos; pos += tlen; // Base64-encode the Token size_t b64len = 0; char * b64token = base64_encode(token_data, tlen, & b64len); // Run the Callback if (cb != NULL) cb(userdata, dive_data, dlen, b64token); } if (pos != size) { dev->errcode = DRIVER_ERR_INVALID; dev->errmsg = "Found additional bytes at end of received data in libdc_driver_extract"; return -1; } return DRIVER_ERR_UNSUPPORTED; }
static void save(int exiting) { int i; time_t now; char *bi, *bo; int n; char hgz[256]; char tmp[128]; _dprintf("save\n"); f_write("/var/lib/misc/rstats-stime", &save_utime, sizeof(save_utime), 0, 0); comp(speed_fn, speed, sizeof(speed[0]) * speed_count); if ((now = time(0)) < Y2K) { _dprintf("time not set\n"); return; } comp(history_fn, &history, sizeof(history)); if (exiting) { _dprintf("exiting=1\n"); return; } _dprintf("save ext\n"); sprintf(hgz, "%s.gz", history_fn); if (strcmp(save_path, "*nvram") == 0) { if (!wait_action_idle(10)) { _dprintf("busy, not saving\n"); return; } if ((n = f_read_alloc(hgz, &bi, 20 * 1024)) > 0) { if ((bo = malloc(base64_encoded_len(n) + 1)) != NULL) { n = base64_encode(bi, bo, n); bo[n] = 0; _dprintf("rstats_data=%s\n", bo); nvram_set("rstats_data", bo); if (!nvram_match("debug_nocommit", "1")) nvram_commit(); free(bo); } } free(bi); } else if (save_path[0] != 0) { strcpy(tmp, save_path); strcat(tmp, "_tmp"); for (i = 15; i > 0; --i) { if (!wait_action_idle(10)) { _dprintf("busy, not saving\n"); } else { _dprintf("copy %s to %s\n", hgz, save_path); if (eval("cp", hgz, tmp) == 0) { _dprintf("copy ok\n"); if (rename(tmp, save_path) == 0) { _dprintf("rename ok\n"); break; } } } // might not be ready sleep(3); } } }