From b6aed64e47b831305c05a4132e7c7f21257ea663 Mon Sep 17 00:00:00 2001 From: Neil Horman Date: Tue, 30 Dec 2025 14:52:08 -0500 Subject: [PATCH] Fix overflow in EVP_EncodeFinal MIME-Version: 1.0 Content-Type: text/plain; charset=utf8 Content-Transfer-Encoding: 8bit https://scan5.scan.coverity.com/#/project-view/60762/10222?selectedIssue=1677829 With recent changes, evp_encodeblock_int may return a negative value, which EVP_EncodeFinal does not anticipate. As the latter sets out[ret] to "\0" where ret is the return value of evp_encodeblock_int, we may underflow the array index and access invalid memory locations. Only update the output buffer if the return value is greater or equal to zero. Reviewed-by: Saša Nedvědický Reviewed-by: Nikola Pajkovsky (Merged from https://github.com/openssl/openssl/pull/29525) --- crypto/evp/encode.c | 10 ++++++---- 1 file changed, 6 insertions(+), 4 deletions(-) diff --git a/crypto/evp/encode.c b/crypto/evp/encode.c index bbd36c0820b..dd5992d09e6 100644 --- a/crypto/evp/encode.c +++ b/crypto/evp/encode.c @@ -457,10 +457,12 @@ void EVP_EncodeFinal(EVP_ENCODE_CTX *ctx, unsigned char *out, int *outl) if (ctx->num != 0) { ret = evp_encodeblock_int(ctx, out, ctx->enc_data, ctx->num, &wrap_cnt); - if ((ctx->flags & EVP_ENCODE_CTX_NO_NEWLINES) == 0) - out[ret++] = '\n'; - out[ret] = '\0'; - ctx->num = 0; + if (ossl_assert(ret >= 0)) { + if ((ctx->flags & EVP_ENCODE_CTX_NO_NEWLINES) == 0) + out[ret++] = '\n'; + out[ret] = '\0'; + ctx->num = 0; + } } *outl = ret; } -- 2.47.3