From 625ba8f45cd432911792ed78befa553b456887c4 Mon Sep 17 00:00:00 2001 From: Kareem Date: Fri, 24 May 2024 12:22:32 -0700 Subject: [PATCH 1/3] Keep RNG seed file descriptor open until the RNG is freed. --- wolfcrypt/src/random.c | 33 ++++++++++++++++++++------------- 1 file changed, 20 insertions(+), 13 deletions(-) diff --git a/wolfcrypt/src/random.c b/wolfcrypt/src/random.c index c6d667c029..35da606ee7 100644 --- a/wolfcrypt/src/random.c +++ b/wolfcrypt/src/random.c @@ -2026,6 +2026,12 @@ int wc_FreeRng(WC_RNG* rng) ret = WC_HW_E; #endif +#ifndef USE_WINDOWS_API + if(rng->seed.fd != 0 && rng->seed.fd != -1) { + close(rng->seed.fd); + } +#endif + return ret; } @@ -3990,20 +3996,22 @@ int wc_GenerateSeed(OS_Seed* os, byte* output, word32 sz) #endif /* HAVE_INTEL_RDSEED || HAVE_AMD_RDSEED */ #ifndef NO_DEV_URANDOM /* way to disable use of /dev/urandom */ - os->fd = open("/dev/urandom", O_RDONLY); + if (os->fd == 0 || os->fd == -1) { + os->fd = open("/dev/urandom", O_RDONLY); + #if defined(DEBUG_WOLFSSL) + WOLFSSL_MSG("opened /dev/urandom."); + #endif + if (os->fd == -1) + #endif + { + /* may still have /dev/random */ + os->fd = open("/dev/random", O_RDONLY); #if defined(DEBUG_WOLFSSL) - WOLFSSL_MSG("opened /dev/urandom."); + WOLFSSL_MSG("opened /dev/random."); #endif - if (os->fd == -1) - #endif - { - /* may still have /dev/random */ - os->fd = open("/dev/random", O_RDONLY); - #if defined(DEBUG_WOLFSSL) - WOLFSSL_MSG("opened /dev/random."); - #endif - if (os->fd == -1) - return OPEN_RAN_E; + if (os->fd == -1) + return OPEN_RAN_E; + } } #if defined(DEBUG_WOLFSSL) WOLFSSL_MSG("rnd read..."); @@ -4027,7 +4035,6 @@ int wc_GenerateSeed(OS_Seed* os, byte* output, word32 sz) #endif } } - close(os->fd); return ret; } From 288b63c8754f63f3d4cfff78bbbf8338ba8eae2c Mon Sep 17 00:00:00 2001 From: Kareem Date: Fri, 24 May 2024 12:57:34 -0700 Subject: [PATCH 2/3] Initalize RNG seed fd in _InitRng. --- wolfcrypt/src/random.c | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/wolfcrypt/src/random.c b/wolfcrypt/src/random.c index 35da606ee7..21d46ba1ba 100644 --- a/wolfcrypt/src/random.c +++ b/wolfcrypt/src/random.c @@ -1652,6 +1652,10 @@ static int _InitRng(WC_RNG* rng, byte* nonce, word32 nonceSz, } #endif +#ifndef USE_WINDOWS_API + rng->seed.fd = 0; +#endif + #ifdef CUSTOM_RAND_GENERATE_BLOCK ret = 0; /* success */ #else From 54b36137b9cc59820498667f26d84de01f641981 Mon Sep 17 00:00:00 2001 From: Kareem Date: Tue, 28 May 2024 16:15:19 -0700 Subject: [PATCH 3/3] Reset fd after closing it. --- wolfcrypt/src/random.c | 1 + 1 file changed, 1 insertion(+) diff --git a/wolfcrypt/src/random.c b/wolfcrypt/src/random.c index 21d46ba1ba..7141c97ad9 100644 --- a/wolfcrypt/src/random.c +++ b/wolfcrypt/src/random.c @@ -2033,6 +2033,7 @@ int wc_FreeRng(WC_RNG* rng) #ifndef USE_WINDOWS_API if(rng->seed.fd != 0 && rng->seed.fd != -1) { close(rng->seed.fd); + rng->seed.fd = -1; } #endif