From d5c02e2de86a28ab2c06e866f0db858c43d00355 Mon Sep 17 00:00:00 2001
From: Tomas Mraz <tomas@openssl.org>
Date: Tue, 11 Oct 2022 17:26:23 +0200
Subject: [PATCH] Release the drbg in the global default context before engines

Fixes #17995
Fixes #18578

Reviewed-by: Paul Dale <pauli@openssl.org>
Reviewed-by: Bernd Edlinger <bernd.edlinger@hotmail.de>
(Merged from https://github.com/openssl/openssl/pull/19386)

(cherry picked from commit a88e97fcace01ecf557b207f04328a72df5110df)
---
 crypto/context.c         | 9 +++++++++
 crypto/rand/rand_lib.c   | 1 +
 include/crypto/context.h | 1 +
 3 files changed, 11 insertions(+)

diff --git a/crypto/context.c b/crypto/context.c
index aec9ecd4ac..c6358afc81 100644
--- a/crypto/context.c
+++ b/crypto/context.c
@@ -456,6 +456,15 @@ OSSL_LIB_CTX *OSSL_LIB_CTX_set0_default(OSSL_LIB_CTX *libctx)
 
     return NULL;
 }
+
+void ossl_release_default_drbg_ctx(void)
+{
+    /* early release of the DRBG in global default libctx */
+    if (default_context_int.drbg != NULL) {
+        ossl_rand_ctx_free(default_context_int.drbg);
+        default_context_int.drbg = NULL;
+    }
+}
 #endif
 
 OSSL_LIB_CTX *ossl_lib_ctx_get_concrete(OSSL_LIB_CTX *ctx)
diff --git a/crypto/rand/rand_lib.c b/crypto/rand/rand_lib.c
index 3f04ec171e..b186ec7f27 100644
--- a/crypto/rand/rand_lib.c
+++ b/crypto/rand/rand_lib.c
@@ -97,6 +97,7 @@ void ossl_rand_cleanup_int(void)
     CRYPTO_THREAD_lock_free(rand_meth_lock);
     rand_meth_lock = NULL;
 # endif
+    ossl_release_default_drbg_ctx();
     rand_inited = 0;
 }
 
diff --git a/include/crypto/context.h b/include/crypto/context.h
index 143f6d6b6d..cc06c71be8 100644
--- a/include/crypto/context.h
+++ b/include/crypto/context.h
@@ -38,3 +38,4 @@ void ossl_self_test_set_callback_free(void *);
 void ossl_rand_crng_ctx_free(void *);
 void ossl_thread_event_ctx_free(void *);
 void ossl_fips_prov_ossl_ctx_free(void *);
+void ossl_release_default_drbg_ctx(void);
-- 
2.33.0

