From 8323eb38c90c1caf98c505e7b7e5ee348e7820f2 Mon Sep 17 00:00:00 2001 From: Jordan Bancino Date: Sat, 7 Jan 2023 00:18:44 +0000 Subject: [PATCH] Make UtilRandomString() more secure. Two ways this is more secure: 1. The seed is only generated once, not every time the function is called. 2. All threads share the same seed, which means timing attacks aren't possible. Because we are using a mutex, performance may suffer slightly. --- src/Util.c | 17 +++++++++++++---- 1 file changed, 13 insertions(+), 4 deletions(-) diff --git a/src/Util.c b/src/Util.c index 3b6d958..1986d43 100644 --- a/src/Util.c +++ b/src/Util.c @@ -32,6 +32,7 @@ #include #include +#include #include #include #include @@ -399,14 +400,13 @@ UtilGetLine(char **linePtr, size_t * n, FILE * stream) char * UtilRandomString(size_t len) { - static const char charset[] = - "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"; + static const char charset[] = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"; + static pthread_mutex_t seedLock = PTHREAD_MUTEX_INITIALIZER; + static unsigned int seed = 0; char *str; size_t i; - unsigned int seed = UtilServerTs() * (unsigned long) pthread_self(); - if (!len) { return NULL; @@ -418,11 +418,20 @@ UtilRandomString(size_t len) return NULL; } + pthread_mutex_lock(&seedLock); + + if (!seed) + { + seed = UtilServerTs() ^ getpid() ^ (unsigned long) pthread_self(); + } + for (i = 0; i < len; i++) { str[i] = charset[rand_r(&seed) % (sizeof(charset) - 1)]; } + pthread_mutex_unlock(&seedLock); + str[len] = '\0'; return str; }