int EVP_SignFinal(EVP_MD_CTX *ctx, unsigned char *sigret, unsigned int *siglen, EVP_PKEY *pkey) { unsigned char m[EVP_MAX_MD_SIZE]; unsigned int m_len = 0; int i = 0, ok = 0, v = 0; EVP_PKEY_CTX *pkctx = NULL; *siglen = 0; if (ctx->flags & EVP_MD_CTX_FLAG_FINALISE) { if (!EVP_DigestFinal_ex(ctx, m, &m_len)) goto err; } else { int rv = 0; EVP_MD_CTX tmp_ctx; EVP_MD_CTX_init(&tmp_ctx); rv = EVP_MD_CTX_copy_ex(&tmp_ctx, ctx); if (rv) rv = EVP_DigestFinal_ex(&tmp_ctx, m, &m_len); EVP_MD_CTX_cleanup(&tmp_ctx); if (!rv) return 0; } if (ctx->digest->flags & EVP_MD_FLAG_PKEY_METHOD_SIGNATURE) { size_t sltmp = (size_t)EVP_PKEY_size(pkey); i = 0; pkctx = EVP_PKEY_CTX_new(pkey, NULL); if (!pkctx) goto err; if (EVP_PKEY_sign_init(pkctx) <= 0) goto err; if (EVP_PKEY_CTX_set_signature_md(pkctx, ctx->digest) <= 0) goto err; if (EVP_PKEY_sign(pkctx, sigret, &sltmp, m, m_len) <= 0) goto err; *siglen = sltmp; i = 1; err: EVP_PKEY_CTX_free(pkctx); return i; } for (i = 0; i < 4; i++) { v = ctx->digest->required_pkey_type[i]; if (v == 0) break; if (pkey->type == v) { ok = 1; break; } } if (!ok) { EVPerr(EVP_F_EVP_SIGNFINAL, EVP_R_WRONG_PUBLIC_KEY_TYPE); return (0); } if (ctx->digest->sign == NULL) { EVPerr(EVP_F_EVP_SIGNFINAL, EVP_R_NO_SIGN_FUNCTION_CONFIGURED); return (0); } return ctx->digest->sign(ctx->digest->type, m, m_len, sigret, siglen, pkey->pkey.ptr); }
int ssl3_change_cipher_state(SSL *s, int which) { unsigned char *p,*mac_secret; unsigned char exp_key[EVP_MAX_KEY_LENGTH]; unsigned char exp_iv[EVP_MAX_IV_LENGTH]; unsigned char *ms,*key,*iv,*er1,*er2; EVP_CIPHER_CTX *dd; const EVP_CIPHER *c; #ifndef OPENSSL_NO_COMP COMP_METHOD *comp; #endif const EVP_MD *m; EVP_MD_CTX md; int is_exp,n,i,j,k,cl; int reuse_dd = 0; is_exp=SSL_C_IS_EXPORT(s->s3->tmp.new_cipher); c=s->s3->tmp.new_sym_enc; m=s->s3->tmp.new_hash; /* m == NULL will lead to a crash later */ OPENSSL_assert(m); #ifndef OPENSSL_NO_COMP if (s->s3->tmp.new_compression == NULL) comp=NULL; else comp=s->s3->tmp.new_compression->method; #endif if (which & SSL3_CC_READ) { if (s->enc_read_ctx != NULL) reuse_dd = 1; else if ((s->enc_read_ctx=OPENSSL_malloc(sizeof(EVP_CIPHER_CTX))) == NULL) goto err; else /* make sure it's intialized in case we exit later with an error */ EVP_CIPHER_CTX_init(s->enc_read_ctx); dd= s->enc_read_ctx; ssl_replace_hash(&s->read_hash,m); #ifndef OPENSSL_NO_COMP /* COMPRESS */ if (s->expand != NULL) { COMP_CTX_free(s->expand); s->expand=NULL; } if (comp != NULL) { s->expand=COMP_CTX_new(comp); if (s->expand == NULL) { SSLerr(SSL_F_SSL3_CHANGE_CIPHER_STATE,SSL_R_COMPRESSION_LIBRARY_ERROR); goto err2; } if (s->s3->rrec.comp == NULL) s->s3->rrec.comp=(unsigned char *) OPENSSL_malloc(SSL3_RT_MAX_PLAIN_LENGTH); if (s->s3->rrec.comp == NULL) goto err; } #endif memset(&(s->s3->read_sequence[0]),0,8); mac_secret= &(s->s3->read_mac_secret[0]); } else { if (s->enc_write_ctx != NULL) reuse_dd = 1; else if ((s->enc_write_ctx=OPENSSL_malloc(sizeof(EVP_CIPHER_CTX))) == NULL) goto err; else /* make sure it's intialized in case we exit later with an error */ EVP_CIPHER_CTX_init(s->enc_write_ctx); dd= s->enc_write_ctx; ssl_replace_hash(&s->write_hash,m); #ifndef OPENSSL_NO_COMP /* COMPRESS */ if (s->compress != NULL) { COMP_CTX_free(s->compress); s->compress=NULL; } if (comp != NULL) { s->compress=COMP_CTX_new(comp); if (s->compress == NULL) { SSLerr(SSL_F_SSL3_CHANGE_CIPHER_STATE,SSL_R_COMPRESSION_LIBRARY_ERROR); goto err2; } } #endif memset(&(s->s3->write_sequence[0]),0,8); mac_secret= &(s->s3->write_mac_secret[0]); } if (reuse_dd) EVP_CIPHER_CTX_cleanup(dd); p=s->s3->tmp.key_block; i=EVP_MD_size(m); if (i < 0) goto err2; cl=EVP_CIPHER_key_length(c); j=is_exp ? (cl < SSL_C_EXPORT_KEYLENGTH(s->s3->tmp.new_cipher) ? cl : SSL_C_EXPORT_KEYLENGTH(s->s3->tmp.new_cipher)) : cl; /* Was j=(is_exp)?5:EVP_CIPHER_key_length(c); */ k=EVP_CIPHER_iv_length(c); if ( (which == SSL3_CHANGE_CIPHER_CLIENT_WRITE) || (which == SSL3_CHANGE_CIPHER_SERVER_READ)) { ms= &(p[ 0]); n=i+i; key= &(p[ n]); n+=j+j; iv= &(p[ n]); n+=k+k; er1= &(s->s3->client_random[0]); er2= &(s->s3->server_random[0]); } else { n=i; ms= &(p[ n]); n+=i+j; key= &(p[ n]); n+=j+k; iv= &(p[ n]); n+=k; er1= &(s->s3->server_random[0]); er2= &(s->s3->client_random[0]); } if (n > s->s3->tmp.key_block_length) { SSLerr(SSL_F_SSL3_CHANGE_CIPHER_STATE,ERR_R_INTERNAL_ERROR); goto err2; } EVP_MD_CTX_init(&md); memcpy(mac_secret,ms,i); if (is_exp) { /* In here I set both the read and write key/iv to the * same value since only the correct one will be used :-). */ EVP_DigestInit_ex(&md,EVP_md5(), NULL); EVP_DigestUpdate(&md,key,j); EVP_DigestUpdate(&md,er1,SSL3_RANDOM_SIZE); EVP_DigestUpdate(&md,er2,SSL3_RANDOM_SIZE); EVP_DigestFinal_ex(&md,&(exp_key[0]),NULL); key= &(exp_key[0]); if (k > 0) { EVP_DigestInit_ex(&md,EVP_md5(), NULL); EVP_DigestUpdate(&md,er1,SSL3_RANDOM_SIZE); EVP_DigestUpdate(&md,er2,SSL3_RANDOM_SIZE); EVP_DigestFinal_ex(&md,&(exp_iv[0]),NULL); iv= &(exp_iv[0]); } } s->session->key_arg_length=0; EVP_CipherInit_ex(dd,c,NULL,key,iv,(which & SSL3_CC_WRITE)); OPENSSL_cleanse(&(exp_key[0]),sizeof(exp_key)); OPENSSL_cleanse(&(exp_iv[0]),sizeof(exp_iv)); EVP_MD_CTX_cleanup(&md); return(1); err: SSLerr(SSL_F_SSL3_CHANGE_CIPHER_STATE,ERR_R_MALLOC_FAILURE); err2: return(0); }
int RSA_padding_add_PKCS1_PSS(RSA *rsa, unsigned char *EM, const unsigned char *mHash, const EVP_MD *Hash, int sLen) { int i; int ret = 0; int hLen, maskedDBLen, MSBits, emLen; unsigned char *H, *salt = NULL, *p; EVP_MD_CTX ctx; hLen = EVP_MD_size(Hash); if (hLen < 0) goto err; /* * Negative sLen has special meanings: * -1 sLen == hLen * -2 salt length is maximized * -N reserved */ if (sLen == -1) sLen = hLen; else if (sLen == -2) sLen = -2; else if (sLen < -2) { RSAerr(RSA_F_RSA_PADDING_ADD_PKCS1_PSS, RSA_R_SLEN_CHECK_FAILED); goto err; } MSBits = (BN_num_bits(rsa->n) - 1) & 0x7; emLen = RSA_size(rsa); if (MSBits == 0) { *EM++ = 0; emLen--; } if (sLen == -2) { sLen = emLen - hLen - 2; } else if (emLen < (hLen + sLen + 2)) { RSAerr(RSA_F_RSA_PADDING_ADD_PKCS1_PSS, RSA_R_DATA_TOO_LARGE_FOR_KEY_SIZE); goto err; } if (sLen > 0) { salt = (unsigned char*)OPENSSL_malloc(sLen); if (!salt) { RSAerr(RSA_F_RSA_PADDING_ADD_PKCS1_PSS, ERR_R_MALLOC_FAILURE); goto err; } if (RAND_bytes(salt, sLen) <= 0) goto err; } maskedDBLen = emLen - hLen - 1; H = EM + maskedDBLen; EVP_MD_CTX_init(&ctx); EVP_DigestInit_ex(&ctx, Hash, NULL); EVP_DigestUpdate(&ctx, zeroes, sizeof zeroes); EVP_DigestUpdate(&ctx, mHash, hLen); if (sLen) EVP_DigestUpdate(&ctx, salt, sLen); EVP_DigestFinal(&ctx, H, NULL); EVP_MD_CTX_cleanup(&ctx); /* Generate dbMask in place then perform XOR on it */ if (PKCS1_MGF1(EM, maskedDBLen, H, hLen, Hash)) goto err; p = EM; /* Initial PS XORs with all zeroes which is a NOP so just update * pointer. Note from a test above this value is guaranteed to * be non-negative. */ p += emLen - sLen - hLen - 2; *p++ ^= 0x1; if (sLen > 0) { for (i = 0; i < sLen; i++) *p++ ^= salt[i]; } if (MSBits) EM[0] &= 0xFF >> (8 - MSBits); /* H is already in place so just set final 0xbc */ EM[emLen - 1] = 0xbc; ret = 1; err: if (salt) OPENSSL_free(salt); return ret; }
static int ssl3_handshake_mac(SSL *s, int md_nid, const char *sender, int len, uint8_t *p) { unsigned int ret; int npad, n; unsigned int i; uint8_t md_buf[EVP_MAX_MD_SIZE]; EVP_MD_CTX ctx, *d = NULL; if (s->s3->handshake_buffer && !ssl3_digest_cached_records(s, free_handshake_buffer)) { return 0; } /* Search for digest of specified type in the handshake_dgst array. */ for (i = 0; i < SSL_MAX_DIGEST; i++) { if (s->s3->handshake_dgst[i] && EVP_MD_CTX_type(s->s3->handshake_dgst[i]) == md_nid) { d = s->s3->handshake_dgst[i]; break; } } if (!d) { OPENSSL_PUT_ERROR(SSL, ssl3_handshake_mac, SSL_R_NO_REQUIRED_DIGEST); return 0; } EVP_MD_CTX_init(&ctx); if (!EVP_MD_CTX_copy_ex(&ctx, d)) { EVP_MD_CTX_cleanup(&ctx); OPENSSL_PUT_ERROR(SSL, ssl3_handshake_mac, ERR_LIB_EVP); return 0; } n = EVP_MD_CTX_size(&ctx); if (n < 0) { return 0; } npad = (48 / n) * n; if (sender != NULL) { EVP_DigestUpdate(&ctx, sender, len); } EVP_DigestUpdate(&ctx, s->session->master_key, s->session->master_key_length); EVP_DigestUpdate(&ctx, ssl3_pad_1, npad); EVP_DigestFinal_ex(&ctx, md_buf, &i); if (!EVP_DigestInit_ex(&ctx, EVP_MD_CTX_md(&ctx), NULL)) { EVP_MD_CTX_cleanup(&ctx); OPENSSL_PUT_ERROR(SSL, ssl3_handshake_mac, ERR_LIB_EVP); return 0; } EVP_DigestUpdate(&ctx, s->session->master_key, s->session->master_key_length); EVP_DigestUpdate(&ctx, ssl3_pad_2, npad); EVP_DigestUpdate(&ctx, md_buf, i); EVP_DigestFinal_ex(&ctx, p, &ret); EVP_MD_CTX_cleanup(&ctx); return ret; }
int EVP_BytesToKey(const EVP_CIPHER *type, const EVP_MD *md, const unsigned char *salt, const unsigned char *data, int datal, int count, unsigned char *key, unsigned char *iv) { EVP_MD_CTX c; unsigned char md_buf[EVP_MAX_MD_SIZE]; int niv,nkey,addmd=0; unsigned int mds=0,i; nkey=type->key_len; niv=type->iv_len; OPENSSL_assert(nkey <= EVP_MAX_KEY_LENGTH); OPENSSL_assert(niv <= EVP_MAX_IV_LENGTH); if (data == NULL) return(nkey); EVP_MD_CTX_init(&c); for (;;) { EVP_DigestInit_ex(&c,md, NULL); if (addmd++) EVP_DigestUpdate(&c,&(md_buf[0]),mds); EVP_DigestUpdate(&c,data,datal); if (salt != NULL) EVP_DigestUpdate(&c,salt,PKCS5_SALT_LEN); EVP_DigestFinal_ex(&c,&(md_buf[0]),&mds); for (i=1; i<(unsigned int)count; i++) { EVP_DigestInit_ex(&c,md, NULL); EVP_DigestUpdate(&c,&(md_buf[0]),mds); EVP_DigestFinal_ex(&c,&(md_buf[0]),&mds); } i=0; if (nkey) { for (;;) { if (nkey == 0) break; if (i == mds) break; if (key != NULL) *(key++)=md_buf[i]; nkey--; i++; } } if (niv && (i != mds)) { for (;;) { if (niv == 0) break; if (i == mds) break; if (iv != NULL) *(iv++)=md_buf[i]; niv--; i++; } } if ((nkey == 0) && (niv == 0)) break; } EVP_MD_CTX_cleanup(&c); OPENSSL_cleanse(&(md_buf[0]),EVP_MAX_MD_SIZE); return(type->key_len); }
/* seed1 through seed5 are virtually concatenated */ static int tls1_P_hash(const EVP_MD *md, const unsigned char *sec, int sec_len, const void *seed1, int seed1_len, const void *seed2, int seed2_len, const void *seed3, int seed3_len, const void *seed4, int seed4_len, const void *seed5, int seed5_len, unsigned char *out, int olen) { int chunk; size_t j; EVP_MD_CTX ctx, ctx_tmp, ctx_init; EVP_PKEY *mac_key; unsigned char A1[EVP_MAX_MD_SIZE]; size_t A1_len; int ret = 0; chunk=EVP_MD_size(md); OPENSSL_assert(chunk >= 0); EVP_MD_CTX_init(&ctx); EVP_MD_CTX_init(&ctx_tmp); EVP_MD_CTX_init(&ctx_init); EVP_MD_CTX_set_flags(&ctx_init, EVP_MD_CTX_FLAG_NON_FIPS_ALLOW); mac_key = EVP_PKEY_new_mac_key(EVP_PKEY_HMAC, NULL, sec, sec_len); if (!mac_key) goto err; if (!EVP_DigestSignInit(&ctx_init,NULL,md, NULL, mac_key)) goto err; if (!EVP_MD_CTX_copy_ex(&ctx,&ctx_init)) goto err; if (seed1 && !EVP_DigestSignUpdate(&ctx,seed1,seed1_len)) goto err; if (seed2 && !EVP_DigestSignUpdate(&ctx,seed2,seed2_len)) goto err; if (seed3 && !EVP_DigestSignUpdate(&ctx,seed3,seed3_len)) goto err; if (seed4 && !EVP_DigestSignUpdate(&ctx,seed4,seed4_len)) goto err; if (seed5 && !EVP_DigestSignUpdate(&ctx,seed5,seed5_len)) goto err; if (!EVP_DigestSignFinal(&ctx,A1,&A1_len)) goto err; for (;;) { /* Reinit mac contexts */ if (!EVP_MD_CTX_copy_ex(&ctx,&ctx_init)) goto err; if (!EVP_DigestSignUpdate(&ctx,A1,A1_len)) goto err; if (olen>chunk && !EVP_MD_CTX_copy_ex(&ctx_tmp,&ctx)) goto err; if (seed1 && !EVP_DigestSignUpdate(&ctx,seed1,seed1_len)) goto err; if (seed2 && !EVP_DigestSignUpdate(&ctx,seed2,seed2_len)) goto err; if (seed3 && !EVP_DigestSignUpdate(&ctx,seed3,seed3_len)) goto err; if (seed4 && !EVP_DigestSignUpdate(&ctx,seed4,seed4_len)) goto err; if (seed5 && !EVP_DigestSignUpdate(&ctx,seed5,seed5_len)) goto err; if (olen > chunk) { if (!EVP_DigestSignFinal(&ctx,out,&j)) goto err; out+=j; olen-=j; /* calc the next A1 value */ if (!EVP_DigestSignFinal(&ctx_tmp,A1,&A1_len)) goto err; } else /* last one */ { if (!EVP_DigestSignFinal(&ctx,A1,&A1_len)) goto err; memcpy(out,A1,olen); break; } } ret = 1; err: EVP_PKEY_free(mac_key); EVP_MD_CTX_cleanup(&ctx); EVP_MD_CTX_cleanup(&ctx_tmp); EVP_MD_CTX_cleanup(&ctx_init); OPENSSL_cleanse(A1,sizeof(A1)); return ret; }
int PKCS7_dataFinal(PKCS7 *p7, BIO *bio) { int ret=0; int i,j; BIO *btmp; PKCS7_SIGNER_INFO *si; EVP_MD_CTX *mdc,ctx_tmp; STACK_OF(X509_ATTRIBUTE) *sk; STACK_OF(PKCS7_SIGNER_INFO) *si_sk=NULL; ASN1_OCTET_STRING *os=NULL; EVP_MD_CTX_init(&ctx_tmp); i=OBJ_obj2nid(p7->type); p7->state=PKCS7_S_HEADER; switch (i) { case NID_pkcs7_data: os = p7->d.data; break; case NID_pkcs7_signedAndEnveloped: /* XXX */ si_sk=p7->d.signed_and_enveloped->signer_info; os = p7->d.signed_and_enveloped->enc_data->enc_data; if (!os) { os=M_ASN1_OCTET_STRING_new(); if (!os) { PKCS7err(PKCS7_F_PKCS7_DATAFINAL,ERR_R_MALLOC_FAILURE); goto err; } p7->d.signed_and_enveloped->enc_data->enc_data=os; } break; case NID_pkcs7_enveloped: /* XXX */ os = p7->d.enveloped->enc_data->enc_data; if (!os) { os=M_ASN1_OCTET_STRING_new(); if (!os) { PKCS7err(PKCS7_F_PKCS7_DATAFINAL,ERR_R_MALLOC_FAILURE); goto err; } p7->d.enveloped->enc_data->enc_data=os; } break; case NID_pkcs7_signed: si_sk=p7->d.sign->signer_info; os=PKCS7_get_octet_string(p7->d.sign->contents); if (os == NULL) { PKCS7err(PKCS7_F_PKCS7_DATAFINAL, PKCS7_R_DECODE_ERROR); goto err; } /* If detached data then the content is excluded */ if(PKCS7_type_is_data(p7->d.sign->contents) && p7->detached) { M_ASN1_OCTET_STRING_free(os); p7->d.sign->contents->d.data = NULL; } break; case NID_pkcs7_digest: os=PKCS7_get_octet_string(p7->d.digest->contents); if (os == NULL) { PKCS7err(PKCS7_F_PKCS7_DATAFINAL, PKCS7_R_DECODE_ERROR); goto err; } /* If detached data then the content is excluded */ if(PKCS7_type_is_data(p7->d.digest->contents) && p7->detached) { M_ASN1_OCTET_STRING_free(os); p7->d.digest->contents->d.data = NULL; } break; default: PKCS7err(PKCS7_F_PKCS7_DATAFINAL,PKCS7_R_UNSUPPORTED_CONTENT_TYPE); goto err; } if (si_sk != NULL) { for (i=0; i<sk_PKCS7_SIGNER_INFO_num(si_sk); i++) { si=sk_PKCS7_SIGNER_INFO_value(si_sk,i); if (si->pkey == NULL) continue; j = OBJ_obj2nid(si->digest_alg->algorithm); btmp=bio; btmp = PKCS7_find_digest(&mdc, btmp, j); if (btmp == NULL) goto err; /* We now have the EVP_MD_CTX, lets do the * signing. */ if (!EVP_MD_CTX_copy_ex(&ctx_tmp,mdc)) goto err; sk=si->auth_attr; /* If there are attributes, we add the digest * attribute and only sign the attributes */ if (sk_X509_ATTRIBUTE_num(sk) > 0) { if (!do_pkcs7_signed_attrib(si, &ctx_tmp)) goto err; } else { unsigned char *abuf = NULL; unsigned int abuflen; abuflen = EVP_PKEY_size(si->pkey); abuf = malloc(abuflen); if (!abuf) goto err; if (!EVP_SignFinal(&ctx_tmp, abuf, &abuflen, si->pkey)) { PKCS7err(PKCS7_F_PKCS7_DATAFINAL, ERR_R_EVP_LIB); goto err; } ASN1_STRING_set0(si->enc_digest, abuf, abuflen); } } } else if (i == NID_pkcs7_digest) { unsigned char md_data[EVP_MAX_MD_SIZE]; unsigned int md_len; if (!PKCS7_find_digest(&mdc, bio, OBJ_obj2nid(p7->d.digest->md->algorithm))) goto err; if (!EVP_DigestFinal_ex(mdc,md_data,&md_len)) goto err; M_ASN1_OCTET_STRING_set(p7->d.digest->digest, md_data, md_len); } if (!PKCS7_is_detached(p7) && !(os->flags & ASN1_STRING_FLAG_NDEF)) { char *cont; long contlen; btmp=BIO_find_type(bio,BIO_TYPE_MEM); if (btmp == NULL) { PKCS7err(PKCS7_F_PKCS7_DATAFINAL,PKCS7_R_UNABLE_TO_FIND_MEM_BIO); goto err; } contlen = BIO_get_mem_data(btmp, &cont); /* Mark the BIO read only then we can use its copy of the data * instead of making an extra copy. */ BIO_set_flags(btmp, BIO_FLAGS_MEM_RDONLY); BIO_set_mem_eof_return(btmp, 0); ASN1_STRING_set0(os, (unsigned char *)cont, contlen); } ret=1; err: EVP_MD_CTX_cleanup(&ctx_tmp); return(ret); }
int ASN1_item_verify(const ASN1_ITEM *it, X509_ALGOR *a, ASN1_BIT_STRING *signature, void *asn, EVP_PKEY *pkey) { EVP_MD_CTX ctx; const EVP_MD *type = NULL; unsigned char *buf_in=NULL; int ret= -1,inl; int mdnid, pknid; if (!pkey) { ASN1err(ASN1_F_ASN1_ITEM_VERIFY, ERR_R_PASSED_NULL_PARAMETER); return -1; } if (signature->type == V_ASN1_BIT_STRING && signature->flags & 0x7) { ASN1err(ASN1_F_ASN1_ITEM_VERIFY, ASN1_R_INVALID_BIT_STRING_BITS_LEFT); return -1; } EVP_MD_CTX_init(&ctx); /* Convert signature OID into digest and public key OIDs */ if (!OBJ_find_sigid_algs(OBJ_obj2nid(a->algorithm), &mdnid, &pknid)) { ASN1err(ASN1_F_ASN1_ITEM_VERIFY,ASN1_R_UNKNOWN_SIGNATURE_ALGORITHM); goto err; } type=EVP_get_digestbynid(mdnid); if (type == NULL) { ASN1err(ASN1_F_ASN1_ITEM_VERIFY,ASN1_R_UNKNOWN_MESSAGE_DIGEST_ALGORITHM); goto err; } /* Check public key OID matches public key type */ if (EVP_PKEY_type(pknid) != pkey->ameth->pkey_id) { ASN1err(ASN1_F_ASN1_ITEM_VERIFY,ASN1_R_WRONG_PUBLIC_KEY_TYPE); goto err; } if (!EVP_VerifyInit_ex(&ctx,type, NULL)) { ASN1err(ASN1_F_ASN1_ITEM_VERIFY,ERR_R_EVP_LIB); ret=0; goto err; } inl = ASN1_item_i2d(asn, &buf_in, it); if (buf_in == NULL) { ASN1err(ASN1_F_ASN1_ITEM_VERIFY,ERR_R_MALLOC_FAILURE); goto err; } EVP_VerifyUpdate(&ctx,(unsigned char *)buf_in,inl); OPENSSL_cleanse(buf_in,(unsigned int)inl); OPENSSL_free(buf_in); if (EVP_VerifyFinal(&ctx,(unsigned char *)signature->data, (unsigned int)signature->length,pkey) <= 0) { ASN1err(ASN1_F_ASN1_ITEM_VERIFY,ERR_R_EVP_LIB); ret=0; goto err; } /* we don't need to zero the 'ctx' because we just checked * public information */ /* memset(&ctx,0,sizeof(ctx)); */ ret=1; err: EVP_MD_CTX_cleanup(&ctx); return(ret); }
int ASN1_item_sign(const ASN1_ITEM *it, X509_ALGOR *algor1, X509_ALGOR *algor2, ASN1_BIT_STRING *signature, void *asn, EVP_PKEY *pkey, const EVP_MD *type) { EVP_MD_CTX ctx; unsigned char *buf_in=NULL,*buf_out=NULL; int i,inl=0,outl=0,outll=0; X509_ALGOR *a; EVP_MD_CTX_init(&ctx); for (i=0; i<2; i++) { if (i == 0) a=algor1; else a=algor2; if (a == NULL) continue; if (type->pkey_type == NID_dsaWithSHA1 || type->pkey_type == NID_ecdsa_with_SHA1) { /* special case: RFC 3279 tells us to omit 'parameters' * with id-dsa-with-sha1 and ecdsa-with-SHA1 */ ASN1_TYPE_free(a->parameter); a->parameter = NULL; } else if ((a->parameter == NULL) || (a->parameter->type != V_ASN1_NULL)) { ASN1_TYPE_free(a->parameter); if ((a->parameter=ASN1_TYPE_new()) == NULL) goto err; a->parameter->type=V_ASN1_NULL; } ASN1_OBJECT_free(a->algorithm); a->algorithm=OBJ_nid2obj(type->pkey_type); if (a->algorithm == NULL) { ASN1err(ASN1_F_ASN1_ITEM_SIGN,ASN1_R_UNKNOWN_OBJECT_TYPE); goto err; } if (a->algorithm->length == 0) { ASN1err(ASN1_F_ASN1_ITEM_SIGN,ASN1_R_THE_ASN1_OBJECT_IDENTIFIER_IS_NOT_KNOWN_FOR_THIS_MD); goto err; } } inl=ASN1_item_i2d(asn,&buf_in, it); outll=outl=EVP_PKEY_size(pkey); buf_out=(unsigned char *)OPENSSL_malloc((unsigned int)outl); if ((buf_in == NULL) || (buf_out == NULL)) { outl=0; ASN1err(ASN1_F_ASN1_ITEM_SIGN,ERR_R_MALLOC_FAILURE); goto err; } EVP_SignInit_ex(&ctx,type, NULL); EVP_SignUpdate(&ctx,(unsigned char *)buf_in,inl); if (!EVP_SignFinal(&ctx,(unsigned char *)buf_out, (unsigned int *)&outl,pkey)) { outl=0; ASN1err(ASN1_F_ASN1_ITEM_SIGN,ERR_R_EVP_LIB); goto err; } if (signature->data != NULL) OPENSSL_free(signature->data); signature->data=buf_out; buf_out=NULL; signature->length=outl; /* In the interests of compatibility, I'll make sure that * the bit string has a 'not-used bits' value of 0 */ signature->flags&= ~(ASN1_STRING_FLAG_BITS_LEFT|0x07); signature->flags|=ASN1_STRING_FLAG_BITS_LEFT; err: EVP_MD_CTX_cleanup(&ctx); if (buf_in != NULL) { OPENSSL_cleanse((char *)buf_in,(unsigned int)inl); OPENSSL_free(buf_in); } if (buf_out != NULL) { OPENSSL_cleanse((char *)buf_out,outll); OPENSSL_free(buf_out); } return(outl); }
ldns_rdf * ldns_sign_public_evp(ldns_buffer *to_sign, EVP_PKEY *key, const EVP_MD *digest_type) { unsigned int siglen; ldns_rdf *sigdata_rdf; ldns_buffer *b64sig; EVP_MD_CTX ctx; const EVP_MD *md_type; int r; siglen = 0; b64sig = ldns_buffer_new(LDNS_MAX_PACKETLEN); if (!b64sig) { return NULL; } /* initializes a signing context */ md_type = digest_type; if(!md_type) { /* unknown message difest */ ldns_buffer_free(b64sig); return NULL; } EVP_MD_CTX_init(&ctx); r = EVP_SignInit(&ctx, md_type); if(r == 1) { r = EVP_SignUpdate(&ctx, (unsigned char*) ldns_buffer_begin(to_sign), ldns_buffer_position(to_sign)); } else { ldns_buffer_free(b64sig); return NULL; } if(r == 1) { r = EVP_SignFinal(&ctx, (unsigned char*) ldns_buffer_begin(b64sig), &siglen, key); } else { ldns_buffer_free(b64sig); return NULL; } if(r != 1) { ldns_buffer_free(b64sig); return NULL; } /* unfortunately, OpenSSL output is differenct from DNS DSA format */ #ifndef S_SPLINT_S if (EVP_PKEY_type(key->type) == EVP_PKEY_DSA) { sigdata_rdf = ldns_convert_dsa_rrsig_asn12rdf(b64sig, siglen); #ifdef USE_ECDSA } else if(EVP_PKEY_type(key->type) == EVP_PKEY_EC && ldns_pkey_is_ecdsa(key)) { sigdata_rdf = ldns_convert_ecdsa_rrsig_asn12rdf(b64sig, siglen); #endif } else { /* ok output for other types is the same */ sigdata_rdf = ldns_rdf_new_frm_data(LDNS_RDF_TYPE_B64, siglen, ldns_buffer_begin(b64sig)); } #endif /* splint */ ldns_buffer_free(b64sig); EVP_MD_CTX_cleanup(&ctx); return sigdata_rdf; }
void EVP_MD_CTX_destroy(EVP_MD_CTX *ctx) { EVP_MD_CTX_cleanup(ctx); OPENSSL_free(ctx); }
static int rsa_sign_with_key(RSA *rsa, struct checksum_algo *checksum_algo, const struct image_region region[], int region_count, uint8_t **sigp, uint *sig_size) { EVP_PKEY *key; EVP_MD_CTX *context; int size, ret = 0; uint8_t *sig; int i; key = EVP_PKEY_new(); if (!key) return rsa_err("EVP_PKEY object creation failed"); if (!EVP_PKEY_set1_RSA(key, rsa)) { ret = rsa_err("EVP key setup failed"); goto err_set; } size = EVP_PKEY_size(key); sig = malloc(size); if (!sig) { fprintf(stderr, "Out of memory for signature (%d bytes)\n", size); ret = -ENOMEM; goto err_alloc; } context = EVP_MD_CTX_create(); if (!context) { ret = rsa_err("EVP context creation failed"); goto err_create; } EVP_MD_CTX_init(context); if (!EVP_SignInit(context, checksum_algo->calculate_sign())) { ret = rsa_err("Signer setup failed"); goto err_sign; } for (i = 0; i < region_count; i++) { if (!EVP_SignUpdate(context, region[i].data, region[i].size)) { ret = rsa_err("Signing data failed"); goto err_sign; } } if (!EVP_SignFinal(context, sig, sig_size, key)) { ret = rsa_err("Could not obtain signature"); goto err_sign; } EVP_MD_CTX_cleanup(context); EVP_MD_CTX_destroy(context); EVP_PKEY_free(key); debug("Got signature: %d bytes, expected %d\n", *sig_size, size); *sigp = sig; *sig_size = size; return 0; err_sign: EVP_MD_CTX_destroy(context); err_create: free(sig); err_alloc: err_set: EVP_PKEY_free(key); return ret; }
static int ssl3_handshake_mac(SSL *ssl, int md_nid, const char *sender, size_t sender_len, uint8_t *p) { unsigned int ret; size_t npad, n; unsigned int i; uint8_t md_buf[EVP_MAX_MD_SIZE]; EVP_MD_CTX ctx; const EVP_MD_CTX *ctx_template; if (md_nid == NID_md5) { ctx_template = &ssl->s3->handshake_md5; } else if (md_nid == EVP_MD_CTX_type(&ssl->s3->handshake_hash)) { ctx_template = &ssl->s3->handshake_hash; } else { OPENSSL_PUT_ERROR(SSL, SSL_R_NO_REQUIRED_DIGEST); return 0; } EVP_MD_CTX_init(&ctx); if (!EVP_MD_CTX_copy_ex(&ctx, ctx_template)) { EVP_MD_CTX_cleanup(&ctx); OPENSSL_PUT_ERROR(SSL, ERR_LIB_EVP); return 0; } static const uint8_t kPad1[48] = { 0x36, 0x36, 0x36, 0x36, 0x36, 0x36, 0x36, 0x36, 0x36, 0x36, 0x36, 0x36, 0x36, 0x36, 0x36, 0x36, 0x36, 0x36, 0x36, 0x36, 0x36, 0x36, 0x36, 0x36, 0x36, 0x36, 0x36, 0x36, 0x36, 0x36, 0x36, 0x36, 0x36, 0x36, 0x36, 0x36, 0x36, 0x36, 0x36, 0x36, 0x36, 0x36, 0x36, 0x36, 0x36, 0x36, 0x36, 0x36, }; static const uint8_t kPad2[48] = { 0x5c, 0x5c, 0x5c, 0x5c, 0x5c, 0x5c, 0x5c, 0x5c, 0x5c, 0x5c, 0x5c, 0x5c, 0x5c, 0x5c, 0x5c, 0x5c, 0x5c, 0x5c, 0x5c, 0x5c, 0x5c, 0x5c, 0x5c, 0x5c, 0x5c, 0x5c, 0x5c, 0x5c, 0x5c, 0x5c, 0x5c, 0x5c, 0x5c, 0x5c, 0x5c, 0x5c, 0x5c, 0x5c, 0x5c, 0x5c, 0x5c, 0x5c, 0x5c, 0x5c, 0x5c, 0x5c, 0x5c, 0x5c, }; n = EVP_MD_CTX_size(&ctx); npad = (48 / n) * n; if (sender != NULL) { EVP_DigestUpdate(&ctx, sender, sender_len); } EVP_DigestUpdate(&ctx, ssl->session->master_key, ssl->session->master_key_length); EVP_DigestUpdate(&ctx, kPad1, npad); EVP_DigestFinal_ex(&ctx, md_buf, &i); if (!EVP_DigestInit_ex(&ctx, EVP_MD_CTX_md(&ctx), NULL)) { EVP_MD_CTX_cleanup(&ctx); OPENSSL_PUT_ERROR(SSL, ERR_LIB_EVP); return 0; } EVP_DigestUpdate(&ctx, ssl->session->master_key, ssl->session->master_key_length); EVP_DigestUpdate(&ctx, kPad2, npad); EVP_DigestUpdate(&ctx, md_buf, i); EVP_DigestFinal_ex(&ctx, p, &ret); EVP_MD_CTX_cleanup(&ctx); return ret; }
void ssl3_free_handshake_hash(SSL *ssl) { EVP_MD_CTX_cleanup(&ssl->s3->handshake_hash); EVP_MD_CTX_cleanup(&ssl->s3->handshake_md5); }
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; }
/* some tests from the X9.62 draft */ int x9_62_test_internal(BIO *out, int nid, const char *r_in, const char *s_in) { int ret = 0; const char message[] = "abc"; unsigned char digest[20]; unsigned int dgst_len = 0; EVP_MD_CTX md_ctx; EC_KEY *key = NULL; ECDSA_SIG *signature = NULL; BIGNUM *r = NULL, *s = NULL; EVP_MD_CTX_init(&md_ctx); /* get the message digest */ if (!EVP_DigestInit(&md_ctx, EVP_ecdsa()) || !EVP_DigestUpdate(&md_ctx, (const void*)message, 3) || !EVP_DigestFinal(&md_ctx, digest, &dgst_len)) goto x962_int_err; BIO_printf(out, "testing %s: ", OBJ_nid2sn(nid)); /* create the key */ if ((key = EC_KEY_new_by_curve_name(nid)) == NULL) goto x962_int_err; use_fake = 1; if (!EC_KEY_generate_key(key)) goto x962_int_err; BIO_printf(out, "."); (void)BIO_flush(out); /* create the signature */ use_fake = 1; signature = ECDSA_do_sign(digest, 20, key); if (signature == NULL) goto x962_int_err; BIO_printf(out, "."); (void)BIO_flush(out); /* compare the created signature with the expected signature */ if ((r = BN_new()) == NULL || (s = BN_new()) == NULL) goto x962_int_err; if (!BN_dec2bn(&r, r_in) || !BN_dec2bn(&s, s_in)) goto x962_int_err; if (BN_cmp(signature->r ,r) || BN_cmp(signature->s, s)) goto x962_int_err; BIO_printf(out, "."); (void)BIO_flush(out); /* verify the signature */ if (ECDSA_do_verify(digest, 20, signature, key) != 1) goto x962_int_err; BIO_printf(out, "."); (void)BIO_flush(out); BIO_printf(out, " ok\n"); ret = 1; x962_int_err: if (!ret) BIO_printf(out, " failed\n"); if (key) EC_KEY_free(key); if (signature) ECDSA_SIG_free(signature); if (r) BN_free(r); if (s) BN_free(s); EVP_MD_CTX_cleanup(&md_ctx); return ret; }
void isc_gost_invalidate(isc_gost_t *ctx) { EVP_MD_CTX_cleanup(ctx); }
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; }
int PKCS7_signatureVerify(BIO *bio, PKCS7 *p7, PKCS7_SIGNER_INFO *si, X509 *x509) { ASN1_OCTET_STRING *os; EVP_MD_CTX mdc_tmp,*mdc; int ret=0,i; int md_type; STACK_OF(X509_ATTRIBUTE) *sk; BIO *btmp; EVP_PKEY *pkey; EVP_MD_CTX_init(&mdc_tmp); if (!PKCS7_type_is_signed(p7) && !PKCS7_type_is_signedAndEnveloped(p7)) { PKCS7err(PKCS7_F_PKCS7_SIGNATUREVERIFY, PKCS7_R_WRONG_PKCS7_TYPE); goto err; } md_type=OBJ_obj2nid(si->digest_alg->algorithm); btmp=bio; for (;;) { if ((btmp == NULL) || ((btmp=BIO_find_type(btmp,BIO_TYPE_MD)) == NULL)) { PKCS7err(PKCS7_F_PKCS7_SIGNATUREVERIFY, PKCS7_R_UNABLE_TO_FIND_MESSAGE_DIGEST); goto err; } BIO_get_md_ctx(btmp,&mdc); if (mdc == NULL) { PKCS7err(PKCS7_F_PKCS7_SIGNATUREVERIFY, ERR_R_INTERNAL_ERROR); goto err; } if (EVP_MD_CTX_type(mdc) == md_type) break; /* Workaround for some broken clients that put the signature * OID instead of the digest OID in digest_alg->algorithm */ if (EVP_MD_pkey_type(EVP_MD_CTX_md(mdc)) == md_type) break; btmp=BIO_next(btmp); } /* mdc is the digest ctx that we want, unless there are attributes, * in which case the digest is the signed attributes */ if (!EVP_MD_CTX_copy_ex(&mdc_tmp,mdc)) goto err; sk=si->auth_attr; if ((sk != NULL) && (sk_X509_ATTRIBUTE_num(sk) != 0)) { unsigned char md_dat[EVP_MAX_MD_SIZE], *abuf = NULL; unsigned int md_len; int alen; ASN1_OCTET_STRING *message_digest; if (!EVP_DigestFinal_ex(&mdc_tmp,md_dat,&md_len)) goto err; message_digest=PKCS7_digest_from_attributes(sk); if (!message_digest) { PKCS7err(PKCS7_F_PKCS7_SIGNATUREVERIFY, PKCS7_R_UNABLE_TO_FIND_MESSAGE_DIGEST); goto err; } if ((message_digest->length != (int)md_len) || (memcmp(message_digest->data,md_dat,md_len))) { #if 0 { int ii; for (ii=0; ii<message_digest->length; ii++) printf("%02X",message_digest->data[ii]); printf(" sent\n"); for (ii=0; ii<md_len; ii++) printf("%02X",md_dat[ii]); printf(" calc\n"); } #endif PKCS7err(PKCS7_F_PKCS7_SIGNATUREVERIFY, PKCS7_R_DIGEST_FAILURE); ret= -1; goto err; } if (!EVP_VerifyInit_ex(&mdc_tmp,EVP_get_digestbynid(md_type), NULL)) goto err; alen = ASN1_item_i2d((ASN1_VALUE *)sk, &abuf, ASN1_ITEM_rptr(PKCS7_ATTR_VERIFY)); if (alen <= 0) { PKCS7err(PKCS7_F_PKCS7_SIGNATUREVERIFY,ERR_R_ASN1_LIB); ret = -1; goto err; } if (!EVP_VerifyUpdate(&mdc_tmp, abuf, alen)) goto err; free(abuf); } os=si->enc_digest; pkey = X509_get_pubkey(x509); if (!pkey) { ret = -1; goto err; } i=EVP_VerifyFinal(&mdc_tmp,os->data,os->length, pkey); EVP_PKEY_free(pkey); if (i <= 0) { PKCS7err(PKCS7_F_PKCS7_SIGNATUREVERIFY, PKCS7_R_SIGNATURE_FAILURE); ret= -1; goto err; } else ret=1; err: EVP_MD_CTX_cleanup(&mdc_tmp); return(ret); }
/* read the data and then respond */ static int client_certificate(SSL *s) { unsigned char *buf; unsigned char *p,*d; int i; unsigned int n; int cert_ch_len; unsigned char *cert_ch; buf=(unsigned char *)s->init_buf->data; /* We have a cert associated with the SSL, so attach it to * the session if it does not have one */ if (s->state == SSL2_ST_SEND_CLIENT_CERTIFICATE_A) { i=ssl2_read(s,(char *)&(buf[s->init_num]), SSL2_MAX_CERT_CHALLENGE_LENGTH+2-s->init_num); if (i<(SSL2_MIN_CERT_CHALLENGE_LENGTH+2-s->init_num)) return(ssl2_part_read(s,SSL_F_CLIENT_CERTIFICATE,i)); s->init_num += i; if (s->msg_callback) s->msg_callback(0, s->version, 0, buf, (size_t)s->init_num, s, s->msg_callback_arg); /* REQUEST-CERTIFICATE */ /* type=buf[0]; */ /* type eq x509 */ if (buf[1] != SSL2_AT_MD5_WITH_RSA_ENCRYPTION) { ssl2_return_error(s,SSL2_PE_UNSUPPORTED_CERTIFICATE_TYPE); SSLerr(SSL_F_CLIENT_CERTIFICATE,SSL_R_BAD_AUTHENTICATION_TYPE); return(-1); } if ((s->cert == NULL) || (s->cert->key->x509 == NULL) || (s->cert->key->privatekey == NULL)) { s->state=SSL2_ST_X509_GET_CLIENT_CERTIFICATE; } else s->state=SSL2_ST_SEND_CLIENT_CERTIFICATE_C; } cert_ch = buf + 2; cert_ch_len = s->init_num - 2; if (s->state == SSL2_ST_X509_GET_CLIENT_CERTIFICATE) { X509 *x509=NULL; EVP_PKEY *pkey=NULL; /* If we get an error we need to * ssl->rwstate=SSL_X509_LOOKUP; * return(error); * We should then be retried when things are ok and we * can get a cert or not */ i=0; if (s->ctx->client_cert_cb != NULL) { i=s->ctx->client_cert_cb(s,&(x509),&(pkey)); } if (i < 0) { s->rwstate=SSL_X509_LOOKUP; return(-1); } s->rwstate=SSL_NOTHING; if ((i == 1) && (pkey != NULL) && (x509 != NULL)) { s->state=SSL2_ST_SEND_CLIENT_CERTIFICATE_C; if ( !SSL_use_certificate(s,x509) || !SSL_use_PrivateKey(s,pkey)) { i=0; } X509_free(x509); EVP_PKEY_free(pkey); } else if (i == 1) { if (x509 != NULL) X509_free(x509); if (pkey != NULL) EVP_PKEY_free(pkey); SSLerr(SSL_F_CLIENT_CERTIFICATE,SSL_R_BAD_DATA_RETURNED_BY_CALLBACK); i=0; } if (i == 0) { /* We have no client certificate to respond with * so send the correct error message back */ s->state=SSL2_ST_SEND_CLIENT_CERTIFICATE_B; p=buf; *(p++)=SSL2_MT_ERROR; s2n(SSL2_PE_NO_CERTIFICATE,p); s->init_off=0; s->init_num=3; /* Write is done at the end */ } } if (s->state == SSL2_ST_SEND_CLIENT_CERTIFICATE_B) { return(ssl2_do_write(s)); } if (s->state == SSL2_ST_SEND_CLIENT_CERTIFICATE_C) { EVP_MD_CTX ctx; /* ok, now we calculate the checksum * do it first so we can reuse buf :-) */ p=buf; EVP_MD_CTX_init(&ctx); EVP_SignInit_ex(&ctx,s->ctx->rsa_md5, NULL); EVP_SignUpdate(&ctx,s->s2->key_material, s->s2->key_material_length); EVP_SignUpdate(&ctx,cert_ch,(unsigned int)cert_ch_len); i=i2d_X509(s->session->sess_cert->peer_key->x509,&p); /* Don't update the signature if it fails - FIXME: probably should handle this better */ if(i > 0) EVP_SignUpdate(&ctx,buf,(unsigned int)i); p=buf; d=p+6; *(p++)=SSL2_MT_CLIENT_CERTIFICATE; *(p++)=SSL2_CT_X509_CERTIFICATE; n=i2d_X509(s->cert->key->x509,&d); s2n(n,p); if (!EVP_SignFinal(&ctx,d,&n,s->cert->key->privatekey)) { /* this is not good. If things have failed it * means there so something wrong with the key. * We will continue with a 0 length signature */ } EVP_MD_CTX_cleanup(&ctx); s2n(n,p); d+=n; s->state=SSL2_ST_SEND_CLIENT_CERTIFICATE_D; s->init_num=d-buf; s->init_off=0; } /* if (s->state == SSL2_ST_SEND_CLIENT_CERTIFICATE_D) */ return(ssl2_do_write(s)); }
int ssl3_prf(SSL *s, uint8_t *out, size_t out_len, const uint8_t *secret, size_t secret_len, const char *label, size_t label_len, const uint8_t *seed1, size_t seed1_len, const uint8_t *seed2, size_t seed2_len) { EVP_MD_CTX md5; EVP_MD_CTX sha1; uint8_t buf[16], smd[SHA_DIGEST_LENGTH]; uint8_t c = 'A'; size_t i, j, k; k = 0; EVP_MD_CTX_init(&md5); EVP_MD_CTX_init(&sha1); for (i = 0; i < out_len; i += MD5_DIGEST_LENGTH) { k++; if (k > sizeof(buf)) { /* bug: 'buf' is too small for this ciphersuite */ OPENSSL_PUT_ERROR(SSL, ssl3_prf, ERR_R_INTERNAL_ERROR); return 0; } for (j = 0; j < k; j++) { buf[j] = c; } c++; if (!EVP_DigestInit_ex(&sha1, EVP_sha1(), NULL)) { OPENSSL_PUT_ERROR(SSL, ssl3_prf, ERR_LIB_EVP); return 0; } EVP_DigestUpdate(&sha1, buf, k); EVP_DigestUpdate(&sha1, secret, secret_len); /* |label| is ignored for SSLv3. */ if (seed1_len) { EVP_DigestUpdate(&sha1, seed1, seed1_len); } if (seed2_len) { EVP_DigestUpdate(&sha1, seed2, seed2_len); } EVP_DigestFinal_ex(&sha1, smd, NULL); if (!EVP_DigestInit_ex(&md5, EVP_md5(), NULL)) { OPENSSL_PUT_ERROR(SSL, ssl3_prf, ERR_LIB_EVP); return 0; } EVP_DigestUpdate(&md5, secret, secret_len); EVP_DigestUpdate(&md5, smd, SHA_DIGEST_LENGTH); if (i + MD5_DIGEST_LENGTH > out_len) { EVP_DigestFinal_ex(&md5, smd, NULL); memcpy(out, smd, out_len - i); } else { EVP_DigestFinal_ex(&md5, out, NULL); } out += MD5_DIGEST_LENGTH; } OPENSSL_cleanse(smd, SHA_DIGEST_LENGTH); EVP_MD_CTX_cleanup(&md5); EVP_MD_CTX_cleanup(&sha1); return 1; }
void HMAC_CTX_cleanup(HMAC_CTX *ctx) { EVP_MD_CTX_cleanup(&ctx->i_ctx); EVP_MD_CTX_cleanup(&ctx->o_ctx); EVP_MD_CTX_cleanup(&ctx->md_ctx); OPENSSL_cleanse(ctx, sizeof(HMAC_CTX)); }
int PKCS12_key_gen_uni(unsigned char *pass, int passlen, unsigned char *salt, int saltlen, int id, int iter, int n, unsigned char *out, const EVP_MD *md_type) { unsigned char *B, *D, *I, *p, *Ai; int Slen, Plen, Ilen, Ijlen; int i, j, u, v; int ret = 0; BIGNUM *Ij, *Bpl1; /* These hold Ij and B + 1 */ EVP_MD_CTX ctx; #ifdef DEBUG_KEYGEN unsigned char *tmpout = out; int tmpn = n; #endif EVP_MD_CTX_init(&ctx); #ifdef DEBUG_KEYGEN fprintf(stderr, "KEYGEN DEBUG\n"); fprintf(stderr, "ID %d, ITER %d\n", id, iter); fprintf(stderr, "Password (length %d):\n", passlen); h__dump(pass, passlen); fprintf(stderr, "Salt (length %d):\n", saltlen); h__dump(salt, saltlen); #endif v = EVP_MD_block_size(md_type); u = EVP_MD_size(md_type); if (u < 0) return 0; D = OPENSSL_malloc(v); Ai = OPENSSL_malloc(u); B = OPENSSL_malloc(v + 1); Slen = v * ((saltlen + v - 1) / v); if (passlen) Plen = v * ((passlen + v - 1) / v); else Plen = 0; Ilen = Slen + Plen; I = OPENSSL_malloc(Ilen); Ij = BN_new(); Bpl1 = BN_new(); if (!D || !Ai || !B || !I || !Ij || !Bpl1) goto err; for (i = 0; i < v; i++) D[i] = id; p = I; for (i = 0; i < Slen; i++) *p++ = salt[i % saltlen]; for (i = 0; i < Plen; i++) *p++ = pass[i % passlen]; for (;;) { if (!EVP_DigestInit_ex(&ctx, md_type, NULL) || !EVP_DigestUpdate(&ctx, D, v) || !EVP_DigestUpdate(&ctx, I, Ilen) || !EVP_DigestFinal_ex(&ctx, Ai, NULL)) goto err; for (j = 1; j < iter; j++) { if (!EVP_DigestInit_ex(&ctx, md_type, NULL) || !EVP_DigestUpdate(&ctx, Ai, u) || !EVP_DigestFinal_ex(&ctx, Ai, NULL)) goto err; } memcpy(out, Ai, min(n, u)); if (u >= n) { #ifdef DEBUG_KEYGEN fprintf(stderr, "Output KEY (length %d)\n", tmpn); h__dump(tmpout, tmpn); #endif ret = 1; goto end; } n -= u; out += u; for (j = 0; j < v; j++) B[j] = Ai[j % u]; /* Work out B + 1 first then can use B as tmp space */ if (!BN_bin2bn(B, v, Bpl1)) goto err; if (!BN_add_word(Bpl1, 1)) goto err; for (j = 0; j < Ilen; j += v) { if (!BN_bin2bn(I + j, v, Ij)) goto err; if (!BN_add(Ij, Ij, Bpl1)) goto err; if (!BN_bn2bin(Ij, B)) goto err; Ijlen = BN_num_bytes(Ij); /* If more than 2^(v*8) - 1 cut off MSB */ if (Ijlen > v) { if (!BN_bn2bin(Ij, B)) goto err; memcpy(I + j, B + 1, v); #ifndef PKCS12_BROKEN_KEYGEN /* If less than v bytes pad with zeroes */ } else if (Ijlen < v) { memset(I + j, 0, v - Ijlen); if (!BN_bn2bin(Ij, I + j + v - Ijlen)) goto err; #endif } else if (!BN_bn2bin(Ij, I + j)) goto err; } } err: PKCS12err(PKCS12_F_PKCS12_KEY_GEN_UNI, ERR_R_MALLOC_FAILURE); end: OPENSSL_free(Ai); OPENSSL_free(B); OPENSSL_free(D); OPENSSL_free(I); BN_free(Ij); BN_free(Bpl1); EVP_MD_CTX_cleanup(&ctx); return ret; }
static int ssleay_rand_add(const void *buf, int num, double add) { int i,j,k,st_idx; long md_c[2]; unsigned char local_md[MD_DIGEST_LENGTH]; EVP_MD_CTX m; int do_not_lock; int rv = 0; /* * (Based on the rand(3) manpage) * * The input is chopped up into units of 20 bytes (or less for * the last block). Each of these blocks is run through the hash * function as follows: The data passed to the hash function * is the current 'md', the same number of bytes from the 'state' * (the location determined by in incremented looping index) as * the current 'block', the new key data 'block', and 'count' * (which is incremented after each use). * The result of this is kept in 'md' and also xored into the * 'state' at the same locations that were used as input into the * hash function. */ EVP_MD_CTX_init(&m); /* check if we already have the lock */ if (crypto_lock_rand) { CRYPTO_THREADID cur; CRYPTO_THREADID_current(&cur); CRYPTO_r_lock(CRYPTO_LOCK_RAND2); do_not_lock = !CRYPTO_THREADID_cmp(&locking_threadid, &cur); CRYPTO_r_unlock(CRYPTO_LOCK_RAND2); } else do_not_lock = 0; if (!do_not_lock) CRYPTO_w_lock(CRYPTO_LOCK_RAND); st_idx=state_index; /* use our own copies of the counters so that even * if a concurrent thread seeds with exactly the * same data and uses the same subarray there's _some_ * difference */ md_c[0] = md_count[0]; md_c[1] = md_count[1]; memcpy(local_md, md, sizeof md); /* state_index <= state_num <= STATE_SIZE */ state_index += num; if (state_index >= STATE_SIZE) { state_index%=STATE_SIZE; state_num=STATE_SIZE; } else if (state_num < STATE_SIZE) { if (state_index > state_num) state_num=state_index; } /* state_index <= state_num <= STATE_SIZE */ /* state[st_idx], ..., state[(st_idx + num - 1) % STATE_SIZE] * are what we will use now, but other threads may use them * as well */ md_count[1] += (num / MD_DIGEST_LENGTH) + (num % MD_DIGEST_LENGTH > 0); if (!do_not_lock) CRYPTO_w_unlock(CRYPTO_LOCK_RAND); for (i=0; i<num; i+=MD_DIGEST_LENGTH) { j=(num-i); j=(j > MD_DIGEST_LENGTH)?MD_DIGEST_LENGTH:j; if (!MD_Init(&m)) goto err; if (!MD_Update(&m,local_md,MD_DIGEST_LENGTH)) goto err; k=(st_idx+j)-STATE_SIZE; if (k > 0) { if (!MD_Update(&m,&(state[st_idx]),j-k)) goto err; if (!MD_Update(&m,&(state[0]),k)) goto err; } else if (!MD_Update(&m,&(state[st_idx]),j)) goto err; /* DO NOT REMOVE THE FOLLOWING CALL TO MD_Update()! */ if (!MD_Update(&m,buf,j)) goto err; /* We know that line may cause programs such as purify and valgrind to complain about use of uninitialized data. The problem is not, it's with the caller. Removing that line will make sure you get really bad randomness and thereby other problems such as very insecure keys. */ if (!MD_Update(&m,(unsigned char *)&(md_c[0]),sizeof(md_c))) goto err; if (!MD_Final(&m,local_md)) goto err; md_c[1]++; buf=(const char *)buf + j; for (k=0; k<j; k++) { /* Parallel threads may interfere with this, * but always each byte of the new state is * the XOR of some previous value of its * and local_md (itermediate values may be lost). * Alway using locking could hurt performance more * than necessary given that conflicts occur only * when the total seeding is longer than the random * state. */ state[st_idx++]^=local_md[k]; if (st_idx >= STATE_SIZE) st_idx=0; } } if (!do_not_lock) CRYPTO_w_lock(CRYPTO_LOCK_RAND); /* Don't just copy back local_md into md -- this could mean that * other thread's seeding remains without effect (except for * the incremented counter). By XORing it we keep at least as * much entropy as fits into md. */ for (k = 0; k < (int)sizeof(md); k++) { md[k] ^= local_md[k]; } if (entropy < ENTROPY_NEEDED) /* stop counting when we have enough */ entropy += add; if (!do_not_lock) CRYPTO_w_unlock(CRYPTO_LOCK_RAND); #if !defined(OPENSSL_THREADS) && !defined(OPENSSL_SYS_WIN32) assert(md_c[1] == md_count[1]); #endif rv = 1; err: EVP_MD_CTX_cleanup(&m); return rv; }
void ssl3_update_handshake_digests( DSSL_Session* sess, u_char* data, uint32_t len ) { DSSL_handshake_buffer *q = NULL, *next; /* sanity check in case client hello is not received */ if( sess->handshake_digest_md5.digest == NULL || sess->handshake_digest_sha.digest == NULL) { ssl3_init_handshake_digests( sess ); } EVP_DigestUpdate( &sess->handshake_digest_md5, data, len ); EVP_DigestUpdate( &sess->handshake_digest_sha, data, len ); if ( sess->version >= TLS1_2_VERSION ) { /* if digest is still unknown, then queue the packets. * we'll calculate the handshake hash once we determine which digest we should use. */ EVP_MD* digest = NULL; DSSL_CipherSuite* suite = sess->dssl_cipher_suite; if ( !suite ) suite = DSSL_GetSSL3CipherSuite( sess->cipher_suite ); digest = EVP_get_digestbyname( suite->digest ); /* 'sha256' is the default for TLS 1.2, and can be replaced with a different (but stronger) hash */ if ( !digest ) { q = (DSSL_handshake_buffer*) malloc( sizeof(DSSL_handshake_buffer) ); q->next = NULL; q->data = (u_char*) malloc( len ); memcpy(q->data, data, len); q->len = len; if (NULL == sess->handshake_queue) sess->handshake_queue = q; else sess->handshake_queue->next = q; DEBUG_TRACE3( "Queue handshake packet %p (%u @ %p)", q, q->len, q->data ); } else if ( digest != sess->handshake_digest.digest && EVP_MD_size( digest ) >= EVP_MD_size( sess->handshake_digest.digest ) ) { /* specified digest is different than the default. * re-init and re-hash all queued packets. */ EVP_MD_CTX_cleanup( &sess->handshake_digest ); EVP_DigestInit_ex( &sess->handshake_digest, digest, NULL ); for (q = sess->handshake_queue; q != NULL; q = next) { DEBUG_TRACE3( "Re-hash handshake packet %p (%u @ %p)", q, q->len, q->data ); EVP_DigestUpdate( &sess->handshake_digest, q->data, q->len ); next = q->next; free ( q->data ); free ( q ); } sess->handshake_queue = NULL; } else { /* specified digest is identical to the default. * throw away all the queued packets. */ for (q = sess->handshake_queue; q != NULL; q = next) { DEBUG_TRACE3( "discard handshake packet %p (%u @ %p)", q, q->len, q->data ); next = q->next; free ( q->data ); free ( q ); } sess->handshake_queue = NULL; } if ( sess->handshake_digest.digest ) EVP_DigestUpdate( &sess->handshake_digest, data, len ); } }
static int ssleay_rand_bytes(unsigned char *buf, int num, int pseudo) { static volatile int stirred_pool = 0; int i,j,k,st_num,st_idx; int num_ceil; int ok; long md_c[2]; unsigned char local_md[MD_DIGEST_LENGTH]; EVP_MD_CTX m; #ifndef GETPID_IS_MEANINGLESS pid_t curr_pid = getpid(); #endif time_t curr_time = time(NULL); int do_stir_pool = 0; /* time value for various platforms */ #ifdef OPENSSL_SYS_WIN32 FILETIME tv; # ifdef _WIN32_WCE SYSTEMTIME t; GetSystemTime(&t); SystemTimeToFileTime(&t, &tv); # else GetSystemTimeAsFileTime(&tv); # endif #elif defined(OPENSSL_SYS_VXWORKS) struct timespec tv; clock_gettime(CLOCK_REALTIME, &ts); #elif defined(OPENSSL_SYSNAME_DSPBIOS) unsigned long long tv, OPENSSL_rdtsc(); tv = OPENSSL_rdtsc(); #else struct timeval tv; gettimeofday(&tv, NULL); #endif #ifdef PREDICT if (rand_predictable) { static unsigned char val=0; for (i=0; i<num; i++) buf[i]=val++; return(1); } #endif if (num <= 0) return 1; EVP_MD_CTX_init(&m); /* round upwards to multiple of MD_DIGEST_LENGTH/2 */ num_ceil = (1 + (num-1)/(MD_DIGEST_LENGTH/2)) * (MD_DIGEST_LENGTH/2); /* * (Based on the rand(3) manpage:) * * For each group of 10 bytes (or less), we do the following: * * Input into the hash function the local 'md' (which is initialized from * the global 'md' before any bytes are generated), the bytes that are to * be overwritten by the random bytes, and bytes from the 'state' * (incrementing looping index). From this digest output (which is kept * in 'md'), the top (up to) 10 bytes are returned to the caller and the * bottom 10 bytes are xored into the 'state'. * * Finally, after we have finished 'num' random bytes for the * caller, 'count' (which is incremented) and the local and global 'md' * are fed into the hash function and the results are kept in the * global 'md'. */ CRYPTO_w_lock(CRYPTO_LOCK_RAND); /* prevent ssleay_rand_bytes() from trying to obtain the lock again */ CRYPTO_w_lock(CRYPTO_LOCK_RAND2); CRYPTO_THREADID_current(&locking_threadid); CRYPTO_w_unlock(CRYPTO_LOCK_RAND2); crypto_lock_rand = 1; if (!initialized) { RAND_poll(); initialized = 1; } if (!stirred_pool) do_stir_pool = 1; ok = (entropy >= ENTROPY_NEEDED); if (!ok) { /* If the PRNG state is not yet unpredictable, then seeing * the PRNG output may help attackers to determine the new * state; thus we have to decrease the entropy estimate. * Once we've had enough initial seeding we don't bother to * adjust the entropy count, though, because we're not ambitious * to provide *information-theoretic* randomness. * * NOTE: This approach fails if the program forks before * we have enough entropy. Entropy should be collected * in a separate input pool and be transferred to the * output pool only when the entropy limit has been reached. */ entropy -= num; if (entropy < 0) entropy = 0; } if (do_stir_pool) { /* In the output function only half of 'md' remains secret, * so we better make sure that the required entropy gets * 'evenly distributed' through 'state', our randomness pool. * The input function (ssleay_rand_add) chains all of 'md', * which makes it more suitable for this purpose. */ int n = STATE_SIZE; /* so that the complete pool gets accessed */ while (n > 0) { #if MD_DIGEST_LENGTH > 20 # error "Please adjust DUMMY_SEED." #endif #define DUMMY_SEED "...................." /* at least MD_DIGEST_LENGTH */ /* Note that the seed does not matter, it's just that * ssleay_rand_add expects to have something to hash. */ ssleay_rand_add(DUMMY_SEED, MD_DIGEST_LENGTH, 0.0); n -= MD_DIGEST_LENGTH; } if (ok) stirred_pool = 1; } st_idx=state_index; st_num=state_num; md_c[0] = md_count[0]; md_c[1] = md_count[1]; memcpy(local_md, md, sizeof md); state_index+=num_ceil; if (state_index > state_num) state_index %= state_num; /* state[st_idx], ..., state[(st_idx + num_ceil - 1) % st_num] * are now ours (but other threads may use them too) */ md_count[0] += 1; /* before unlocking, we must clear 'crypto_lock_rand' */ crypto_lock_rand = 0; CRYPTO_w_unlock(CRYPTO_LOCK_RAND); while (num > 0) { /* num_ceil -= MD_DIGEST_LENGTH/2 */ j=(num >= MD_DIGEST_LENGTH/2)?MD_DIGEST_LENGTH/2:num; num-=j; if (!MD_Init(&m)) goto err; #ifndef GETPID_IS_MEANINGLESS if (curr_pid) /* just in the first iteration to save time */ { if (!MD_Update(&m,(unsigned char*)&curr_pid, sizeof curr_pid)) goto err; curr_pid = 0; } #endif if (curr_time) /* just in the first iteration to save time */ { if (!MD_Update(&m,(unsigned char*)&curr_time, sizeof curr_time)) goto err; if (!MD_Update(&m,(unsigned char*)&tv, sizeof tv)) goto err; curr_time = 0; rand_hw_seed(&m); } if (!MD_Update(&m,local_md,MD_DIGEST_LENGTH)) goto err; if (!MD_Update(&m,(unsigned char *)&(md_c[0]),sizeof(md_c))) goto err; #ifndef PURIFY /* purify complains */ /* The following line uses the supplied buffer as a small * source of entropy: since this buffer is often uninitialised * it may cause programs such as purify or valgrind to * complain. So for those builds it is not used: the removal * of such a small source of entropy has negligible impact on * security. */ if (!MD_Update(&m,buf,j)) goto err; #endif k=(st_idx+MD_DIGEST_LENGTH/2)-st_num; if (k > 0) { if (!MD_Update(&m,&(state[st_idx]),MD_DIGEST_LENGTH/2-k)) goto err; if (!MD_Update(&m,&(state[0]),k)) goto err; } else if (!MD_Update(&m,&(state[st_idx]),MD_DIGEST_LENGTH/2)) goto err; if (!MD_Final(&m,local_md)) goto err; for (i=0; i<MD_DIGEST_LENGTH/2; i++) { state[st_idx++]^=local_md[i]; /* may compete with other threads */ if (st_idx >= st_num) st_idx=0; if (i < j) *(buf++)=local_md[i+MD_DIGEST_LENGTH/2]; } } if (!MD_Init(&m) || !MD_Update(&m,(unsigned char *)&(md_c[0]),sizeof(md_c)) || !MD_Update(&m,local_md,MD_DIGEST_LENGTH)) goto err; CRYPTO_w_lock(CRYPTO_LOCK_RAND); if (!MD_Update(&m,md,MD_DIGEST_LENGTH) || !MD_Final(&m,md)) { CRYPTO_w_unlock(CRYPTO_LOCK_RAND); goto err; } CRYPTO_w_unlock(CRYPTO_LOCK_RAND); EVP_MD_CTX_cleanup(&m); if (ok) return(1); else if (pseudo) return 0; else { RANDerr(RAND_F_SSLEAY_RAND_BYTES,RAND_R_PRNG_NOT_SEEDED); ERR_add_error_data(1, "You need to read the OpenSSL FAQ, " "http://www.openssl.org/support/faq.html"); return(0); } err: EVP_MD_CTX_cleanup(&m); RANDerr(RAND_F_SSLEAY_RAND_BYTES,ERR_R_EVP_LIB); return 0; }
int PKCS5_PBE_keyivgen(EVP_CIPHER_CTX *cctx, const char *pass, int passlen, ASN1_TYPE *param, const EVP_CIPHER *cipher, const EVP_MD *md, int en_de) { EVP_MD_CTX ctx; unsigned char md_tmp[EVP_MAX_MD_SIZE]; unsigned char key[EVP_MAX_KEY_LENGTH], iv[EVP_MAX_IV_LENGTH]; int i; PBEPARAM *pbe; int saltlen, iter; unsigned char *salt; const unsigned char *pbuf; int mdsize; /* Extract useful info from parameter */ if (param == NULL || param->type != V_ASN1_SEQUENCE || param->value.sequence == NULL) { EVPerr(EVP_F_PKCS5_PBE_KEYIVGEN,EVP_R_DECODE_ERROR); return 0; } pbuf = param->value.sequence->data; if (!(pbe = d2i_PBEPARAM(NULL, &pbuf, param->value.sequence->length))) { EVPerr(EVP_F_PKCS5_PBE_KEYIVGEN,EVP_R_DECODE_ERROR); return 0; } if (!pbe->iter) iter = 1; else iter = ASN1_INTEGER_get (pbe->iter); salt = pbe->salt->data; saltlen = pbe->salt->length; if(!pass) passlen = 0; else if(passlen == -1) passlen = strlen(pass); EVP_MD_CTX_init(&ctx); EVP_DigestInit_ex(&ctx, md, NULL); EVP_DigestUpdate(&ctx, pass, passlen); EVP_DigestUpdate(&ctx, salt, saltlen); PBEPARAM_free(pbe); EVP_DigestFinal_ex(&ctx, md_tmp, NULL); mdsize = EVP_MD_size(md); if (mdsize < 0) return 0; for (i = 1; i < iter; i++) { EVP_DigestInit_ex(&ctx, md, NULL); EVP_DigestUpdate(&ctx, md_tmp, mdsize); EVP_DigestFinal_ex (&ctx, md_tmp, NULL); } EVP_MD_CTX_cleanup(&ctx); OPENSSL_assert(EVP_CIPHER_key_length(cipher) <= (int)sizeof(md_tmp)); memcpy(key, md_tmp, EVP_CIPHER_key_length(cipher)); OPENSSL_assert(EVP_CIPHER_iv_length(cipher) <= 16); memcpy(iv, md_tmp + (16 - EVP_CIPHER_iv_length(cipher)), EVP_CIPHER_iv_length(cipher)); EVP_CipherInit_ex(cctx, cipher, NULL, key, iv, en_de); OPENSSL_cleanse(md_tmp, EVP_MAX_MD_SIZE); OPENSSL_cleanse(key, EVP_MAX_KEY_LENGTH); OPENSSL_cleanse(iv, EVP_MAX_IV_LENGTH); return 1; }
int EVP_tls_cbc_digest_record(const EVP_MD *md, uint8_t *md_out, size_t *md_out_size, const uint8_t header[13], const uint8_t *data, size_t data_plus_mac_size, size_t data_plus_mac_plus_padding_size, const uint8_t *mac_secret, unsigned mac_secret_length) { HASH_CTX md_state; void (*md_final_raw)(HASH_CTX *ctx, uint8_t *md_out); void (*md_transform)(HASH_CTX *ctx, const uint8_t *block); unsigned md_size, md_block_size = 64, md_block_shift = 6; // md_length_size is the number of bytes in the length field that terminates // the hash. unsigned md_length_size = 8; // Bound the acceptable input so we can forget about many possible overflows // later in this function. This is redundant with the record size limits in // TLS. if (data_plus_mac_plus_padding_size >= 1024 * 1024) { assert(0); return 0; } switch (EVP_MD_type(md)) { case NID_sha1: SHA1_Init(&md_state.sha1); md_final_raw = tls1_sha1_final_raw; md_transform = tls1_sha1_transform; md_size = SHA_DIGEST_LENGTH; break; case NID_sha256: SHA256_Init(&md_state.sha256); md_final_raw = tls1_sha256_final_raw; md_transform = tls1_sha256_transform; md_size = SHA256_DIGEST_LENGTH; break; case NID_sha384: SHA384_Init(&md_state.sha512); md_final_raw = tls1_sha512_final_raw; md_transform = tls1_sha512_transform; md_size = SHA384_DIGEST_LENGTH; md_block_size = 128; md_block_shift = 7; md_length_size = 16; break; default: // EVP_tls_cbc_record_digest_supported should have been called first to // check that the hash function is supported. assert(0); *md_out_size = 0; return 0; } assert(md_length_size <= MAX_HASH_BIT_COUNT_BYTES); assert(md_block_size <= MAX_HASH_BLOCK_SIZE); assert(md_block_size == (1u << md_block_shift)); assert(md_size <= EVP_MAX_MD_SIZE); static const size_t kHeaderLength = 13; // kVarianceBlocks is the number of blocks of the hash that we have to // calculate in constant time because they could be altered by the // padding value. // // TLSv1 has MACs up to 48 bytes long (SHA-384) and the padding is not // required to be minimal. Therefore we say that the final |kVarianceBlocks| // blocks can vary based on the padding and on the hash used. This value // must be derived from public information. const size_t kVarianceBlocks = ( 255 + 1 + // maximum padding bytes + padding length md_size + // length of hash's output md_block_size - 1 // ceiling ) / md_block_size + 1; // the 0x80 marker and the encoded message length could or not // require an extra block; since the exact value depends on the // message length; thus, one extra block is always added to run // in constant time. // From now on we're dealing with the MAC, which conceptually has 13 // bytes of `header' before the start of the data. size_t len = data_plus_mac_plus_padding_size + kHeaderLength; // max_mac_bytes contains the maximum bytes of bytes in the MAC, including // |header|, assuming that there's no padding. size_t max_mac_bytes = len - md_size - 1; // num_blocks is the maximum number of hash blocks. size_t num_blocks = (max_mac_bytes + 1 + md_length_size + md_block_size - 1) / md_block_size; // In order to calculate the MAC in constant time we have to handle // the final blocks specially because the padding value could cause the // end to appear somewhere in the final |kVarianceBlocks| blocks and we // can't leak where. However, |num_starting_blocks| worth of data can // be hashed right away because no padding value can affect whether // they are plaintext. size_t num_starting_blocks = 0; // k is the starting byte offset into the conceptual header||data where // we start processing. size_t k = 0; // mac_end_offset is the index just past the end of the data to be MACed. size_t mac_end_offset = data_plus_mac_size + kHeaderLength - md_size; // c is the index of the 0x80 byte in the final hash block that contains // application data. size_t c = mac_end_offset & (md_block_size - 1); // index_a is the hash block number that contains the 0x80 terminating value. size_t index_a = mac_end_offset >> md_block_shift; // index_b is the hash block number that contains the 64-bit hash length, in // bits. size_t index_b = (mac_end_offset + md_length_size) >> md_block_shift; if (num_blocks > kVarianceBlocks) { num_starting_blocks = num_blocks - kVarianceBlocks; k = md_block_size * num_starting_blocks; } // bits is the hash-length in bits. It includes the additional hash // block for the masked HMAC key. size_t bits = 8 * mac_end_offset; // at most 18 bits to represent // Compute the initial HMAC block. bits += 8 * md_block_size; // hmac_pad is the masked HMAC key. uint8_t hmac_pad[MAX_HASH_BLOCK_SIZE]; OPENSSL_memset(hmac_pad, 0, md_block_size); assert(mac_secret_length <= sizeof(hmac_pad)); OPENSSL_memcpy(hmac_pad, mac_secret, mac_secret_length); for (size_t i = 0; i < md_block_size; i++) { hmac_pad[i] ^= 0x36; } md_transform(&md_state, hmac_pad); // The length check means |bits| fits in four bytes. uint8_t length_bytes[MAX_HASH_BIT_COUNT_BYTES]; OPENSSL_memset(length_bytes, 0, md_length_size - 4); length_bytes[md_length_size - 4] = (uint8_t)(bits >> 24); length_bytes[md_length_size - 3] = (uint8_t)(bits >> 16); length_bytes[md_length_size - 2] = (uint8_t)(bits >> 8); length_bytes[md_length_size - 1] = (uint8_t)bits; if (k > 0) { // k is a multiple of md_block_size. uint8_t first_block[MAX_HASH_BLOCK_SIZE]; OPENSSL_memcpy(first_block, header, 13); OPENSSL_memcpy(first_block + 13, data, md_block_size - 13); md_transform(&md_state, first_block); for (size_t i = 1; i < k / md_block_size; i++) { md_transform(&md_state, data + md_block_size * i - 13); } } uint8_t mac_out[EVP_MAX_MD_SIZE]; OPENSSL_memset(mac_out, 0, sizeof(mac_out)); // We now process the final hash blocks. For each block, we construct // it in constant time. If the |i==index_a| then we'll include the 0x80 // bytes and zero pad etc. For each block we selectively copy it, in // constant time, to |mac_out|. for (size_t i = num_starting_blocks; i <= num_starting_blocks + kVarianceBlocks; i++) { uint8_t block[MAX_HASH_BLOCK_SIZE]; uint8_t is_block_a = constant_time_eq_8(i, index_a); uint8_t is_block_b = constant_time_eq_8(i, index_b); for (size_t j = 0; j < md_block_size; j++) { uint8_t b = 0; if (k < kHeaderLength) { b = header[k]; } else if (k < data_plus_mac_plus_padding_size + kHeaderLength) { b = data[k - kHeaderLength]; } k++; uint8_t is_past_c = is_block_a & constant_time_ge_8(j, c); uint8_t is_past_cp1 = is_block_a & constant_time_ge_8(j, c + 1); // If this is the block containing the end of the // application data, and we are at the offset for the // 0x80 value, then overwrite b with 0x80. b = constant_time_select_8(is_past_c, 0x80, b); // If this the the block containing the end of the // application data and we're past the 0x80 value then // just write zero. b = b & ~is_past_cp1; // If this is index_b (the final block), but not // index_a (the end of the data), then the 64-bit // length didn't fit into index_a and we're having to // add an extra block of zeros. b &= ~is_block_b | is_block_a; // The final bytes of one of the blocks contains the // length. if (j >= md_block_size - md_length_size) { // If this is index_b, write a length byte. b = constant_time_select_8( is_block_b, length_bytes[j - (md_block_size - md_length_size)], b); } block[j] = b; } md_transform(&md_state, block); md_final_raw(&md_state, block); // If this is index_b, copy the hash value to |mac_out|. for (size_t j = 0; j < md_size; j++) { mac_out[j] |= block[j] & is_block_b; } } EVP_MD_CTX md_ctx; EVP_MD_CTX_init(&md_ctx); if (!EVP_DigestInit_ex(&md_ctx, md, NULL /* engine */)) { EVP_MD_CTX_cleanup(&md_ctx); return 0; } // Complete the HMAC in the standard manner. for (size_t i = 0; i < md_block_size; i++) { hmac_pad[i] ^= 0x6a; } EVP_DigestUpdate(&md_ctx, hmac_pad, md_block_size); EVP_DigestUpdate(&md_ctx, mac_out, md_size); unsigned md_out_size_u; EVP_DigestFinal(&md_ctx, md_out, &md_out_size_u); *md_out_size = md_out_size_u; EVP_MD_CTX_cleanup(&md_ctx); return 1; }
int RSA_verify_PKCS1_PSS(RSA *rsa, const unsigned char *mHash, const EVP_MD *Hash, const unsigned char *EM, int sLen) { int i; int ret = 0; int hLen, maskedDBLen, MSBits, emLen; const unsigned char *H; unsigned char *DB = NULL; EVP_MD_CTX ctx; unsigned char H_[EVP_MAX_MD_SIZE]; hLen = EVP_MD_size(Hash); if (hLen < 0) goto err; /* * Negative sLen has special meanings: * -1 sLen == hLen * -2 salt length is autorecovered from signature * -N reserved */ if (sLen == -1) sLen = hLen; else if (sLen == -2) sLen = -2; else if (sLen < -2) { RSAerr(RSA_F_RSA_VERIFY_PKCS1_PSS, RSA_R_SLEN_CHECK_FAILED); goto err; } MSBits = (BN_num_bits(rsa->n) - 1) & 0x7; emLen = RSA_size(rsa); if (EM[0] & (0xFF << MSBits)) { RSAerr(RSA_F_RSA_VERIFY_PKCS1_PSS, RSA_R_FIRST_OCTET_INVALID); goto err; } if (MSBits == 0) { EM++; emLen--; } if (emLen < (hLen + sLen + 2)) /* sLen can be small negative */ { RSAerr(RSA_F_RSA_VERIFY_PKCS1_PSS, RSA_R_DATA_TOO_LARGE); goto err; } if (EM[emLen - 1] != 0xbc) { RSAerr(RSA_F_RSA_VERIFY_PKCS1_PSS, RSA_R_LAST_OCTET_INVALID); goto err; } maskedDBLen = emLen - hLen - 1; H = EM + maskedDBLen; DB = (unsigned char*)OPENSSL_malloc(maskedDBLen); if (!DB) { RSAerr(RSA_F_RSA_VERIFY_PKCS1_PSS, ERR_R_MALLOC_FAILURE); goto err; } if (PKCS1_MGF1(DB, maskedDBLen, H, hLen, Hash) < 0) goto err; for (i = 0; i < maskedDBLen; i++) DB[i] ^= EM[i]; if (MSBits) DB[0] &= 0xFF >> (8 - MSBits); for (i = 0; DB[i] == 0 && i < (maskedDBLen-1); i++) ; if (DB[i++] != 0x1) { RSAerr(RSA_F_RSA_VERIFY_PKCS1_PSS, RSA_R_SLEN_RECOVERY_FAILED); goto err; } if (sLen >= 0 && (maskedDBLen - i) != sLen) { RSAerr(RSA_F_RSA_VERIFY_PKCS1_PSS, RSA_R_SLEN_CHECK_FAILED); goto err; } EVP_MD_CTX_init(&ctx); EVP_DigestInit_ex(&ctx, Hash, NULL); EVP_DigestUpdate(&ctx, zeroes, sizeof zeroes); EVP_DigestUpdate(&ctx, mHash, hLen); if (maskedDBLen - i) EVP_DigestUpdate(&ctx, DB + i, maskedDBLen - i); EVP_DigestFinal(&ctx, H_, NULL); EVP_MD_CTX_cleanup(&ctx); if (TINYCLR_SSL_MEMCMP(H_, H, hLen)) { RSAerr(RSA_F_RSA_VERIFY_PKCS1_PSS, RSA_R_BAD_SIGNATURE); ret = 0; } else ret = 1; err: if (DB) OPENSSL_free(DB); return ret; }
int ASN1_item_verify(const ASN1_ITEM *it, X509_ALGOR *a, ASN1_BIT_STRING *signature, void *asn, EVP_PKEY *pkey) { EVP_MD_CTX ctx; unsigned char *buf_in = NULL; int ret = -1, inl; int mdnid, pknid; if (!pkey) { ASN1err(ASN1_F_ASN1_ITEM_VERIFY, ERR_R_PASSED_NULL_PARAMETER); return -1; } EVP_MD_CTX_init(&ctx); /* Convert signature OID into digest and public key OIDs */ if (!OBJ_find_sigid_algs(OBJ_obj2nid(a->algorithm), &mdnid, &pknid)) { ASN1err(ASN1_F_ASN1_ITEM_VERIFY, ASN1_R_UNKNOWN_SIGNATURE_ALGORITHM); goto err; } if (mdnid == NID_undef) { if (!pkey->ameth || !pkey->ameth->item_verify) { ASN1err(ASN1_F_ASN1_ITEM_VERIFY, ASN1_R_UNKNOWN_SIGNATURE_ALGORITHM); goto err; } ret = pkey->ameth->item_verify(&ctx, it, asn, a, signature, pkey); /* Return value of 2 means carry on, anything else means we * exit straight away: either a fatal error of the underlying * verification routine handles all verification. */ if (ret != 2) goto err; ret = -1; } else { const EVP_MD *type; type = EVP_get_digestbynid(mdnid); if (type == NULL) { ASN1err(ASN1_F_ASN1_ITEM_VERIFY, ASN1_R_UNKNOWN_MESSAGE_DIGEST_ALGORITHM); goto err; } /* Check public key OID matches public key type */ if (EVP_PKEY_type(pknid) != pkey->ameth->pkey_id) { ASN1err(ASN1_F_ASN1_ITEM_VERIFY, ASN1_R_WRONG_PUBLIC_KEY_TYPE); goto err; } if (!EVP_DigestVerifyInit(&ctx, NULL, type, NULL, pkey)) { ASN1err(ASN1_F_ASN1_ITEM_VERIFY, ERR_R_EVP_LIB); ret = 0; goto err; } } inl = ASN1_item_i2d(asn, &buf_in, it); if (buf_in == NULL) { ASN1err(ASN1_F_ASN1_ITEM_VERIFY, ERR_R_MALLOC_FAILURE); goto err; } if (!EVP_DigestVerifyUpdate(&ctx, buf_in, inl)) { ASN1err(ASN1_F_ASN1_ITEM_VERIFY, ERR_R_EVP_LIB); ret = 0; goto err; } OPENSSL_cleanse(buf_in, (unsigned int)inl); free(buf_in); if (EVP_DigestVerifyFinal(&ctx, signature->data, (size_t)signature->length) <= 0) { ASN1err(ASN1_F_ASN1_ITEM_VERIFY, ERR_R_EVP_LIB); ret = 0; goto err; } /* we don't need to zero the 'ctx' because we just checked * public information */ /* memset(&ctx,0,sizeof(ctx)); */ ret = 1; err: EVP_MD_CTX_cleanup(&ctx); return (ret); }