Commit 238cae9374 for openssl.org
commit 238cae93748666317ac05f470c13e199da46346d
Author: Niels Dossche <niels.dossche@ugent.be>
Date: Tue Sep 8 12:21:24 2026 +0200
Fix memory leaks in rsa_multiprime_keygen() on error
There are two leaks:
- The BIGNUM stacks may still contain BIGNUMs when an error path is taken.
- sk_BIGNUM_insert() can fail and already has an error check, but then
the BIGNUM returned by `sk_BIGNUM_delete(factors, 0)` can still leak.
Reviewed-by: Paul Yang <paulyang.inf@gmail.com>
Reviewed-by: Nikola Pajkovsky <nikolap@openssl.org>
Merge-date: Fri Oct 2 08:02:54 2026
Merged-from: https://github.com/openssl/openssl/pull/32739
diff --git a/crypto/rsa/rsa_gen.c b/crypto/rsa/rsa_gen.c
index bd481f7b08..d7c37e7c78 100644
--- a/crypto/rsa/rsa_gen.c
+++ b/crypto/rsa/rsa_gen.c
@@ -536,8 +536,12 @@ static int rsa_multiprime_keygen(RSA *rsa, int bits, int primes,
rsa->p = rsa->q;
rsa->q = tmp;
/* mirror this in our factor stack */
- if (!sk_BIGNUM_insert(factors, sk_BIGNUM_delete(factors, 0), 1))
+ tmp = sk_BIGNUM_delete(factors, 0);
+ if (!sk_BIGNUM_insert(factors, tmp, 1)) {
+ /* the factor is no longer on the stack, so free it here */
+ BN_clear_free(tmp);
goto err;
+ }
}
/* calculate d */
@@ -601,9 +605,10 @@ static int rsa_multiprime_keygen(RSA *rsa, int bits, int primes,
}
ok = 1;
err:
- sk_BIGNUM_free(factors);
- sk_BIGNUM_free(exps);
- sk_BIGNUM_free(coeffs);
+ /* On error, these stacks may still contain BIGNUMs. */
+ sk_BIGNUM_pop_free(factors, BN_clear_free);
+ sk_BIGNUM_pop_free(exps, BN_clear_free);
+ sk_BIGNUM_pop_free(coeffs, BN_clear_free);
if (ok == -1) {
ERR_raise(ERR_LIB_RSA, ERR_R_BN_LIB);
ok = 0;