From 5eb9f6b6d5677f18bd9aaf5d03c4631d7d478cc0 Mon Sep 17 00:00:00 2001 From: johnnyq Date: Tue, 14 Jul 2026 16:57:16 -0400 Subject: [PATCH] Fix weak RNG in key32gen (TOTP secret generation) Replace srand()/rand() with random_int() for cryptographically secure, unbiased key generation. The previous implementation seeded rand() from microtime(), making TOTP secrets predictable if the generation time could be approximated. Also removes modulo bias and dead while(1) wrapper. Output format is unchanged: 32 chars from the base32 alphabet (A-Z, 2-7), so existing TOTP enrollments are unaffected. --- functions/security.php | 13 ++++--------- 1 file changed, 4 insertions(+), 9 deletions(-) diff --git a/functions/security.php b/functions/security.php index 16d8eea6..eec3cdaf 100644 --- a/functions/security.php +++ b/functions/security.php @@ -16,15 +16,10 @@ function randomString(int $length = 16): string { // Older keygen function - only used for TOTP currently function key32gen() { - $chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"; - $chars .= "234567"; - while (1) { - $key = ''; - srand((float) microtime() * 1000000); - for ($i = 0; $i < 32; $i++) { - $key .= substr($chars, (rand() % (strlen($chars))), 1); - } - break; + $chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZ234567"; + $key = ''; + for ($i = 0; $i < 32; $i++) { + $key .= $chars[random_int(0, strlen($chars) - 1)]; } return $key; }