From 71d5deed5eed3949ee09c5f0a53b4de0b09b4afc Mon Sep 17 00:00:00 2001 From: David Gibson Date: Thu, 14 Nov 2024 14:33:08 +1100 Subject: util: Add general low-level random bytes helper Currently secret_init() open codes getting good quality random bytes from the OS, either via getrandom(2) or reading /dev/random. We're going to add at least one more place that needs random data in future, so make a general helper for getting random bytes. While we're there, fix a number of minor bugs: - getrandom() can theoretically return a "short read", so handle that case - getrandom() as well as read can return a transient EINTR - We would attempt to read data from /dev/random if we failed to open it (open() returns -1), but not if we opened it as fd 0 (unlikely, but ok) - More specific error reporting Signed-off-by: David Gibson Signed-off-by: Stefano Brivio --- passt.c | 30 +----------------------------- 1 file changed, 1 insertion(+), 29 deletions(-) (limited to 'passt.c') diff --git a/passt.c b/passt.c index fac6101..73649de 100644 --- a/passt.c +++ b/passt.c @@ -36,9 +36,6 @@ #include #include #include -#ifdef HAS_GETRANDOM -#include -#endif #include "util.h" #include "passt.h" @@ -118,32 +115,7 @@ static void post_handler(struct ctx *c, const struct timespec *now) */ static void secret_init(struct ctx *c) { -#ifndef HAS_GETRANDOM - int dev_random = open("/dev/random", O_RDONLY); - unsigned int random_read = 0; - - while (dev_random && random_read < sizeof(c->hash_secret)) { - int ret = read(dev_random, - (uint8_t *)&c->hash_secret + random_read, - sizeof(c->hash_secret) - random_read); - - if (ret == -1 && errno == EINTR) - continue; - - if (ret <= 0) - break; - - random_read += ret; - } - if (dev_random >= 0) - close(dev_random); - - if (random_read < sizeof(c->hash_secret)) -#else - if (getrandom(&c->hash_secret, sizeof(c->hash_secret), - GRND_RANDOM) < 0) -#endif /* !HAS_GETRANDOM */ - die_perror("Failed to get random bytes for hash table and TCP"); + raw_random(&c->hash_secret, sizeof(c->hash_secret)); } /** -- cgit v1.2.3