Fix usage of deallocated EVP_RAND_CTX after execution of FIPS on-demand self tests

Once RNG is used, triggering FIPS on-demand self tests (via
OSSL_PROVIDER_self_test() API) crashes the application. This happens because the
RNG context is stored before self tests, and restored after their execution.
In the meantime - before context restoration - RAND_set0_private() function is
called, which decrements the stored RNG context reference counter and frees it.
To resolve the issue, the stored RNG context refcount has been incremented via
the EVP_RAND_CTX_up_ref() API to avoid its deallocation during the RNG context
switch performed by the self test function.
The provider_status_test test has been updated to reproduce the issue as
a regression test.

Signed-off-by: Karol Brzuskiewicz <kabr@arista.com>

Reviewed-by: Shane Lontis <shane.lontis@oracle.com>
Reviewed-by: Tom Cosgrove <tom.cosgrove@arm.com>
Reviewed-by: Paul Dale <ppzgs1@gmail.com>
Reviewed-by: Tomas Mraz <tomas@openssl.org>
(Merged from https://github.com/openssl/openssl/pull/24599)
This commit is contained in:
Karol Brzuskiewicz 2024-06-10 01:48:31 -07:00 committed by Tomas Mraz
parent d38f62ea11
commit 42a8ef844e
2 changed files with 17 additions and 0 deletions

View file

@ -858,8 +858,12 @@ int SELF_TEST_kats(OSSL_SELF_TEST *st, OSSL_LIB_CTX *libctx)
EVP_RAND_CTX *saved_rand = ossl_rand_get0_private_noncreating(libctx);
int ret = 1;
if (saved_rand != NULL && !EVP_RAND_CTX_up_ref(saved_rand))
return 0;
if (!setup_main_random(libctx)
|| !RAND_set0_private(libctx, main_rand)) {
/* Decrement saved_rand reference counter */
EVP_RAND_CTX_free(saved_rand);
EVP_RAND_CTX_free(main_rand);
return 0;
}

View file

@ -14,6 +14,7 @@
#include <openssl/core_names.h>
#include <openssl/self_test.h>
#include <openssl/evp.h>
#include <openssl/rsa.h>
#include "testutil.h"
typedef enum OPTION_choice {
@ -147,6 +148,8 @@ static int test_provider_status(void)
OSSL_PROVIDER *prov = NULL;
OSSL_PARAM params[2];
EVP_MD *fetch = NULL;
EVP_PKEY_CTX *pctx = NULL;
EVP_PKEY *pkey = NULL;
if (!TEST_ptr(prov = OSSL_PROVIDER_load(libctx, provider_name)))
goto err;
@ -163,6 +166,16 @@ static int test_provider_status(void)
goto err;
EVP_MD_free(fetch);
fetch = NULL;
/* Use RNG before triggering on-demand self tests */
if (!TEST_ptr((pctx = EVP_PKEY_CTX_new_from_name(libctx, "RSA", NULL)))
|| !TEST_int_gt(EVP_PKEY_keygen_init(pctx), 0)
|| !TEST_int_gt(EVP_PKEY_CTX_set_rsa_keygen_bits(pctx, 2048), 0)
|| !TEST_int_gt(EVP_PKEY_keygen(pctx, &pkey), 0))
goto err;
EVP_PKEY_free(pkey);
EVP_PKEY_CTX_free(pctx);
pkey = NULL;
pctx = NULL;
/* Test that the provider self test is ok */
self_test_args.count = 0;