From 0655eaf4f6e428d3c2e7c1c1937a852c52fcaa5c Mon Sep 17 00:00:00 2001 From: =?utf8?q?Ond=C5=99ej=20Sur=C3=BD?= Date: Wed, 8 Oct 2025 11:06:00 +0200 Subject: [PATCH] threads: Cleanup master key sparse array in OPENSSL_thread_stop() Fixes #28770 Reviewed-by: Neil Horman Reviewed-by: Tomas Mraz (Merged from https://github.com/openssl/openssl/pull/28781) --- crypto/initthread.c | 2 ++ crypto/threads_common.c | 21 +++++++++++++++++++++ include/internal/threads_common.h | 2 ++ 3 files changed, 25 insertions(+) diff --git a/crypto/initthread.c b/crypto/initthread.c index 4c6a53fd602..07f0cc1c5fe 100644 --- a/crypto/initthread.c +++ b/crypto/initthread.c @@ -272,6 +272,8 @@ void OPENSSL_thread_stop(void) init_thread_remove_handlers(hands); OPENSSL_free(hands); + + CRYPTO_THREAD_clean_local(); } } diff --git a/crypto/threads_common.c b/crypto/threads_common.c index 3a5597266be..e626e3168a5 100644 --- a/crypto/threads_common.c +++ b/crypto/threads_common.c @@ -192,6 +192,9 @@ static void clean_master_key(void *data) MASTER_KEY_ENTRY *mkey = data; int i; + if (data == NULL) + return; + for (i = 0; i < CRYPTO_THREAD_LOCAL_KEY_MAX; i++) { if (mkey[i].ctx_table != NULL) clean_master_key_id(&mkey[i]); @@ -392,6 +395,24 @@ int CRYPTO_THREAD_set_local_ex(CRYPTO_THREAD_LOCAL_KEY_ID id, (uintptr_t)ctx, data); } +void CRYPTO_THREAD_clean_local(void) +{ + MASTER_KEY_ENTRY *mkey; + + /* + * If we never initialized the master key, there + * is no data to clean, so we are done here + */ + if (master_key_init == 0) + return; + + mkey = CRYPTO_THREAD_get_local(&master_key); + if (mkey != NULL) { + clean_master_key(mkey); + CRYPTO_THREAD_set_local(&master_key, NULL); + } +} + #ifdef FIPS_MODULE void CRYPTO_THREAD_clean_local_for_fips(void) { diff --git a/include/internal/threads_common.h b/include/internal/threads_common.h index 5992d65add2..f42d601e74a 100644 --- a/include/internal/threads_common.h +++ b/include/internal/threads_common.h @@ -28,6 +28,8 @@ void *CRYPTO_THREAD_get_local_ex(CRYPTO_THREAD_LOCAL_KEY_ID id, int CRYPTO_THREAD_set_local_ex(CRYPTO_THREAD_LOCAL_KEY_ID id, OSSL_LIB_CTX *ctx, void *data); +void CRYPTO_THREAD_clean_local(void); + # ifdef FIPS_MODULE void CRYPTO_THREAD_clean_local_for_fips(void); # endif -- 2.47.3