From 274e786be970a659e6082b7733b451349335252c Mon Sep 17 00:00:00 2001 From: Xi Ruoyao Date: Mon, 13 Jun 2022 16:44:14 +0800 Subject: [PATCH] libmisc: use /dev/urandom as a generic fallback for read_random_bytes() On systems with Linux kernel < 3.17, getentropy() and getrandom() may exist but return ENOSYS. Use /dev/urandom as a fallback to avoid a hard requirement on Linux kernel version. Fixes #512. Signed-off-by: Xi Ruoyao --- libmisc/salt.c | 22 ++++++++++------------ 1 file changed, 10 insertions(+), 12 deletions(-) diff --git a/libmisc/salt.c b/libmisc/salt.c index 450293d7..1279ca09 100644 --- a/libmisc/salt.c +++ b/libmisc/salt.c @@ -156,24 +156,23 @@ static long read_random_bytes (void) /* arc4random_buf, if it exists, can never fail. */ arc4random_buf (&randval, sizeof (randval)); goto end; +#endif -#elif defined(HAVE_GETENTROPY) +#ifdef HAVE_GETENTROPY /* getentropy may exist but lack kernel support. */ - if (getentropy (&randval, sizeof (randval))) { - goto fail; + if (getentropy (&randval, sizeof (randval)) == 0) { + goto end; } +#endif - goto end; - -#elif defined(HAVE_GETRANDOM) +#ifdef HAVE_GETRANDOM /* Likewise getrandom. */ - if ((size_t) getrandom (&randval, sizeof (randval), 0) != sizeof (randval)) { - goto fail; + if ((size_t) getrandom (&randval, sizeof (randval), 0) == sizeof (randval)) { + goto end; } +#endif - goto end; - -#else + /* Use /dev/urandom as a last resort. */ FILE *f = fopen ("/dev/urandom", "r"); if (NULL == f) { goto fail; @@ -186,7 +185,6 @@ static long read_random_bytes (void) fclose(f); goto end; -#endif fail: fprintf (log_get_logfd(),