diff options
| author | Leah Rowe <leah@libreboot.org> | 2026-03-26 08:56:15 +0000 |
|---|---|---|
| committer | Leah Rowe <leah@libreboot.org> | 2026-03-26 08:56:15 +0000 |
| commit | cf16d07df97b8fbec9fe17b3f437ffc297af9ed2 (patch) | |
| tree | 1aa125b05c15a7888a7bb5d005616e63b792bec6 /util/libreboot-utils/lib/rand.c | |
| parent | dbc99be9a0b0b05b23f0f6e5623faae3876829e7 (diff) | |
rand: fix modulo bias in rmalloc
Signed-off-by: Leah Rowe <leah@libreboot.org>
Diffstat (limited to 'util/libreboot-utils/lib/rand.c')
| -rw-r--r-- | util/libreboot-utils/lib/rand.c | 10 |
1 files changed, 8 insertions, 2 deletions
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); } |
