From 9e7bb63615f8a9921e657027501f2aaf1be07454 Mon Sep 17 00:00:00 2001 From: Mark Hamstra Date: Tue, 17 Sep 2024 21:29:27 +0100 Subject: [PATCH] Improve generate password logic (#16521) ### What does it do? Re-up of #15894 Changes password generation method to be more secure. ### Why is it needed? Actually random generation. ### How to test Apply and see passwords still get generated. ### Related issue(s)/PR(s) Re-up of #15894 Fixes #15740 --------- Co-authored-by: crystaldaking Co-authored-by: Jan Peca --- core/src/Revolution/modUser.php | 23 +++++++++++++---------- 1 file changed, 13 insertions(+), 10 deletions(-) diff --git a/core/src/Revolution/modUser.php b/core/src/Revolution/modUser.php index 9cdee5042dd..f7c2b788469 100644 --- a/core/src/Revolution/modUser.php +++ b/core/src/Revolution/modUser.php @@ -898,28 +898,31 @@ public function removeLocks(array $options = []) public function generatePassword($length = null, array $options = []) { if ($length === null) { - $length = $this->xpdo->getOption('password_generated_length', null, 10, true); + $length = (int)$this->xpdo->getOption('password_generated_length', null, 10, true); } - $passwordMinimumLength = $this->xpdo->getOption('password_min_length', null, 8, true); + + $passwordMinimumLength = (int)$this->xpdo->getOption('password_min_length', null, 8, true); if ($length < $passwordMinimumLength) { $length = $passwordMinimumLength; } - $options = array_merge([ - 'allowable_characters' => 'abcdefghjkmnpqrstuvxyzABCDEFGHJKLMNPQRSTUVWXYZ23456789', - 'srand_seed_multiplier' => 1000000, - ], $options); - $ps_len = strlen($options['allowable_characters']); - srand((double)microtime() * $options['srand_seed_multiplier']); + if (empty($options['allowable_characters'])) { + $options['allowable_characters'] = 'abcdefghjkmnpqrstuvxyzABCDEFGHJKLMNPQRSTUVWXYZ23456789'; + } + + $allowableCharactersLength = strlen($options['allowable_characters']); + + $randomBytes = random_bytes($length); + $pass = ''; for ($i = 0; $i < $length; $i++) { - $pass .= $options['allowable_characters'][mt_rand(0, $ps_len - 1)]; + $randomIndex = ord($randomBytes[$i]) % $allowableCharactersLength; + $pass .= $options['allowable_characters'][$randomIndex]; } return $pass; } - /** * Send an email to the user *