From 7f6ea1b97a307b0f844ac4f7d4ad68de1784b5b2 Mon Sep 17 00:00:00 2001 From: Songling Han Date: Sun, 22 Sep 2024 08:12:32 +0000 Subject: [PATCH] Fix potential memory leak for do_hash Signed-off-by: Songling Han --- src/common/sha2/sha2_ossl.c | 20 +++++++++++++++----- 1 file changed, 15 insertions(+), 5 deletions(-) diff --git a/src/common/sha2/sha2_ossl.c b/src/common/sha2/sha2_ossl.c index 234d4b1e3..723b2d234 100644 --- a/src/common/sha2/sha2_ossl.c +++ b/src/common/sha2/sha2_ossl.c @@ -14,13 +14,23 @@ #include "../ossl_helpers.h" static void do_hash(uint8_t *output, const uint8_t *input, size_t inplen, const EVP_MD *md) { - EVP_MD_CTX *mdctx; + EVP_MD_CTX *mdctx = NULL; unsigned int outlen; + mdctx = OSSL_FUNC(EVP_MD_CTX_new)(); - OQS_EXIT_IF_NULLPTR(mdctx, "OpenSSL"); - OQS_OPENSSL_GUARD(OSSL_FUNC(EVP_DigestInit_ex)(mdctx, md, NULL)); - OQS_OPENSSL_GUARD(OSSL_FUNC(EVP_DigestUpdate)(mdctx, input, inplen)); - OQS_OPENSSL_GUARD(OSSL_FUNC(EVP_DigestFinal_ex)(mdctx, output, &outlen)); + if (mdctx == NULL) { + OQS_EXIT_IF_NULLPTR(mdctx, "OpenSSL"); + return; + } + + if (OSSL_FUNC(EVP_DigestInit_ex)(mdctx, md, NULL) != 1 || + OSSL_FUNC(EVP_DigestUpdate)(mdctx, input, inplen) != 1 || + OSSL_FUNC(EVP_DigestFinal_ex)(mdctx, output, &outlen) != 1) { + OSSL_FUNC(EVP_MD_CTX_free)(mdctx); + OQS_EXIT_IF_NULLPTR(NULL, "OpenSSL digest operation failed"); + return; + } + OSSL_FUNC(EVP_MD_CTX_free)(mdctx); }