From 52a2b3d82f37c87b5b2cff68abbc93861978a853 Mon Sep 17 00:00:00 2001 From: Tomas Mraz Date: Thu, 22 May 2025 16:22:13 +0200 Subject: [PATCH] Avoid leaking duplicated EVP_PKEY_CTX in case of error Fixes Coverity 1647946 1647947 Reviewed-by: Neil Horman Reviewed-by: Tim Hudson (Merged from https://github.com/openssl/openssl/pull/27686) (cherry picked from commit 240228979b92b5f45d5c0a42997d86755c850001) --- crypto/evp/m_sigver.c | 29 ++++++++++++++++------------- 1 file changed, 16 insertions(+), 13 deletions(-) diff --git a/crypto/evp/m_sigver.c b/crypto/evp/m_sigver.c index 9ce7a02becf..d5df497da77 100644 --- a/crypto/evp/m_sigver.c +++ b/crypto/evp/m_sigver.c @@ -508,12 +508,6 @@ int EVP_DigestSignFinal(EVP_MD_CTX *ctx, unsigned char *sigret, || pctx->op.sig.signature == NULL) goto legacy; - if (sigret != NULL && (ctx->flags & EVP_MD_CTX_FLAG_FINALISE) == 0) { - /* try dup */ - dctx = EVP_PKEY_CTX_dup(pctx); - if (dctx != NULL) - pctx = dctx; - } signature = pctx->op.sig.signature; desc = signature->description != NULL ? signature->description : ""; if (signature->digest_sign_final == NULL) { @@ -521,6 +515,14 @@ int EVP_DigestSignFinal(EVP_MD_CTX *ctx, unsigned char *sigret, "%s digest_sign_final:%s", signature->type_name, desc); return 0; } + + if (sigret != NULL && (ctx->flags & EVP_MD_CTX_FLAG_FINALISE) == 0) { + /* try dup */ + dctx = EVP_PKEY_CTX_dup(pctx); + if (dctx != NULL) + pctx = dctx; + } + r = signature->digest_sign_final(pctx->op.sig.algctx, sigret, siglen, sigret == NULL ? 0 : *siglen); if (!r) @@ -672,13 +674,6 @@ int EVP_DigestVerifyFinal(EVP_MD_CTX *ctx, const unsigned char *sig, || pctx->op.sig.signature == NULL) goto legacy; - if ((ctx->flags & EVP_MD_CTX_FLAG_FINALISE) == 0) { - /* try dup */ - dctx = EVP_PKEY_CTX_dup(pctx); - if (dctx != NULL) - pctx = dctx; - } - signature = pctx->op.sig.signature; desc = signature->description != NULL ? signature->description : ""; if (signature->digest_verify_final == NULL) { @@ -686,6 +681,14 @@ int EVP_DigestVerifyFinal(EVP_MD_CTX *ctx, const unsigned char *sig, "%s digest_verify_final:%s", signature->type_name, desc); return 0; } + + if ((ctx->flags & EVP_MD_CTX_FLAG_FINALISE) == 0) { + /* try dup */ + dctx = EVP_PKEY_CTX_dup(pctx); + if (dctx != NULL) + pctx = dctx; + } + r = signature->digest_verify_final(pctx->op.sig.algctx, sig, siglen); if (!r) ERR_raise_data(ERR_LIB_EVP, EVP_R_PROVIDER_SIGNATURE_FAILURE, -- 2.47.3