/** Initialize the SSL context. * \return pointer to SSL context object. */ SSL_CTX * ssl_init(char *private_key_file, char *ca_file, int req_client_cert) { const SSL_METHOD *meth; /* If this const gives you a warning, you're using an old version of OpenSSL. */ unsigned char context[128]; DH *dh; unsigned int reps = 1; if (!bio_err) { if (!SSL_library_init()) return NULL; SSL_load_error_strings(); /* Error write context */ bio_err = BIO_new_fp(stderr, BIO_NOCLOSE); } do_rawlog(LT_ERR, "Seeding OpenSSL random number pool."); while (!RAND_status()) { /* At this point, a system with /dev/urandom or a EGD file in the usual places will have enough entropy. Otherwise, be lazy and use random numbers until it's satisfied. */ uint32_t gibberish[4]; int n; for (n = 0; n < 4; n++) gibberish[n] = gen_rand32(); RAND_seed(gibberish, sizeof gibberish); reps += 1; } do_rawlog(LT_ERR, "Seeded after %u %s.", reps, reps > 1 ? "cycles" : "cycle"); /* Set up SIGPIPE handler here? */ /* Create context */ meth = SSLv23_server_method(); ctx = SSL_CTX_new(meth); /* Load keys/certs */ if (private_key_file && *private_key_file) { if (!SSL_CTX_use_certificate_chain_file(ctx, private_key_file)) { ssl_errordump ("Unable to load server certificate - only anonymous ciphers supported."); } if (!SSL_CTX_use_PrivateKey_file(ctx, private_key_file, SSL_FILETYPE_PEM)) { ssl_errordump ("Unable to load private key - only anonymous ciphers supported."); } } /* Load trusted CAs */ if (ca_file && *ca_file) { if (!SSL_CTX_load_verify_locations(ctx, ca_file, NULL)) { ssl_errordump("Unable to load CA certificates"); } else { if (req_client_cert) SSL_CTX_set_verify(ctx, SSL_VERIFY_PEER | SSL_VERIFY_FAIL_IF_NO_PEER_CERT, client_verify_callback); else SSL_CTX_set_verify(ctx, SSL_VERIFY_PEER, client_verify_callback); #if (OPENSSL_VERSION_NUMBER < 0x0090600fL) SSL_CTX_set_verify_depth(ctx, 1); #endif } } SSL_CTX_set_options(ctx, SSL_OP_SINGLE_DH_USE | SSL_OP_ALL); SSL_CTX_set_mode(ctx, SSL_MODE_ENABLE_PARTIAL_WRITE | SSL_MODE_ACCEPT_MOVING_WRITE_BUFFER); /* Set up DH callback */ dh = get_dh1024(); SSL_CTX_set_tmp_dh(ctx, dh); /* The above function makes a private copy of this */ DH_free(dh); /* Set the cipher list to the usual default list, except that * we'll allow anonymous diffie-hellman, too. */ SSL_CTX_set_cipher_list(ctx, "ALL:ADH:RC4+RSA:+SSLv2:@STRENGTH"); /* Set up session cache if we can */ strncpy((char *) context, MUDNAME, 128); SSL_CTX_set_session_id_context(ctx, context, u_strlen(context)); /* Load hash algorithms */ OpenSSL_add_all_digests(); return ctx; }
/** * Plugin open (init) */ OPENVPN_EXPORT openvpn_plugin_handle_t openvpn_plugin_open_v1 (unsigned int *type_mask, const char *argv[], const char *envp[]) { OpenSSL_add_all_digests(); /* * We are only interested in intercepting the * --auth-user-pass-verify callback. */ *type_mask = OPENVPN_PLUGIN_MASK (OPENVPN_PLUGIN_AUTH_USER_PASS_VERIFY); /* * Set up configuration variables * */ const char * cfg_otp_secrets = get_env("otp_secrets", argv); if (cfg_otp_secrets != NULL) { otp_secrets = strdup(cfg_otp_secrets); } LOG("OTP-AUTH: otp_secrets=%s\n", otp_secrets); const char * cfg_hotp_counter_file = get_env("hotp_counters", argv); if (cfg_hotp_counter_file != NULL) { hotp_counters = strdup(cfg_hotp_counter_file); } LOG("OTP-AUTH: hotp_counters=%s\n", hotp_counters); const char * cfg_otp_slop = get_env("otp_slop", argv); if (cfg_otp_slop != NULL) { otp_slop = atoi(cfg_otp_slop); } LOG("OTP-AUTH: otp_slop=%i\n", otp_slop); const char * cfg_totp_t0 = get_env("totp_t0", argv); if (cfg_totp_t0 != NULL) { totp_t0 = atoi(cfg_totp_t0); } LOG("OTP-AUTH: totp_t0=%i\n", totp_t0); const char * cfg_totp_step= get_env("totp_step", argv); if (cfg_totp_step != NULL) { totp_step = atoi(cfg_totp_step); } LOG("OTP-AUTH: totp_step=%i\n", totp_step); const char * cfg_totp_digits = get_env("totp_digits", argv); if (cfg_totp_digits != NULL) { totp_digits = atoi(cfg_totp_digits); } LOG("OTP-AUTH: totp_digits=%i\n", totp_digits); const char * cfg_motp_step = get_env("motp_step", argv); if (cfg_motp_step != NULL) { motp_step = atoi(cfg_motp_step); } LOG("OTP-AUTH: motp_step=%i\n", motp_step); const char * cfg_hotp_syncwindow = get_env("hotp_syncwindow", argv); if (cfg_hotp_syncwindow != NULL) { hotp_syncwindow = atoi(cfg_hotp_syncwindow); } LOG("OTP-AUTH: hotp_syncwindow=%i\n", hotp_syncwindow); return (openvpn_plugin_handle_t) otp_secrets; }
int main(int argc,char **argv) { const char *szTestFile; FILE *f; if(argc != 2) { fprintf(stderr,"%s <test file>\n",argv[0]); EXIT(1); } CRYPTO_malloc_debug_init(); CRYPTO_set_mem_debug_options(V_CRYPTO_MDEBUG_ALL); CRYPTO_mem_ctrl(CRYPTO_MEM_CHECK_ON); szTestFile=argv[1]; f=fopen(szTestFile,"r"); if(!f) { perror(szTestFile); EXIT(2); } /* Load up the software EVP_CIPHER and EVP_MD definitions */ OpenSSL_add_all_ciphers(); OpenSSL_add_all_digests(); #ifndef OPENSSL_NO_ENGINE /* Load all compiled-in ENGINEs */ ENGINE_load_builtin_engines(); #endif #if 0 OPENSSL_config(); #endif #ifndef OPENSSL_NO_ENGINE /* Register all available ENGINE implementations of ciphers and digests. * This could perhaps be changed to "ENGINE_register_all_complete()"? */ ENGINE_register_all_ciphers(); ENGINE_register_all_digests(); /* If we add command-line options, this statement should be switchable. * It'll prevent ENGINEs being ENGINE_init()ialised for cipher/digest use if * they weren't already initialised. */ /* ENGINE_set_cipher_flags(ENGINE_CIPHER_FLAG_NOINIT); */ #endif for( ; ; ) { char line[4096]; char *p; char *cipher; unsigned char *iv,*key,*plaintext,*ciphertext; int encdec; int kn,in,pn,cn; if(!fgets((char *)line,sizeof line,f)) break; if(line[0] == '#' || line[0] == '\n') continue; p=line; cipher=sstrsep(&p,":"); key=ustrsep(&p,":"); iv=ustrsep(&p,":"); plaintext=ustrsep(&p,":"); ciphertext=ustrsep(&p,":"); if (p[-1] == '\n') { p[-1] = '\0'; encdec = -1; } else { encdec = atoi(sstrsep(&p,"\n")); } kn=convert(key); in=convert(iv); pn=convert(plaintext); cn=convert(ciphertext); if(!test_cipher(cipher,key,kn,iv,in,plaintext,pn,ciphertext,cn,encdec) && !test_digest(cipher,plaintext,pn,ciphertext,cn)) { #ifdef OPENSSL_NO_AES if (strstr(cipher, "AES") == cipher) { fprintf(stdout, "Cipher disabled, skipping %s\n", cipher); continue; } #endif #ifdef OPENSSL_NO_DES if (strstr(cipher, "DES") == cipher) { fprintf(stdout, "Cipher disabled, skipping %s\n", cipher); continue; } #endif #ifdef OPENSSL_NO_RC4 if (strstr(cipher, "RC4") == cipher) { fprintf(stdout, "Cipher disabled, skipping %s\n", cipher); continue; } #endif #ifdef OPENSSL_NO_CAMELLIA if (strstr(cipher, "CAMELLIA") == cipher) { fprintf(stdout, "Cipher disabled, skipping %s\n", cipher); continue; } #endif #ifdef OPENSSL_NO_SEED if (strstr(cipher, "SEED") == cipher) { fprintf(stdout, "Cipher disabled, skipping %s\n", cipher); continue; } #endif fprintf(stderr,"Can't find %s\n",cipher); EXIT(3); } } fclose(f); #ifndef OPENSSL_NO_ENGINE ENGINE_cleanup(); #endif EVP_cleanup(); CRYPTO_cleanup_all_ex_data(); ERR_remove_thread_state(NULL); ERR_free_strings(); CRYPTO_mem_leaks_fp(stderr); return 0; }
int main() { struct sockaddr_in server; struct sockaddr_in dest; int socket_fd, client_fd,num; socklen_t size; SSL_CTX *ctx; /******* START SSL ***************/ /* http://mooon.blog.51cto.com/1246491/909932 */ /* SSL Libraries Init */ SSL_library_init(); /* add all SSL algorithms */ OpenSSL_add_all_algorithms(); /* add all SSL ciphers */ OpenSSL_add_all_ciphers(); /* add all digests */ OpenSSL_add_all_digests(); /* load all SSL errors */ SSL_load_error_strings(); /* Build SSL_CTX -> SSL Content Text * SSLv2_server_method() or SSLv3_server_method() relative to SSL V2 * and SSL V3 */ ctx = SSL_CTX_new(SSLv23_server_method()); if(ctx == NULL){ ERR_print_errors_fp(stdout); exit(EXIT_FAILURE); } /* Load the server certificate into the SSL_CTX structure */ if(SSL_CTX_use_certificate_file(ctx,RSA_SERVER_CERT,SSL_FILETYPE_PEM) <= 0){ ERR_print_errors_fp(stdout); exit(EXIT_FAILURE); } /* Load the private-key corresponding to the server certificate */ if(SSL_CTX_use_PrivateKey_file(ctx,RSA_SERVER_KEY,SSL_FILETYPE_PEM) <= 0){ ERR_print_errors_fp(stdout); exit(EXIT_FAILURE); } /* Check if the server certificate and private-key matches */ if(!SSL_CTX_check_private_key(ctx)){ ERR_print_errors_fp(stdout); exit(EXIT_FAILURE); } /*********** END SSL ****************/ int yes =1; /* Open a socket to listen */ if ((socket_fd = socket(AF_INET, SOCK_STREAM, 0))== -1) { fprintf(stderr, "Socket failure!!\n"); exit(EXIT_FAILURE); } if (setsockopt(socket_fd, SOL_SOCKET, SO_REUSEADDR, &yes, sizeof(int)) == -1) { perror("setsockopt"); exit(EXIT_FAILURE); } /* init memory for server and dest */ memset(&server, 0, sizeof(server)); memset(&dest,0,sizeof(dest)); server.sin_family = AF_INET; //same to PF_INET server.sin_port = htons(PORT); server.sin_addr.s_addr = INADDR_ANY; /* BIND SOCKET */ if ((bind(socket_fd, (struct sockaddr *)&server, sizeof(struct sockaddr )))== -1) { //sizeof(struct sockaddr) fprintf(stderr, "Binding Failure\n"); exit(EXIT_FAILURE); } /* START LISTENING */ if ((listen(socket_fd, BACKLOG))== -1){ fprintf(stderr, "Listening Failure\n"); exit(EXIT_FAILURE); } while(1) { SSL *ssl; size = sizeof(struct sockaddr_in); /* Waiting for client to connect */ if ((client_fd = accept(socket_fd, (struct sockaddr *)&dest, &size))==-1 ) { perror("accept"); continue; //exit(EXIT_FAILURE); } else{ printf("Server got connection from client %s, port %d, socket %d\n", inet_ntoa(dest.sin_addr),ntohs(dest.sin_port),client_fd); } /* /connection complete */ /* create a new ssl based on ctx */ ssl = SSL_new(ctx); /* add socket : client_fd to SSL */ SSL_set_fd(ssl,client_fd); /* Build up SSL connection */ if(SSL_accept(ssl) == -1){ perror("accept"); SSL_shutdown(ssl); SSL_free(ssl); close(client_fd); continue; //exit(EXIT_FAILURE); } /******* START PROCESSING DATA *************/ /* read header - then do action based on header parsing */ char header_buf[HEADER_SIZE]; int len = HEADER_SIZE; if ((num = recv_all(ssl, (unsigned char *)header_buf, &len))== -1) { printf("Read header failed\n"); perror("recv"); SSL_shutdown(ssl); SSL_free(ssl); close(client_fd); continue; //exit(EXIT_FAILURE); } char *hr = NULL; hr = malloc(3); SSL_read(ssl, hr, sizeof(hr)); if(strcmp("100",hr)){ printf("Header receiving failed\n"); SSL_write(ssl,"-1",strlen("-1")); /* Close SSL Connection */ SSL_shutdown(ssl); /* Release SSL */ SSL_free(ssl); //Close Connection Socket close(client_fd); continue; } else{ printf("Header received successfully\n"); } /* unpack header string */ header h; if (unpack_header_string(header_buf, &h) == -1) { fprintf(stderr, "[SERVER] Could not unpack header information from client\n"); h.action = FAIL_ERROR; //exit(EXIT_FAILURE); } if (h.action == FAIL_ERROR) { printf("Header action is FAIL ERROR\n"); SSL_write(ssl,"-1",strlen("-1")); /* Close SSL Connection */ SSL_shutdown(ssl); /* Release SSL */ SSL_free(ssl); //Close Connection Socket close(client_fd); continue; } //inform client header unpacked successfully SSL_write(ssl,"100",strlen("100")); printf("Header unpacked successfully\n"); // header part end // if client requests to uplaod file if (h.action == ADD_FILE) { char *target = NULL; target = malloc(BLOCK_SIZE); sprintf(target, "%s/%s", SERVER_FILE_DIR, h.file_name); printf("[SERVER] Adding file %s\n", target); receive_file(ssl, target, h.file_size); free(target); } else if (h.action == FETCH_FILE) { char *target = NULL; target = malloc(BLOCK_SIZE); sprintf(target, "%s/%s", SERVER_FILE_DIR, h.file_name); printf("[SERVER] Fetching file %s\n", target); FILE *fp; if (!(fp = fopen(target, "r"))) { perror("fopen"); /* Close SSL Connection */ SSL_shutdown(ssl); /* Release SSL */ SSL_free(ssl); //Close Connection Socket close(client_fd); continue; //exit(EXIT_FAILURE); } free(target); // get file's protection rating to compare to // client's requested circumference int protectionRating = getProtectionRating(h.file_name); header h_send; if (protectionRating >= h.circ) { h_send.action = ADD_FILE; } else { h_send.action = FAIL_ERROR; // client will fail out } h_send.file_size = get_file_size(fp); h_send.file_name = h.file_name; h_send.certificate = " "; send_header(ssl, h_send); if (protectionRating >= h.circ) send_file(ssl, fp); fclose(fp); } else if (h.action == UPLOAD_CERT) { char target[MAXSIZE]; sprintf(target, "%s/%s_crt.pem", SERVER_CERT_DIR, h.file_name); printf("Receiving cert and storing: %s\n", target); receive_file(ssl, target, h.file_size); }// if client requests to list files else if (h.action == LIST_FILE) { char **files; size_t count; unsigned int i; count = file_list(SERVER_FILE_DIR, &files); for (i = 0; i < count; i++) { char *send_str = NULL; send_str = malloc(MAXSIZE); int protectionRating = getProtectionRating(files[i]); if (protectionRating >= h.circ) { sprintf(send_str, "Protected (c = %i): %s",protectionRating,files[i]); } else { sprintf(send_str, "Unprotected (c = %i): %s",protectionRating,files[i]); } send_message(ssl, send_str); free(send_str); } printf("File list transmitting completed.\n"); close(client_fd); printf("Client connection closed.\n"); } /* if client requires to vouch a file * https://gitorious.org/random_play/random_play/source/b9f19d4d9e8d4a9ba0ef55a6b0e2113d1c6a5587:openssl_sign.c */ else if (h.action == VOUCH_FILE){ // vouch for this file const char *clearTextFileName = h.file_name; int isCertFile = isNameCertFile(clearTextFileName); // vouch using this certificate char *certificate_file_name = h.certificate; char *cert_loc = NULL; cert_loc = malloc(MAXSIZE); sprintf(cert_loc, "%s/%s", SERVER_CERT_DIR, certificate_file_name); if (!check_if_file_exists(cert_loc)) { char *message = NULL; message = malloc(MAXSIZE); sprintf(message, "Unable to locate %s certificate on the server. Please upload using -a\n", cert_loc); SSL_write(ssl, message,strlen(message)); free(message); /* Close SSL Connection */ SSL_shutdown(ssl); /* Release SSL */ SSL_free(ssl); //Close Connection Socket close(client_fd); continue; // should notify client here somehow } else{ char *message = NULL; message = malloc(MAXSIZE); sprintf(message, "Located %s certificate on the server. \n", cert_loc); SSL_write(ssl, message,strlen(message)); free(message); } free(cert_loc); char *target = NULL; target = malloc(MAXSIZE); if (isCertFile) { sprintf(target, "%s/%s", SERVER_CERT_DIR, h.file_name); } else { sprintf(target, "%s/%s", SERVER_FILE_DIR, h.file_name); } unsigned char *md5Value = NULL; md5Value = malloc(MD5_DIGEST_LENGTH); if(hashFile(md5Value, (const char *)target)!=0){ printf("Couldn't open file"); free(target); /* Close SSL Connection */ SSL_shutdown(ssl); /* Release SSL */ SSL_free(ssl); //Close Connection Socket close(client_fd); continue; } free(target); send_message(ssl, (char *)md5Value); unsigned char signature[MAXSIZE]; SSL_read(ssl, signature, 128); char *sig_name = NULL; sig_name = malloc(MAXSIZE); // keep certificate signatures with certificates if (isCertFile) { sprintf(sig_name, "%s/%s_%s.sig", SERVER_CERT_DIR, clearTextFileName, certificate_file_name); } else { sprintf(sig_name, "%s/%s_%s.sig", SERVER_SIG_DIR, clearTextFileName, certificate_file_name); } if (writeSig(signature, sig_name) != 0) { fprintf(stderr, "Could not save signature file\n"); free(sig_name); SSL_write(ssl,"-1",strlen("-1")); /* Close SSL Connection */ SSL_shutdown(ssl); /* Release SSL */ SSL_free(ssl); //Close Connection Socket close(client_fd); continue; //exit(EXIT_FAILURE); } else{ printf("Sig loc: %s\n", sig_name); SSL_write(ssl,"100",strlen("100")); } free(sig_name); } else if (h.action == VERIFY_FILE){ // test verification of signature files char signatoryCertName[MAXSIZE]; sprintf( signatoryCertName, "%s_crt.pem", h.certificate ); const char *clearText = h.file_name; if(!verifySig(signatoryCertName,clearText)){ printf("Verify failed\n"); } } else if (h.action == FIND_ISSUER){ char certPath[MAXSIZE]; sprintf( certPath, "%s", h.certificate ); } else if (h.action == TEST_RINGOFTRUST) { ringOfTrust(h.file_name); } /********** END DATA PROCESSING **************/ free(h.certificate); free(h.file_name); /* Close SSL Connection */ SSL_shutdown(ssl); /* Release SSL */ SSL_free(ssl); //Close Connection Socket close(client_fd); } //Outer While /* Close listening socket */ close(socket_fd); /* Release CTX */ SSL_CTX_free(ctx); return 0; } //End of main
int main(int argc, char *argv[]) { wchar_t **argv1 = CommandLineArgs(argc,argv); CParameter parameter; if (! parameter.CommandLine (argc, argv1)) { return 4; } if (parameter.Sis().empty()) { cleanup(argc,argv1); return 0; } ERR_load_crypto_strings (); OpenSSL_add_all_algorithms (); OpenSSL_add_all_ciphers (); OpenSSL_add_all_digests (); int retValue = 0; try { bool isSisFile = CSISContents::IsSisFile(parameter.Sis ()); if(isSisFile) { CSISContents content; content.Load (parameter.Sis ()); CSignSis signsis(parameter.Sis ()); if (parameter.Sign ()) { if (parameter.Verbose ()) { std::cout << "Signing" << std::endl; } signsis.SignSis(parameter.Output (), parameter.Certificate(), parameter.Key(), parameter.PassPhrase(), parameter.Algorithm()); } if (parameter.Unsign ()) { if (parameter.Verbose ()) { std::cout << "Removing signature" << std::endl; } signsis.RemoveSignature (parameter.Output ()); } if (parameter.Report() || parameter.ExtractCert()) { ReportSignatures(content.Controller(), parameter.ExtractCert()); } if (parameter.Dump ()) { content.Dump (std::cout, 0); } } else { if (parameter.Report ()||parameter.ExtractCert()) { std::cout<<"Reporting Stub Sis Controller"<<std::endl; CSISController ctrl; ctrl.Load (parameter.Sis ()); ReportSignatures(ctrl, parameter.ExtractCert()); } } } catch(const CSISException& oops) { std::wcout << oops.widewhat () << std::endl; retValue = 1; } catch (...) { std::wcout << L"Unexpected error." << std::endl; retValue = 1; } EVP_cleanup (); ERR_free_strings (); // cleanup the memory cleanup(argc,argv1); return retValue; }
int main(int argc, char const *argv[]) { // Check for arguments if (argc < 8) { exit_error_f( "Usage:\n" "%s DEV BLOCK_SIZE JB_TRANSACTIONS HASH_TYPE SALT HMAC_TYPE SECRET lazy|nolazy\n" "%s MINT_DEV DATA_DEV BLOCK_SIZE JB_TRANSACTIONS HASH_TYPE SALT HMAC_TYPE SECRET lazy|nolazy\n", argv[0], argv[0]); } const char *dev, *dev2, *hash_type, *hmac_type, *salt_str, *secret_str; uint32_t block_size, journal_blocks; bool zero; if (!strcmp(argv[argc - 1], "lazy")) { zero = false; } else if (!strcmp(argv[argc - 1], "nolazy")) { zero = true; } else { exit_error_f("Unsupported optional argument: %s", argv[argc - 1]); } bool two_disks = (argc == 10); dev = argv[1]; dev2 = argv[2]; hash_type = argv[4 + two_disks]; salt_str = argv[5 + two_disks]; hmac_type = argv[6 + two_disks]; secret_str = argv[7 + two_disks]; // Open destination device int file, file2; if ((file = open(dev, O_RDWR)) < 0) { exit_error_f("Could not open: '%s' for writing, %s", dev, strerror(errno)); } // Get size // TODO: size of file in 512 chunks? struct stat file_stats, file_stats2; if (fstat(file, &file_stats) != 0) { exit_error_f("Could not get file stats for: '%s', %s", dev, strerror(errno)); } if (!(S_ISREG(file_stats.st_mode) || S_ISBLK(file_stats.st_mode))) { exit_error_f("File is neither a regular file nor block device"); } if (two_disks) { if ((file2 = open(dev2, O_RDWR)) < 0) { exit_error_f("Could not open: '%s' for writing, %s", dev2, strerror(errno)); } // Get size // TODO: size of file in 512 chunks? if (fstat(file2, &file_stats2) != 0) { exit_error_f("Could not get file stats for: '%s', %s", dev2, strerror(errno)); } if (!(S_ISREG(file_stats2.st_mode) || S_ISBLK(file_stats2.st_mode))) { exit_error_f("File is neither a regular file nor block device"); } } // Get block size if (sscanf(argv[2 + two_disks], "%u", &block_size) != 1) { exit_error_f("Invalid block size: '%s'", argv[2 + two_disks]); } if (block_size < 512) { exit_error_f("Invalid block size: '%u' < 512", block_size); } // Remainder check if (S_ISREG(file_stats.st_mode) && file_stats.st_size % block_size != 0) { warn("File is not a multiple of block_size: %d. %ju bytes left over", block_size, file_stats.st_size % block_size); } if (two_disks && S_ISREG(file_stats2.st_mode) && file_stats2.st_size % block_size != 0) { warn("File is not a multiple of block_size: %d. %ju bytes left over", block_size, file_stats.st_size % block_size); } // Number of journal blocks if (sscanf(argv[3 + two_disks], "%u", &journal_blocks) != 1) { exit_error_f("Invalid journal blocks number: '%s'", argv[3 + two_disks]); } OpenSSL_add_all_digests(); // Block hash algorithm EVP_MD_CTX *mdctx_hash = EVP_MD_CTX_create(); const EVP_MD *md_hash; md_hash = EVP_get_digestbyname(hash_type); if (!md_hash) { exit_error_f("Unsupported hash type: %s", hash_type); } uint32_t hash_bytes = EVP_MD_size(md_hash); // Hmac algorithm const EVP_MD *md_hmac; md_hmac = EVP_get_digestbyname(hmac_type); if (!md_hmac) { exit_error_f("Unsupported hmac type: %s", hmac_type); } // Parse and check salt char salt[128]; if (strlen(salt_str) % 2 != 0) { exit_error_f("Invalid hex salt: length not a multiple of 2"); } if (strlen(salt_str) > 256) { exit_error_f("Salt is too long. %lu > %d", strlen(salt_str), 256); } if (hex_to_bytes(salt_str, strlen(salt_str), (char*)salt) != 0) { exit_error_f("Invalid hex salt: '%s'", salt_str); } // Parse and check secrets char secret[hash_bytes]; if (strlen(secret_str) % 2 != 0) { exit_error_f("Invalid hex secret: length not a multiple of 2"); } if (hex_to_bytes(secret_str, strlen(secret_str), (char*)secret) != 0) { exit_error_f("Invalid hex inner pad: '%s'", secret_str); } // Calculate data size, hash block size, journal size // TODO: uh...this is 64 bits... uint64_t data_blocks = 0; uint32_t hash_blocks = 0; uint32_t jb_blocks = 0; uint32_t pad_blocks = 0; uint32_t *blocks_per_level = malloc(sizeof(uint32_t) * DM_MINTEGRITY_MAX_LEVELS); uint32_t levels = 0; uint64_t blocks, blocks2; if (S_ISREG(file_stats.st_mode)) { blocks = file_stats.st_size / block_size; } else if (S_ISBLK(file_stats.st_mode)) { if(ioctl(file, BLKGETSIZE64, &blocks) != 0){ exit_error_f("ioctl for block size failed: %s", strerror(errno)); } blocks = blocks / block_size; } if (two_disks) { if (S_ISREG(file_stats2.st_mode)) { blocks2 = file_stats2.st_size / block_size; } else if (S_ISBLK(file_stats2.st_mode)) { if(ioctl(file2, BLKGETSIZE64, &blocks2) != 0){ exit_error_f("ioctl for block size failed: %s", strerror(errno)); } blocks2 = blocks2 / block_size; } } // Fanout uint8_t fls, pls = 0; uint32_t fanout = block_size / hash_bytes; while (fanout > 0) { if ((fanout & 1) == 1) { fls = pls; } pls ++; fanout = fanout >> 1; } fanout = 1 << fls; // Use up entire block device if (!two_disks) { compute_block_numbers(blocks, block_size, fanout, journal_blocks, &data_blocks, &hash_blocks, &jb_blocks, &pad_blocks, &levels, blocks_per_level, hash_bytes); } else { jb_blocks = journal_blocks; data_blocks = blocks2; compute_hash_blocks(blocks2, fanout, &levels, &hash_blocks, blocks_per_level); if (hash_blocks + journal_blocks > blocks2) { exit_error_f("Need: %u hash + journal blocks, but %s only has %ju", hash_blocks + journal_blocks, dev, blocks); } } // Result info info("Blocks: %ju = Superblock: 1, Data: %ju, Hash: %u, JB: %u, Pad: %u, Levels: %u", blocks, data_blocks, hash_blocks, jb_blocks, pad_blocks, levels); // Calculate each hash block level char **hash_levels = (char**)malloc(sizeof(char*) * levels); char hash_output[EVP_MAX_MD_SIZE]; uint32_t hash_length; char *zero_block = (char*)malloc(block_size); char *temp_block = (char*)malloc(block_size); bzero(zero_block, block_size); char buf[128]; // Data hash hash(md_hash, mdctx_hash, zero_block, block_size, salt, strlen(salt_str) / 2, hash_output, &hash_length); // Now loop through each level for (uint32_t i = 0; i < levels; i++) { hash_levels[i] = (char*)malloc(block_size); // Fill block with hashes - padding is zeros bzero(hash_levels[i], block_size); for (uint32_t f = 0; f < fanout; f++) { for (int b = 0; b < hash_bytes; b++) { hash_levels[i][f * (block_size / (1 << fls)) + b] = hash_output[b]; } } // Compute hash of this level for next iteration/root hash(md_hash, mdctx_hash, hash_levels[i], block_size, salt, strlen(salt_str) / 2, hash_output, &hash_length); } // Write out hash superblock struct mint_superblock *msb = malloc(sizeof(struct mint_superblock)); // Zero out everything bzero(msb, sizeof(struct mint_superblock)); // Magic msb->magic = 0x796c694c; // Version msb->version = 1; // Make a new uuid! uuid_t uuid; uuid_generate(uuid); // TODO: is there a better way of doing this? memcpy(&msb->uuid, &uuid, 16); // Copy hash algorithm name strcpy(msb->hash_algorithm, hash_type); // Copy hmac algorithm name strcpy(msb->hmac_algorithm, hmac_type); // Block size! msb->block_size = block_size; // Set block numbers msb->data_blocks = data_blocks; msb->hash_blocks = hash_blocks; msb->jb_blocks = jb_blocks; // Set salt size msb->salt_size = strlen(salt_str) / 2; // Copy salt memcpy(msb->salt, salt, msb->salt_size); // Set root hash memcpy(msb->root, hash_output, hash_length); // Write it out! if (write(file, msb, sizeof(struct mint_superblock)) < 0) { exit_error_f("Failed to write MSB: %s", strerror(errno)); } if (write(file, zero_block, block_size - 512) < 0) { exit_error_f("Failed to write MSB pad: %s", strerror(errno)); } // Big block buffer uint32_t multiple = 1024; char *big_block = (char*)malloc(block_size * multiple); bzero(big_block, block_size * multiple); // Write out hash block levels uint8_t p = 0; info("Writing hash blocks..."); uint32_t h_written = 1; for (int i = levels - 1; i >= 0; i--) { // Copy into big buffer for (uint32_t m = 0; m < multiple; m++) { memcpy(big_block + m * block_size, hash_levels[i], block_size); } // Write out big buffer for (uint32_t j = 0; j < blocks_per_level[i] / multiple; j++) { h_written += multiple; p = progress(h_written, hash_blocks, 79, p); if(write(file, big_block, block_size * multiple) < 0){ exit_error_f("Failed to write hash block: %u, %s", h_written - 1, strerror(errno)); } } for (uint32_t j = 0; j < blocks_per_level[i] % multiple; j++) { p = progress(h_written++, hash_blocks, 79, p); if(write(file, hash_levels[i], block_size) < 0){ exit_error_f("Failed to write hash block: %u, %s", h_written - 1, strerror(errno)); } } } fprintf(stderr, "\n"); // Initialize journal struct mint_journal_superblock *mjsb = (struct mint_journal_superblock*) malloc(sizeof(struct mint_journal_superblock)); bzero(mjsb, sizeof(struct mint_journal_superblock)); // Magic mjsb->header.magic = MJ_MAGIC; // Superblock mjsb->header.type = TYPE_MJSB; // Number of blocks mjsb->blocks = jb_blocks; // Head, tail, and fill are 0 mjsb->head = 0; mjsb->tail = 0; mjsb->fill = 0; mjsb->sequence = 0; // Clean mjsb->state = 0; info("Writing journal..."); if (write(file, mjsb, sizeof(struct mint_journal_superblock)) < 0) { exit_error_f("Failed to write journal superblock:, %s", strerror(errno)); } if (write(file, zero_block, block_size - 512) < 0) { exit_error_f("Failed to write journal superblock pad: %s", strerror(errno)); } struct mint_journal_header *mjh = (struct mint_journal_header*) malloc(sizeof(struct mint_journal_header)); bzero(mjh, sizeof(struct mint_journal_header)); // Magic mjh->magic = MJ_MAGIC; // Nothing block mjh->type = TYPE_MJNB; // Copy headers into start of every block bzero(big_block, block_size * multiple); for (uint64_t i = 0; i < multiple; i++) { memcpy(big_block + i * block_size, mjh, sizeof(struct mint_journal_header)); } p = 0; for (uint64_t i = 0; i < (jb_blocks - 1) / multiple; i++) { if(write(file, big_block, block_size * multiple) < 0){ exit_error_f("Failed to write journal block: %ju, %s", i, strerror(errno)); } p = progress(i * multiple + 1, jb_blocks, 79, p); } for (uint64_t i = 0; i < (jb_blocks - 1) % multiple; i++) { if(write(file, big_block, block_size) < 0){ exit_error_f("Failed to write journal block: %ju, %s", i, strerror(errno)); } p = progress(jb_blocks - ((jb_blocks - 1) % multiple) + i + 2, jb_blocks, 79, p); } fprintf(stderr, "\n"); // Zero out data if (zero) { int f = two_disks ? file2 : file; bzero(big_block, block_size * multiple); info("Writing data blocks..."); p = 0; for (uint64_t i = 0; i < data_blocks / multiple; i++) { if(write(f, big_block, block_size * multiple) < 0){ exit_error_f("Failed to write data block: %ju, %s", i, strerror(errno)); } p = progress(i * multiple, data_blocks, 79, p); } for (uint64_t i = 0; i < data_blocks % multiple; i++) { if(write(f, zero_block, block_size) < 0){ exit_error_f("Failed to write data block: %ju, %s", i, strerror(errno)); } p = progress(data_blocks - (data_blocks % multiple) + i + 1, data_blocks, 79, p); } fprintf(stderr, "\n"); } else { info("Skipping disk zeroing..."); } close(file); if (two_disks) { close(file2); } print_superblock(msb); bytes_to_hex(msb->root, hash_bytes, buf); printf("dmsetup create meow --table \"%u %ju mintegrity %s%s%s %u %u %u %ju " "%s %s %s %s %s%s\"\n", 0, // Start is 0 data_blocks * (block_size / 512), // Size of device given to device mapper // Mintegrity options dev, // String of block device two_disks ? " " : "", two_disks ? dev2 : "", block_size, // Block size hash_blocks, // Number of hash blocks jb_blocks, // Number of journaling blocks data_blocks, // Number of data blocks hash_type, // Hash type buf, // Root digest to verity salt_str, // Salt hmac_type, // Hash type for hmac secret_str, // Hmac secret zero ? "" : " lazy" ); free(mjh); free(mjsb); free(msb); free(blocks_per_level); free(zero_block); free(big_block); free(temp_block); for (int i = 0; i < levels; i++) { free(hash_levels[i]); } free(hash_levels); EVP_MD_CTX_destroy(mdctx_hash); return 0; }
char * caps_create_sha1_str(xmpp_stanza_t * const query) { char *category = NULL; char *type = NULL; char *lang = NULL; char *name = NULL; char *feature_str = NULL; GSList *identities = NULL; GSList *features = NULL; GSList *form_names = NULL; DataForm *form = NULL; FormField *field = NULL; GHashTable *forms = g_hash_table_new_full(g_str_hash, g_str_equal, g_free, (GDestroyNotify)stanza_destroy_form); GString *s = g_string_new(""); xmpp_stanza_t *child = xmpp_stanza_get_children(query); while (child != NULL) { if (g_strcmp0(xmpp_stanza_get_name(child), STANZA_NAME_IDENTITY) == 0) { category = xmpp_stanza_get_attribute(child, "category"); type = xmpp_stanza_get_attribute(child, "type"); lang = xmpp_stanza_get_attribute(child, "xml:lang"); name = xmpp_stanza_get_attribute(child, "name"); GString *identity_str = g_string_new(category); g_string_append(identity_str, "/"); if (type != NULL) { g_string_append(identity_str, type); } g_string_append(identity_str, "/"); if (lang != NULL) { g_string_append(identity_str, lang); } g_string_append(identity_str, "/"); if (name != NULL) { g_string_append(identity_str, name); } g_string_append(identity_str, "<"); identities = g_slist_insert_sorted(identities, g_strdup(identity_str->str), (GCompareFunc)strcmp); g_string_free(identity_str, TRUE); } else if (g_strcmp0(xmpp_stanza_get_name(child), STANZA_NAME_FEATURE) == 0) { feature_str = xmpp_stanza_get_attribute(child, "var"); features = g_slist_insert_sorted(features, g_strdup(feature_str), (GCompareFunc)strcmp); } else if (g_strcmp0(xmpp_stanza_get_name(child), STANZA_NAME_X) == 0) { if (strcmp(xmpp_stanza_get_ns(child), STANZA_NS_DATA) == 0) { form = stanza_create_form(child); form_names = g_slist_insert_sorted(form_names, g_strdup(form->form_type), (GCompareFunc)strcmp); g_hash_table_insert(forms, g_strdup(form->form_type), form); } } child = xmpp_stanza_get_next(child); } GSList *curr = identities; while (curr != NULL) { g_string_append(s, curr->data); curr = g_slist_next(curr); } curr = features; while (curr != NULL) { g_string_append(s, curr->data); g_string_append(s, "<"); curr = g_slist_next(curr); } curr = form_names; while (curr != NULL) { form = g_hash_table_lookup(forms, curr->data); g_string_append(s, form->form_type); g_string_append(s, "<"); GSList *curr_field = form->fields; while (curr_field != NULL) { field = curr_field->data; g_string_append(s, field->var); g_string_append(s, "<"); GSList *curr_value = field->values; while (curr_value != NULL) { g_string_append(s, curr_value->data); g_string_append(s, "<"); curr_value = g_slist_next(curr_value); } curr_field = g_slist_next(curr_field); } curr = g_slist_next(curr); } EVP_MD_CTX mdctx; const EVP_MD *md; unsigned char md_value[EVP_MAX_MD_SIZE]; unsigned int md_len; OpenSSL_add_all_digests(); md = EVP_get_digestbyname("SHA1"); EVP_MD_CTX_init(&mdctx); EVP_DigestInit_ex(&mdctx, md, NULL); EVP_DigestUpdate(&mdctx, s->str, strlen(s->str)); EVP_DigestFinal_ex(&mdctx, md_value, &md_len); EVP_MD_CTX_cleanup(&mdctx); char *result = g_base64_encode(md_value, md_len); g_string_free(s, TRUE); g_slist_free_full(identities, g_free); g_slist_free_full(features, g_free); g_slist_free_full(form_names, g_free); g_hash_table_destroy(forms); return result; }
LUALIB_API int luaopen_openssl(lua_State*L) { //CRYPTO_thread_setup(); OpenSSL_add_all_ciphers(); OpenSSL_add_all_digests(); SSL_library_init(); ERR_load_ERR_strings(); ERR_load_EVP_strings(); ERR_load_crypto_strings(); ENGINE_load_dynamic(); ENGINE_load_openssl(); #ifdef LOAD_ENGINE_CUSTOM LOAD_ENGINE_CUSTOM(); #endif #ifdef OPENSSL_SYS_WINDOWS RAND_screen(); #endif lua_newtable(L); luaL_setfuncs(L, eay_functions, 0); openssl_register_lhash(L); openssl_register_engine(L); luaopen_bio(L); lua_setfield(L, -2, "bio"); luaopen_asn1(L); lua_setfield(L, -2, "asn1"); luaopen_digest(L); lua_setfield(L, -2, "digest"); luaopen_cipher(L); lua_setfield(L, -2, "cipher"); luaopen_hmac(L); lua_setfield(L, -2, "hmac"); luaopen_pkey(L); lua_setfield(L, -2, "pkey"); #ifdef EVP_PKEY_EC luaopen_ec(L); lua_setfield(L, -2, "ec"); #endif luaopen_x509(L); lua_setfield(L, -2, "x509"); luaopen_pkcs7(L); lua_setfield(L, -2, "pkcs7"); luaopen_pkcs12(L); lua_setfield(L, -2, "pkcs12"); luaopen_csr(L); lua_setfield(L, -2, "csr"); luaopen_crl(L); lua_setfield(L, -2, "crl"); luaopen_ocsp(L); lua_setfield(L, -2, "ocsp"); #ifdef OPENSSL_HAVE_TS /* timestamp handling */ luaopen_ts(L); lua_setfield(L, -2, "ts"); #endif luaopen_cms(L); lua_setfield(L, -2, "cms"); luaopen_ssl(L); lua_setfield(L, -2, "ssl"); /* third part */ luaopen_bn(L); lua_setfield(L, -2, "bn"); luaopen_rsa(L); luaopen_dsa(L); luaopen_dh(L); lua_pushvalue(L, -1); lua_setglobal(L, "openssl"); return 1; }
int app_proxy( int argc, char const * const * argv, const char * copyright_notice , CryptoContext & cctx , ExtraOptions const & extrax_options, ExtracOptionChecker extrac_options_checker , PreLoopFn pre_loop_fn = PreLoopFn() ) { setlocale(LC_CTYPE, "C"); const unsigned uid = getuid(); const unsigned gid = getgid(); unsigned euid = uid; unsigned egid = gid; std::string config_filename = CFG_PATH "/" RDPPROXY_INI; program_options::options_description desc({ {'h', "help", "produce help message"}, {'v', "version", "show software version"}, {'k', "kill", "shut down rdpproxy"}, {'n', "nodaemon", "don't fork into background"}, {'u', "uid", &euid, "run with given uid"}, {'g', "gid", &egid, "run with given gid"}, //{'t', "trace", "trace behaviour"}, {'c', "check", "check installation files"}, {'f', "force", "remove application lock file"}, {'i', "inetd", "launch redemption with inetd like launcher"}, {"config-file", &config_filename, "used an another ini file"}, //{"test", "check Inifile syntax"} }); for (extra_option const & extra : extrax_options) { desc.add({extra.option_long, extra.description}); } auto options = program_options::parse_command_line(argc, const_cast<char**>(argv), desc); if (options.count("kill")) { int status = shutdown(PID_PATH "/redemption/" LOCKFILE); if (status){ // TODO check the real error that occured std::clog << "problem opening " << PID_PATH "/redemption/" LOCKFILE << "." " Maybe rdpproxy is not running\n"; } return status; } if (options.count("help")) { std::cout << copyright_notice << "\n\n"; std::cout << "Usage: rdpproxy [options]\n\n"; std::cout << desc << std::endl; return 0; } if (options.count("version")) { std::cout << copyright_notice << std::endl; return 0; } { bool quit = false; if (int status = extrac_options_checker(options, &quit)) { return status; } else if (quit) { return 0; } } openlog("rdpproxy", LOG_CONS | LOG_PERROR, LOG_USER); if (options.count("check")) { bool user_check_file_result = ((uid != euid) || (gid != egid)) ? CheckFile::check(user_check_file_list) : true; /* setgid(egid); setuid(euid); */ bool euser_check_file_result = CheckFile::check(euser_check_file_list); /* setgid(gid); setuid(uid); */ if ((uid != euid) || (gid != egid)) { CheckFile::ShowAll(user_check_file_list, uid, gid); } CheckFile::ShowAll(euser_check_file_list, euid, egid); if (!user_check_file_result || !euser_check_file_result) { if ((uid != euid) || (gid != egid)) { CheckFile::ShowErrors(user_check_file_list, uid, gid); } CheckFile::ShowErrors(euser_check_file_list, euid, egid); LOG(LOG_INFO, "%s", "Please verify that all tests passed. If not, " "you may need to remove " PID_PATH "/redemption/" LOCKFILE " or reinstall rdpproxy if some configuration " "files are missing."); } return 0; } if (options.count("inetd")) { redemption_new_session(cctx, config_filename.c_str()); return 0; } // if -f (force option) is set // force kill running rdpproxy // force remove pid file // don't check if it fails (proxy may be allready stopped) // and try to continue normal start process afterward if (mkdir(PID_PATH "/redemption", 0700) < 0){ // TODO check only for relevant errors (exists with expected permissions is OK) } if (chown(PID_PATH "/redemption", euid, egid) < 0){ LOG(LOG_INFO, "Failed to set owner %u.%u to " PID_PATH "/redemption", euid, egid); return 1; } if (options.count("force")){ shutdown(PID_PATH "/redemption/" LOCKFILE); } if (0 == access(PID_PATH "/redemption/" LOCKFILE, F_OK)) { std::clog << "File " << PID_PATH "/redemption/" LOCKFILE << " already exists. " "It looks like rdpproxy is already running, " "if not, try again with -f (force) option or delete the " PID_PATH "/redemption/" LOCKFILE " file and try again\n"; return 1; } /* write the pid to file */ int fd = open(PID_PATH "/redemption/" LOCKFILE, O_WRONLY | O_CREAT, S_IRWXU); if (fd == -1) { std::clog << "Writing process id to " PID_PATH "/redemption/" LOCKFILE " failed. Maybe no rights ?" << " : " << errno << ":'" << strerror(errno) << "'\n"; return 1; } { io::posix::fdbuf file(fd); const int pid = getpid(); char text[256]; size_t lg = snprintf(text, 255, "%d", pid); if (file.write(text, lg) == -1) { LOG(LOG_ERR, "Couldn't write pid to %s: %s", PID_PATH "/redemption/" LOCKFILE, strerror(errno)); return 1; } } if (!options.count("nodaemon")) { daemonize(PID_PATH "/redemption/" LOCKFILE); } Inifile ini; { ConfigurationLoader cfg_loader(ini.configuration_holder(), config_filename.c_str()); } OpenSSL_add_all_digests(); if (!ini.get<cfg::globals::enable_ip_transparent>()) { if (setgid(egid) != 0){ LOG(LOG_ERR, "Changing process group to %u failed with error: %s\n", egid, strerror(errno)); return 1; } if (setuid(euid) != 0){ LOG(LOG_ERR, "Changing process user to %u failed with error: %s\n", euid, strerror(errno)); return 1; } } pre_loop_fn(ini); LOG(LOG_INFO, "ReDemPtion " VERSION " starting"); redemption_main_loop(ini, cctx, euid, egid, std::move(config_filename)); /* delete the .pid file if it exists */ /* don't care about errors. */ /* If we are not in daemon mode this file will not exists, */ /* hence some errors are expected */ unlink(PID_PATH "/redemption/" LOCKFILE); return 0; }
static int pkcs5_pbkdf2(const char *hash, const char *P, size_t Plen, const char *S, size_t Slen, unsigned int c, unsigned int dkLen, char *DK, int perfcheck) { char U[MAX_PRF_BLOCK_LEN]; char T[MAX_PRF_BLOCK_LEN]; const EVP_MD *PRF; HMAC_CTX ctx; int i, k, rc = -EINVAL; unsigned int u, hLen, l, r; unsigned char *p; size_t tmplen = Slen + 4; char *tmp; tmp = alloca(tmplen); if (tmp == NULL) return -ENOMEM; OpenSSL_add_all_digests(); PRF = EVP_get_digestbyname(hash); if (PRF == NULL) { printf("pkcs5_pbkdf2: invalid hash %s\n", hash); return -EINVAL; } hLen = EVP_MD_size(PRF); if (hLen == 0 || hLen > MAX_PRF_BLOCK_LEN) return -EINVAL; if (c == 0) return -EINVAL; if (dkLen == 0) return -EINVAL; /* * * Steps: * * 1. If dkLen > (2^32 - 1) * hLen, output "derived key too long" and * stop. */ if (dkLen > 4294967295U) return -EINVAL; /* * 2. Let l be the number of hLen-octet blocks in the derived key, * rounding up, and let r be the number of octets in the last * block: * * l = CEIL (dkLen / hLen) , * r = dkLen - (l - 1) * hLen . * * Here, CEIL (x) is the "ceiling" function, i.e. the smallest * integer greater than, or equal to, x. */ l = dkLen / hLen; if (dkLen % hLen) l++; r = dkLen - (l - 1) * hLen; /* * 3. For each block of the derived key apply the function F defined * below to the password P, the salt S, the iteration count c, and * the block index to compute the block: * * T_1 = F (P, S, c, 1) , * T_2 = F (P, S, c, 2) , * ... * T_l = F (P, S, c, l) , * * where the function F is defined as the exclusive-or sum of the * first c iterates of the underlying pseudorandom function PRF * applied to the password P and the concatenation of the salt S * and the block index i: * * F (P, S, c, i) = U_1 \xor U_2 \xor ... \xor U_c * * where * * U_1 = PRF (P, S || INT (i)) , * U_2 = PRF (P, U_1) , * ... * U_c = PRF (P, U_{c-1}) . * * Here, INT (i) is a four-octet encoding of the integer i, most * significant octet first. * * 4. Concatenate the blocks and extract the first dkLen octets to * produce a derived key DK: * * DK = T_1 || T_2 || ... || T_l<0..r-1> * * 5. Output the derived key DK. * * Note. The construction of the function F follows a "belt-and- * suspenders" approach. The iterates U_i are computed recursively to * remove a degree of parallelism from an opponent; they are exclusive- * ored together to reduce concerns about the recursion degenerating * into a small set of values. * */ HMAC_CTX_init(&ctx); for (i = 1; (uint) i <= l; i++) { memset(T, 0, hLen); for (u = 1; u <= c ; u++) { if (u == 1) { memcpy(tmp, S, Slen); tmp[Slen + 0] = (i & 0xff000000) >> 24; tmp[Slen + 1] = (i & 0x00ff0000) >> 16; tmp[Slen + 2] = (i & 0x0000ff00) >> 8; tmp[Slen + 3] = (i & 0x000000ff) >> 0; HMAC_Init_ex(&ctx, P, Plen, PRF, NULL); HMAC_Update(&ctx, tmp, tmplen); HMAC_Final(&ctx, U, NULL); } else { HMAC(PRF, P, Plen, U, hLen, U, NULL); } for (k = 0; (uint) k < hLen; k++) T[k] ^= U[k]; if (perfcheck && __PBKDF2_performance) { rc = 0; goto out; } if (perfcheck) __PBKDF2_global_j++; }
int main(int argc, char *argv[]) { char *password_file = NULL; char *username = NULL; bool create_new = false; bool delete_user = false; FILE *fptr, *ftmp; char password[MAX_BUFFER_LEN]; int rc; bool do_update_file = false; char *backup_file; signal(SIGINT, handle_sigint); signal(SIGTERM, handle_sigint); OpenSSL_add_all_digests(); if(argc == 4){ if(!strcmp(argv[1], "-c")){ create_new = true; }else if(!strcmp(argv[1], "-D")){ delete_user = true; } password_file = argv[2]; username = argv[3]; }else if(argc == 3){ if(!strcmp(argv[1], "-U")){ do_update_file = true; password_file = argv[2]; }else{ password_file = argv[1]; username = argv[2]; } }else{ print_usage(); return 1; } if(create_new){ rc = get_password(password, 1024); if(rc) return rc; fptr = fopen(password_file, "wt"); if(!fptr){ fprintf(stderr, "Error: Unable to open file %s for writing. %s.\n", password_file, strerror(errno)); return 1; } rc = output_new_password(fptr, username, password); fclose(fptr); return rc; }else{ fptr = fopen(password_file, "r+t"); if(!fptr){ fprintf(stderr, "Error: Unable to open password file %s. %s.\n", password_file, strerror(errno)); return 1; } backup_file = malloc(strlen(password_file)+5); snprintf(backup_file, strlen(password_file)+5, "%s.tmp", password_file); if(create_backup(backup_file, fptr)){ fclose(fptr); free(backup_file); return 1; } ftmp = tmpfile(); if(!ftmp){ fprintf(stderr, "Error: Unable to open temporary file. %s.\n", strerror(errno)); fclose(fptr); free(backup_file); return 1; } if(delete_user){ rc = delete_pwuser(fptr, ftmp, username); }else if(do_update_file){ rc = update_file(fptr, ftmp); }else{ rc = get_password(password, 1024); if(rc){ fclose(fptr); fclose(ftmp); unlink(backup_file); free(backup_file); return rc; } /* Update password for individual user */ rc = update_pwuser(fptr, ftmp, username, password); } if(rc){ fclose(fptr); fclose(ftmp); unlink(backup_file); free(backup_file); return rc; } if(copy_contents(ftmp, fptr)){ fclose(fptr); fclose(ftmp); fprintf(stderr, "Error occurred updating password file.\n"); fprintf(stderr, "Password file may be corrupt, check the backup file: %s.\n", backup_file); free(backup_file); return 1; } fclose(fptr); fclose(ftmp); /* Everything was ok so backup no longer needed. May contain old * passwords so shouldn't be kept around. */ unlink(backup_file); free(backup_file); } return 0; }
int main(int argc, char *argv[]) { pev_config_t config; PEV_INITIALIZE(&config); if (argc < 2) { usage(); return EXIT_FAILURE; } output_set_cmdline(argc, argv); OpenSSL_add_all_digests(); options_t *options = parse_options(argc, argv); pe_ctx_t ctx; pe_err_e err = pe_load_file(&ctx, argv[argc-1]); if (err != LIBPE_E_OK) { pe_error_print(stderr, err); return EXIT_FAILURE; } err = pe_parse(&ctx); if (err != LIBPE_E_OK) { pe_error_print(stderr, err); return EXIT_FAILURE; } if (!pe_is_pe(&ctx)) EXIT_ERROR("not a valid PE file"); const IMAGE_SECTION_HEADER *section_ptr = NULL; const unsigned char *data = NULL; uint64_t data_size = 0; unsigned c = pe_sections_count(&ctx); IMAGE_SECTION_HEADER ** const sections = pe_sections(&ctx); char hash_value[EVP_MAX_MD_SIZE * 2 + 1]; data = ctx.map_addr; data_size = pe_filesize(&ctx); output_open_document(); if (options->all) { output_open_scope("file", OUTPUT_SCOPE_TYPE_OBJECT); output("filepath", ctx.path); print_basic_hash(data, data_size); output_close_scope(); // file } output_open_scope("headers", OUTPUT_SCOPE_TYPE_ARRAY); if (options->all || options->headers.all || options->headers.dos) { const IMAGE_DOS_HEADER *dos_hdr = pe_dos(&ctx); data = (const unsigned char *)dos_hdr; data_size = sizeof(IMAGE_DOS_HEADER); output_open_scope("header", OUTPUT_SCOPE_TYPE_OBJECT); output("header_name", "IMAGE_DOS_HEADER"); PRINT_HASH_OR_HASHES; output_close_scope(); // header } if (options->all || options->headers.all || options->headers.coff) { const IMAGE_COFF_HEADER *coff_hdr = pe_coff(&ctx); data = (const unsigned char *)coff_hdr; data_size = sizeof(IMAGE_COFF_HEADER); output_open_scope("header", OUTPUT_SCOPE_TYPE_OBJECT); output("header_name", "IMAGE_COFF_HEADER"); PRINT_HASH_OR_HASHES; output_close_scope(); // header } if (options->all || options->headers.all || options->headers.optional) { const IMAGE_OPTIONAL_HEADER *opt_hdr = pe_optional(&ctx); switch (opt_hdr->type) { case MAGIC_ROM: // Oh boy! We do not support ROM. Abort! fprintf(stderr, "ROM image is not supported\n"); break; case MAGIC_PE32: if (!pe_can_read(&ctx, opt_hdr->_32, sizeof(IMAGE_OPTIONAL_HEADER_32))) { // TODO: Should we report something? break; } data = (const unsigned char *)opt_hdr->_32; data_size = sizeof(IMAGE_OPTIONAL_HEADER_32); break; case MAGIC_PE64: if (!pe_can_read(&ctx, opt_hdr->_64, sizeof(IMAGE_OPTIONAL_HEADER_64))) { // TODO: Should we report something? break; } data = (const unsigned char *)opt_hdr->_64; data_size = sizeof(IMAGE_OPTIONAL_HEADER_64); break; } output_open_scope("header", OUTPUT_SCOPE_TYPE_OBJECT); output("header_name", "IMAGE_OPTIONAL_HEADER"); PRINT_HASH_OR_HASHES; output_close_scope(); // header } output_close_scope(); // headers if (options->all) { output_open_scope("sections", OUTPUT_SCOPE_TYPE_ARRAY); for (unsigned int i=0; i<c; i++) { data_size = sections[i]->SizeOfRawData; data = LIBPE_PTR_ADD(ctx.map_addr, sections[i]->PointerToRawData); output_open_scope("section", OUTPUT_SCOPE_TYPE_OBJECT); output("section_name", (char *)sections[i]->Name); if (data_size) { PRINT_HASH_OR_HASHES; } output_close_scope(); // section } output_close_scope(); // sections } else if (options->sections.name != NULL) { const IMAGE_SECTION_HEADER *section = pe_section_by_name(&ctx, options->sections.name); if (section == NULL) { EXIT_ERROR("The requested section could not be found on this binary"); } section_ptr = section; } else if (options->sections.index > 0) { const uint16_t num_sections = pe_sections_count(&ctx); if (num_sections == 0 || options->sections.index > num_sections) { EXIT_ERROR("The requested section could not be found on this binary"); } IMAGE_SECTION_HEADER ** const sections = pe_sections(&ctx); const IMAGE_SECTION_HEADER *section = sections[options->sections.index - 1]; section_ptr = section; } if (section_ptr != NULL) { if (section_ptr->SizeOfRawData > 0) { const uint8_t *section_data_ptr = LIBPE_PTR_ADD(ctx.map_addr, section_ptr->PointerToRawData); // printf("map_addr = %p\n", ctx.map_addr); // printf("section_data_ptr = %p\n", section_data_ptr); // printf("SizeOfRawData = %u\n", section_ptr->SizeOfRawData); if (!pe_can_read(&ctx, section_data_ptr, section_ptr->SizeOfRawData)) { EXIT_ERROR("The requested section has an invalid size"); } data = (const unsigned char *)section_data_ptr; data_size = section_ptr->SizeOfRawData; } else { data = (const unsigned char *)""; data_size = 0; } } if (!options->all && data != NULL) { char hash_value[EVP_MAX_MD_SIZE * 2 + 1]; if (options->algorithms.all && options->all) { print_basic_hash(data, data_size); } else if (options->algorithms.alg_name != NULL) { calc_hash(options->algorithms.alg_name, data, data_size, hash_value); output(options->algorithms.alg_name, hash_value); } else { print_basic_hash(data, data_size); } } output_close_document(); // free free_options(options); err = pe_unload(&ctx); if (err != LIBPE_E_OK) { pe_error_print(stderr, err); return EXIT_FAILURE; } EVP_cleanup(); // Clean OpenSSL_add_all_digests. PEV_FINALIZE(&config); return EXIT_SUCCESS; }
/** * post processing of profile, e.g. init SSL * * @param ctx * * @return */ dpl_status_t dpl_profile_post(dpl_ctx_t *ctx) { int ret, ret2; //sanity checks if (NULL == ctx->host) { fprintf(stderr, "missing 'host' in profile\n"); ret = DPL_FAILURE; goto end; } if (-1 == ctx->port) { if (0 == ctx->use_https) ctx->port = 80; else ctx->port = 443; } //ssl stuff if (1 == ctx->use_https) { #if OPENSSL_VERSION_NUMBER >= 0x10000000L const SSL_METHOD *method; #else SSL_METHOD *method; #endif if (NULL == ctx->ssl_cert_file || NULL == ctx->ssl_key_file || NULL == ctx->ssl_password) return DPL_EINVAL; ctx->ssl_bio_err = BIO_new_fp(stderr, BIO_NOCLOSE); if (NULL == ctx->ssl_bio_err) { ret = DPL_FAILURE; goto end; } method = SSLv23_method(); ctx->ssl_ctx = SSL_CTX_new(method); if (!(SSL_CTX_use_certificate_chain_file(ctx->ssl_ctx, ctx->ssl_cert_file))) { BIO_printf(ctx->ssl_bio_err, "use_certificate_chain_file: "); ERR_print_errors(ctx->ssl_bio_err); BIO_printf(ctx->ssl_bio_err, "\n"); ret = DPL_FAILURE; goto end; } SSL_CTX_set_default_passwd_cb(ctx->ssl_ctx, passwd_cb); SSL_CTX_set_default_passwd_cb_userdata(ctx->ssl_ctx, ctx); if (!(SSL_CTX_use_PrivateKey_file(ctx->ssl_ctx, ctx->ssl_key_file, SSL_FILETYPE_PEM))) { BIO_printf(ctx->ssl_bio_err, "use_private_key_file: "); ERR_print_errors(ctx->ssl_bio_err); BIO_printf(ctx->ssl_bio_err, "\n"); ret = DPL_FAILURE; goto end; } if (NULL != ctx->ssl_ca_list) { if (!(SSL_CTX_load_verify_locations(ctx->ssl_ctx, ctx->ssl_ca_list, 0))) { BIO_printf(ctx->ssl_bio_err, "load_verify_location: "); ERR_print_errors(ctx->ssl_bio_err); BIO_printf(ctx->ssl_bio_err, "\n"); ret = DPL_FAILURE; goto end; } } } //pricing if (NULL != ctx->pricing) { ret2 = dpl_pricing_load(ctx); if (DPL_SUCCESS != ret2) { ret = DPL_FAILURE; goto end; } } //encrypt OpenSSL_add_all_digests(); OpenSSL_add_all_ciphers(); //event log ret2 = dpl_open_event_log(ctx); if (DPL_SUCCESS != ret2) { ret = DPL_FAILURE; goto end; } //connection pool ret2 = dpl_conn_pool_init(ctx); if (DPL_SUCCESS != ret2) { ret = DPL_FAILURE; goto end; } ctx->cwds = dpl_dict_new(13); if (NULL == ctx->cwds) { ret = DPL_FAILURE; goto end; } ctx->cur_bucket = strdup(""); if (NULL == ctx->cur_bucket) { ret = DPL_FAILURE; goto end; } ret = DPL_SUCCESS; end: return ret; }
int vendor_fy(void) { //You need to add a valid 16 byte vendor key in Hex unsigned char vendor_key1[16] = {0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00}; unsigned char man_id[49]; unsigned long crc_32; unsigned char vendor_crc[4]; unsigned char vendor_id[16]; unsigned char serial_id[16]; int i; //Copy eeprom SFP details into A50 if(!read_eeprom(0x50)); else exit(EXIT_FAILURE); memcpy(&vendor_id, &A50[20],16); memcpy(&serial_id, &A50[68],16); //vendor_tmp holds = man_id 1 byte + 16 byte vendor + 16 byte serial + // 16 byte vendor_key1 man_id[0] = 0x00; //You need to provide a manufacturer id number. for(i = 1; i <17; i++) man_id[i] = vendor_id[i-1]; for(i = 17; i <33; i++) man_id[i] = serial_id[i-17]; for(i = 33; i <49; i++) man_id[i] = vendor_key1[i-33]; //need to calculate the md5 of the concatenated string //using openssl envelope functions from openssl libcrypto EVP_MD_CTX *mdctx; const EVP_MD *md; unsigned char md_value[EVP_MAX_MD_SIZE]; int md_len; OpenSSL_add_all_digests(); mdctx = EVP_MD_CTX_create(); md = EVP_get_digestbyname("md5"); EVP_DigestInit_ex(mdctx, md, NULL); EVP_DigestUpdate(mdctx, man_id, 49); EVP_DigestFinal_ex(mdctx, md_value, &md_len); //clean up EVP_MD_CTX_destroy(mdctx); printf("\nDigest is: "); for(i = 0; i < md_len; i++) printf("%02x", md_value[i]); //Create valid id unsigned char vendor_trailer[9+1] = {0x00,0x00,0x00,0x00,0x00 ,0x00,0x00,0x00,0x00}; unsigned char vendor_valid_id[28+1]; vendor_valid_id[0] = 0x00; vendor_valid_id[1] = 0x00; vendor_valid_id[2] = man_id[0];//first byte of man_id. for(i = 0; i < 16; i++) vendor_valid_id[i+3] = md_value[i]; for(i = 0; i < 10; i++) vendor_valid_id[i+19] = vendor_trailer[i]; printf("\nVendor Valid Id = "); for(i=0; i < 29; i++) printf("%x",vendor_valid_id[i]); //write the vendor_valid_id from address 96(0x60) to address 124(0x7b) printf("\nWrite valid_vendor_id Yes/No?"); int ch = 0; ch = getchar(); getchar(); if ((ch == 'Y') || (ch == 'y')) { printf("Writing Digest wait....\n"); #ifdef BEAGLEBONE xio = open(filenm, O_RDWR); if (xio < 0) { fprintf (stderr, "Unable to open device: %s\n", filenm); return(1); } if (ioctl(xio, I2C_SLAVE, 0x50) < 0) { fprintf (stderr, "xio: Unable to initialise I2C: %s\n", strerror (errno)); return(1); } #else xio = wiringPiI2CSetup (0x50); if (xio < 0){ fprintf (stderr, "xio: Unable to initialise I2C: %s\n", strerror (errno)); return 1; } #endif for(i = 0; i < 28; i++) { #ifndef BEAGLEBONE wiringPiI2CWriteReg8(xio, 0x60+i, vendor_valid_id[i]); #else i2c_smbus_write_byte_data(xio, 0x60+i, vendor_valid_id[i]); #endif usleep(50000);//sleep for 0.5ms per byte } } else printf("nothing written"); //now need to get the crc32 of the header+md5+trailer crc_32 = crc32(0, vendor_valid_id, 28); //printf("\nvalue of returned crc = %x",crc_32); vendor_crc[0] = (int) crc_32 & 0xff; //A50[124] vendor_crc[1] = (int) crc_32 >> 8 & 0xff; //A50[125] vendor_crc[2] = (int) crc_32 >> 16 & 0xff;//A50[126] vendor_crc[3] = (int) crc_32 >> 24 & 0xff;//A50[127] printf("\nCRC32 of the Vendor Padded MD5 ="); for(i = 0; i < 4; i++) printf(" %x", vendor_crc[i]); //need to write the crc values to the eeprom // printf("\nWrite CRC32 of the padded Digest in reverse (4 seconds) Yes/No?"); ch =0; ch = getchar(); getchar(); if ((ch == 'Y') || (ch == 'y')) { printf("Writing CRC32 wait....\n"); #ifndef BEAGLEBONE xio = wiringPiI2CSetup (0x50); if (xio < 0){ fprintf (stderr, "xio: Unable to initialise I2C: %s\n", strerror (errno)); return 1; } #else xio = open(filenm, O_RDWR); if (xio < 0) { fprintf (stderr, "Unable to open device: %s\n", filenm); return(1); } if (ioctl(xio, I2C_SLAVE, 0x50) < 0) { fprintf (stderr, "xio: Unable to initialise I2C: %s\n", strerror (errno)); return(1); } #endif for(i = 0; i < 4; i++) { #ifndef BEAGLEBONE wiringPiI2CWriteReg8(xio, 0x7c+i,vendor_crc[i]); #else i2c_smbus_write_byte_data(xio, 0x7c+i, vendor_crc[i]); #endif usleep(50000);//wait 0.5ms per byte } } else printf("nothing written\n"); if (write_checksum) { //Calculate the checksum: Add up the first 31 bytes and store //the last 8 bits in the 32nd byte mychecksum(0x0, 0x3f); //Calculate the extended checksum: Add up 31 bytes and store //the last 8 bits in the 32nd byte mychecksum(0x40, 0x5f); } return 0; }
/** * Esta función se encargará de producir, lo que para el SAT[1], es un sello * digital. Este sello digital consiste en el firmado digital del hash de un * string, que para los casos de un CFDi se trataría de la cadena original * * El usuario es responsable de liberar la memoria del resultado (con free()) * [1]: http://www.sat.gob.mx */ unsigned char * sello_alloc(const char *keyfile, const char *digest, const unsigned char *cadena, const int verbose) { int read = 0; int len = 0; unsigned char *buffer = NULL; const unsigned char *tmp; unsigned char signbuffer[1024]; unsigned int signlen = 0; char *data = NULL; FILE *file = NULL; BIO* err = NULL; EVP_MD_CTX mdctx; EVP_PKEY *privateKey = NULL; file = fopen(keyfile, "rb"); if ( file == NULL ) { /* An error ocurred */ if ( verbose ) { fprintf(stderr, "No fue posible leer correctamente el archivo %s.\n", keyfile); } return NULL; } len = fseek(file, 0, SEEK_END); if ( len ) { /* An error did occur */ if ( verbose ) { fprintf(stderr, "No fue posible obtener el final del archivo %s.\n", keyfile); } fclose(file); return NULL; } len = ftell(file); rewind(file); buffer = (unsigned char *)calloc(len + 1, sizeof(unsigned char)); read = fread(buffer, sizeof(unsigned char), len, file); fclose(file); if ( read != len ) { if ( verbose ) { fprintf(stderr, "An error has ocurred. The number of items read was %d, but it should be %d instead.\n", read, len); free(buffer); } return NULL; } /* Set the BIO method for the error messages */ if ( err == NULL ) { if ( (err = BIO_new(BIO_s_file())) ) { BIO_set_fp(err, stderr, BIO_NOCLOSE|BIO_FP_TEXT); } } /* Now convert the bytes to a EVP_PKEY structure */ tmp = buffer; privateKey = d2i_AutoPrivateKey(NULL, &tmp, len); if ( privateKey == NULL ) { if ( verbose ) { BIO_printf(err, "Error at reading the private key on %s.\n", keyfile); ERR_print_errors(err); } free(buffer); return NULL; } free(buffer); /* Add all digest algorithms to the table */ OpenSSL_add_all_digests(); /* Initialize the digest context */ EVP_MD_CTX_init(&mdctx); if ( EVP_DigestInit_ex(&mdctx, EVP_get_digestbyname(digest), 0 ) == 0 ) { if ( verbose ) { BIO_printf(err, "Error at initializing the digest context to use '%s' as digest algorithm.\n", digest); ERR_print_errors(err); } EVP_PKEY_free(privateKey); EVP_cleanup(); BIO_free(err); return NULL; } /* Sign up the data in the current context */ if ( EVP_SignInit_ex(&mdctx, EVP_get_digestbyname(digest), 0) == 0 ) { if ( verbose ) { BIO_printf(err, "Error at setting up the signing context to use digest '%s'.\n", digest); ERR_print_errors(err); } EVP_PKEY_free(privateKey); EVP_cleanup(); BIO_free(err); return NULL; } if ( EVP_SignUpdate(&mdctx, cadena, strlen((char *)cadena)) == 0 ) { if ( verbose ) { BIO_printf(err, "Error hashing the data into the signing context.\n"); ERR_print_errors(err); } EVP_PKEY_free(privateKey); EVP_cleanup(); BIO_free(err); return NULL; } signlen = sizeof(signbuffer); memset(signbuffer, 0, 1024); if ( EVP_SignFinal(&mdctx, signbuffer, (unsigned int* )&signlen, privateKey) == 0 ) { if ( verbose ) { BIO_printf(err, "Error signing the data in the context with the private key.\n"); ERR_print_errors(err); } EVP_PKEY_free(privateKey); EVP_cleanup(); BIO_free(err); return NULL; } EVP_MD_CTX_cleanup(&mdctx); EVP_PKEY_free(privateKey); EVP_cleanup(); BIO_free(err); /* Now prepare the data to be base64 encoded */ base64_encode_alloc((const char *)signbuffer, signlen, &data); return (unsigned char *)data; }
main(int argc, char *argv[]) { EVP_MD_CTX *mdctx; EVP_MD_CTX *mdctxdup; const EVP_MD *md; const EVP_MD *mddup; char *mess1; unsigned char md_value[EVP_MAX_MD_SIZE]; unsigned char md_valuedup[EVP_MAX_MD_SIZE]; int md_len,md_lendup, i; char originalBinary[24]; char randomBinary[24]; OpenSSL_add_all_digests(); if(!argv[1]) { printf("Usage: mdtest digestname\n"); exit(1); } md = EVP_get_digestbyname(argv[1]) ; if(!md) { printf("Unknown message digest %s\n", argv[1]); exit(1); } int dontExit =1; char *str ; int num1,num2,timesExecuted=0; srand(time(NULL)); while(dontExit) { timesExecuted++; mess1 = (char*)malloc(33); num1 = rand(); sprintf(mess1,"%d",num1); //mess1 = rand_string(mess1,3); mdctx = EVP_MD_CTX_create(); EVP_DigestInit_ex(mdctx, md, NULL); EVP_DigestUpdate(mdctx, mess1, strlen(mess1)); EVP_DigestFinal_ex(mdctx, md_value, &md_len); EVP_MD_CTX_destroy(mdctx); //printf("Input Original: %s\n",mess1); //printf("Digest Original: "); //for(i = 0; i < md_len; i++) //printf("%02x", md_value[i]); //printf("\n"); str = (char*)malloc(32); num2 = rand(); sprintf(str,"%d",num2); mdctxdup = EVP_MD_CTX_create(); EVP_DigestInit_ex(mdctxdup, md, NULL); EVP_DigestUpdate(mdctxdup, str, strlen(str)); EVP_DigestFinal_ex(mdctxdup, md_valuedup, &md_lendup); EVP_MD_CTX_destroy(mdctxdup); if((md_value[0] == md_valuedup[0]) && (md_value[1] == md_valuedup[1]) && (md_value[2] == md_valuedup[2]) ) { break; } free(mess1); free(str); } printf("Input Original: %s\n",mess1); printf("Digest Original: "); for(i = 0; i < md_len; i++) printf("%02x", md_value[i]); printf("\n"); printf("Input Random: %s\n",str); printf("Digest Random: "); for(i = 0; i < md_lendup; i++) printf("%02x", md_valuedup[i]); printf("\n"); printf("Times executed : %d\n",timesExecuted); /* Call this once before exit. */ EVP_cleanup(); exit(0); }
char *Cmd5::digest(unsigned char *pstr) { #ifdef WIN32 HCRYPTPROV hCryptProv; HCRYPTHASH hHash; unsigned char bHash[0x7f]; DWORD dwHashLen = 16; // The MD5 algorithm always returns 16 bytes. if (CryptAcquireContext(&hCryptProv, NULL, NULL, PROV_RSA_FULL, CRYPT_VERIFYCONTEXT | CRYPT_MACHINE_KEYSET)) { if (CryptCreateHash(hCryptProv, CALG_MD5, // algorithm identifier definitions see: wincrypt.h 0, 0, &hHash)) { if (CryptHashData(hHash, pstr, strlen((const char *) pstr), 0)) { if (CryptGetHashParam(hHash, HP_HASHVAL, bHash, &dwHashLen, 0)) { // Make a string version of the numeric digest value *m_szDigest = 0; char tmp[ 10 ]; for (int i = 0; i < 16; i++) { sprintf(tmp, "%02x", bHash[i]); strcat(m_szDigest, tmp); } } else { return NULL; } } else { return NULL; } } else { return NULL; } } else { return NULL; } CryptDestroyHash(hHash); CryptReleaseContext(hCryptProv, 0); #else EVP_MD_CTX mdctx; const EVP_MD *md; unsigned char md_value[EVP_MAX_MD_SIZE]; unsigned int md_len; OpenSSL_add_all_digests(); md = EVP_get_digestbyname("md5"); EVP_MD_CTX_init(&mdctx); EVP_DigestInit_ex(&mdctx, md, NULL); EVP_DigestUpdate(&mdctx, pstr, strlen((const char *) pstr)); EVP_DigestFinal_ex(&mdctx, md_value, &md_len); EVP_MD_CTX_cleanup(&mdctx); memset(m_szDigest, 0, sizeof(m_szDigest)); sprintf(m_szDigest, "%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x", md_value[0], md_value[1], md_value[2], md_value[3], md_value[4], md_value[5], md_value[6], md_value[7], md_value[8], md_value[9], md_value[10], md_value[11], md_value[12], md_value[13], md_value[14], md_value[15]); /* MD5_CTX *pctx; if ( 0 == MD5_Init( pctx ) ) return NULL; if ( 0 == MD5_Update( pctx, pstr, strlen( (const char *)pstr ) ) ) return NULL; unsigned char buf[ 17 ]; if ( 0 == MD5_Final( buf, pctx ) ) return NULL; sprintf( m_szDigest, "%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x\0", buf[0],buf[1],buf[2],buf[3],buf[4],buf[5],buf[6],buf[7], buf[8],buf[9],buf[10],buf[11],buf[12],buf[13],buf[14],buf[15] ); */ #endif return m_szDigest; }
int main(int argc, char *argv[]) { #ifndef _WIN32 if (geteuid() == 0) { fprintf(stderr, "Running IRC services is root is not recommended."); return 1; } setup_corefile(); #endif memset(&ServicesInfo, 0, sizeof(ServicesInfo)); memset(&ServicesState, 0, sizeof(ServicesState)); ServicesState.configfile = CPATH; ServicesState.logfile = LPATH; ServicesState.pidfile = PPATH; ServicesState.fully_connected = 0; parseargs(&argc, &argv, myopts); if(ServicesState.printversion) { printf("oftc-ircservices: version: %s\n", VERSION); exit(EXIT_SUCCESS); } if(chdir(DPATH)) { perror("chdir"); exit(EXIT_FAILURE); } #ifndef _WIN32 if(!ServicesState.foreground) make_daemon(); else print_startup(getpid()); #endif setup_signals(); memset(&me, 0, sizeof(me)); libio_init(!ServicesState.foreground); init_events(); iorecv_cb = register_callback("iorecv", iorecv_default); connected_cb = register_callback("server connected", server_connected); iosend_cb = register_callback("iosend", iosend_default); OpenSSL_add_all_digests(); init_interface(); check_pidfile(ServicesState.pidfile); init_log(ServicesState.logfile); #ifdef HAVE_RUBY init_ruby(); signal(SIGSEGV, SIG_DFL); #endif init_channel(); init_conf(); init_client(); init_parser(); init_channel_modes(); init_mqueue(); init_tor(); me.from = me.servptr = &me; SetServer(&me); SetMe(&me); dlinkAdd(&me, &me.node, &global_client_list); read_services_conf(TRUE); init_db(); init_uid(); #ifdef HAVE_PYTHON init_python(); #endif init_kill(); write_pidfile(ServicesState.pidfile); ilog(L_NOTICE, "Services Ready"); db_load_driver(); #ifdef USE_SHARED_MODULES if(chdir(MODPATH)) { ilog(L_ERROR, "Could not load core modules from %s: %s", MODPATH, strerror(errno)); exit(EXIT_FAILURE); } /* Go back to DPATH after checking to see if we can chdir to MODPATH */ chdir(DPATH); #else load_all_modules(1); #endif boot_modules(1); connect_server(); for(;;) { while (eventNextTime() <= CurrentTime) eventRun(); execute_callback(do_event_cb); if(events_loop() == -1) { ilog(L_CRIT, "libevent returned error %d", errno); services_die("Libevent returned some sort of error", NO); break; } comm_select(); send_queued_all(); if(dorehash) { ilog(L_INFO, "Got SIGHUP, reloading configuration"); read_services_conf(NO); dorehash = 0; } } return 0; }
LUA_API int luaopen_openssl(lua_State*L) { char * config_filename; #ifdef ENABLE_CRYPTO_THREAD CRYPTO_thread_setup(); CRYPTO_lock(CRYPTO_LOCK,CRYPTO_LOCK_ERR,__FILE__,__LINE__); #endif if(g_init==0) { g_init = 1; OpenSSL_add_all_ciphers(); OpenSSL_add_all_digests(); SSL_library_init(); ERR_load_ERR_strings(); ERR_load_crypto_strings(); ERR_load_EVP_strings(); ERR_load_SSL_strings(); ENGINE_load_dynamic(); ENGINE_load_openssl(); } #ifdef ENABLE_CRYPTO_THREAD CRYPTO_lock(CRYPTO_UNLOCK,CRYPTO_LOCK_ERR,__FILE__,__LINE__); #endif /* Determine default SSL configuration file */ config_filename = getenv("OPENSSL_CONF"); if (config_filename == NULL) { config_filename = getenv("SSLEAY_CONF"); } /* default to 'openssl.cnf' if no environment variable is set */ if (config_filename == NULL) { snprintf(default_ssl_conf_filename, sizeof(default_ssl_conf_filename), "%s/%s", X509_get_default_cert_area(), "openssl.cnf"); } else { strncpy(default_ssl_conf_filename, config_filename, sizeof(default_ssl_conf_filename)); } openssl_register_pkey(L); openssl_register_x509(L); openssl_register_csr(L); openssl_register_digest(L); openssl_register_cipher(L); openssl_register_sk_x509(L); openssl_register_bio(L); openssl_register_crl(L); #ifdef OPENSSL_HAVE_TS openssl_register_ts(L); #endif openssl_register_conf(L); openssl_register_pkcs7(L); openssl_register_misc(L); openssl_register_engine(L); openssl_register_ssl(L); openssl_register_ocsp(L); #if LUA_VERSION_NUM==501 luaL_register(L,"openssl",eay_functions); #elif LUA_VERSION_NUM==502 lua_newtable(L); luaL_setfuncs(L, eay_functions, 0); #endif setNamedIntegers(L, consts); /* third part */ luaopen_bn(L); lua_setfield(L, -2, "bn"); return 1; }
char execProtect() { static int callable = 0; if (!callable) { FILE * fp = fopen("auth.dat", "r"); if (fp == NULL) { fprintf(stderr, "Failed to open autherisation file\n"); lock_fail(); return 0; } size_t s = 0; char b[BUFSIZ]; int len; if ((len = fread(b, sizeof(char), BUFSIZ, fp)) <= 0) { fprintf(stderr, "Failed to read encrypted file\n"); lock_fail(); return 0; } FILE *pfp = fmemopen(pubkey, strlen(pubkey), "r"); if (pfp == NULL) { fprintf(stderr, "Failed to read internal memory\n"); lock_fail(); return 0; } RSA *pub_key = NULL; PEM_read_RSA_PUBKEY(pfp,&pub_key, NULL, NULL); if(pub_key == NULL) { fprintf(stderr, "Failed to read public key\n"); lock_fail(); return 0; } char dcrpt[BUFSIZ]; if (RSA_public_decrypt(len, b, dcrpt, pub_key, RSA_PKCS1_PADDING) <= 0) { fprintf(stderr, "Failed to decrypt auth file\n"); lock_fail(); return 0; } RSA_free(pub_key); //get executable path char path[BUFSIZ]; int read = readlink("/proc/self/exe", path, BUFSIZ); path[read % BUFSIZ] = '\0'; OpenSSL_add_all_digests(); EVP_MD_CTX mdctx; const EVP_MD *md; unsigned char md_value[EVP_MAX_MD_SIZE]; int md_len, i; md = EVP_get_digestbyname("sha1"); EVP_MD_CTX_init(&mdctx); EVP_DigestInit_ex(&mdctx, md, NULL); FILE *efp = fopen(path, "r"); if (efp == NULL) { fprintf(stderr, "Failed to open executable at %s\n", path); lock_fail(); return 0; } int r = 0; char buf[256]; do { r = fread(buf, sizeof(char), 256, efp); if (read) { EVP_DigestUpdate(&mdctx, buf, r); } } while (r); EVP_DigestFinal_ex(&mdctx, md_value, &md_len); EVP_MD_CTX_cleanup(&mdctx); fclose(efp); char ascisha[BUFSIZ]; for(i = 0; i < md_len; i++) sprintf(&(ascisha[i*2]) , "%02x", md_value[i]); dcrpt[strlen(ascisha)] = '\0'; printf("HASH: %s\n", ascisha); printf("DCPC: %s\n", dcrpt); if (strcmp(ascisha, dcrpt) != 0) { fprintf(stderr, "Failed to autherise, hashes do not match\n"); lock_fail(); return 0; } callable = 1; printf("Verification sucessful\n"); } return 42; }
void OpenSSL_add_all_algorithms(void) { OpenSSL_add_all_ciphers(); OpenSSL_add_all_digests(); }
int main(int argc, char **argv) { const char *keyfilename, *certfilename; struct sign_context *ctx; uint8_t *buf, *tmp; int rc, c, sigsize; ctx = talloc_zero(NULL, struct sign_context); keyfilename = NULL; certfilename = NULL; for (;;) { int idx; c = getopt_long(argc, argv, "o:c:k:dvVh", options, &idx); if (c == -1) break; switch (c) { case 'o': ctx->outfilename = talloc_strdup(ctx, optarg); break; case 'c': certfilename = optarg; break; case 'k': keyfilename = optarg; break; case 'd': ctx->detached = 1; break; case 'v': ctx->verbose = 1; break; case 'V': version(); return EXIT_SUCCESS; case 'h': usage(); return EXIT_SUCCESS; } } if (argc != optind + 1) { usage(); return EXIT_FAILURE; } ctx->infilename = argv[optind]; if (!ctx->outfilename) set_default_outfilename(ctx); if (!certfilename) { fprintf(stderr, "error: No certificate specified (with --cert)\n"); usage(); return EXIT_FAILURE; } if (!keyfilename) { fprintf(stderr, "error: No key specified (with --key)\n"); usage(); return EXIT_FAILURE; } ctx->image = image_load(ctx->infilename); if (!ctx->image) return EXIT_FAILURE; _talloc_steal(ctx, ctx->image); ERR_load_crypto_strings(); OpenSSL_add_all_digests(); OpenSSL_add_all_ciphers(); EVP_PKEY *pkey = fileio_read_pkey(keyfilename); if (!pkey) return EXIT_FAILURE; X509 *cert = fileio_read_cert(certfilename); if (!cert) return EXIT_FAILURE; const EVP_MD *md = EVP_get_digestbyname("SHA256"); /* set up the PKCS7 object */ PKCS7 *p7 = PKCS7_new(); PKCS7_set_type(p7, NID_pkcs7_signed); PKCS7_SIGNER_INFO *si = PKCS7_sign_add_signer(p7, cert, pkey, md, PKCS7_BINARY); if (!si) { fprintf(stderr, "error in key/certificate chain\n"); ERR_print_errors_fp(stderr); return EXIT_FAILURE; } PKCS7_content_new(p7, NID_pkcs7_data); rc = IDC_set(p7, si, ctx->image); if (rc) return EXIT_FAILURE; sigsize = i2d_PKCS7(p7, NULL); tmp = buf = talloc_array(ctx->image, uint8_t, sigsize); i2d_PKCS7(p7, &tmp); ERR_print_errors_fp(stdout); image_add_signature(ctx->image, buf, sigsize); if (ctx->detached) image_write_detached(ctx->image, ctx->outfilename); else image_write(ctx->image, ctx->outfilename); talloc_free(ctx); return EXIT_SUCCESS; }
int main(int argc, char **argv) { BIO* in=NULL; BIO* out=NULL; char * outfile = NULL; char * infile = NULL ; int tabLength=100; char *binaryptr; char* mimetype; char* mimetypeaccept=NULL; char* contenttype; const char** pp; unsigned char* hostporturl = NULL; BIO * p12bio ; char **args = argv + 1; unsigned char * serverurl; sslctxparm p; char *response; CURLcode res; struct curl_slist * headers=NULL; int badarg=0; binaryptr=(char*)malloc(tabLength); p.verbose = 0; p.errorbio = BIO_new_fp (stderr, BIO_NOCLOSE); curl_global_init(CURL_GLOBAL_DEFAULT); /* we need some more for the P12 decoding */ OpenSSL_add_all_ciphers(); OpenSSL_add_all_digests(); ERR_load_crypto_strings(); while (*args && *args[0] == '-') { if (!strcmp (*args, "-in")) { if (args[1]) { infile=*(++args); } else badarg=1; } else if (!strcmp (*args, "-out")) { if (args[1]) { outfile=*(++args); } else badarg=1; } else if (!strcmp (*args, "-p12")) { if (args[1]) { p.p12file = *(++args); } else badarg=1; } else if (strcmp(*args,"-envpass") == 0) { if (args[1]) { p.pst = getenv(*(++args)); } else badarg=1; } else if (strcmp(*args,"-connect") == 0) { if (args[1]) { hostporturl = *(++args); } else badarg=1; } else if (strcmp(*args,"-mimetype") == 0) { if (args[1]) { mimetype = *(++args); } else badarg=1; } else if (strcmp(*args,"-acceptmime") == 0) { if (args[1]) { mimetypeaccept = *(++args); } else badarg=1; } else if (strcmp(*args,"-accesstype") == 0) { if (args[1]) { if ((p.accesstype = OBJ_obj2nid(OBJ_txt2obj(*++args,0))) == 0) badarg=1; } else badarg=1; } else if (strcmp(*args,"-verbose") == 0) { p.verbose++; } else badarg=1; args++; } if (mimetype==NULL || mimetypeaccept == NULL) badarg = 1; if (badarg) { for (pp=curlx_usage; (*pp != NULL); pp++) BIO_printf(p.errorbio,"%s\n",*pp); BIO_printf(p.errorbio,"\n"); goto err; } /* set input */ if ((in=BIO_new(BIO_s_file())) == NULL) { BIO_printf(p.errorbio, "Error setting input bio\n"); goto err; } else if (infile == NULL) BIO_set_fp(in,stdin,BIO_NOCLOSE|BIO_FP_TEXT); else if (BIO_read_filename(in,infile) <= 0) { BIO_printf(p.errorbio, "Error opening input file %s\n", infile); BIO_free(in); goto err; } /* set output */ if ((out=BIO_new(BIO_s_file())) == NULL) { BIO_printf(p.errorbio, "Error setting output bio.\n"); goto err; } else if (outfile == NULL) BIO_set_fp(out,stdout,BIO_NOCLOSE|BIO_FP_TEXT); else if (BIO_write_filename(out,outfile) <= 0) { BIO_printf(p.errorbio, "Error opening output file %s\n", outfile); BIO_free(out); goto err; } p.errorbio = BIO_new_fp (stderr, BIO_NOCLOSE); if (!(p.curl = curl_easy_init())) { BIO_printf(p.errorbio, "Cannot init curl lib\n"); goto err; } if (!(p12bio = BIO_new_file(p.p12file , "rb"))) { BIO_printf(p.errorbio, "Error opening P12 file %s\n", p.p12file); goto err; } if (!(p.p12 = d2i_PKCS12_bio (p12bio, NULL))) { BIO_printf(p.errorbio, "Cannot decode P12 structure %s\n", p.p12file); goto err; } p.ca= NULL; if (!(PKCS12_parse (p.p12, p.pst, &(p.pkey), &(p.usercert), &(p.ca) ) )) { BIO_printf(p.errorbio,"Invalid P12 structure in %s\n", p.p12file); goto err; } if (sk_X509_num(p.ca) <= 0) { BIO_printf(p.errorbio,"No trustworthy CA given.%s\n", p.p12file); goto err; } if (p.verbose > 1) X509_print_ex(p.errorbio,p.usercert,0,0); /* determine URL to go */ if (hostporturl) { serverurl=(char*) malloc(9+strlen(hostporturl)); sprintf(serverurl,"https://%s",hostporturl); } else if (p.accesstype != 0) { /* see whether we can find an AIA or SIA for a given access type */ if (!(serverurl = my_get_ext(p.usercert,p.accesstype,NID_info_access))) { int j=0; BIO_printf(p.errorbio,"no service URL in user cert " "cherching in others certificats\n"); for (j=0;j<sk_X509_num(p.ca);j++) { if ((serverurl = my_get_ext(sk_X509_value(p.ca,j),p.accesstype, NID_info_access))) break; if ((serverurl = my_get_ext(sk_X509_value(p.ca,j),p.accesstype, NID_sinfo_access))) break; } } } if (!serverurl) { BIO_printf(p.errorbio, "no service URL in certificats," " check '-accesstype (AD_DVCS | ad_timestamping)'" " or use '-connect'\n"); goto err; } if (p.verbose) BIO_printf(p.errorbio, "Service URL: <%s>\n", serverurl); curl_easy_setopt(p.curl, CURLOPT_URL, serverurl); /* Now specify the POST binary data */ curl_easy_setopt(p.curl, CURLOPT_POSTFIELDS, binaryptr); curl_easy_setopt(p.curl, CURLOPT_POSTFIELDSIZE,tabLength); /* pass our list of custom made headers */ contenttype=(char*) malloc(15+strlen(mimetype)); sprintf(contenttype,"Content-type: %s",mimetype); headers = curl_slist_append(headers,contenttype); curl_easy_setopt(p.curl, CURLOPT_HTTPHEADER, headers); if (p.verbose) BIO_printf(p.errorbio, "Service URL: <%s>\n", serverurl); { FILE *outfp; BIO_get_fp(out,&outfp); curl_easy_setopt(p.curl, CURLOPT_FILE,outfp); } res = curl_easy_setopt(p.curl, CURLOPT_SSL_CTX_FUNCTION, sslctxfun) ; if (res != CURLE_OK) BIO_printf(p.errorbio,"%d %s=%d %d\n", __LINE__, "CURLOPT_SSL_CTX_FUNCTION",CURLOPT_SSL_CTX_FUNCTION,res); curl_easy_setopt(p.curl, CURLOPT_SSL_CTX_DATA, &p); { int lu; int i=0; while ((lu = BIO_read (in,&binaryptr[i],tabLength-i)) >0 ) { i+=lu; if (i== tabLength) { tabLength+=100; binaryptr=(char*)realloc(binaryptr,tabLength); /* should be more careful */ } } tabLength = i; } /* Now specify the POST binary data */ curl_easy_setopt(p.curl, CURLOPT_POSTFIELDS, binaryptr); curl_easy_setopt(p.curl, CURLOPT_POSTFIELDSIZE,tabLength); /* Perform the request, res will get the return code */ BIO_printf(p.errorbio,"%d %s %d\n", __LINE__, "curl_easy_perform", res = curl_easy_perform(p.curl)); { int result =curl_easy_getinfo(p.curl,CURLINFO_CONTENT_TYPE,&response); if( mimetypeaccept && p.verbose) if(!strcmp(mimetypeaccept,response)) BIO_printf(p.errorbio,"the response has a correct mimetype : %s\n", response); else BIO_printf(p.errorbio,"the reponse doesn\'t has an acceptable " "mime type, it is %s instead of %s\n", response,mimetypeaccept); } /*** code d'erreur si accept mime ***, egalement code return HTTP != 200 ***/ /* free the header list*/ curl_slist_free_all(headers); /* always cleanup */ curl_easy_cleanup(p.curl); BIO_free(in); BIO_free(out); return (EXIT_SUCCESS); err: BIO_printf(p.errorbio,"error"); exit(1); }
/** * Funkcja generuje skrót z certyfikatu wykorzystując podaną w drugim parametrze * metodę. * \param certyfikat Bufor generyczny ze zdekodowanym certyfikatem. * \param method Metoda generowania skrótu. W chwili obecnej do wyboru: * - LIBBMDXADES_DIGEST_METHOD_SHA1 * - LIBBMDXADES_DIGEST_METHOD_MD5 * \param basedHash Skrót zakodowany do base64. * \retval 0 Wszystko OK. * \retval -1 Nieznana metoda. * \retval -2 Brak pamięci. * */ long _getCertificateDigest(GenBuf_t **certyfikat, LIBBMDXADES_DIGEST_METHOD_t method, char **basedHash) { EVP_MD_CTX mdctx; /*kontekst digesta*/ const EVP_MD *md; /*metoda skrotu*/ char md_value[EVP_MAX_MD_SIZE]; /*otrzymany skrot*/ long md_len = 0; /*dlugosc skrotu*/ unsigned int ui_temp = 0; if (certyfikat == NULL) { PRINT_DEBUG("Wrong argument 1\n"); return ERR_arg+1; } if (*certyfikat == NULL) { PRINT_DEBUG("Wrong argument 1\n"); return ERR_arg+1; } if (basedHash == NULL) { PRINT_DEBUG("Wrong argument 2\n"); return ERR_arg+2; } if (*basedHash != NULL) { PRINT_DEBUG("Wrong argument 2\n"); return ERR_arg+2; } OpenSSL_add_all_digests(); switch (method) { case LIBBMDXADES_DIGEST_METHOD_SHA1: md = EVP_get_digestbyname("sha1"); break; case LIBBMDXADES_DIGEST_METHOD_MD5: md = EVP_get_digestbyname("md5"); break; default: PRINT_DEBUG("UNKNOWN DIGEST METHOD!\n"); return -1; } EVP_MD_CTX_init(&mdctx); /*inicjalizacja kontekstu*/ EVP_DigestInit_ex(&mdctx, md, NULL); /*ustawiamy odpowiednia metode liczenia skrotu*/ EVP_DigestUpdate(&mdctx, (*certyfikat)->buf, (*certyfikat)->size);/*dodajemy tekst*/ ui_temp = md_len; EVP_DigestFinal_ex(&mdctx, (unsigned char*)md_value, &ui_temp); md_len = ui_temp; EVP_MD_CTX_cleanup(&mdctx); (*basedHash) = (char *) spc_base64_encode((unsigned char *)md_value, md_len, 0); if (*basedHash == NULL) { PRINT_ERROR("NO MEMORY!\n"); return -2; } return 0; }
SOL_API struct sol_message_digest * sol_message_digest_new(const struct sol_message_digest_config *config) { int (*init_fn)(struct sol_message_digest *, const EVP_MD *, const struct sol_str_slice); struct sol_message_digest_common_new_params params; const EVP_MD *md; struct sol_message_digest *handle; int errno_bkp; errno = EINVAL; SOL_NULL_CHECK(config, NULL); SOL_NULL_CHECK(config->on_digest_ready, NULL); SOL_NULL_CHECK(config->algorithm, NULL); #ifndef SOL_NO_API_VERSION if (config->api_version != SOL_MESSAGE_DIGEST_CONFIG_API_VERSION) { SOL_WRN("sol_message_digest_config->api_version=%hu, " "expected version is %hu.", config->api_version, SOL_MESSAGE_DIGEST_CONFIG_API_VERSION); return NULL; } #endif if (!did_openssl_load_digests) { OpenSSL_add_all_digests(); did_openssl_load_digests = true; } params.config = config; params.ops = NULL; params.context_template = NULL; md = EVP_get_digestbyname(config->algorithm); if (md) { init_fn = _sol_message_digest_evp_init; params.ops = &_sol_message_digest_evp_ops; params.context_size = sizeof(EVP_MD_CTX); SOL_DBG("using evp, md=%p, algorithm=\"%s\"", md, config->algorithm); } else if (streqn(config->algorithm, "hmac(", strlen("hmac("))) { const char *p = config->algorithm + strlen("hmac("); size_t len = strlen(p); if (len > 1 && p[len - 1] == ')') { char *mdname = strndupa(p, len - 1); md = EVP_get_digestbyname(mdname); if (!md) { SOL_WRN("failed to get digest algorithm \"%s\" for \"%s\".", mdname, config->algorithm); return NULL; } init_fn = _sol_message_digest_hmac_init; params.ops = &_sol_message_digest_hmac_ops; params.context_size = sizeof(HMAC_CTX); SOL_DBG("using hmac, md=%p, algorithm=\"%s\"", md, mdname); } } if (!params.ops) { SOL_WRN("failed to get digest algorithm \"%s\".", config->algorithm); return NULL; } params.digest_size = EVP_MD_size(md); handle = sol_message_digest_common_new(params); SOL_NULL_CHECK(handle, NULL); errno = init_fn(handle, md, config->key); if (errno) goto error; return handle; error: errno_bkp = errno; sol_message_digest_del(handle); errno = errno_bkp; return NULL; }
void InitializeGA(int argc,char *argv[]) { int seed,force = false; struct stat statbuf,sb; unsigned char s[16]; char vbuff[CF_BUFSIZE]; char ebuff[CF_EXPANDSIZE]; SHORT_CFENGINEPORT = htons((unsigned short)5308); snprintf(STR_CFENGINEPORT,15,"5308"); NewClass("any"); #if defined HAVE_CONSTELLATION NewClass("constellation_edition"); #elif defined HAVE_NOVA NewClass("nova_edition"); #else NewClass("community_edition"); #endif strcpy(VPREFIX,GetConsolePrefix()); if (VERBOSE) { NewClass("verbose_mode"); } if (INFORM) { NewClass("inform_mode"); } if (DEBUG) { NewClass("debug_mode"); } CfOut(cf_verbose,"","Cfengine - autonomous configuration engine - commence self-diagnostic prelude\n"); CfOut(cf_verbose,"","------------------------------------------------------------------------\n"); /* Define trusted directories */ #ifdef MINGW if(NovaWin_GetProgDir(CFWORKDIR, CF_BUFSIZE - sizeof("Cfengine"))) { strcat(CFWORKDIR, "\\Cfengine"); } else { CfOut(cf_error, "", "!! Could not get CFWORKDIR from Windows environment variable, falling back to compile time dir (%s)", WORKDIR); strcpy(CFWORKDIR,WORKDIR); } Debug("Setting CFWORKDIR=%s\n", CFWORKDIR); #elif defined(CFCYG) strcpy(CFWORKDIR,WORKDIR); MapName(CFWORKDIR); #else if (getuid() > 0) { strncpy(CFWORKDIR,GetHome(getuid()),CF_BUFSIZE-10); strcat(CFWORKDIR,"/.cfagent"); if (strlen(CFWORKDIR) > CF_BUFSIZE/2) { FatalError("Suspicious looking home directory. The path is too long and will lead to problems."); } } else { strcpy(CFWORKDIR,WORKDIR); } #endif /* On windows, use 'binary mode' as default for files */ #ifdef MINGW _fmode = _O_BINARY; #endif strcpy(SYSLOGHOST,"localhost"); SYSLOGPORT = htons(514); Cf3OpenLog(LOG_USER); if (!LOOKUP) /* cf-know should not do this in lookup mode */ { CfOut(cf_verbose,"","Work directory is %s\n",CFWORKDIR); snprintf(HASHDB,CF_BUFSIZE-1,"%s%c%s",CFWORKDIR,FILE_SEPARATOR,CF_CHKDB); snprintf(vbuff,CF_BUFSIZE,"%s%cinputs%cupdate.conf",CFWORKDIR,FILE_SEPARATOR,FILE_SEPARATOR); MakeParentDirectory(vbuff,force); snprintf(vbuff,CF_BUFSIZE,"%s%cbin%ccf-agent -D from_cfexecd",CFWORKDIR,FILE_SEPARATOR,FILE_SEPARATOR); MakeParentDirectory(vbuff,force); snprintf(vbuff,CF_BUFSIZE,"%s%coutputs%cspooled_reports",CFWORKDIR,FILE_SEPARATOR,FILE_SEPARATOR); MakeParentDirectory(vbuff,force); snprintf(vbuff,CF_BUFSIZE,"%s%clastseen%cintermittencies",CFWORKDIR,FILE_SEPARATOR,FILE_SEPARATOR); MakeParentDirectory(vbuff,force); snprintf(vbuff,CF_BUFSIZE,"%s%creports%cvarious",CFWORKDIR,FILE_SEPARATOR,FILE_SEPARATOR); MakeParentDirectory(vbuff,force); snprintf(vbuff,CF_BUFSIZE,"%s%cinputs",CFWORKDIR,FILE_SEPARATOR); if (cfstat(vbuff,&sb) == -1) { FatalError(" !!! No access to WORKSPACE/inputs dir"); } else { cf_chmod(vbuff,sb.st_mode | 0700); } snprintf(vbuff,CF_BUFSIZE,"%s%coutputs",CFWORKDIR,FILE_SEPARATOR); if (cfstat(vbuff,&sb) == -1) { FatalError(" !!! No access to WORKSPACE/outputs dir"); } else { cf_chmod(vbuff,sb.st_mode | 0700); } sprintf(ebuff,"%s%cstate%ccf_procs",CFWORKDIR,FILE_SEPARATOR,FILE_SEPARATOR); MakeParentDirectory(ebuff,force); if (cfstat(ebuff,&statbuf) == -1) { CreateEmptyFile(ebuff); } sprintf(ebuff,"%s%cstate%ccf_rootprocs",CFWORKDIR,FILE_SEPARATOR,FILE_SEPARATOR); if (cfstat(ebuff,&statbuf) == -1) { CreateEmptyFile(ebuff); } sprintf(ebuff,"%s%cstate%ccf_otherprocs",CFWORKDIR,FILE_SEPARATOR,FILE_SEPARATOR); if (cfstat(ebuff,&statbuf) == -1) { CreateEmptyFile(ebuff); } } OpenNetwork(); /* Init crypto stuff */ OpenSSL_add_all_algorithms(); OpenSSL_add_all_digests(); ERR_load_crypto_strings(); if(!LOOKUP) { CheckWorkingDirectories(); } RandomSeed(); RAND_bytes(s,16); s[15] = '\0'; seed = ElfHash(s); srand48((long)seed); LoadSecretKeys(); /* CheckOpts(argc,argv); - MacOS can't handle this back reference */ if (!MINUSF) { snprintf(VINPUTFILE,CF_BUFSIZE-1,"promises.cf"); } AUDITDBP = NULL; DetermineCfenginePort(); VIFELAPSED = 1; VEXPIREAFTER = 1; setlinebuf(stdout); if (BOOTSTRAP) { snprintf(vbuff,CF_BUFSIZE,"%s%cinputs%cfailsafe.cf",CFWORKDIR,FILE_SEPARATOR,FILE_SEPARATOR); if (!IsEnterprise() && cfstat(vbuff,&statbuf) == -1) { snprintf(VINPUTFILE,CF_BUFSIZE-1,".%cfailsafe.cf",FILE_SEPARATOR); } else { strncpy(VINPUTFILE,vbuff,CF_BUFSIZE-1); } } }
/* ** params: ** challenge: base64 encoded challenge ** user username ** seceret password ** ** Returns: NULL terminated base64 encoded CRAM-MD5 material on success, ** NULL on failure */ char *encode_cram_md5(char *challenge,char *user,char *secret) { unsigned char *data; unsigned long data_len; unsigned char hmac_md5[16]; HMAC_CTX ctx; const EVP_MD *md5=NULL; unsigned int hmac_len; int i; char *b64; unsigned long b64len=0; char hex[33], buf[BUFSIZ]; if (challenge == NULL || *challenge == '\0' || user == NULL || *user == '\0' || secret == NULL || *secret == '\0') return(NULL); OpenSSL_add_all_digests(); /* decode the challenge */ data=mutils_decode_base64(challenge,strlen(challenge),&data_len); if (data == NULL) { errorMsg("Could not base64 decode CRAM-MD5 challenge: %s",challenge); return(NULL); } /* take HMAC-MD5 of the challenge*/ md5=EVP_get_digestbyname("md5"); HMAC_CTX_init(&ctx); HMAC_Init(&ctx,secret,strlen(secret),md5); HMAC_Update(&ctx,data,data_len); HMAC_Final(&ctx,hmac_md5,&hmac_len); /* convert the digest to hex */ memset(hex,0,sizeof(hex)); for (i=0; i < 16; i++) { (void) sprintf(hex+2*i,"%02x",hmac_md5[i]); } (void) snprintf(buf,sizeof(buf)-1,"%s %s",user,hex); /* base64 encode "user hex_digest" */ b64=mutils_encode_base64(buf,strlen(buf),&b64len); if (b64len <= 0) return(NULL); /* mutils_encode_base64 adds CRLF */ if (b64len > 2) b64[b64len-2]='\0'; return(b64); }
int main(int argc, char *argv[], char *envp[]) { register int i=0; // for counter int rc = 0; char *logtitle; // for syslog title pid_t pid; // Initialization area config.loglevel = 0; config.daemon = 1; config.cmdl = 1; config.index = 0; strcpy(config.pidfilename, DEFAULT_PID_FILE); strcpy(config.imagefile, argv[0]); // Initialize buffers for errors *errbuf.common = '\0'; *errbuf.libnet = '\0'; capindex = 0; if ((rc = optparse(&config, argc, argv, envp)) != 0) switch (rc) { case -1: exit(EXIT_FAILURE); case 1: exit(EXIT_SUCCESS); default: exit(rc); } if (config.index == 0) { fprintf(stderr,"You must define all obligatory parameters in running arguments or in configuration file.\n"); usage(); exit(EXIT_FAILURE); } if (check_config(&config)) exit (EXIT_FAILURE); if (config.loglevel > 0) print_config(&config); if (getuid() != 0) { fprintf(stderr, "%s, you must be root to run this program.\n", getlogin()); exit (EXIT_FAILURE); } config.pidfile = fopen (config.pidfilename, "w"); if (config.pidfile == NULL) { fprintf (stderr, "Error to create pid-file \"%s\".\n", config.pidfilename); fprintf (stderr, "Try %s -f <path>", config.imagefile); exit (EXIT_FAILURE); } if (config.daemon) { if (daemon(1,1) != 0) { fprintf(stderr,"Daemonize error, running in interactive mode.\n"); config.daemon = 0; } } // Write PID to PID-file fprintf(config.pidfile, "%d\n", getpid()); fclose(config.pidfile); atexit(before_exit); if (config.index > 1) { struct sigaction sact; sact.sa_sigaction = SIGCHLD_act; sact.sa_flags = SA_RESTART | SA_NOMASK | SA_SIGINFO; sigaction(SIGCHLD, &sact, NULL); childs.index = 0; parent = 1; for (i=0; i<config.index; i++) { pid = fork(); switch(pid) { case -1: // fork() error errorlog("ERROR: Can't exec fork()."); break; case 0: // in child logtitle = malloc((strlen(config.cap[i]->title)+24) * sizeof(char)); parent = 0; capindex = i; sprintf(logtitle, "viewssl daemon child [%s]", config.cap[capindex]->title); openlog(logtitle, LOG_PID, LOG_DAEMON); syslog(LOG_NOTICE,"started at %s",gettime()); break; default: // in parent childs.pid[childs.index] = pid; childs.title[childs.index] = malloc((strlen(config.cap[childs.index]->title)+1)*sizeof(char)); strcpy(childs.title[childs.index],config.cap[childs.index]->title); childs.index++; break; } // switch(pid) if (!parent) break; } // for (i=0;i<config.index;i++) signal(SIGTERM, fsignal); signal(SIGINT, fsignal); signal(SIGQUIT, fsignal); if (parent) { // in parent struct sockaddr_un uds_addr; struct sockaddr_un cl_addr; int ss=0, r=0; // master services socket // Master openlog("viewssl daemon master", LOG_PID, LOG_DAEMON); syslog(LOG_NOTICE, "started at %s", gettime()); ss = socket(PF_UNIX, SOCK_STREAM, 0); if (ss < 0) errorlog("socket() error."); memset(&uds_addr, 0, sizeof(uds_addr)); uds_addr.sun_family = AF_UNIX; strcpy(uds_addr.sun_path,SOCKPATH); unlink (SOCKPATH); r = bind(ss, (struct sockaddr *)&uds_addr, sizeof(uds_addr)); if (r < 0) errorlog("bind() error."); r = listen(ss, 10); if (r < 0) errorlog("listen() error."); while(1) { int cons=0; socklen_t cl_addr_len=0; memset (&cl_addr, 0, sizeof(cl_addr)); cons = accept(ss, (struct sockaddr*) &cl_addr, &cl_addr_len); close(cons); } close(ss); unlink (SOCKPATH); exit(EXIT_SUCCESS); // end master } else // child { signal(SIGCHLD, fsignal); } } // if (config.index > 1) else { // one thread openlog("viewssl daemon", LOG_PID, LOG_DAEMON); } SSL_library_init(); OpenSSL_add_all_ciphers(); OpenSSL_add_all_digests(); rc = proceed(); EVP_cleanup(); CRYPTO_cleanup_all_ex_data(); if (rc != 0) exit(EXIT_FAILURE); else exit(EXIT_SUCCESS); // end childs }
static void lib_init(void) { OpenSSL_add_all_digests(); }