hmac_init cleanup and fix key zeroization issue
Reviewed-by: Matthias St. Pierre <Matthias.St.Pierre@ncp-e.com>
Reviewed-by: Paul Dale <paul.dale@oracle.com>
(Merged from https://github.com/openssl/openssl/pull/7092)
Shane Lontis authored 5 years ago
Pauli committed 5 years ago
0 | 0 | /* |
1 | * Copyright 1995-2016 The OpenSSL Project Authors. All Rights Reserved. | |
1 | * Copyright 1995-2018 The OpenSSL Project Authors. All Rights Reserved. | |
2 | 2 | * |
3 | 3 | * Licensed under the OpenSSL license (the "License"). You may not use |
4 | 4 | * this file except in compliance with the License. You can obtain a copy |
17 | 17 | int HMAC_Init_ex(HMAC_CTX *ctx, const void *key, int len, |
18 | 18 | const EVP_MD *md, ENGINE *impl) |
19 | 19 | { |
20 | int rv = 0; | |
20 | 21 | int i, j, reset = 0; |
21 | 22 | unsigned char pad[HMAC_MAX_MD_CBLOCK]; |
22 | 23 | |
37 | 38 | reset = 1; |
38 | 39 | j = EVP_MD_block_size(md); |
39 | 40 | if (!ossl_assert(j <= (int)sizeof(ctx->key))) |
40 | goto err; | |
41 | return 0; | |
41 | 42 | if (j < len) { |
42 | if (!EVP_DigestInit_ex(ctx->md_ctx, md, impl)) | |
43 | goto err; | |
44 | if (!EVP_DigestUpdate(ctx->md_ctx, key, len)) | |
45 | goto err; | |
46 | if (!EVP_DigestFinal_ex(ctx->md_ctx, ctx->key, | |
47 | &ctx->key_length)) | |
48 | goto err; | |
43 | if (!EVP_DigestInit_ex(ctx->md_ctx, md, impl) | |
44 | || !EVP_DigestUpdate(ctx->md_ctx, key, len) | |
45 | || !EVP_DigestFinal_ex(ctx->md_ctx, ctx->key, | |
46 | &ctx->key_length)) | |
47 | return 0; | |
49 | 48 | } else { |
50 | 49 | if (len < 0 || len > (int)sizeof(ctx->key)) |
51 | 50 | return 0; |
60 | 59 | if (reset) { |
61 | 60 | for (i = 0; i < HMAC_MAX_MD_CBLOCK; i++) |
62 | 61 | pad[i] = 0x36 ^ ctx->key[i]; |
63 | if (!EVP_DigestInit_ex(ctx->i_ctx, md, impl)) | |
64 | goto err; | |
65 | if (!EVP_DigestUpdate(ctx->i_ctx, pad, EVP_MD_block_size(md))) | |
62 | if (!EVP_DigestInit_ex(ctx->i_ctx, md, impl) | |
63 | || !EVP_DigestUpdate(ctx->i_ctx, pad, EVP_MD_block_size(md))) | |
66 | 64 | goto err; |
67 | 65 | |
68 | 66 | for (i = 0; i < HMAC_MAX_MD_CBLOCK; i++) |
69 | 67 | pad[i] = 0x5c ^ ctx->key[i]; |
70 | if (!EVP_DigestInit_ex(ctx->o_ctx, md, impl)) | |
68 | if (!EVP_DigestInit_ex(ctx->o_ctx, md, impl) | |
69 | || !EVP_DigestUpdate(ctx->o_ctx, pad, EVP_MD_block_size(md))) | |
71 | 70 | goto err; |
72 | if (!EVP_DigestUpdate(ctx->o_ctx, pad, EVP_MD_block_size(md))) | |
73 | goto err; | |
74 | 71 | } |
75 | 72 | if (!EVP_MD_CTX_copy_ex(ctx->md_ctx, ctx->i_ctx)) |
76 | 73 | goto err; |
77 | return 1; | |
78 | err: | |
79 | return 0; | |
74 | rv = 1; | |
75 | err: | |
76 | if (reset) | |
77 | OPENSSL_cleanse(pad, sizeof(pad)); | |
78 | return rv; | |
80 | 79 | } |
81 | 80 | |
82 | 81 | #if OPENSSL_API_COMPAT < 0x10100000L |