Skip to content

Commit 442d3f3

Browse files
committed
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.
1 parent 59290cd commit 442d3f3

1 file changed

Lines changed: 17 additions & 13 deletions

File tree

src/ssl.c

Lines changed: 17 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -289,7 +289,7 @@ int wc_OBJ_sn2nid(const char *sn)
289289

290290
#define HAVE_GLOBAL_RNG /* consolidate flags for using globalRNG */
291291
static WC_RNG globalRNG;
292-
static int initGlobalRNG = 0;
292+
static volatile int initGlobalRNG = 0;
293293

294294
static WC_MAYBE_UNUSED wolfSSL_Mutex globalRNGMutex
295295
WOLFSSL_MUTEX_INITIALIZER_CLAUSE(globalRNGMutex);
@@ -23925,22 +23925,26 @@ int wolfSSL_RAND_bytes(unsigned char* buf, int num)
2392523925
}
2392623926
#endif
2392723927
#ifdef HAVE_GLOBAL_RNG
23928-
if (wc_LockMutex(&globalRNGMutex) != 0) {
23929-
WOLFSSL_MSG("Bad Lock Mutex rng");
23930-
return ret;
23931-
}
23932-
2393323928
if (initGlobalRNG) {
23934-
rng = &globalRNG;
23935-
used_global = 1;
23929+
if (wc_LockMutex(&globalRNGMutex) != 0) {
23930+
WOLFSSL_MSG("Bad Lock Mutex rng");
23931+
return ret;
23932+
}
23933+
/* the above access to initGlobalRNG is racey -- recheck it now that we
23934+
* have the lock.
23935+
*/
23936+
if (initGlobalRNG) {
23937+
rng = &globalRNG;
23938+
used_global = 1;
23939+
}
23940+
else {
23941+
wc_UnLockMutex(&globalRNGMutex);
23942+
}
2393623943
}
23937-
else
23944+
23945+
if (used_global == 0)
2393823946
#endif
2393923947
{
23940-
#ifdef HAVE_GLOBAL_RNG
23941-
wc_UnLockMutex(&globalRNGMutex);
23942-
#endif
23943-
2394423948
#ifdef WOLFSSL_SMALL_STACK
2394523949
tmpRNG = (WC_RNG*)XMALLOC(sizeof(WC_RNG), NULL, DYNAMIC_TYPE_RNG);
2394623950
if (tmpRNG == NULL)

0 commit comments

Comments
 (0)