From 58d5aa84e48b2442f87fa5134c1669c0ca49f7cf Mon Sep 17 00:00:00 2001 From: Vishal Pankaj Chandratreya <19171016+tfpf@users.noreply.github.com> Date: Sun, 1 Oct 2023 14:13:08 +0530 Subject: [PATCH] Used OS-specific entropy sources. --- lib/hdrbg.c | 49 ++++++++++++++++++++++++++++++++++++++++++++----- 1 file changed, 44 insertions(+), 5 deletions(-) diff --git a/lib/hdrbg.c b/lib/hdrbg.c index 7ebcc23..3ac8f40 100644 --- a/lib/hdrbg.c +++ b/lib/hdrbg.c @@ -28,6 +28,13 @@ static enum hdrbg_err_t #endif hdrbg_err = HDRBG_ERR_NONE; +#if defined _WIN32 +#include +#include +#elif defined __linux__ || defined __APPLE__ +#include +#endif + #define HDRBG_SEED_LENGTH 55 #define HDRBG_SECURITY_STRENGTH 32 #define HDRBG_NONCE1_LENGTH 8 @@ -186,7 +193,41 @@ hdrbg_seed(struct hdrbg_t *hd, uint8_t *s_bytes, size_t s_length) static size_t streamtobytes(FILE *fptr_, uint8_t *m_bytes, size_t m_length) { - FILE *fptr = fptr_ == NULL ? fopen("/dev/urandom", "rb") : fptr_; + // The file will be specified only while testing. + if(fptr_ != NULL) + { + size_t len = fread(m_bytes, sizeof *m_bytes, m_length, fptr_); + if(len < m_length) + { + hdrbg_err = HDRBG_ERR_INSUFFICIENT_ENTROPY; + } + return len; + } + + // During normal operation, the file won't be specified. Obtain bytes from + // an entropy source. +#if defined _WIN32 && CHAR_BIT == 8 + NTSTATUS status = BCryptGenRandom(NULL, m_bytes, m_length, BCRYPT_USE_SYSTEM_PREFERRED_RNG); + if(status != STATUS_SUCCESS) + { + hdrbg_err = HDRBG_ERR_NO_ENTROPY; + return 0; + } + return m_length; +#elif (defined __linux__ || defined __APPLE__) && CHAR_BIT == 8 + ssize_t len = getrandom(m_bytes, m_length, 0); + if(len < 0) + { + hdrbg_err = HDRBG_ERR_NO_ENTROPY; + return 0; + } + if((size_t)len < m_length) + { + hdrbg_err = HDRBG_ERR_INSUFFICIENT_ENTROPY; + } + return len; +#else + FILE *fptr = fopen("/dev/urandom"); if(fptr == NULL) { hdrbg_err = HDRBG_ERR_NO_ENTROPY; @@ -197,11 +238,9 @@ streamtobytes(FILE *fptr_, uint8_t *m_bytes, size_t m_length) { hdrbg_err = HDRBG_ERR_INSUFFICIENT_ENTROPY; } - if(fptr_ == NULL) - { - fclose(fptr); - } + fclose(fptr); return len; +#endif } /******************************************************************************