From ac8b81c2b7ed378528e5cc60754e10be1e369e40 Mon Sep 17 00:00:00 2001 From: Alejandro Colomar Date: Fri, 30 Dec 2022 12:48:55 +0100 Subject: [PATCH] Prefer getrandom(3)/getentropy(3) over arc4random(3bsd) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit arc4random(3) without kernel support is unsafe, as it can't know when to drop the buffer. Since we depend on libbsd since recently, we have arc4random(3) functions always available, and thus, this code would have always called arc4random_buf(3bsd), which is unsafe. Put it after some better alternatives, at least until in a decade or so all systems have a recent enough glibc. glibc implements arc4random(3) safely, since it's just a wrapper around getrandom(2). Link: Link: Cc: Cristian Rodríguez Cc: Adhemerval Zanella Cc: Guillem Jover Cc: Björn Esser Reviewed-by: "Jason A. Donenfeld" Signed-off-by: Alejandro Colomar --- libmisc/salt.c | 12 ++++++------ 1 file changed, 6 insertions(+), 6 deletions(-) diff --git a/libmisc/salt.c b/libmisc/salt.c index 0aeff738..9c5ca006 100644 --- a/libmisc/salt.c +++ b/libmisc/salt.c @@ -114,12 +114,6 @@ static long read_random_bytes (void) { long randval = 0; -#ifdef HAVE_ARC4RANDOM_BUF - /* arc4random_buf, if it exists, can never fail. */ - arc4random_buf (&randval, sizeof (randval)); - goto end; -#endif - #ifdef HAVE_GETENTROPY /* getentropy may exist but lack kernel support. */ if (getentropy (&randval, sizeof (randval)) == 0) { @@ -134,6 +128,12 @@ static long read_random_bytes (void) } #endif +#ifdef HAVE_ARC4RANDOM_BUF + /* arc4random_buf, if it exists, can never fail. */ + arc4random_buf (&randval, sizeof (randval)); + goto end; +#endif + /* Use /dev/urandom as a last resort. */ FILE *f = fopen ("/dev/urandom", "r"); if (NULL == f) {