From 755097d512a226add52e5449312de8a9053d3111 Mon Sep 17 00:00:00 2001 From: Kareem Date: Thu, 18 Dec 2025 15:27:00 -0700 Subject: [PATCH] Track if RNG seed FD was opened and only close it if it was already open. This fixes the case where wc_FreeRng is called when _InitRng was not called on the RNG. Since the FD value defaults to 0 before _InitRng was called, and 0 is potentially a valid FD, it was being closed. --- wolfcrypt/src/random.c | 14 +++++++++++--- wolfssl/wolfcrypt/random.h | 1 + 2 files changed, 12 insertions(+), 3 deletions(-) diff --git a/wolfcrypt/src/random.c b/wolfcrypt/src/random.c index 766ef1e458..7d2fcfa60d 100644 --- a/wolfcrypt/src/random.c +++ b/wolfcrypt/src/random.c @@ -895,7 +895,8 @@ static int _InitRng(WC_RNG* rng, byte* nonce, word32 nonceSz, #endif #ifndef USE_WINDOWS_API - rng->seed.fd = -1; + if (!rng->seed.fdOpen) + rng->seed.fd = -1; #endif #ifdef CUSTOM_RAND_GENERATE_BLOCK @@ -1378,9 +1379,10 @@ int wc_FreeRng(WC_RNG* rng) #endif #ifdef XCLOSE - if(rng->seed.fd != -1) { + if(rng->seed.fdOpen && rng->seed.fd != -1) { XCLOSE(rng->seed.fd); rng->seed.fd = -1; + rng->seed.fdOpen = 0; } #endif @@ -3564,7 +3566,7 @@ int wc_GenerateSeed(OS_Seed* os, byte* output, word32 sz) #ifndef NO_FILESYSTEM #ifndef NO_DEV_URANDOM /* way to disable use of /dev/urandom */ - if (os->fd == -1) { + if (!os->fdOpen && os->fd == -1) { os->fd = open("/dev/urandom", O_RDONLY); #if defined(DEBUG_WOLFSSL) WOLFSSL_MSG("opened /dev/urandom."); @@ -3579,6 +3581,12 @@ int wc_GenerateSeed(OS_Seed* os, byte* output, word32 sz) #endif if (os->fd == -1) return OPEN_RAN_E; + else + os->fdOpen = 1; + } + else + { + os->fdOpen = 1; } } #if defined(DEBUG_WOLFSSL) diff --git a/wolfssl/wolfcrypt/random.h b/wolfssl/wolfcrypt/random.h index 93890fe9ac..f5c9ceb1da 100644 --- a/wolfssl/wolfcrypt/random.h +++ b/wolfssl/wolfcrypt/random.h @@ -156,6 +156,7 @@ struct OS_Seed { ProviderHandle handle; #else int fd; + byte fdOpen:1; #endif #if defined(WOLF_CRYPTO_CB) int devId;