void encodeParameter( FILE *fp, FILE *gp, const char *param, const char *paramName, char *key, unsigned char **rsaString, bool &encrypted ) { int len; unsigned char *cryptedString = NULL; len = encodeByRSA( param, rsaString, &cryptedString ); if ( len > 0 ) { encrypted = true; if ( !(key[0]) ) strcpy( key, base64(*rsaString, strlen((char *)*rsaString)) ); if ( fp ) fprintf( fp, "%sEncrypted: %s\n", paramName, base64( cryptedString, len ) ); if ( gp ) fprintf( gp, "%sEncrypted: %s\n", paramName, base64( cryptedString, len ) ); freeRSAbuffer( (char *)cryptedString ); } else { if ( fp ) fprintf( fp, "%s: %s\n", paramName, param ); } }
void encodeParameter( FILE *fp, // (I/O) 暗号化済みデータ出力先 const char *param, // (I) 暗号化対象データ本体 const char *paramName, // (I) 暗号化対象データ名 char *key, // (I) 暗号生成に利用する公開鍵 unsigned char **rsaString, // (O) 復号に必要な情報(秘密鍵) bool &encrypted ) // (O) 暗号化に成功したか否か { int len; unsigned char *cryptedString = NULL; len = encodeByRSA( param, rsaString, &cryptedString ); if ( len > 0 ) { encrypted = true; if ( !(key[0]) ) strcpy( key, base64(*rsaString, strlen((char *)*rsaString)) ); fprintf( fp, "%sEncrypted: %s\n", paramName, base64( cryptedString, len ) ); freeRSAbuffer( (char *)cryptedString ); } else fprintf( fp, "%s: %s\n", paramName, param ); }
static char *get_request(UrlResource *rsrc) { char *request = NULL; char *auth = NULL; char *tmp_string = NULL; char buf[32]; Url *u; off_t file_size; u = rsrc->url; request = MALLOC(2048); MEMSET(request, 0, 2048); strconcat2(request, "GET ", u->path, u->file, " HTTP/1.0\r\n", "Host: ", u->host, "\r\n", NULL); if ( u->username && u->password ) { tmp_string = strconcat( u->username, ":", u->password, NULL); auth = base64(tmp_string, strlen(tmp_string)); strconcat2(request, "Authorization: Basic ", auth, "\r\n", NULL); FREE(auth); FREE(tmp_string); } if ( rsrc->proxy_username && rsrc->proxy_password ) { tmp_string = strconcat( rsrc->proxy_username, ":", rsrc->proxy_password, NULL); auth = base64(tmp_string, strlen(tmp_string)); strconcat2(request, "Proxy-Authorization: Basic ", auth, "\r\n", NULL); FREE(auth); FREE(tmp_string); } if ((rsrc->options & OPT_RESUME) && (rsrc->outfile_offset > 0)) { sprintf(buf, "%ld-", (long int )rsrc->outfile_offset); strconcat2(request, "Range: bytes=", buf, "\r\n", NULL); } /* Use user's SNARF_HTTP_USER_AGENT env. var if present, as they might want to spoof some discriminant sites. (Or just increase the hit count for their favorite browser.) Alternately, use Mozilla or MSIE's User-Agent strings based on options set. */ strconcat2(request, "User-Agent: ", NULL); strconcat2(request, MSIE_USER_AGENT, NULL); //strconcat2(request, "\r\nConnection: Keep-Alive", NULL); /* This CRLF pair closes the User-Agent key-value set. */ strconcat2(request, "\r\n", NULL); strconcat2(request, "\r\n", NULL); return request; }
NOEXPORT char *ntlm3(char *username, char *password, char *phase2) { MD4_CTX md4; char *decoded; /* decoded reply from proxy */ char phase3[146]; unsigned char md4_hash[21]; unsigned int userlen=strlen(username); unsigned int phase3len=s_min(88+userlen, sizeof phase3); /* setup phase3 structure */ memset(phase3, 0, sizeof phase3); strcpy(phase3, "NTLMSSP"); phase3[8]=3; /* type: 3 */ phase3[16]=phase3len; /* LM-resp off */ phase3[20]=24; /* NT-resp len */ phase3[22]=24; /* NT-Resp len */ phase3[24]=64; /* NT-resp off */ phase3[32]=phase3len; /* domain offset */ phase3[36]=userlen; /* user length */ phase3[38]=userlen; /* user length */ phase3[40]=88; /* user offset */ phase3[48]=phase3len; /* host offset */ phase3[56]=phase3len; /* message len */ phase3[60]=2; /* flag: negotiate OEM */ phase3[61]=2; /* flag: negotiate NTLM */ /* calculate MD4 of UTF-16 encoded password */ MD4_Init(&md4); while(*password) { MD4_Update(&md4, password++, 1); MD4_Update(&md4, "", 1); /* UTF-16 */ } MD4_Final(md4_hash, &md4); memset(md4_hash+16, 0, 5); /* pad to 21 bytes */ /* decode challenge and calculate response */ decoded=base64(0, phase2, strlen(phase2)); /* decode */ if(!decoded) return NULL; crypt_DES((unsigned char *)phase3+64, (unsigned char *)decoded+24, md4_hash); crypt_DES((unsigned char *)phase3+72, (unsigned char *)decoded+24, md4_hash+7); crypt_DES((unsigned char *)phase3+80, (unsigned char *)decoded+24, md4_hash+14); str_free(decoded); strncpy(phase3+88, username, sizeof phase3-88); return base64(1, phase3, phase3len); /* encode */ }
char *cipher_base64(const char *bytes, size_t len) { _cleanup_free_ char *iv = NULL; _cleanup_free_ char *data = NULL; char *output; if (len >= 33 && bytes[0] == '!' && len % 16 == 1) { iv = base64(bytes + 1, 16); data = base64(bytes + 17, len - 17); xasprintf(&output, "!%s|%s", iv, data); return output; } return base64(bytes, len); }
static void http_head(http_t *http, const char *field, const char *value) { static char hash[20] = {}; static char extra[] = "258EAFA5-E914-47DA-95CA-C5AB0DC85B11"; trace(" http_head: %-20s -> [%s]", field, value); if (!strcasecmp(field, "Upgrade")) { http->hdr_upgrade = !!strcasestr(value, "websocket"); } else if (!strcasecmp(field, "Connection")) { http->hdr_connect = !!strcasestr(value, "upgrade"); } else if (!strcasecmp(field, "Sec-WebSocket-Key")) { #ifdef USE_GNUTLS gnutls_hash_hd_t sha1; gnutls_hash_init(&sha1, GNUTLS_DIG_SHA1); gnutls_hash(sha1, value, strlen(value)); gnutls_hash(sha1, extra, strlen(extra)); gnutls_hash_output(sha1, hash); #endif #ifdef USE_OPENSSL SHA_CTX sha1; SHA1_Init(&sha1); SHA1_Update(&sha1, value, strlen(value)); SHA1_Update(&sha1, extra, strlen(extra)); SHA1_Final((unsigned char*)hash, &sha1); #endif http->hdr_accept = base64(hash, sizeof(hash), http->hdr_key, sizeof(http->hdr_key)); } }
/** * @brief get the command line corresponding to a process * @param pid process id * @return a base64 encoded string with the process command line, or * an empty string if it could not be extrcated **/ static char* get_command_line(int pid) { size_t size = 256; size_t i = 0; char* path; FILE* f; char c; char* string = (char*) malloc(size); char* b64; asprintf(&path, "/proc/%d/cmdline", pid); if((f = fopen(path, "r")) != NULL) { while((c = fgetc(f)) != EOF) { if(c == 0) c = ' '; if(i >= (size - 1)) { size += 256; char* string = (char*) realloc(string, size); } string[i++] = c; } fclose(f); } string[i] = 0; free(path); b64 = base64(string, strlen(string)); free(string); return b64; }
/* Examine a Basic auth challenge. * Returns 0 if an valid challenge, else non-zero. */ static int basic_challenge(http_auth_session *sess, struct http_auth_chall *parms) { char *tmp, *password; /* Verify challenge... must have a realm */ if (parms->realm == NULL) { return -1; } DEBUG(DEBUG_HTTPAUTH, "Got Basic challenge with realm [%s]\n", parms->realm); clean_session(sess); sess->unq_realm = shave_string(parms->realm, '"'); if (get_credentials(sess, &password)) { /* Failed to get credentials */ HTTP_FREE(sess->unq_realm); return -1; } sess->scheme = http_auth_scheme_basic; CONCAT3(tmp, sess->username, ":", password?password:""); sess->basic = base64(tmp); free(tmp); HTTP_FREE(password); return 0; }
// ***************************************************************************** // * * // * Function: TokenKeyContents::populate * // * * // * Populates fields of a token key using information from current * // * process (node, PID, etc.) and encoding (base64). * // * * // ***************************************************************************** void TokenKeyContents::populate() { msg_mon_get_my_process_name(u.token.processName, MS_MON_MAX_PROCESS_NAME); msg_mon_get_process_info( NULL, &u.token.nodeId, &u.token.processId ); ID[0] = USERTOKEN_ID_1; ID[1] = USERTOKEN_ID_2; // Generate Random bytes srandom ((unsigned)time(NULL)); for (int i=0; i < sizeof(u.token.rand); i++) u.token.rand[i] = (char)(random() & 0xFF); // Base 64 encoding char buf[sizeof(u)]= {0}; base64((const char *)&u.token, sizeof(u.token), buf, true); memcpy(u.encoded.b64, buf, sizeof(u.encoded.b64)); u.encoded.zero='\0'; }
// ***************************************************************************** // * * // * Function: TokenKey::verify * // * * // * Determines if a token key is valid. * // * * // ***************************************************************************** // * * // * Parameters: * // * * // * <tokenKey> TokenKey & In * // * is the token key to be validated against. * // * * // ***************************************************************************** bool TokenKey::verify(TokenKey &tokenKey) const { // Check to see that the process name matches with the node ID and process IDd int retval = XZFIL_ERR_OK; int nid, pid, decoded_nid, decoded_pid; if (!(*this == tokenKey)) return false; // decode the token to get the process info TokenKeyContents decoded_token; base64((const char *) self.u.encoded.b64,sizeof(self.u.encoded.b64), (char *) decoded_token.u.encoded.b64,false); retval = msg_mon_get_process_info(decoded_token.u.token.processName,&nid,&pid); decoded_nid = decoded_token.u.token.nodeId; decoded_pid = decoded_token.u.token.processId; if ((retval == XZFIL_ERR_OK) && (nid == decoded_nid) && (pid == decoded_pid)) return true; return false; }
// ***************************************************************************** // * * // * Function: TokenKey::getTokenKeyAsString * // * Returns the Token Key as a formatted ASCII string. * // * * // ***************************************************************************** // * * // * Parameters: * // * * // * <tokenKeyString> char * Out * // * returns the Token Key as a formatted ASCII string. * // * * // ***************************************************************************** void TokenKey::getTokenKeyAsString(char *tokenKeyString) const { TokenKeyContents decoded; base64((const char *) self.u.encoded.b64,sizeof(self.u.encoded.b64), (char *) decoded.u.encoded.b64,false); int count = sprintf(tokenKeyString, "ID = '0x%X,0x%X'\nNode ID = %d\nProcess ID = %d\n", self.ID[0],self.ID[1],decoded.u.token.nodeId, decoded.u.token.processId); char *ptr = &tokenKeyString[count]; strcpy(ptr,"Random value = 0x"); ptr += strlen(ptr); for (size_t i = 0; i < sizeof(self.u.token.rand) / sizeof(self.u.token.rand[0]); i ++) { count = sprintf(ptr,"%X",decoded.u.token.rand[i]); ptr += count; } strcpy(ptr,"\nEncoded value = "); strcat(ptr,self.u.encoded.b64); }
/** * @brief actually does the write to kafka of a string with the given * file path * @param path file path to save to kafka * @param buf write buffer * @param size size of the buffer to write * @param offset starting point in the buffer * @return 0 if the write succeeded, 1 otherwise **/ static int actual_kafka_write(const char *path, const char *buf, size_t size, off_t offset) { char* ret = NULL; (void) path; char timestamp[] = "YYYY-MM-ddTHH:mm:ss.SSS+0000"; char* text = base64(buf, size); struct fuse_context* context = fuse_get_context(); struct group* sgroup = getgrgid(context->gid); struct passwd* suser = getpwuid(context->uid); char* user = suser == NULL ? "":suser->pw_name; char* group = sgroup == NULL ? "":sgroup->gr_name; char* command = get_command_line(context->pid); char* format = "{\"path\": \"%s%s\", \"pid\": %d, \"uid\": %d, " "\"gid\": %d, \"@message\": \"%s\", \"@timestamp\": \"%s\"," "\"user\": \"%s\", \"group\": \"%s\", \"command\": \"%s\"," "\"@version\": \"%s\", \"@fields\": %s, \"@tags\": %s}"; kafka_t *private_data = (kafka_t*) fuse_get_context()->private_data; config* conf = (config*)private_data->conf; set_timestamp(timestamp); asprintf(&ret, format, conf->directories[conf->directory_n], path + 1, context->pid, context->uid, context->gid, text, timestamp, user, group, command, VERSION, conf->fields_s, conf->tags_s); free(command); free(text); if (ret == NULL) { fprintf(stderr, "Error in asprintf\n"); return 1; } send_kafka(context->private_data, ret, strlen(ret)); free(ret); return 0; }
/* * Create Server's accept key in *dst*. * *client_key* is the value of |Sec-WebSocket-Key| header field in * client's handshake and it must be length of 24. */ char * create_accept_key(const char *client_key) { uint8_t sha1buf[20], key_src[60]; memcpy(key_src, client_key, 24); memcpy(key_src+24, WS_GUID, 36); sha1(sha1buf, key_src, sizeof(key_src)); return base64(sha1buf, 20); }
/* Returns cnonce-value. We just use base64(time). * TODO: Could improve this? */ static char *get_cnonce(void) { char *ret, *tmp; tmp = rfc1123_date(time(NULL)); ret = base64(tmp); free(tmp); return ret; }
int main(int argc, char **argv) { char *input = strcat(strcat(argv[1], "\n"), "\0"); char *output = base64((unsigned char *)input, strlen(input)); printf("Base64: %s\n", output); free(output); return 0; }
/* * Create Server's accept key in *dst*. * *client_key* is the value of |Sec-WebSocket-Key| header field in * client's handshake and it must be length of 24. * *dst* must be at least BASE64_ENCODE_RAW_LENGTH(20)+1. */ void create_accept_key(char *dst, const char *client_key) { uint8_t sha1buf[20], key_src[60]; memcpy(key_src, client_key, 24); memcpy(key_src+24, WS_GUID, 36); sha1(sha1buf, key_src, sizeof(key_src)); base64((uint8_t*)dst, sha1buf, 20); dst[BASE64_ENCODE_RAW_LENGTH(20)] = '\0'; }
void buff_read_cb(struct bufferevent *bev, void *ctx) { struct evbuffer *input = bufferevent_get_input(bev); size_t recvlen = evbuffer_get_length(input); // not enough size of a header if (recvlen < (sizeof(pdu_header) + 1)) { //LOG(INFO) << "not enough size of a header"; return; } uint8_t head_data[sizeof(pdu_header)+1]; evbuffer_copyout(input, head_data, sizeof(pdu_header)+1); struct pdu_header* ptr_header = (struct pdu_header *) (head_data+1); // not enough size of a complete package if (ptr_header->length > recvlen) { //LOG(INFO) << "not enough size, header->length["<<ptr_header->length <<"] received["<<recvlen<<"]" ; return; } else { //LOG(INFO) << "receive size["<< recvlen << "]" ; } void* pdu_data = malloc(ptr_header->length); if (pdu_data == NULL) { LOG(ERROR)<< "malloc failed for pdu data"; return; } std::shared_ptr<void> ap_pdu_data(pdu_data, free); evbuffer_remove(input, pdu_data, ptr_header->length); LOG(INFO) << "package content: " << bin2hex((uint8_t*)pdu_data, ptr_header->length); bool valid = valid_pdu_package(pdu_data, ptr_header->length); if (!valid) { LOG(WARNING) << "not a valid pdu package"; return; } LOG(INFO) << "received complete package"; bufferevent_disable(bev, EV_READ); char* resp_data; //Base64Encode((const unsigned char *)pdu_data, ptr_header->length, &resp_data); uint8_t *pdu_body = (uint8_t *)pdu_data + 1 +sizeof(pdu_header); size_t body_length = ptr_header->length - 2 - sizeof(ptr_header); resp_data = base64((const unsigned char *)pdu_body, body_length); LOG(INFO) << "base64 encode: " << resp_data; std::shared_ptr<void> ap_resp_data(resp_data, free); struct evbuffer* write_evbuf = evbuffer_new(); evbuffer_add_pdu(write_evbuf, resp_data, strlen(resp_data)+1); bufferevent_write_buffer(bev,write_evbuf); evbuffer_free(write_evbuf); bufferevent_enable(bev, EV_WRITE); }
NOEXPORT char *ntlm1() { char phase1[16]; memset(phase1, 0, sizeof phase1); strcpy(phase1, "NTLMSSP"); phase1[8]=1; /* type: 1 */ phase1[12]=2; /* flag: negotiate OEM */ phase1[13]=2; /* flag: negotiate NTLM */ return base64(1, phase1, sizeof phase1); /* encode */ }
std::string WebSocket::createKey() { Poco::Random rnd; std::ostringstream ostr; Poco::Base64Encoder base64(ostr); Poco::BinaryWriter writer(base64); writer << rnd.next() << rnd.next() << rnd.next() << rnd.next(); base64.close(); return ostr.str(); }
// Reads MessagePack bin bytes and outputs a JSON base64 string static bool base64_bin(mpack_reader_t* reader, yajl_gen gen, options_t* options, uint32_t len, bool prefix) { uint32_t new_len = base64_len(len) + (prefix ? strlen(b64_str) : 0); char* output = (char*)malloc(new_len); bool ret = base64(reader, gen, options, len, output, output, prefix); mpack_done_bin(reader); free(output); return ret; }
char * build_signature(const char * method, const char * path, const struct curl_slist *headers, const char * secret) { int signature_length = 0; char * data = canonical_string(method, path, headers); debug("cs = '%s'", data); char *signature = hmac(secret, data, &signature_length); char *base64_sig = base64(signature, signature_length); free(data); free(signature); return base64_sig; }
std::string WebSocket::computeAccept(const std::string& key) { std::string accept(key); accept += WEBSOCKET_GUID; Poco::SHA1Engine sha1; sha1.update(accept); Poco::DigestEngine::Digest d = sha1.digest(); std::ostringstream ostr; Poco::Base64Encoder base64(ostr); base64.write(reinterpret_cast<const char*>(&d[0]), d.size()); base64.close(); return ostr.str(); }
bool validate(char *raw_str, char *file){ FILE *f = fopen(file, "r"); char line[AUTH_LEN]; sscanf(raw_str, "%*[^ ]%*[ ] %s", raw_str);//By now, only basic auth can be applied while(fgets(line, AUTH_LEN, f)) { line[strlen(line) - 1] = 0; char *enc = (char*)base64(line); if(strcmp(enc, raw_str) == 0) return 1; uws_free(enc); } fclose(f); return 0; }
std::string base64Encode(const std::string& unencoded) { std::stringstream os; if (unencoded.size() == 0) { return std::string(); } unsigned int writePaddChars = (3-unencoded.length()%3)%3; std::string base64(it_base64(unencoded.begin()), it_base64(unencoded.end())); base64.append(writePaddChars,'='); os << base64; return os.str(); }
NOEXPORT void connect_client(CLI *c) { char *line, *encoded; if(!c->opt->protocol_host) { s_log(LOG_ERR, "protocolHost not specified"); longjmp(c->err, 1); } fd_printf(c, c->remote_fd.fd, "CONNECT %s HTTP/1.1", c->opt->protocol_host); fd_printf(c, c->remote_fd.fd, "Host: %s", c->opt->protocol_host); if(c->opt->protocol_username && c->opt->protocol_password) { if(!strcasecmp(c->opt->protocol_authentication, "ntlm")) { #if !defined(OPENSSL_NO_MD4) && OPENSSL_VERSION_NUMBER>=0x0090700fL ntlm(c); #else s_log(LOG_ERR, "NTLM authentication is not available"); longjmp(c->err, 1); #endif } else { /* basic authentication */ line=str_printf("%s:%s", c->opt->protocol_username, c->opt->protocol_password); encoded=base64(1, line, strlen(line)); str_free(line); if(!encoded) { s_log(LOG_ERR, "Base64 encoder failed"); longjmp(c->err, 1); } fd_printf(c, c->remote_fd.fd, "Proxy-Authorization: basic %s", encoded); str_free(encoded); } } fd_putline(c, c->remote_fd.fd, ""); /* empty line */ line=fd_getline(c, c->remote_fd.fd); if(!is_prefix(line, "HTTP/1.0 2") && !is_prefix(line, "HTTP/1.1 2")) { /* not "HTTP/1.x 2xx Connection established" */ s_log(LOG_ERR, "CONNECT request rejected"); do { /* read all headers */ str_free(line); line=fd_getline(c, c->remote_fd.fd); } while(*line); str_free(line); longjmp(c->err, 1); } s_log(LOG_INFO, "CONNECT request accepted"); do { str_free(line); line=fd_getline(c, c->remote_fd.fd); /* read all headers */ } while(*line); str_free(line); }
// {{{ socket_open() int socket_open(const char *host, const char *url, size_t port, const char *credentials) { struct hostent *hn; if ((hn = gethostbyname(host))==0) return -1; char *ip = inet_ntoa(*(struct in_addr *)*hn->h_addr_list); struct sockaddr_in pin; memset (&pin, 0, sizeof(pin)); pin.sin_family = AF_INET; pin.sin_addr.s_addr = htonl(INADDR_ANY); pin.sin_port = htons(port); inet_pton(AF_INET, ip, &pin.sin_addr); int sockfd = socket (AF_INET, SOCK_STREAM, 0); if (sockfd == -1) return -2; if(connect(sockfd, (void *)&pin, sizeof(pin))==-1) return -3; char buffer[2048]; char b64[256]; if(strlen(credentials)>0) { base64(credentials, b64, sizeof(b64)); //syslog(LOG_NOTICE, "send credentials: %s|%s\n", credentials, b64); snprintf(buffer, sizeof(buffer), "GET %s HTTP/1.1\r\n" "Authorization: Basic %s\r\n\r\n" , url, b64); } else { //syslog(LOG_NOTICE, "no credentials\n"); snprintf(buffer, sizeof(buffer), "GET %s HTTP/1.1\r\n\r\n", url); } write(sockfd, buffer, strlen(buffer)); return sockfd; }
/** * Sign a string * * @param sdb the SimpleDB handle * @param str the string to sign * @param buffer the buffer to write the signature to (must be at least EVP_MAX_MD_SIZE * 2 bytes) * @param plen the pointer to the place to store the length of the signature (can be NULL) * @return SDB_OK if no errors occurred */ int sdb_sign(struct SDB* sdb, const char* str, char* buffer, size_t* plen) { unsigned char md[EVP_MAX_MD_SIZE]; unsigned mdl; HMAC(EVP_sha256(), sdb->sdb_secret, sdb->sdb_secret_len, (const unsigned char*) str, strlen(str), md, &mdl); size_t l = base64(md, mdl, buffer, EVP_MAX_MD_SIZE * 2); if (l == 0) return SDB_E_OPEN_SSL_FAILED; if (plen != NULL) *plen = l; return SDB_OK; }
QStringList StubKeyring::getStoredAccounts(QString service) { service = base64(service).append('/'); QStringList out; QStringList in(m_settings.allKeys()); QStringListIterator it(in); while (it.hasNext()) { QString c = it.next(); if (c.startsWith(service)) out << unscramble64(c.mid(service.length())); } return out; }
// to see the format of the charts.xml file, look at the serialize() // function at the bottom of this source file. bool LTMChartParser::endElement( const QString&, const QString&, const QString &qName ) { // // Single Attribute elements // if(qName == "chart") { QString string = buffer.mid(1,buffer.length()-2); QByteArray base64(string.toLatin1()); QByteArray unmarshall = QByteArray::fromBase64(base64); QDataStream s(&unmarshall, QIODevice::ReadOnly); LTMSettings x; s >> x; settings << x; }
// Reads MessagePack ext bytes and outputs a JSON base64 string static bool base64_ext(mpack_reader_t* reader, yajl_gen gen, options_t* options, int8_t exttype, uint32_t len) { uint32_t new_len = base64_len(len) + strlen(ext_str) + 5 + strlen(b64_str); char* output = (char*)malloc(new_len); char* p = output; strcpy(p, ext_str); p += strlen(ext_str); sprintf(p, "%i", exttype); p += strlen(p); *p++ = ':'; bool ret = base64(reader, gen, options, len, output, p, true); mpack_done_ext(reader); free(output); return ret; }