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 <xry111@xry111.site>
This commit is contained in:
Xi Ruoyao 2022-06-13 16:44:14 +08:00 committed by Serge Hallyn
parent 6688f1c1eb
commit 274e786be9

View File

@ -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(),