From cf16d07df97b8fbec9fe17b3f437ffc297af9ed2 Mon Sep 17 00:00:00 2001 From: Leah Rowe Date: Thu, 26 Mar 2026 08:56:15 +0000 Subject: rand: fix modulo bias in rmalloc Signed-off-by: Leah Rowe --- util/libreboot-utils/lib/rand.c | 10 ++++++++-- 1 file changed, 8 insertions(+), 2 deletions(-) (limited to 'util') diff --git a/util/libreboot-utils/lib/rand.c b/util/libreboot-utils/lib/rand.c index 3a0a94bf..06d5f49e 100644 --- a/util/libreboot-utils/lib/rand.c +++ b/util/libreboot-utils/lib/rand.c @@ -81,7 +81,7 @@ win_lottery(char **buf) /* are u lucky? */ char *s1 = rmalloc(&size); char *s2 = rmalloc(&size); - if (scmp(s1, s2, BUFSIZ + 2, &rval) >= 0 && + if (scmp(s1, s2, BUFSIZ + 1, &rval) >= 0 && rval == 0) rval = 1; /* winner! */ else @@ -98,10 +98,16 @@ win_lottery(char **buf) /* are u lucky? */ void * rmalloc(size_t *rval) { + /* clamp rand to prevent modulo bias */ + size_t limit = SIZE_MAX - (SIZE_MAX % BUFSIZ); + if (if_err(rval == NULL, EFAULT)) return NULL; - rset(rval, sizeof(*rval)); + do { + rset(rval, sizeof(*rval)); + } while (*rval >= limit); + return mkrstr(*rval %= BUFSIZ); } -- cgit v1.2.1