From ab78716adf163b7bce7981e13ca6474cd8abe0e4 Mon Sep 17 00:00:00 2001 From: Nik Bougalis Date: Fri, 12 Jul 2024 17:45:40 -0700 Subject: [PATCH] Address `noise_rand_bytes` silent failure on Windows: Per its documentation, `noise_rand_bytes` returns "cryptographically-strong random bytes from the operating system." On Windows, the existing implementation of the function does not check that the `CryptGenRandom` API succeeds. While failure is unlikely, it is prudent to actually check. If merged this commit will cause the process to exit if the function is not able to generate the requested number of random bytes; the code also checks that the provided buffer is non-null and that the number of bytes requested is non-zero. --- src/protocol/rand_os.c | 13 +++++++++---- 1 file changed, 9 insertions(+), 4 deletions(-) diff --git a/src/protocol/rand_os.c b/src/protocol/rand_os.c index af4202da..5c2afe90 100644 --- a/src/protocol/rand_os.c +++ b/src/protocol/rand_os.c @@ -65,8 +65,12 @@ * * \note Not part of the public API. */ -void noise_rand_bytes(void *bytes, size_t size) -{ +void noise_rand_bytes(void *bytes, size_t size) { + if (size == 0 || bytes == NULL) { + fprintf(stderr, "Invalid size or buffer provided for noise_rand_bytes. Abort!\n"); + exit(1); + } + #if defined(RANDOM_DEVICE) int fd = open(RANDOM_DEVICE, O_RDONLY); if (fd >= 0) { @@ -95,9 +99,10 @@ void noise_rand_bytes(void *bytes, size_t size) memset(bytes, 0, size); if (CryptAcquireContextW(&provider, 0, 0, PROV_RSA_FULL, CRYPT_VERIFYCONTEXT | CRYPT_SILENT)) { - CryptGenRandom(provider, size, bytes); + BOOL success = CryptGenRandom(provider, size, bytes); CryptReleaseContext(provider, 0); - return; + if (success) + return; } #endif fprintf(stderr, "Do not know how to generate random numbers! Abort!\n");