From: Niels Dossche Date: Wed, 22 Jan 2025 14:43:14 +0000 (+0100) Subject: Fix potential memory leaks in error paths in ossl_rsa_multiprime_derive() X-Git-Tag: openssl-3.5.0-alpha1~72 X-Git-Url: http://git.ipfire.org/?a=commitdiff_plain;h=8cdba24ceea00de9c0cd8f90bf662d632c37e14b;p=thirdparty%2Fopenssl.git Fix potential memory leaks in error paths in ossl_rsa_multiprime_derive() There are several cases where new BIGNUM instances are created, not using the context, but not freed when an error occurs. Fix this by adding the necessary calls to BN_free(). Reviewed-by: Tom Cosgrove Reviewed-by: Tomas Mraz (Merged from https://github.com/openssl/openssl/pull/26515) --- diff --git a/crypto/rsa/rsa_gen.c b/crypto/rsa/rsa_gen.c index c04a4ea3d92..3caee1a9bf0 100644 --- a/crypto/rsa/rsa_gen.c +++ b/crypto/rsa/rsa_gen.c @@ -147,6 +147,7 @@ int ossl_rsa_multiprime_derive(RSA *rsa, int bits, int primes, goto err; if (!sk_BIGNUM_insert(pplist, tmp, sk_BIGNUM_num(pplist))) goto err; + tmp = NULL; break; default: factor = sk_BIGNUM_value(factors, i); @@ -158,6 +159,7 @@ int ossl_rsa_multiprime_derive(RSA *rsa, int bits, int primes, goto err; if (!sk_BIGNUM_insert(pplist, tmp, sk_BIGNUM_num(pplist))) goto err; + tmp = NULL; break; } } @@ -182,6 +184,7 @@ int ossl_rsa_multiprime_derive(RSA *rsa, int bits, int primes, goto err; if (!sk_BIGNUM_insert(pdlist, dval, sk_BIGNUM_num(pdlist))) goto err; + dval = NULL; } /* Calculate dmp1, dmq1 and additional exponents */ @@ -209,12 +212,11 @@ int ossl_rsa_multiprime_derive(RSA *rsa, int bits, int primes, newexp = BN_new(); if (newexp == NULL) goto err; - if (!BN_mod(newexp, rsa->d, newpd, ctx)) { - BN_free(newexp); + if (!BN_mod(newexp, rsa->d, newpd, ctx)) goto err; - } if (!sk_BIGNUM_insert(exps, newexp, sk_BIGNUM_num(exps))) goto err; + newexp = NULL; } /* Calculate iqmp and additional coefficients */ @@ -235,16 +237,19 @@ int ossl_rsa_multiprime_derive(RSA *rsa, int bits, int primes, if (newcoeff == NULL) goto err; if (BN_mod_inverse(newcoeff, newpp, sk_BIGNUM_value(factors, i), - ctx) == NULL) { - BN_free(newcoeff); + ctx) == NULL) goto err; - } if (!sk_BIGNUM_insert(coeffs, newcoeff, sk_BIGNUM_num(coeffs))) goto err; + newcoeff = NULL; } ret = 1; err: + BN_free(newcoeff); + BN_free(newexp); + BN_free(dval); + BN_free(tmp); sk_BIGNUM_pop_free(pplist, BN_free); sk_BIGNUM_pop_free(pdlist, BN_free); BN_CTX_end(ctx);