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 <tom.cosgrove@arm.com>
Reviewed-by: Tomas Mraz <tomas@openssl.org>
(Merged from https://github.com/openssl/openssl/pull/26515)
This commit is contained in:
Niels Dossche 2025-01-22 15:43:14 +01:00 committed by Tomas Mraz
parent 7e80b16776
commit 8cdba24cee
1 changed files with 11 additions and 6 deletions

View File

@ -147,6 +147,7 @@ int ossl_rsa_multiprime_derive(RSA *rsa, int bits, int primes,
goto err; goto err;
if (!sk_BIGNUM_insert(pplist, tmp, sk_BIGNUM_num(pplist))) if (!sk_BIGNUM_insert(pplist, tmp, sk_BIGNUM_num(pplist)))
goto err; goto err;
tmp = NULL;
break; break;
default: default:
factor = sk_BIGNUM_value(factors, i); factor = sk_BIGNUM_value(factors, i);
@ -158,6 +159,7 @@ int ossl_rsa_multiprime_derive(RSA *rsa, int bits, int primes,
goto err; goto err;
if (!sk_BIGNUM_insert(pplist, tmp, sk_BIGNUM_num(pplist))) if (!sk_BIGNUM_insert(pplist, tmp, sk_BIGNUM_num(pplist)))
goto err; goto err;
tmp = NULL;
break; break;
} }
} }
@ -182,6 +184,7 @@ int ossl_rsa_multiprime_derive(RSA *rsa, int bits, int primes,
goto err; goto err;
if (!sk_BIGNUM_insert(pdlist, dval, sk_BIGNUM_num(pdlist))) if (!sk_BIGNUM_insert(pdlist, dval, sk_BIGNUM_num(pdlist)))
goto err; goto err;
dval = NULL;
} }
/* Calculate dmp1, dmq1 and additional exponents */ /* Calculate dmp1, dmq1 and additional exponents */
@ -209,12 +212,11 @@ int ossl_rsa_multiprime_derive(RSA *rsa, int bits, int primes,
newexp = BN_new(); newexp = BN_new();
if (newexp == NULL) if (newexp == NULL)
goto err; goto err;
if (!BN_mod(newexp, rsa->d, newpd, ctx)) { if (!BN_mod(newexp, rsa->d, newpd, ctx))
BN_free(newexp);
goto err; goto err;
}
if (!sk_BIGNUM_insert(exps, newexp, sk_BIGNUM_num(exps))) if (!sk_BIGNUM_insert(exps, newexp, sk_BIGNUM_num(exps)))
goto err; goto err;
newexp = NULL;
} }
/* Calculate iqmp and additional coefficients */ /* Calculate iqmp and additional coefficients */
@ -235,16 +237,19 @@ int ossl_rsa_multiprime_derive(RSA *rsa, int bits, int primes,
if (newcoeff == NULL) if (newcoeff == NULL)
goto err; goto err;
if (BN_mod_inverse(newcoeff, newpp, sk_BIGNUM_value(factors, i), if (BN_mod_inverse(newcoeff, newpp, sk_BIGNUM_value(factors, i),
ctx) == NULL) { ctx) == NULL)
BN_free(newcoeff);
goto err; goto err;
}
if (!sk_BIGNUM_insert(coeffs, newcoeff, sk_BIGNUM_num(coeffs))) if (!sk_BIGNUM_insert(coeffs, newcoeff, sk_BIGNUM_num(coeffs)))
goto err; goto err;
newcoeff = NULL;
} }
ret = 1; ret = 1;
err: err:
BN_free(newcoeff);
BN_free(newexp);
BN_free(dval);
BN_free(tmp);
sk_BIGNUM_pop_free(pplist, BN_free); sk_BIGNUM_pop_free(pplist, BN_free);
sk_BIGNUM_pop_free(pdlist, BN_free); sk_BIGNUM_pop_free(pdlist, BN_free);
BN_CTX_end(ctx); BN_CTX_end(ctx);