From 442d3f30cc0f2d478a11583cf6d257bd4f969fff Mon Sep 17 00:00:00 2001 From: Daniel Pouzzner Date: Thu, 25 Apr 2024 23:47:39 -0500 Subject: [PATCH] src/ssl.c: refactor fix in wolfSSL_RAND_bytes() for race on initGlobalRNG to retain the initial check on initGlobalRNG, and just recheck it, to avoid possible access to uninitialized globalRNGMutex. --- src/ssl.c | 30 +++++++++++++++++------------- 1 file changed, 17 insertions(+), 13 deletions(-) diff --git a/src/ssl.c b/src/ssl.c index 2c339860c..594445014 100644 --- a/src/ssl.c +++ b/src/ssl.c @@ -289,7 +289,7 @@ int wc_OBJ_sn2nid(const char *sn) #define HAVE_GLOBAL_RNG /* consolidate flags for using globalRNG */ static WC_RNG globalRNG; -static int initGlobalRNG = 0; +static volatile int initGlobalRNG = 0; static WC_MAYBE_UNUSED wolfSSL_Mutex globalRNGMutex WOLFSSL_MUTEX_INITIALIZER_CLAUSE(globalRNGMutex); @@ -23925,22 +23925,26 @@ int wolfSSL_RAND_bytes(unsigned char* buf, int num) } #endif #ifdef HAVE_GLOBAL_RNG - if (wc_LockMutex(&globalRNGMutex) != 0) { - WOLFSSL_MSG("Bad Lock Mutex rng"); - return ret; + if (initGlobalRNG) { + if (wc_LockMutex(&globalRNGMutex) != 0) { + WOLFSSL_MSG("Bad Lock Mutex rng"); + return ret; + } + /* the above access to initGlobalRNG is racey -- recheck it now that we + * have the lock. + */ + if (initGlobalRNG) { + rng = &globalRNG; + used_global = 1; + } + else { + wc_UnLockMutex(&globalRNGMutex); + } } - if (initGlobalRNG) { - rng = &globalRNG; - used_global = 1; - } - else + if (used_global == 0) #endif { - #ifdef HAVE_GLOBAL_RNG - wc_UnLockMutex(&globalRNGMutex); - #endif - #ifdef WOLFSSL_SMALL_STACK tmpRNG = (WC_RNG*)XMALLOC(sizeof(WC_RNG), NULL, DYNAMIC_TYPE_RNG); if (tmpRNG == NULL)