Skip to content

Commit 755097d

Browse files
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.
1 parent 0420c94 commit 755097d

2 files changed

Lines changed: 12 additions & 3 deletions

File tree

wolfcrypt/src/random.c

Lines changed: 11 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -895,7 +895,8 @@ static int _InitRng(WC_RNG* rng, byte* nonce, word32 nonceSz,
895895
#endif
896896

897897
#ifndef USE_WINDOWS_API
898-
rng->seed.fd = -1;
898+
if (!rng->seed.fdOpen)
899+
rng->seed.fd = -1;
899900
#endif
900901

901902
#ifdef CUSTOM_RAND_GENERATE_BLOCK
@@ -1378,9 +1379,10 @@ int wc_FreeRng(WC_RNG* rng)
13781379
#endif
13791380

13801381
#ifdef XCLOSE
1381-
if(rng->seed.fd != -1) {
1382+
if(rng->seed.fdOpen && rng->seed.fd != -1) {
13821383
XCLOSE(rng->seed.fd);
13831384
rng->seed.fd = -1;
1385+
rng->seed.fdOpen = 0;
13841386
}
13851387
#endif
13861388

@@ -3564,7 +3566,7 @@ int wc_GenerateSeed(OS_Seed* os, byte* output, word32 sz)
35643566

35653567
#ifndef NO_FILESYSTEM
35663568
#ifndef NO_DEV_URANDOM /* way to disable use of /dev/urandom */
3567-
if (os->fd == -1) {
3569+
if (!os->fdOpen && os->fd == -1) {
35683570
os->fd = open("/dev/urandom", O_RDONLY);
35693571
#if defined(DEBUG_WOLFSSL)
35703572
WOLFSSL_MSG("opened /dev/urandom.");
@@ -3579,6 +3581,12 @@ int wc_GenerateSeed(OS_Seed* os, byte* output, word32 sz)
35793581
#endif
35803582
if (os->fd == -1)
35813583
return OPEN_RAN_E;
3584+
else
3585+
os->fdOpen = 1;
3586+
}
3587+
else
3588+
{
3589+
os->fdOpen = 1;
35823590
}
35833591
}
35843592
#if defined(DEBUG_WOLFSSL)

wolfssl/wolfcrypt/random.h

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -156,6 +156,7 @@ struct OS_Seed {
156156
ProviderHandle handle;
157157
#else
158158
int fd;
159+
byte fdOpen:1;
159160
#endif
160161
#if defined(WOLF_CRYPTO_CB)
161162
int devId;

0 commit comments

Comments
 (0)