bool Digestor::HashFile(const std::string &path, int required, ByteArray &res) { const int kBufferSize = 1024 * 16; //FileInfo::FileStatus st_before = FileInfo::StatFile(path); unsigned char md5hash[16] = {0}; unsigned char sha1hash[20] = {0}; unsigned char sha512hash[64] = {0}; MD5_CTX md5ctx; SHA_CTX sha1ctx; SHA512_CTX sha512ctx; MD5_Init(&md5ctx); SHA1_Init(&sha1ctx); SHA512_Init(&sha512ctx); File inf; char buffer[kBufferSize]; if (!inf.OpenForRead(path)) { return false; } unsigned long read_bytes; while (1) { if (!inf.Read(buffer, kBufferSize, &read_bytes)) { inf.Close(); return false; } if (read_bytes == 0) break; if (required & HASH_MD5) MD5_Update(&md5ctx, buffer, read_bytes); if (required & HASH_SHA1) SHA1_Update(&sha1ctx, buffer, read_bytes); if (required & HASH_SHA512) SHA512_Update(&sha512ctx, buffer, read_bytes); } inf.Close(); if (required & HASH_MD5) { MD5_Final(md5hash, &md5ctx); res.insert(res.end(), md5hash, md5hash + 16); } if (required & HASH_SHA1) { SHA1_Final(sha1hash, &sha1ctx); res.insert(res.end(), sha1hash, sha1hash + 20); } if (required & HASH_SHA512) { SHA512_Final(sha512hash, &sha512ctx); res.insert(res.end(), sha512hash, sha512hash + 64); } // FileInfo::FileStatus st_after = FileInfo::StatFile(path); // if (st_before.size != st_after.size || st_before.modifytime != st_after.modifytime) { // res.clear(); // return false; // } return true; }
static int init(EVP_MD_CTX *ctx) { return SHA1_Init(ctx->md_data); }
void ICACHE_FLASH_ATTR WebSocketGotData( uint8_t c ) { switch( curhttp->state_deets ) { case 0: { int i = 0; char inkey[120]; unsigned char hash[SHA1_HASH_LEN]; SHA1_CTX c; int inkeylen = 0; curhttp->is_dynamic = 1; while( curlen > 20 ) { curdata++; curlen--; if( strncmp( curdata, "Sec-WebSocket-Key: ", 19 ) == 0 ) { break; } } if( curlen <= 21 ) { HTDEBUG( "No websocket key found.\n" ); curhttp->state = HTTP_WAIT_CLOSE; return; } curdata+= 19; curlen -= 19; #define WS_KEY_LEN 36 #define WS_KEY "258EAFA5-E914-47DA-95CA-C5AB0DC85B11" #define WS_RETKEY_SIZEM1 32 while( curlen > 1 ) { uint8_t lc = *(curdata++); inkey[i] = lc; curlen--; if( lc == '\r' ) { inkey[i] = 0; break; } i++; if( i >= sizeof( inkey ) - WS_KEY_LEN - 5 ) { HTDEBUG( "Websocket key too big.\n" ); curhttp->state = HTTP_WAIT_CLOSE; return; } } if( curlen <= 1 ) { HTDEBUG( "Invalid websocket key found.\n" ); curhttp->state = HTTP_WAIT_CLOSE; return; } if( i + WS_KEY_LEN + 1 >= sizeof( inkey ) ) { HTDEBUG( "WSKEY Too Big.\n" ); curhttp->state = HTTP_WAIT_CLOSE; return; } ets_memcpy( &inkey[i], WS_KEY, WS_KEY_LEN + 1 ); i += WS_KEY_LEN; SHA1_Init( &c ); SHA1_Update( &c, inkey, i ); SHA1_Final( hash, &c ); #if (WS_RETKEY_SIZE > MAX_PATHLEN - 10 ) #error MAX_PATHLEN too short. #endif my_base64_encode( hash, SHA1_HASH_LEN, curhttp->pathbuffer + (MAX_PATHLEN-WS_RETKEY_SIZEM1) ); curhttp->bytessofar = 0; curhttp->bytesleft = 0; NewWebSocket(); //Respond... curhttp->state_deets = 1; break; } case 1: if( c == '\n' ) curhttp->state_deets = 2; break; case 2: if( c == '\r' ) curhttp->state_deets = 3; else curhttp->state_deets = 1; break; case 3: if( c == '\n' ) curhttp->state_deets = 4; else curhttp->state_deets = 1; break; case 5: //Established connection. { //XXX TODO: Seems to malfunction on large-ish packets. I know it has problems with 140-byte payloads. if( curlen < 5 ) //Can't interpret packet. break; uint8_t fin = c & 1; uint8_t opcode = c << 4; uint16_t payloadlen = *(curdata++); curlen--; if( !(payloadlen & 0x80) ) { HTDEBUG( "Unmasked packet.\n" ); curhttp->state = HTTP_WAIT_CLOSE; break; } payloadlen &= 0x7f; if( payloadlen == 127 ) { //Very long payload. //Not supported. HTDEBUG( "Unsupported payload packet.\n" ); curhttp->state = HTTP_WAIT_CLOSE; break; } else if( payloadlen == 126 ) { payloadlen = (curdata[0] << 8) | curdata[1]; curdata += 2; curlen -= 2; } wsmask[0] = curdata[0]; wsmask[1] = curdata[1]; wsmask[2] = curdata[2]; wsmask[3] = curdata[3]; curdata += 4; curlen -= 4; wsmaskplace = 0; //XXX Warning: When packets get larger, they may split the //websockets packets into multiple parts. We could handle this //but at the cost of prescious RAM. I am chosing to just drop those //packets on the floor, and restarting the connection. if( curlen < payloadlen ) { HTDEBUG( "Websocket Fragmented. %d %d\n", curlen, payloadlen ); curhttp->state = HTTP_WAIT_CLOSE; return; } WebSocketData( payloadlen ); curlen -= payloadlen; curdata += payloadlen; break; } default: break; } }
static int recv_file(int sock, const char *filepath, unsigned char digest[SHA_DIGEST_LENGTH]) { char recvbuf[RECVBUF_SIZE]; ssize_t n; size_t total_bytes = 0, total_bytes_session = 0; SHA_CTX ctx; int ret = EXIT_FAILURE; FILE *f; struct timeval start_time, end_time, diff_time = { 0, 0 }; if (!filepath) filepath = "/tmp/data"; f = fopen(filepath, "w"); if (!f) { fprintf(stderr, "Could not open file %s for writing\n", filepath); return EXIT_FAILURE; } SHA1_Init(&ctx); gettimeofday(&start_time, NULL); printf("Writing data to %s\n", filepath); while (!should_exit) { n = recv_sv(sock, recvbuf, RECVBUF_SIZE, 0); /* printf("received %zd bytes\n", n); */ if (n < 0) { fprintf(stderr, "\rerror receiving data: %s\n", strerror(errno)); ret = EXIT_FAILURE; break; } if (n == 0) { fprintf(stdout, "\rconnection closed\n"); ret = EXIT_SUCCESS; should_exit = 1; SHA1_Final(digest, &ctx); gettimeofday(&end_time, NULL); break; } total_bytes += n; total_bytes_session += n; print_tick(); //printf("Received %zd bytes data, total=%zu\n", n, total_bytes); //long pos = ftell(f); size_t nmem = fwrite(recvbuf, n, 1, f); SHA1_Update(&ctx, recvbuf, n); if (nmem != 1) { fprintf(stderr, "\rError writing to file\n"); break; } //printf("Wrote %ld bytes data to %s\n", ftell(f) - pos, filepath); } if (ret == EXIT_SUCCESS) { timeval_sub(&diff_time, &end_time, &start_time); printf("Finished successfully in %ld.%06ld seconds\n", diff_time.tv_sec, (long)diff_time.tv_usec); } fprintf(stdout, "Read %zu bytes total\n", total_bytes); fprintf(stdout, "Wrote to file %s\n", filepath); fprintf(stdout, "Closing sockets...\n"); return ret; }
void *worker(void *params) { // life cycle of a cracking pthread uint64_t e_be; // storage for our "big-endian" version of e uint8_t buf[SHA1_DIGEST_LEN], der[RSA_EXP_DER_LEN + 1], // TODO: is the size of this right? optimum = *(uint8_t*)params; //char onion[BASE32_ONIONLEN]; char onion[DESC_ID_V2_LEN_BASE32 + 1]; //char identity_key_base32[DESC_ID_V2_LEN_BASE32 + 1]; SHA_CTX hash, copy; RSA *rsa; while(!found) { // keys are only generated every so often // every 549,755,781,120 tries by default if(optimum) rsa = easygen(RSA_OPTM_BITLEN - RSA_PK_E_LENGTH * 8, RSA_PK_E_LENGTH, der, RSA_OPT_DER_LEN, &hash); else rsa = easygen(RSA_KEYS_BITLEN, RSA_PK_E_LENGTH, der, RSA_EXP_DER_LEN, &hash); if(!rsa) // if key generation fails (no [P]RNG seed?) error(X_KEY_GEN_FAILS); uint8_t e_bytes = RSA_PK_E_LENGTH; // number of bytes e occupies uint64_t e = RSA_PK_EXPONENT; // public exponent uint64_t e_byte_thresh; int_pow(2, e_bytes * 8, &e_byte_thresh); e_byte_thresh++; uint8_t *e_ptr = ((uint8_t*)&e_be) + 8 - e_bytes; while((e <= elim) && !found) { // main loop // copy the relevant parts of our already set up context memcpy(©, &hash, SHA_REL_CTX_LEN); // 40 bytes here... copy.num = hash.num; // and don't forget the num (9) // convert e to big-endian format e_be = htobe64(e); // compute SHA1 digest (majority of loop time spent here!) SHA1_Update(©, e_ptr, e_bytes); SHA1_Final(buf, ©); base32_onion(onion, buf); // base32-encode SHA1 digest loop++; // keep track of our tries... if(!regexec(regex, onion, 0, 0, 0)) { // check for a match // let our main thread know on which thread to wait lucky_thread = pthread_self(); found = 1; // kill off our other threads, asynchronously if(monitor) printf("\n"); // keep our printing pretty! if(!BN_bin2bn(e_ptr, e_bytes, rsa->e)) // store our e in the actual key error(X_BIGNUM_FAILED); // and make sure it got there if(!sane_key(rsa)) // check our key error(X_YOURE_UNLUCKY); // bad key :( print_onion(onion); // print our domain print_prkey(rsa); // and more importantly the key RSA_free(rsa); // free up what's left return 0; } e += 2; // do *** NOT *** forget this! if(e == e_byte_thresh) { // ASN.1 stuff (hey, it could be worse!) // calculate our new threshold int_pow(2, ++e_bytes * 8, &e_byte_thresh); e_byte_thresh++; if(optimum) { RSA_free(rsa); easygen(RSA_OPTM_BITLEN - e_bytes * 8, e_bytes, der, RSA_OPT_DER_LEN, &hash); if(!rsa) error(X_KEY_GEN_FAILS); } else { // play with our key structure (do not try this at home!) der[RSA_ADD_DER_OFF]++; der[RSA_EXP_DER_LEN - RSA_PK_E_LENGTH - 1]++; // and our prebuilt hash SHA1_Init(&hash); // TODO: move to a function SHA1_Update(&hash, der, RSA_EXP_DER_LEN - RSA_PK_E_LENGTH); } e_ptr--; // and move the pointer back } } RSA_free(rsa); } return 0; }
/* * Create an access check structure, the format depends on the version parameter. * If broken is specified then we create a stucture that isn't conform to the * specification. * * If the structure can't be created then NULL is returned. */ static DATA_BLOB *create_access_check(struct torture_context *tctx, struct dcerpc_pipe *p, TALLOC_CTX *mem_ctx, const char *user, bool broken, uint32_t version) { TALLOC_CTX *tmp_ctx = talloc_new(mem_ctx); DATA_BLOB *blob = talloc_zero(mem_ctx, DATA_BLOB); enum ndr_err_code ndr_err; const struct dom_sid *sid = get_user_sid(tctx, p, tmp_ctx, user); if (sid == NULL) { return NULL; } if (version == 2) { struct bkrp_access_check_v2 access_struct; struct sha sctx; uint8_t nonce[32]; ZERO_STRUCT(access_struct); generate_random_buffer(nonce, sizeof(nonce)); access_struct.nonce_len = sizeof(nonce); access_struct.nonce = nonce; access_struct.sid = *sid; ndr_err = ndr_push_struct_blob(blob, blob, &access_struct, (ndr_push_flags_fn_t)ndr_push_bkrp_access_check_v2); if (!NDR_ERR_CODE_IS_SUCCESS(ndr_err)) { return NULL; } /* * We pushed the whole structure including a null hash * but the hash need to be calculated only up to the hash field * so we reduce the size of what has to be calculated */ SHA1_Init(&sctx); SHA1_Update(&sctx, blob->data, blob->length - sizeof(access_struct.hash)); SHA1_Final(blob->data + blob->length - sizeof(access_struct.hash), &sctx); /* Altering the SHA */ if (broken) { blob->data[blob->length - 1]++; } } if (version == 3) { struct bkrp_access_check_v3 access_struct; struct hc_sha512state sctx; uint8_t nonce[32]; ZERO_STRUCT(access_struct); generate_random_buffer(nonce, sizeof(nonce)); access_struct.nonce_len = sizeof(nonce); access_struct.nonce = nonce; access_struct.sid = *sid; ndr_err = ndr_push_struct_blob(blob, blob, &access_struct, (ndr_push_flags_fn_t)ndr_push_bkrp_access_check_v3); if (!NDR_ERR_CODE_IS_SUCCESS(ndr_err)) { return NULL; } /*We pushed the whole structure including a null hash * but the hash need to be calculated only up to the hash field * so we reduce the size of what has to be calculated */ SHA512_Init(&sctx); SHA512_Update(&sctx, blob->data, blob->length - sizeof(access_struct.hash)); SHA512_Final(blob->data + blob->length - sizeof(access_struct.hash), &sctx); /* Altering the SHA */ if (broken) { blob->data[blob->length -1]++; } } talloc_free(tmp_ctx); return blob; }
SHA1Hash::SHA1Hash() { SHA1_Init(&mC); }
double hash_command_output(entropy_cmd_t *src, unsigned char *hash) { char buf[8192]; fd_set rdset; int bytes_read, cmd_eof, error_abort, msec_elapsed, p[2]; int status, total_bytes_read; static int devnull = -1; pid_t pid; SHA_CTX sha; struct timeval tv_start, tv_current; debug3("Reading output from \'%s\'", src->cmdstring); if (devnull == -1) { devnull = open("/dev/null", O_RDWR); if (devnull == -1) fatal("Couldn't open /dev/null: %s", strerror(errno)); } if (pipe(p) == -1) fatal("Couldn't open pipe: %s", strerror(errno)); (void)gettimeofday(&tv_start, NULL); /* record start time */ switch (pid = fork()) { case -1: /* Error */ close(p[0]); close(p[1]); fatal("Couldn't fork: %s", strerror(errno)); /* NOTREACHED */ case 0: /* Child */ dup2(devnull, STDIN_FILENO); dup2(p[1], STDOUT_FILENO); dup2(p[1], STDERR_FILENO); close(p[0]); close(p[1]); close(devnull); execv(src->path, (char**)(src->args)); debug("(child) Couldn't exec '%s': %s", src->cmdstring, strerror(errno)); _exit(-1); default: /* Parent */ break; } RAND_add(&pid, sizeof(&pid), 0.0); close(p[1]); /* Hash output from child */ SHA1_Init(&sha); cmd_eof = error_abort = msec_elapsed = total_bytes_read = 0; while (!error_abort && !cmd_eof) { int ret; struct timeval tv; int msec_remaining; (void) gettimeofday(&tv_current, 0); msec_elapsed = timeval_diff(&tv_start, &tv_current); if (msec_elapsed >= entropy_timeout_current) { error_abort=1; continue; } msec_remaining = entropy_timeout_current - msec_elapsed; FD_ZERO(&rdset); FD_SET(p[0], &rdset); tv.tv_sec = msec_remaining / 1000; tv.tv_usec = (msec_remaining % 1000) * 1000; ret = select(p[0] + 1, &rdset, NULL, NULL, &tv); RAND_add(&tv, sizeof(tv), 0.0); switch (ret) { case 0: /* timer expired */ error_abort = 1; kill(pid, SIGINT); break; case 1: /* command input */ do { bytes_read = read(p[0], buf, sizeof(buf)); } while (bytes_read == -1 && errno == EINTR); RAND_add(&bytes_read, sizeof(&bytes_read), 0.0); if (bytes_read == -1) { error_abort = 1; break; } else if (bytes_read) { SHA1_Update(&sha, buf, bytes_read); total_bytes_read += bytes_read; } else { cmd_eof = 1; } break; case -1: default: /* error */ debug("Command '%s': select() failed: %s", src->cmdstring, strerror(errno)); error_abort = 1; break; } } SHA1_Final(hash, &sha); close(p[0]); debug3("Time elapsed: %d msec", msec_elapsed); if (waitpid(pid, &status, 0) == -1) { error("Couldn't wait for child '%s' completion: %s", src->cmdstring, strerror(errno)); return 0.0; } RAND_add(&status, sizeof(&status), 0.0); if (error_abort) { /* * Closing p[0] on timeout causes the entropy command to * SIGPIPE. Take whatever output we got, and mark this * command as slow */ debug2("Command '%s' timed out", src->cmdstring); src->sticky_badness *= 2; src->badness = src->sticky_badness; return total_bytes_read; } if (WIFEXITED(status)) { if (WEXITSTATUS(status) == 0) { return total_bytes_read; } else { debug2("Command '%s' exit status was %d", src->cmdstring, WEXITSTATUS(status)); src->badness = src->sticky_badness = 128; return 0.0; } } else if (WIFSIGNALED(status)) { debug2("Command '%s' returned on uncaught signal %d !", src->cmdstring, status); src->badness = src->sticky_badness = 128; return 0.0; } else return 0.0; }
sendClientFinished (sslStruct *sslC) { uchar buff[1024]; uchar plainText[256]; uchar verifyData[256]; uchar *p = &buff[0]; ushort length = 0; struct timeval tv; time_t curtime; uchar digest[16]; uchar sha1Hash[20]; int result; int i; // Record Hdr (Type, Version, Length) p[0] = handshake; //0x16 // TLS ver 1.2 uses version value 3.3 // SSL v3 is version 0300 p[1] = SSL_VERSION_1; p[2] = SSL_VERSION_2; PUT_BE16(&p[3], 0); // **** fill in this later at this point // current length, used by sendData, and also in pkt length = RECORD_HDR_LEN; // Note that we have done 5 bytes by now, which should be substracted // from the pkt length for the RecordProtocol. p[5] = finished; // 20 p[6] = 0; // 3rd MSByte of the Length, usualy 0 // length of Handshake pkt following length field = 1 byte PUT_BE16(&p[7], 0); // **** fill in this later at this point length = length + 4; // Calculate Master Secret // TLS1.0+ // Function call - tls1_prf() // master_secret = PRF(pre_master_secret, "master secret", // ClientHello.random + ServerHello.random) // Note: randoms are 32 bytes (include the timestamps) // sslC->masterSecret = PRF (sslC->preMasterSecret, "master secret", // sslC->random, sslC->serverRandom) // SSLv3 : Tested with openssl s_server and master_secret is correctly // generated. // Function: ssl3_generate_master_secret() // File: sslV3MasterSecret.c // master_secret = // MD5(pre_master_secret + SHA1('A' + pre_master_secret + randbytes)) + // MD5(pre_master_secret + SHA1('BB' + pre_master_secret + randbytes)) + // MD5(pre_master_secret + SHA1('CCC' + pre_master_secret + randbytes)) + { uchar *dest; dest = malloc(48); if (dest == NULL) { printf("\n Out of memory"); exit(1); } ssl3_generate_master_secret(sslC, dest, sslC->preMasterSecret, 48); printf("\n Master Secret "); for(i = 0; i <48; i++) printf("%02x ", dest[i]); memcpy(sslC->masterSecret, dest, 48); free(dest); }; // Calculate verify_data for Finished Msg - for SSLv3 // Sender: client = 0x434C4E54; server = 0x53525652 // md5_hash[16] = MD5(masterSecret + pad2 + // MD5(handshakeMsgs + Sender + masterSecret + pad1)); // sha_hash[20] = SHA(masterSecret + pad2 + // SHA(handshakeMsgs + Sender + masterSecret + pad1)); // m = MD5(sslC->handshakeMsgs) { uchar *out; out = malloc(36); sslC->clientHandshakeMsgs[sslC->clientHandshakeMsgsIndex] = '\0'; MD5_CTX md5_ctx; MD5_Init(&md5_ctx); MD5_Update(&md5_ctx, sslC->clientHandshakeMsgs, strlen(sslC->clientHandshakeMsgs)); printf("\n Length of Handshake Msgs sent by Client: %d", sslC->clientHandshakeMsgsIndex); SHA_CTX sha1_ctx; SHA1_Init(&sha1_ctx); SHA1_Update(&sha1_ctx, sslC->clientHandshakeMsgs, strlen(sslC->clientHandshakeMsgs)); sslGenerateFinishedHash(&md5_ctx, &sha1_ctx, sslC->masterSecret, out); memcpy(&p[9], out, 36); // TBD: The Finished message in hashed an encrypted. This currently // generates an error on the other side of - bad record MAC. // Need to use ssl3_setup_key_block and _generate_key_block routines free(out); } length += 36; // Finally fill in the lengths of Record and Handshake headers PUT_BE16(&p[3], length-RECORD_HDR_LEN); PUT_BE16(&p[7], length-RECORD_HDR_LEN-4); printf("\n-> Send Client Finished"); sendData(cfg.sslC, buff, length); }
void wr_connect(char *host, int port, char *login, char *password) { SHA_CTX c; static unsigned char hex[] = "0123456789abcdef"; unsigned char sha[SHA_DIGEST_LENGTH]; struct hostent *hp; int i, on = 1; /* disconnect active socket */ if(wr_socket >= 0) wr_close(); /* reset current working directory */ strlcpy(wr_files_cwd, "/", sizeof(wr_files_cwd)); /* copy values */ wr_port = port; if(port != 2000) snprintf(wr_host, sizeof(wr_host), "%s:%d", host, port); else strlcpy(wr_host, host, sizeof(wr_host)); strlcpy(wr_login, login, sizeof(wr_login)); strlcpy(wr_password, password, sizeof(wr_password)); /* log */ wr_printf_prefix("Connecting to %s...\n", wr_host); /* create new socket */ wr_socket = socket(AF_INET, SOCK_STREAM, 0); if(wr_socket < 0) { wr_printf_prefix("Could not create a socket: %s\n", strerror(errno)); wr_close(); return; } /* set socket options */ if(setsockopt(wr_socket, IPPROTO_TCP, TCP_NODELAY, &on, sizeof(on)) < 0) { wr_printf_prefix("Could not set socket options: %s\n", strerror(errno)); wr_close(); return; } /* init address */ memset(&wr_addr, 0, sizeof(wr_addr)); wr_addr.sin_family = AF_INET; wr_addr.sin_port = htons(port); if(!inet_aton(host, &wr_addr.sin_addr)) { hp = gethostbyname(host); if(!hp) { wr_printf_prefix("Could not resolve hostname %s: %s\n", host, hstrerror(h_errno)); wr_close(); return; } memcpy(&wr_addr.sin_addr, hp->h_addr, sizeof(wr_addr.sin_addr)); } /* connect TCP socket */ if(connect(wr_socket, (struct sockaddr *) &wr_addr, sizeof(wr_addr)) < 0) { wr_printf_prefix("Could not connect to %s: %s\n", host, strerror(errno)); wr_close(); return; } /* create SSL context */ wr_ssl_ctx = SSL_CTX_new(TLSv1_client_method()); if(!wr_ssl_ctx) { wr_printf_prefix("Could not create SSL context: %s\n", ERR_reason_error_string(ERR_get_error())); wr_close(); return; } if(SSL_CTX_set_cipher_list(wr_ssl_ctx, "ALL") != 1) { wr_printf_prefix("Could not set SSL cipher list: %s\n", ERR_reason_error_string(ERR_get_error())); wr_close(); return; } /* create SSL socket */ wr_ssl = SSL_new(wr_ssl_ctx); if(!wr_ssl) { wr_printf_prefix("Could not create SSL socket: %s\n", ERR_reason_error_string(ERR_get_error())); wr_close(); return; } if(SSL_set_fd(wr_ssl, wr_socket) != 1) { wr_printf_prefix("Could not set SSL file descriptor: %s\n", ERR_reason_error_string(ERR_get_error())); wr_close(); return; } if(SSL_connect(wr_ssl) != 1) { wr_printf_prefix("Could not connect to %s via SSL: %s\n", host, ERR_reason_error_string(ERR_get_error())); wr_close(); return; } /* log */ wr_printf_prefix("Connected using %s/%s/%u bits, logging in...\n", SSL_get_cipher_version(wr_ssl), SSL_get_cipher_name(wr_ssl), SSL_get_cipher_bits(wr_ssl, NULL)); /* send initial login */ wr_send_command("HELLO%s", WR_MESSAGE_SEPARATOR); /* hash the password */ memset(wr_password_sha, 0, sizeof(wr_password_sha)); if(strlen(wr_password) > 0) { SHA1_Init(&c); SHA1_Update(&c, (unsigned char *) wr_password, strlen(wr_password)); SHA1_Final(sha, &c); /* map into hexademical characters */ for(i = 0; i < SHA_DIGEST_LENGTH; i++) { wr_password_sha[i+i] = hex[sha[i] >> 4]; wr_password_sha[i+i+1] = hex[sha[i] & 0x0F]; } wr_password_sha[i+i] = '\0'; }
void bscrypt_test_sha1(void) { struct { char* str; char hash[21]; } sets[] = { {"The quick brown fox jumps over the lazy dog", {0x2f, 0xd4, 0xe1, 0xc6, 0x7a, 0x2d, 0x28, 0xfc, 0xed, 0x84, 0x9e, 0xe1, 0xbb, 0x76, 0xe7, 0x39, 0x1b, 0x93, 0xeb, 0x12, 0}}, // a set with a string {"", { 0xda, 0x39, 0xa3, 0xee, 0x5e, 0x6b, 0x4b, 0x0d, 0x32, 0x55, 0xbf, 0xef, 0x95, 0x60, 0x18, 0x90, 0xaf, 0xd8, 0x07, 0x09, }}, // an empty set {NULL, {0}} // Stop }; int i = 0; sha1_s sha1; fprintf(stderr, "===================================\n"); fprintf(stderr, "bscrypt SHA-1 struct size: %lu\n", sizeof(sha1_s)); fprintf(stderr, "+ bscrypt"); while (sets[i].str) { sha1 = bscrypt_sha1_init(); bscrypt_sha1_write(&sha1, sets[i].str, strlen(sets[i].str)); if (strcmp(bscrypt_sha1_result(&sha1), sets[i].hash)) { fprintf(stderr, ":\n--- bscrypt SHA-1 Test FAILED!\nstring: %s\nexpected: ", sets[i].str); char* p = sets[i].hash; while (*p) fprintf(stderr, "%02x", *(p++) & 0xFF); fprintf(stderr, "\ngot: "); p = bscrypt_sha1_result(&sha1); while (*p) fprintf(stderr, "%02x", *(p++) & 0xFF); fprintf(stderr, "\n"); return; } i++; } fprintf(stderr, " SHA-1 passed.\n"); #ifdef HAS_OPEN_SSL fprintf(stderr, "===================================\n"); fprintf(stderr, "bscrypt SHA-1 struct size: %lu\n", sizeof(sha1_s)); fprintf(stderr, "OpenSSL SHA-1 struct size: %lu\n", sizeof(SHA_CTX)); fprintf(stderr, "===================================\n"); unsigned char hash[SHA512_DIGEST_LENGTH + 1]; hash[SHA512_DIGEST_LENGTH] = 0; clock_t start; start = clock(); for (size_t i = 0; i < 100000; i++) { sha1 = bscrypt_sha1_init(); bscrypt_sha1_write(&sha1, "The quick brown fox jumps over the lazy dog ", 43); bscrypt_sha1_result(&sha1); } fprintf(stderr, "bscrypt 100K SHA-1: %lf\n", (double)(clock() - start) / CLOCKS_PER_SEC); hash[SHA_DIGEST_LENGTH] = 0; SHA_CTX o_sh1; start = clock(); for (size_t i = 0; i < 100000; i++) { SHA1_Init(&o_sh1); SHA1_Update(&o_sh1, "The quick brown fox jumps over the lazy dog", 43); SHA1_Final(hash, &o_sh1); } fprintf(stderr, "OpenSSL 100K SHA-1: %lf\n", (double)(clock() - start) / CLOCKS_PER_SEC); #endif }
int bootstream_verify(int flags, FILE *fp, const uint8_t *key, long *end_of_file) { int r, i, j, k; struct boot_image_header_t bih; struct section_header_t sh; struct dek_dictionary_entry_t dde; struct boot_command_t bc; uint8_t mac[16]; uint8_t buf[16]; uint8_t buf2[16 * 2]; char ascii[32 * 2 + 1]; aes_encrypt_ctx cxe; aes_decrypt_ctx cxd; int session_key_matched; uint8_t session_key[16]; SHA_CTX sha1_ctx; sha1_digest_t sha1_result; long pos; int dcp_fd = -1; if (!plat_config_data->m_u32EnBootStreamVerify) return 0; /* 1. header */ r = bootstream_image_header_verify(fp, &bih); if (r != 0) { fprintf(stderr, "Unable to verify image header\n"); goto err; } if (flags & F_VERBOSE) bootstream_dump_boot_image_header(&bih); if (bih.m_keyCount > 0) { if (key == NULL) { if (flags & F_VERBOSE) printf("* Using device stored OTP key\n"); dcp_fd = dcpboot_open(); if (dcp_fd == -1) { fprintf(stderr, "ERROR: dcp boot device not found & key device requested\n"); goto err; } memset(mac, 0, 16); dcpboot_cbc_encrypt_update(dcp_fd, mac, (uint8_t *)&bih, NULL, sizeof(bih)); } else { if (flags & F_VERBOSE) printf("* Using user supplied key='%s'\n", vec_ascii(key, ascii)); aes128_cbc_encrypt_init(&cxe, mac, key, NULL); aes128_cbc_encrypt_update(&cxe, mac, (uint8_t *)&bih, NULL, sizeof(bih)); } } /* 2. sections headers */ for (i = 0; i < bih.m_sectionCount; i++) { r = bootstream_section_header_load(fp, &bih, i, &sh); if (r != 0) { fprintf(stderr, "Unable to load section header #%d\n", i); goto err; } if (flags & F_VERBOSE) bootstream_dump_section_header(i, &sh); if (bih.m_keyCount > 0) { if (key == NULL) dcpboot_cbc_encrypt_update(dcp_fd, mac, (uint8_t *)&sh, NULL, sizeof(sh)); else aes128_cbc_encrypt_update(&cxe, mac, (uint8_t *)&sh, NULL, sizeof(sh)); } } session_key_matched = -1; memset(session_key, 0, sizeof(session_key)); if (flags & F_VERBOSE) printf("* %s = %s\n", "calculated-mac", vec_ascii(mac, ascii)); /* 3. dictionaries */ for (i = 0; i < bih.m_keyCount; i++) { r = bootstream_dek_dictionary_load(fp, &bih, i, &dde); if (r != 0) { fprintf(stderr, "Unable to load section header #%d\n", i); goto err; } if (flags & F_VERBOSE) bootstream_dump_dek_dictionary(i, &dde); if (session_key_matched == -1 && memcmp(mac, dde.m_mac, 16) == 0) { if (flags & F_VERBOSE) printf("* Key matched at #%d\n", i); /* retreive session key(s) */ if (key == NULL) { memcpy(mac, bih.m_digest, 16); dcpboot_cbc_decrypt_update(dcp_fd, mac, dde.m_dek, session_key, 16); } else { aes128_cbc_decrypt_init(&cxd, mac, key, bih.m_digest); aes128_cbc_decrypt_update(&cxd, mac, dde.m_dek, session_key, 16); } session_key_matched = i; } } if (session_key_matched == -1) { fprintf(stderr, "Unable to find a matching key dictionary\n"); goto err; } if (flags & F_VERBOSE) printf("* %s = %s\n", "session_key", vec_ascii(session_key, ascii)); /* 2. sections */ for (i = 0; i < bih.m_sectionCount; i++) { r = bootstream_section_header_load(fp, &bih, i, &sh); if (r != 0) { fprintf(stderr, "Unable to load section header #%d\n", i); goto err; } if (bih.m_keyCount > 0 && !(sh.m_flags & ROM_SECTION_CLEARTEXT)) aes128_cbc_decrypt_init(&cxd, mac, session_key, bih.m_digest); fseek(fp, sh.m_offset * 16, SEEK_SET); /* start */ j = sh.m_length; while (j > 0) { memset(&bc, 0, sizeof(bc)); r = fread(&bc, 1, sizeof(bc), fp); if (r != sizeof(bc)) { fprintf(stderr, "Unable to load section contents #%d\n", i); goto err; } j--; if (bih.m_keyCount > 0 && !(sh.m_flags & ROM_SECTION_CLEARTEXT)) aes128_cbc_decrypt_update(&cxd, mac, (void *)&bc, (void *)&bc, sizeof(bc)); if (boot_command_chksum(&bc) != bc.m_checksum) { fprintf(stderr, "boot cmd checksum failed\n"); goto err; } // dump(&bc, sizeof(bc)); switch (bc.m_tag) { case ROM_NOP_CMD: if (flags & F_VERBOSE) printf("NOP\n"); break; case ROM_TAG_CMD: if (flags & F_VERBOSE) printf("TAG\n"); break; case ROM_LOAD_CMD: k = (bc.m_count - 1) / 16 + 1; if (k > j) { fprintf(stderr, "LOAD area out of data #%d\n", i); goto err; } j -= k; if (flags & F_VERBOSE) printf("LOAD m_address=0x%08x m_count=0x%08x\n", bc.m_address, bc.m_count); while (k-- > 0) { r = fread(buf, 1, sizeof(buf), fp); if (r != sizeof(buf)) { fprintf(stderr, "Unable to load section contents #%d\n", i); goto err; } if (bih.m_keyCount > 0 && !(sh.m_flags & ROM_SECTION_CLEARTEXT)) aes128_cbc_decrypt_update(&cxd, mac, buf, buf, sizeof(buf)); // dump(buf, 16); } break; case ROM_FILL_CMD: if (flags & F_VERBOSE) printf("FILL m_address=0x%08x m_count=0x%08x m_data=0x%08x\n", bc.m_address, bc.m_count, bc.m_data); break; case ROM_JUMP_CMD: if (flags & F_VERBOSE) printf("JUMP m_address=0x%08x m_data=0x%08x\n", bc.m_address, bc.m_data); break; case ROM_CALL_CMD: if (flags & F_VERBOSE) printf("CALL m_address=0x%08x m_data=0x%08x\n", bc.m_address, bc.m_data); break; case ROM_MODE_CMD: if (flags & F_VERBOSE) printf("MODE\n"); break; default: fprintf(stderr, "Unknown command\n"); goto err; } } } /* load signature */ pos = ftell(fp); r = fread(buf2, 1, sizeof(buf2), fp); if (r != sizeof(buf2)) { fprintf(stderr, "Unable to load SHA1 image authentication\n"); goto err; } if (bih.m_keyCount > 0) { aes128_cbc_decrypt_init(&cxd, mac, session_key, bih.m_digest); aes128_cbc_decrypt_update(&cxd, mac, buf2, buf2, sizeof(buf2)); } if (flags & F_VERBOSE) printf("* %s = %s\n", "read SHA1", sha_ascii(buf2, ascii)); /* rewind and calculate the SHA1 of the image */ fseek(fp, 0, SEEK_SET); SHA1_Init(&sha1_ctx); for (i = 0; i < pos; i += 16) { r = fread(buf, 1, 16, fp); if (r != 16) { fprintf(stderr, "read error while calculating SHA\n"); goto err; } SHA1_Update(&sha1_ctx, buf, 16); } SHA1_Final(sha1_result, &sha1_ctx); if (flags & F_VERBOSE) printf("* %s = %s\n", "calc SHA1", sha_ascii(sha1_result, ascii)); if (memcmp(sha1_result, buf2, 20) != 0) { fprintf(stderr, "SHA1 hashes mismatch, invalid bootstream\n"); goto err; } /* mark end of file */ if (end_of_file) *end_of_file = pos + 32; return 0; err: if (dcp_fd != -1) close(dcp_fd); return -1; }
static tr_bool verifyTorrent( tr_torrent * tor, tr_bool * stopFlag ) { time_t end; SHA_CTX sha; int fd = -1; int64_t filePos = 0; tr_bool changed = 0; tr_bool hadPiece = 0; time_t lastSleptAt = 0; uint32_t piecePos = 0; tr_file_index_t fileIndex = 0; tr_file_index_t prevFileIndex = !fileIndex; tr_piece_index_t pieceIndex = 0; const time_t begin = tr_time( ); const size_t buflen = 1024 * 128; /* 128 KiB buffer */ uint8_t * buffer = tr_valloc( buflen ); SHA1_Init( &sha ); tr_tordbg( tor, "%s", "verifying torrent..." ); tr_torrentSetChecked( tor, 0 ); while( !*stopFlag && ( pieceIndex < tor->info.pieceCount ) ) { uint32_t leftInPiece; uint32_t bytesThisPass; uint64_t leftInFile; const tr_file * file = &tor->info.files[fileIndex]; /* if we're starting a new piece... */ if( piecePos == 0 ) hadPiece = tr_cpPieceIsComplete( &tor->completion, pieceIndex ); /* if we're starting a new file... */ if( !filePos && (fd<0) && (fileIndex!=prevFileIndex) ) { char * filename = tr_torrentFindFile( tor, fileIndex ); fd = filename == NULL ? -1 : tr_open_file_for_scanning( filename ); tr_free( filename ); prevFileIndex = fileIndex; } /* figure out how much we can read this pass */ leftInPiece = tr_torPieceCountBytes( tor, pieceIndex ) - piecePos; leftInFile = file->length - filePos; bytesThisPass = MIN( leftInFile, leftInPiece ); bytesThisPass = MIN( bytesThisPass, buflen ); /* read a bit */ if( fd >= 0 ) { const ssize_t numRead = tr_pread( fd, buffer, bytesThisPass, filePos ); if( numRead > 0 ) { bytesThisPass = (uint32_t)numRead; SHA1_Update( &sha, buffer, bytesThisPass ); #if defined HAVE_POSIX_FADVISE && defined POSIX_FADV_DONTNEED posix_fadvise( fd, filePos, bytesThisPass, POSIX_FADV_DONTNEED ); #endif } } /* move our offsets */ leftInPiece -= bytesThisPass; leftInFile -= bytesThisPass; piecePos += bytesThisPass; filePos += bytesThisPass; /* if we're finishing a piece... */ if( leftInPiece == 0 ) { time_t now; tr_bool hasPiece; uint8_t hash[SHA_DIGEST_LENGTH]; SHA1_Final( hash, &sha ); hasPiece = !memcmp( hash, tor->info.pieces[pieceIndex].hash, SHA_DIGEST_LENGTH ); if( hasPiece || hadPiece ) { tr_torrentSetHasPiece( tor, pieceIndex, hasPiece ); changed |= hasPiece != hadPiece; } tr_torrentSetPieceChecked( tor, pieceIndex ); now = tr_time( ); tor->anyDate = now; /* sleeping even just a few msec per second goes a long * way towards reducing IO load... */ if( lastSleptAt != now ) { lastSleptAt = now; tr_wait_msec( MSEC_TO_SLEEP_PER_SECOND_DURING_VERIFY ); } SHA1_Init( &sha ); ++pieceIndex; piecePos = 0; } /* if we're finishing a file... */ if( leftInFile == 0 ) { if( fd >= 0 ) { tr_close_file( fd ); fd = -1; } ++fileIndex; filePos = 0; } } /* cleanup */ if( fd >= 0 ) tr_close_file( fd ); free( buffer ); /* stopwatch */ end = tr_time( ); tr_tordbg( tor, "Verification is done. It took %d seconds to verify %"PRIu64" bytes (%"PRIu64" bytes per second)", (int)(end-begin), tor->info.totalSize, (uint64_t)(tor->info.totalSize/(1+(end-begin))) ); return changed; }
static int LAME_ssh2_load_userkey(char *passphrase) { int passlen = strlen(passphrase); unsigned char out[sizeof(cur_salt->private_blob)]; AES_KEY akey; unsigned char iv[32]; /* Decrypt the private blob. */ if (cur_salt->cipher) { unsigned char key[40]; SHA_CTX s; if (cur_salt->private_blob_len % cur_salt->cipherblk) goto error; SHA1_Init(&s); SHA1_Update(&s, (void*)"\0\0\0\0", 4); SHA1_Update(&s, passphrase, passlen); SHA1_Final(key + 0, &s); SHA1_Init(&s); SHA1_Update(&s, (void*)"\0\0\0\1", 4); SHA1_Update(&s, passphrase, passlen); SHA1_Final(key + 20, &s); memset(iv, 0, 32); memset(&akey, 0, sizeof(AES_KEY)); if(AES_set_decrypt_key(key, 256, &akey) < 0) { fprintf(stderr, "AES_set_decrypt_key failed!\n"); } AES_cbc_encrypt(cur_salt->private_blob, out , cur_salt->private_blob_len, &akey, iv, AES_DECRYPT); } /* Verify the MAC. */ { char realmac[41]; unsigned char binary[20]; unsigned char *macdata; unsigned char macdata_ar[4*5+sizeof(cur_salt->alg)+sizeof(cur_salt->encryption)+sizeof(cur_salt->comment)+sizeof(cur_salt->public_blob_len)+sizeof(cur_salt->private_blob_len)+1]; int maclen; int i; if (cur_salt->old_fmt) { /* MAC (or hash) only covers the private blob. */ macdata = out; maclen = cur_salt->private_blob_len; } else { unsigned char *p; int namelen = strlen(cur_salt->alg); int enclen = strlen(cur_salt->encryption); int commlen = strlen(cur_salt->comment); maclen = (4 + namelen + 4 + enclen + 4 + commlen + 4 + cur_salt->public_blob_len + 4 + cur_salt->private_blob_len); p = macdata_ar; #define DO_STR(s,len) PUT_32BIT(p,(len));memcpy(p+4,(s),(len));p+=4+(len) DO_STR(cur_salt->alg, namelen); DO_STR(cur_salt->encryption, enclen); DO_STR(cur_salt->comment, commlen); DO_STR(cur_salt->public_blob, cur_salt->public_blob_len); DO_STR(out, cur_salt->private_blob_len); macdata = macdata_ar; } if (cur_salt->is_mac) { SHA_CTX s; unsigned char mackey[20]; unsigned int length = 20; // HMAC_CTX ctx; char header[] = "putty-private-key-file-mac-key"; SHA1_Init(&s); SHA1_Update(&s, header, sizeof(header)-1); if (cur_salt->cipher && passphrase) SHA_Update(&s, passphrase, passlen); SHA1_Final(mackey, &s); hmac_sha1(mackey, 20, macdata, maclen, binary, length); /* HMAC_Init(&ctx, mackey, 20, EVP_sha1()); * HMAC_Update(&ctx, macdata, maclen); * HMAC_Final(&ctx, binary, &length); * HMAC_CTX_cleanup(&ctx); */ } else { SHA_Simple(macdata, maclen, binary); } for (i = 0; i < 20; i++) sprintf(realmac + 2 * i, "%02x", binary[i]); if (strcmp(cur_salt->mac, realmac) == 0) return 1; } error: return 0; }
static void worker_cp_thr(struct worker_info *wi) { void *buf = NULL; struct client *cli = wi->cli; struct backend_obj *obj = NULL, *out_obj = NULL; enum chunk_errcode err = che_InternalError; unsigned char md[SHA_DIGEST_LENGTH]; buf = malloc(CLI_DATA_BUF_SZ); if (!buf) goto out; cli->in_obj = obj = fs_obj_open(cli->table_id, cli->user, cli->key2, cli->var_len, &err); if (!obj) goto out; cli->in_len = obj->size; cli->out_ce = objcache_get_dirty(&chunkd_srv.actives, cli->key, cli->key_len); if (!cli->out_ce) goto out; cli->out_bo = out_obj = fs_obj_new(cli->table_id, cli->key, cli->key_len, obj->size, &err); if (!cli->out_bo) goto out; SHA1_Init(&cli->out_hash); while (cli->in_len > 0) { ssize_t rrc, wrc; rrc = fs_obj_read(obj, buf, MIN(cli->in_len, CLI_DATA_BUF_SZ)); if (rrc < 0) goto err_out; if (rrc == 0) break; SHA1_Update(&cli->out_hash, buf, rrc); cli->in_len -= rrc; while (rrc > 0) { wrc = fs_obj_write(out_obj, buf, rrc); if (wrc < 0) goto err_out; rrc -= wrc; } } SHA1_Final(md, &cli->out_hash); if (!fs_obj_write_commit(out_obj, cli->user, md, false)) goto err_out; err = che_Success; out: free(buf); cli_in_end(cli); cli_out_end(cli); wi->err = err; worker_pipe_signal(wi); return; err_out: /* FIXME: remove half-written destination object */ goto out; }
static oc::result<void> _mtk_compute_sha1(Writer &writer, SegmentWriter &seg, File &file, unsigned char digest[SHA_DIGEST_LENGTH]) { SHA_CTX sha_ctx; char buf[10240]; uint32_t kernel_mtkhdr_size = 0; uint32_t ramdisk_mtkhdr_size = 0; if (!SHA1_Init(&sha_ctx)) { return android::AndroidError::Sha1InitError; } for (auto const &entry : seg.entries()) { uint64_t remain = *entry.size; auto seek_ret = file.seek(static_cast<int64_t>(entry.offset), SEEK_SET); if (!seek_ret) { if (file.is_fatal()) { writer.set_fatal(); } return seek_ret.as_failure(); } // Update checksum with data while (remain > 0) { auto to_read = std::min<uint64_t>(remain, sizeof(buf)); auto ret = file_read_exact(file, buf, static_cast<size_t>(to_read)); if (!ret) { if (writer.is_fatal()) { writer.set_fatal(); } return ret.as_failure(); } if (!SHA1_Update(&sha_ctx, buf, static_cast<size_t>(to_read))) { return android::AndroidError::Sha1UpdateError; } remain -= to_read; } uint32_t le32_size; // Update checksum with size switch (entry.type) { case ENTRY_TYPE_MTK_KERNEL_HEADER: kernel_mtkhdr_size = *entry.size; continue; case ENTRY_TYPE_MTK_RAMDISK_HEADER: ramdisk_mtkhdr_size = *entry.size; continue; case ENTRY_TYPE_KERNEL: le32_size = mb_htole32(*entry.size + kernel_mtkhdr_size); break; case ENTRY_TYPE_RAMDISK: le32_size = mb_htole32(*entry.size + ramdisk_mtkhdr_size); break; case ENTRY_TYPE_SECONDBOOT: le32_size = mb_htole32(*entry.size); break; case ENTRY_TYPE_DEVICE_TREE: if (*entry.size == 0) { continue; } le32_size = mb_htole32(*entry.size); break; default: continue; } if (!SHA1_Update(&sha_ctx, &le32_size, sizeof(le32_size))) { return android::AndroidError::Sha1UpdateError; } } if (!SHA1_Final(digest, &sha_ctx)) { return android::AndroidError::Sha1UpdateError; } return oc::success(); }
/*******************************************************************-o-****** * generate_Ku * * Parameters: * *hashtype MIB OID for the transform type for hashing. * hashtype_len Length of OID value. * *P Pre-allocated bytes of passpharase. * pplen Length of passphrase. * *Ku Buffer to contain Ku. * *kulen Length of Ku buffer. * * Returns: * SNMPERR_SUCCESS Success. * SNMPERR_GENERR All errors. * * * Convert a passphrase into a master user key, Ku, according to the * algorithm given in RFC 2274 concerning the SNMPv3 User Security Model (USM) * as follows: * * Expand the passphrase to fill the passphrase buffer space, if necessary, * concatenation as many duplicates as possible of P to itself. If P is * larger than the buffer space, truncate it to fit. * * Then hash the result with the given hashtype transform. Return * the result as Ku. * * If successful, kulen contains the size of the hash written to Ku. * * NOTE Passphrases less than USM_LENGTH_P_MIN characters in length * cause an error to be returned. * (Punt this check to the cmdline apps? XXX) */ int generate_Ku(const oid * hashtype, u_int hashtype_len, const u_char * P, size_t pplen, u_char * Ku, size_t * kulen) #if defined(NETSNMP_USE_INTERNAL_MD5) || defined(NETSNMP_USE_OPENSSL) || defined(NETSNMP_USE_INTERNAL_CRYPTO) { int rval = SNMPERR_SUCCESS, nbytes = USM_LENGTH_EXPANDED_PASSPHRASE; #if !defined(NETSNMP_USE_OPENSSL) && \ defined(NETSNMP_USE_INTERNAL_MD5) || defined(NETSNMP_USE_INTERNAL_CRYPTO) int ret; #endif u_int i, pindex = 0; u_char buf[USM_LENGTH_KU_HASHBLOCK], *bufp; #ifdef NETSNMP_USE_OPENSSL EVP_MD_CTX *ctx = NULL; #elif NETSNMP_USE_INTERNAL_CRYPTO SHA_CTX csha1; MD5_CTX cmd5; char cryptotype = 0; #define TYPE_MD5 1 #define TYPE_SHA1 2 #else MDstruct MD; #endif /* * Sanity check. */ if (!hashtype || !P || !Ku || !kulen || (*kulen <= 0) || (hashtype_len != USM_LENGTH_OID_TRANSFORM)) { QUITFUN(SNMPERR_GENERR, generate_Ku_quit); } if (pplen < USM_LENGTH_P_MIN) { snmp_log(LOG_ERR, "Error: passphrase chosen is below the length " "requirements of the USM (min=%d).\n",USM_LENGTH_P_MIN); snmp_set_detail("The supplied password length is too short."); QUITFUN(SNMPERR_GENERR, generate_Ku_quit); } /* * Setup for the transform type. */ #ifdef NETSNMP_USE_OPENSSL #ifdef HAVE_EVP_MD_CTX_CREATE ctx = EVP_MD_CTX_create(); #else ctx = malloc(sizeof(*ctx)); EVP_MD_CTX_init(ctx); #endif #ifndef NETSNMP_DISABLE_MD5 if (ISTRANSFORM(hashtype, HMACMD5Auth)) EVP_DigestInit(ctx, EVP_md5()); else #endif if (ISTRANSFORM(hashtype, HMACSHA1Auth)) EVP_DigestInit(ctx, EVP_sha1()); else QUITFUN(SNMPERR_GENERR, generate_Ku_quit); #elif NETSNMP_USE_INTERNAL_CRYPTO #ifndef NETSNMP_DISABLE_MD5 if (ISTRANSFORM(hashtype, HMACMD5Auth)) { MD5_Init(&cmd5); cryptotype = TYPE_MD5; } else #endif if (ISTRANSFORM(hashtype, HMACSHA1Auth)) { SHA1_Init(&csha1); cryptotype = TYPE_SHA1; } else { return (SNMPERR_GENERR); } #else MDbegin(&MD); #endif /* NETSNMP_USE_OPENSSL */ while (nbytes > 0) { bufp = buf; for (i = 0; i < USM_LENGTH_KU_HASHBLOCK; i++) { *bufp++ = P[pindex++ % pplen]; } #ifdef NETSNMP_USE_OPENSSL EVP_DigestUpdate(ctx, buf, USM_LENGTH_KU_HASHBLOCK); #elif NETSNMP_USE_INTERNAL_CRYPTO if (TYPE_SHA1 == cryptotype) { rval = !SHA1_Update(&csha1, buf, USM_LENGTH_KU_HASHBLOCK); } else { rval = !MD5_Update(&cmd5, buf, USM_LENGTH_KU_HASHBLOCK); } if (rval != 0) { return SNMPERR_USM_ENCRYPTIONERROR; } #elif NETSNMP_USE_INTERNAL_MD5 if (MDupdate(&MD, buf, USM_LENGTH_KU_HASHBLOCK * 8)) { rval = SNMPERR_USM_ENCRYPTIONERROR; goto md5_fin; } #endif /* NETSNMP_USE_OPENSSL */ nbytes -= USM_LENGTH_KU_HASHBLOCK; } #ifdef NETSNMP_USE_OPENSSL { unsigned int tmp_len; tmp_len = *kulen; EVP_DigestFinal(ctx, (unsigned char *) Ku, &tmp_len); *kulen = tmp_len; /* * what about free() */ } #elif NETSNMP_USE_INTERNAL_CRYPTO if (TYPE_SHA1 == cryptotype) { SHA1_Final(Ku, &csha1); } else { MD5_Final(Ku, &cmd5); } ret = sc_get_properlength(hashtype, hashtype_len); if (ret == SNMPERR_GENERR) return SNMPERR_GENERR; *kulen = ret; #elif NETSNMP_USE_INTERNAL_MD5 if (MDupdate(&MD, buf, 0)) { rval = SNMPERR_USM_ENCRYPTIONERROR; goto md5_fin; } ret = sc_get_properlength(hashtype, hashtype_len); if (ret == SNMPERR_GENERR) return SNMPERR_GENERR; *kulen = ret; MDget(&MD, Ku, *kulen); md5_fin: memset(&MD, 0, sizeof(MD)); #endif /* NETSNMP_USE_INTERNAL_MD5 */ #ifdef NETSNMP_ENABLE_TESTING_CODE DEBUGMSGTL(("generate_Ku", "generating Ku (from %s): ", P)); for (i = 0; i < *kulen; i++) DEBUGMSG(("generate_Ku", "%02x", Ku[i])); DEBUGMSG(("generate_Ku", "\n")); #endif /* NETSNMP_ENABLE_TESTING_CODE */ generate_Ku_quit: memset(buf, 0, sizeof(buf)); #ifdef NETSNMP_USE_OPENSSL if (ctx) { #ifdef HAVE_EVP_MD_CTX_DESTROY EVP_MD_CTX_destroy(ctx); #else EVP_MD_CTX_cleanup(ctx); free(ctx); #endif } #endif return rval; } /* end generate_Ku() */
static int dasync_sha1_init(EVP_MD_CTX *ctx) { dummy_pause_job(); return SHA1_Init(data(ctx)); }
/***************************************************************************** 函 数 名 : license_compute_permitcode 功能描述 : 计算验证码 输入参数 : info :传入的license文件信息首地址 shakey:SHA KEY 输出参数 : permitcode:验证码 返 回 值 : ERR_SUCCESS:成功 ERROR_SYSTEM: 内存申请失败 修改历史 : 12.18 修改内容 : 新生成函数 *****************************************************************************/ u32 license_compute_permitcode (license_single_record_s * info ,u8 * shakey ,u8 * aeskey ,u8 * permitcode) { struct tm tm; time_t time_exp; u8 time_tmp[32] = {'0'}; u8 * name_tmp = NULL; SHA_CTX content; u8 * tmp = NULL; u32 len = 0; u8 sha_diget[SHA_DIGEST_LENGTH] = {'0'}; u8 sha_data_in[SHA_DATA_LEN_MAX] = {'0'}; u8 aes_key[AES_KEY_LEN] = {'0'}; u8 aes_data_in[AES_DATA_LEN] = {'0'}; u8 aes_data_out[AES_DATA_LEN] = {'0'}; u8 aes_ivec[AES_IVEC_LEN] = {'0'}; u8 serial_num[DEVICE_SERIAL_NUM_MAX_LEN] = {'0'}; AES_KEY key; license_convert_to_lower(info->dev_serial_num, serial_num); /*sha加密,获取密值*/ snprintf((s8*)sha_data_in, sizeof(sha_data_in), "%s%s", serial_num, shakey); SHA1_Init(&content); SHA1_Update(&content, (char *)sha_data_in, strlen((char * )sha_data_in)); memset(sha_data_in, '0', sizeof(sha_data_in)); name_tmp = info->lib_name; time_exp = info->expire_date; localtime_r(&time_exp, &tm); strftime((s8*)time_tmp, sizeof(time_tmp), "%d-%b-%Y", &tm); snprintf((s8*)sha_data_in, sizeof(sha_data_in), "%s%s%s", name_tmp, time_tmp,shakey); SHA1_Update(&content, (char *)sha_data_in, strlen((char * )sha_data_in)); memset(sha_data_in, '0', sizeof(sha_data_in)); SHA1_Final(sha_diget, &content); /*加密内容*/ snprintf((char *)aes_data_in, sizeof(aes_data_in), "%s%s", serial_num,aeskey); tmp = (u8 *)aes_data_in; len = strlen((char *)aes_data_in); tmp = tmp + len; memset(tmp, '0', sizeof(aes_data_in)-len); /*密值*/ memcpy(aes_key, sha_diget, sizeof(sha_diget)); memset(&aes_key[SHA_DIGEST_LENGTH], '0', sizeof(aes_key) - sizeof(sha_diget)); memset(aes_ivec, '0', sizeof(aes_ivec)); AES_set_encrypt_key(aes_key, sizeof(aes_key) * 8, &key); AES_cbc_encrypt(aes_data_in, aes_data_out, sizeof(aes_data_in), &key, aes_ivec, AES_ENCRYPT); memcpy(permitcode, aes_data_out, sizeof(aes_data_out)); return ERROR_SUCCESS; }
SHA1Hash::SHA1Hash() { SHA1_Init(&mC); memset(mDigest, 0, SHA_DIGEST_LENGTH * sizeof(uint8)); }
void SHA1Hash::Initialize() { SHA1_Init(&mC); }
// don't forward the first argument void CL_ForwardToServer_f (void) { // Added by VVD { char *server_string, client_time_str[9]; int i, server_string_len; extern cvar_t cl_crypt_rcon; time_t client_time; // Added by VVD } if (cls.mvdplayback == QTV_PLAYBACK) { QTV_Cl_ForwardToServer_f(); return; } if (cls.state == ca_disconnected) { Com_Printf ("Can't \"%s\", not connected\n", Cmd_Argv(0)); return; } if (cls.demoplayback) return; // not really connected if (Cmd_Argc() > 1) { if (strcasecmp(Cmd_Argv(1), "snap") == 0) { SCR_RSShot_f (); return; } //bliP -> if (strcasecmp(Cmd_Argv(1), "fileul") == 0) { CL_StartFileUpload (); return; } //<- MSG_WriteByte (&cls.netchan.message, clc_stringcmd); /* johnnycz: disabled due to security reasons -- fixme if (strcasecmp(Cmd_Argv(1), "download") == 0 && Cmd_Argc() > 2) { strlcpy(cls.downloadname, Cmd_Argv(2), sizeof(cls.downloadname)); COM_StripExtension(cls.downloadname, cls.downloadtempname); strlcat(cls.downloadtempname, ".tmp", sizeof(cls.downloadtempname)); cls.downloadtype = dl_single; //snprintf (cls.downloadname, sizeof(cls.downloadname), "%s", Cmd_Argv(2)); //strlcpy (cls.downloadtempname, cls.downloadname, sizeof(cls.downloadtempname)); } */ // Added by VVD { if (cl_crypt_rcon.value && strcasecmp(Cmd_Argv(1), "techlogin") == 0 && Cmd_Argc() > 2) { time(&client_time); for (client_time_str[0] = i = 0; i < sizeof(client_time); i++) { char tmp[3]; snprintf(tmp, sizeof(tmp), "%02X", (unsigned int)((client_time >> (i * 8)) & 0xFF)); strlcat(client_time_str, tmp, sizeof(client_time_str)); } server_string_len = Cmd_Argc() + strlen(Cmd_Argv(1)) + DIGEST_SIZE * 2 + 16; for (i = 3; i < Cmd_Argc(); ++i) server_string_len += strlen(Cmd_Argv(i)); server_string = (char *) Q_malloc(server_string_len); SHA1_Init(); SHA1_Update((unsigned char *)Cmd_Argv(1)); SHA1_Update((unsigned char *)" "); SHA1_Update((unsigned char *)Cmd_Argv(2)); SHA1_Update((unsigned char *)client_time_str); SHA1_Update((unsigned char *)" "); for (i = 3; i < Cmd_Argc(); ++i) { SHA1_Update((unsigned char *)Cmd_Argv(i)); SHA1_Update((unsigned char *)" "); } snprintf(server_string, server_string_len, "%s %s%s ", Cmd_Argv(1), SHA1_Final(), client_time_str); for (i = 3; i < Cmd_Argc(); ++i) { strlcat(server_string, Cmd_Argv(i), server_string_len); strlcat(server_string, " ", server_string_len); } SZ_Print (&cls.netchan.message, server_string); Q_free(server_string); } else
static OSStatus __MFiSAP_Exchange_ServerM1( MFiSAPRef inRef, const uint8_t * inInputPtr, size_t inInputLen, uint8_t ** outOutputPtr, size_t * outOutputLen ) { OSStatus err; const uint8_t * inputEnd; const uint8_t * clientECDHPublicKey; uint8_t ourPrivateKey[ kMFiSAP_ECDHKeyLen ]; uint8_t ourPublicKey[ kMFiSAP_ECDHKeyLen ]; SHA_CTX sha1Context; uint8_t digest[ 20 ]; uint8_t * signaturePtr = NULL; size_t signatureLen; uint8_t * certificatePtr = NULL; size_t certificateLen; uint8_t aesMasterKey[ kMFiSAP_AESKeyLen ]; uint8_t aesMasterIV[ kMFiSAP_AESKeyLen ]; uint8_t * buf; uint8_t * dst; size_t len; if( ( UpTicks() - gMFiSAP_LastTicks ) < UpTicksPerSecond() ) { if( gMFiSAP_ThrottleCounter < 4 ) ++gMFiSAP_ThrottleCounter; SleepForUpTicks( gMFiSAP_ThrottleCounter * UpTicksPerSecond() ); } else { gMFiSAP_ThrottleCounter = 0; } gMFiSAP_LastTicks = UpTicks(); // Validate inputs. Input data must be: <1:version> <32:client's ECDH public key>. inputEnd = inInputPtr + inInputLen; require_action( inputEnd > inInputPtr, exit, err = kSizeErr ); // Detect bad length causing ptr wrap. require_action( ( inputEnd - inInputPtr ) >= kMFiSAP_VersionLen, exit, err = kSizeErr ); inRef->version = *inInputPtr++; require_action( inRef->version == kMFiSAPVersion1, exit, err = kVersionErr ); require_action( ( inputEnd - inInputPtr ) >= kMFiSAP_ECDHKeyLen, exit, err = kSizeErr ); clientECDHPublicKey = inInputPtr; inInputPtr += kMFiSAP_ECDHKeyLen; require_action( inInputPtr == inputEnd, exit, err = kSizeErr ); // Generate a random ECDH key pair. err = PlatformRandomBytes( ourPrivateKey, sizeof( ourPrivateKey ) ); require_noerr( err, exit ); curve25519_donna( ourPublicKey, ourPrivateKey, NULL ); // Use our private key and the client's public key to generate the shared secret. // Hash the shared secret and truncate it to form the AES master key. // Hash the shared secret with salt to derive the AES master IV. curve25519_donna( inRef->sharedSecret, ourPrivateKey, clientECDHPublicKey ); SHA1_Init( &sha1Context ); SHA1_Update( &sha1Context, kMFiSAP_AES_KEY_SaltPtr, kMFiSAP_AES_KEY_SaltLen ); SHA1_Update( &sha1Context, inRef->sharedSecret, sizeof( inRef->sharedSecret ) ); SHA1_Final( digest, &sha1Context ); memcpy( aesMasterKey, digest, sizeof( aesMasterKey ) ); SHA1_Init( &sha1Context ); SHA1_Update( &sha1Context, kMFiSAP_AES_IV_SaltPtr, kMFiSAP_AES_IV_SaltLen ); SHA1_Update( &sha1Context, inRef->sharedSecret, sizeof( inRef->sharedSecret ) ); SHA1_Final( digest, &sha1Context ); memcpy( aesMasterIV, digest, sizeof( aesMasterIV ) ); // Use the auth chip to sign a hash of <32:our ECDH public key> <32:client's ECDH public key>. // And copy the auth chip's certificate so the client can verify the signature. SHA1_Init( &sha1Context ); SHA1_Update( &sha1Context, ourPublicKey, sizeof( ourPublicKey ) ); SHA1_Update( &sha1Context, clientECDHPublicKey, kMFiSAP_ECDHKeyLen ); SHA1_Final( digest, &sha1Context ); err = PlatformMFiAuthCreateSignature( digest, sizeof( digest ), &signaturePtr, &signatureLen ); require_noerr( err, exit ); err = PlatformMFiAuthCopyCertificate( &certificatePtr, &certificateLen ); require_noerr( err, exit ); // Encrypt the signature with the AES master key and master IV. err = AES_CTR_Init( &inRef->aesMasterContext, aesMasterKey, aesMasterIV ); require_noerr( err, exit ); err = AES_CTR_Update( &inRef->aesMasterContext, signaturePtr, signatureLen, signaturePtr ); if( err ) AES_CTR_Final( &inRef->aesMasterContext ); require_noerr( err, exit ); inRef->aesMasterValid = true; // Return the response: // // <32:our ECDH public key> // <4:big endian certificate length> // <N:certificate data> // <4:big endian signature length> // <N:encrypted signature data> len = kMFiSAP_ECDHKeyLen + 4 + certificateLen + 4 + signatureLen; buf = (uint8_t *) malloc( len ); require_action( buf, exit, err = kNoMemoryErr ); dst = buf; memcpy( dst, ourPublicKey, sizeof( ourPublicKey ) ); dst += sizeof( ourPublicKey ); *dst++ = (uint8_t)( ( certificateLen >> 24 ) & 0xFF ); *dst++ = (uint8_t)( ( certificateLen >> 16 ) & 0xFF ); *dst++ = (uint8_t)( ( certificateLen >> 8 ) & 0xFF ); *dst++ = (uint8_t)( certificateLen & 0xFF ); memcpy( dst, certificatePtr, certificateLen ); dst += certificateLen; *dst++ = (uint8_t)( ( signatureLen >> 24 ) & 0xFF ); *dst++ = (uint8_t)( ( signatureLen >> 16 ) & 0xFF ); *dst++ = (uint8_t)( ( signatureLen >> 8 ) & 0xFF ); *dst++ = (uint8_t)( signatureLen & 0xFF ); memcpy( dst, signaturePtr, signatureLen ); dst += signatureLen; check( dst == ( buf + len ) ); *outOutputPtr = buf; *outOutputLen = (size_t)( dst - buf ); exit: if( certificatePtr ) free( certificatePtr ); if( signaturePtr ) free( signaturePtr ); return( err ); }
static void wpapsk_crypt_all(int count) { #ifdef MMX_COEF /*int i;*/ printf("\n"); dump_stuff_mmx(ipad, 64, 0); memcpy(dump, ipad, 64*MMX_COEF); shammx_nosizeupdate( dump, dump, 64); memcpy(dump, cursalt, 64*MMX_COEF); shammx_noinit_uniformsizeupdate(dump, dump, total_len + 64 ); dump_stuff_mmx(dump, SHA_SIZE, 0); shammx_nosizeupdate( dump, opad, 64); shammx_noinit_uniformsizeupdate(dump, dump, SHA_SIZE + 64); dump_stuff_mmx(dump, SHA_SIZE, 0); return; #else unsigned char dump[SHA_SIZE]; unsigned char digest[SHA_SIZE]; unsigned char ptk[20*4]; unsigned int i,j; MD5_CTX md5ctx; //printf("\n"); //first calculation - left part SHA1_Init( &ctx ); SHA1_Update( &ctx, ipad, 64 ); SHA1_Update( &ctx, cursalt, strlen(cursalt) + 4 ); SHA1_Final( dump, &ctx); SHA1_Init( &ctx ); SHA1_Update( &ctx, opad, 64 ); SHA1_Update( &ctx, dump, SHA_SIZE); SHA1_Final( dump, &ctx); memcpy(digest, dump, SHA_SIZE); for(i=1;i<4096;i++) { SHA1_Init( &ctx ); SHA1_Update( &ctx, ipad, 64 ); SHA1_Update( &ctx, dump, SHA_SIZE ); SHA1_Final( dump, &ctx); SHA1_Init( &ctx ); SHA1_Update( &ctx, opad, 64 ); SHA1_Update( &ctx, dump, SHA_SIZE); SHA1_Final( dump, &ctx); for(j=0;j<SHA_SIZE;j++) digest[j] ^= dump[j]; } //first calculation - right part cursalt[ strlen(cursalt) + 3 ] = 2; SHA1_Init( &ctx ); SHA1_Update( &ctx, ipad, 64 ); SHA1_Update( &ctx, cursalt, strlen(cursalt) + 4 ); SHA1_Final( dump, &ctx); SHA1_Init( &ctx ); SHA1_Update( &ctx, opad, 64 ); SHA1_Update( &ctx, dump, SHA_SIZE); SHA1_Final( dump, &ctx); memcpy(digest+SHA_SIZE, dump, 32-SHA_SIZE); for(i=1;i<4096;i++) { SHA1_Init( &ctx ); SHA1_Update( &ctx, ipad, 64 ); SHA1_Update( &ctx, dump, SHA_SIZE ); SHA1_Final( dump, &ctx); SHA1_Init( &ctx ); SHA1_Update( &ctx, opad, 64 ); SHA1_Update( &ctx, dump, SHA_SIZE); SHA1_Final( dump, &ctx); for(j=0;j<32-SHA_SIZE;j++) digest[j+SHA_SIZE] ^= dump[j]; } //we now got pmk in digest,32 //dump_stuff(digest, 32 ); for(i=0;i<32;i++) { nipad[i] = 0x36 ^ digest[i]; nopad[i] = 0x5c ^ digest[i]; } //a hmac must be done with secret key pmk/32, and text "Pairwise key expansion",0,DATA,counter nDATA[23+64+12] = 0; SHA1_Init( &ctx ); SHA1_Update( &ctx, nipad, 64 ); SHA1_Update( &ctx, nDATA, 22+1+12+64+1 ); SHA1_Final( dump, &ctx ); SHA1_Init( &ctx ); SHA1_Update( &ctx, nopad, 64 ); SHA1_Update( &ctx, dump, SHA_SIZE); SHA1_Final( ptk, &ctx); //seems not to be used ... /* nDATA[23+64+12] = 1; SHA1_Init( &ctx ); SHA1_Update( &ctx, nipad, 64 ); SHA1_Update( &ctx, nDATA, 22+1+12+64+1 ); SHA1_Final( dump, &ctx ); SHA1_Init( &ctx ); SHA1_Update( &ctx, nopad, 64 ); SHA1_Update( &ctx, dump, SHA_SIZE); SHA1_Final( ptk + 20, &ctx); nDATA[23+64+12] = 2; SHA1_Init( &ctx ); SHA1_Update( &ctx, nipad, 64 ); SHA1_Update( &ctx, nDATA, 22+1+12+64+1 ); SHA1_Final( dump, &ctx ); SHA1_Init( &ctx ); SHA1_Update( &ctx, nopad, 64 ); SHA1_Update( &ctx, dump, SHA_SIZE); SHA1_Final( ptk + 40, &ctx); nDATA[23+64+12] = 3; SHA1_Init( &ctx ); SHA1_Update( &ctx, nipad, 64 ); SHA1_Update( &ctx, nDATA, 22+1+12+64+1 ); SHA1_Final( dump, &ctx ); SHA1_Init( &ctx ); SHA1_Update( &ctx, nopad, 64 ); SHA1_Update( &ctx, dump, SHA_SIZE); SHA1_Final( ptk + 60, &ctx); */ //we now have the ptk ... //now hmac md5 ... memset(nipad + 16, 0x36 , 16); memset(nopad + 16, 0x5C , 16); for(i=0;i<16;i++) { nipad[i] = 0x36 ^ ptk[i]; nopad[i] = 0x5C ^ ptk[i]; } MD5_Init( &md5ctx ); MD5_Update( &md5ctx, nipad, 64 ); MD5_Update( &md5ctx, EAPOL, sizeof(EAPOL) ); MD5_Final ( dump, &md5ctx ); MD5_Init( &md5ctx ); MD5_Update( &md5ctx, nopad, 64 ); MD5_Update( &md5ctx, dump, 16 ); MD5_Final ( crypt_key, &md5ctx ); #endif }
static int digest_sha1_init(EVP_MD_CTX *ctx) { return SHA1_Init(data(ctx)); }
void close8900(AbstractFile * file) { unsigned char ivec[16]; SHA_CTX sha_ctx; unsigned char md[20]; unsigned char exploit_data[0x54] = { 0 }; /*int align; */ size_t origSize; uint32_t cksum; Info8900 *info = (Info8900 *) (file->data); if (info->dirty) { if (info->header.format == 3) { /* we need to block-align our data, or AES will break */ origSize = info->header.sizeOfData; /* gotta break abstraction here, because Apple is mean */ if (((Img2Header *) info->buffer)->signature == IMG2_SIGNATURE) { ((Img2Header *) info->buffer)->dataLenPadded = ((Img2Header *) info-> buffer)->dataLenPadded % 16 == 0 ? ((Img2Header *) info->buffer)-> dataLenPadded : ((((Img2Header *) info-> buffer)->dataLenPadded / 16) + 1) * 16; info->header.sizeOfData = ((Img2Header *) info-> buffer)->dataLenPadded + sizeof(Img2Header); cksum = crc32(0, (unsigned char *)info->buffer, 0x64); FLIPENDIANLE(cksum); ((Img2Header *) info->buffer)->header_checksum = cksum; } info->header.sizeOfData = (info->header.sizeOfData) % 16 == 0 ? info-> header.sizeOfData : ((info->header.sizeOfData / 16) + 1) * 16; if (info->header.sizeOfData != origSize) { info->buffer = realloc(info->buffer, info->header.sizeOfData); memset((void *)((uint8_t *) info->buffer + origSize), 0, info->header.sizeOfData - origSize); } } info->header.footerSignatureOffset = info->header.sizeOfData; info->header.footerCertOffset = info->header.footerSignatureOffset + 0x80; if (info->header.format == 3) { memset(ivec, 0, 16); AES_cbc_encrypt(info->buffer, info->buffer, info->header.sizeOfData, &(info->encryptKey), ivec, AES_ENCRYPT); } info->file->seek(info->file, sizeof(info->header)); info->file->write(info->file, info->buffer, info->header.sizeOfData); info->file->seek(info->file, sizeof(info->header) + info->header.footerSignatureOffset); info->file->write(info->file, info->footerSignature, 0x80); info->file->seek(info->file, sizeof(info->header) + info->header.footerCertOffset); if (info->exploit) { info->footerCertificate[0x8be] = 0x9F; info->footerCertificate[0xb08] = 0x55; } info->file->write(info->file, info->footerCertificate, info->header.footerCertLen); if (info->exploit) { info->header.footerCertLen = 0xc5e; exploit_data[0x30] = 0x01; exploit_data[0x50] = 0xEC; exploit_data[0x51] = 0x57; exploit_data[0x53] = 0x20; info->file->write(info->file, exploit_data, sizeof(exploit_data)); } flipApple8900Header(&(info->header)); SHA1_Init(&sha_ctx); SHA1_Update(&sha_ctx, &(info->header), 0x40); SHA1_Final(md, &sha_ctx); memset(ivec, 0, 16); AES_cbc_encrypt(md, (unsigned char *)&(info-> header.headerSignature), 0x10, &(info->encryptKey), ivec, AES_ENCRYPT); info->file->seek(info->file, 0); info->file->write(info->file, &(info->header), sizeof(info->header)); } free(info->footerCertificate); free(info->buffer); info->file->close(info->file); free(info); free(file); }
int verify_checksum(blockhdr_t *blockhdr, const unsigned char *bodybufp, int type) { SHA_CTX sum_context; int sum_length; unsigned char alleged_sum[CSUM_MAX_LEN]; unsigned char calculated_sum[CSUM_MAX_LEN]; if (type == CSUM_NONE) { fprintf(stderr, "Chunk has no checksum\n"); return 0; } #ifdef SIGN_CHECKSUM if ((type & CSUM_SIGNED) == 0) { fprintf(stderr, "Chunk checksum must be signed\n"); return 0; } #else if ((type & CSUM_SIGNED) != 0) { fprintf(stderr, "Chunk checksum must not be signed\n"); return 0; } #endif type &= CSUM_TYPE; if (type != CSUM_SHA1) { fprintf(stderr, "Chunk checksum type %d not supported\n", type); return 0; } /* initialize checksum state */ memcpy(alleged_sum, blockhdr->checksum, CSUM_MAX_LEN); memset(blockhdr->checksum, '\0', CSUM_MAX_LEN); memset(calculated_sum, '\0', CSUM_MAX_LEN); SHA1_Init(&sum_context); /* calculate the checksum */ SHA1_Update(&sum_context, bodybufp, blockhdr->size + blockhdr->regionsize); /* save the checksum */ SHA1_Final(calculated_sum, &sum_context); memcpy(blockhdr->checksum, alleged_sum, CSUM_MAX_LEN); #ifdef SIGN_CHECKSUM decrypt_checksum(alleged_sum); #endif /* XXX only SHA1 right now */ sum_length = CSUM_SHA1_LEN; if (memcmp(alleged_sum, calculated_sum, sum_length) != 0) { char sumstr[CSUM_MAX_LEN*2 + 1]; fprintf(stderr, "Checksums do not match:\n"); mem_to_hexstr(sumstr, alleged_sum, sum_length); fprintf(stderr, " Alleged: 0x%s\n", sumstr); mem_to_hexstr(sumstr, calculated_sum, sum_length); fprintf(stderr, " Calculated: 0x%s\n", sumstr); return 0; } return 1; }
CryptoSha1 crypto_sha1_init(void) { CryptoSha1 sha1 = xmalloc(sizeof(*sha1)); SHA1_Init(&sha1->sha_ctx); return sha1; }
Sha1Hash::~Sha1Hash() { SHA1_Init(&mC); }
void trap_init(const char *ver) { int r; uint8_t digest[20]; struct sigaction sa, old; char path[256]; SHA_CTX binsum; int fd; r = readlink("/proc/self/exe", self, sizeof(self) - 1); if(r == -1) self[0] = 0; else self[r] = 0; if((fd = open("/proc/self/exe", O_RDONLY)) != -1) { struct stat st; if(!fstat(fd, &st)) { char *m = malloc(st.st_size); if(m != NULL) { if(read(fd, m, st.st_size) == st.st_size) { SHA1_Init(&binsum); SHA1_Update(&binsum, (void *)m, st.st_size); SHA1_Final(digest, &binsum); } free(m); } } } snprintf(line1, sizeof(line1), "PRG: %s (%s) " "[%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x" "%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x] " "CWD: %s ", ver, tvheadend_version, digest[0], digest[1], digest[2], digest[3], digest[4], digest[5], digest[6], digest[7], digest[8], digest[9], digest[10], digest[11], digest[12], digest[13], digest[14], digest[15], digest[16], digest[17], digest[18], digest[19], getcwd(path, sizeof(path))); memcpy(tvh_binshasum, digest, 20); dl_iterate_phdr(callback, NULL); memset(&sa, 0, sizeof(sa)); sigset_t m; sigemptyset(&m); sigaddset(&m, SIGSEGV); sigaddset(&m, SIGBUS); sigaddset(&m, SIGILL); sigaddset(&m, SIGABRT); sigaddset(&m, SIGFPE); sa.sa_sigaction = traphandler; sa.sa_flags = SA_SIGINFO | SA_RESETHAND; sigaction(SIGSEGV, &sa, &old); sigaction(SIGBUS, &sa, &old); sigaction(SIGILL, &sa, &old); sigaction(SIGABRT, &sa, &old); sigaction(SIGFPE, &sa, &old); sigprocmask(SIG_UNBLOCK, &m, NULL); }