From 3510f05fe82d633c6142abffaad8ab3252cb1ccf Mon Sep 17 00:00:00 2001 From: fowr <89118232+perdedora@users.noreply.github.com> Date: Wed, 16 Apr 2025 12:31:18 -0300 Subject: [PATCH] auth.php: use password_hash with bcrypt and password_verify for login --- inc/mod/auth.php | 20 +++++++++----------- 1 file changed, 9 insertions(+), 11 deletions(-) diff --git a/inc/mod/auth.php b/inc/mod/auth.php index 326f6f53..743543ef 100644 --- a/inc/mod/auth.php +++ b/inc/mod/auth.php @@ -46,22 +46,20 @@ function crypt_password($password) { global $config; // `salt` database field is reused as a version value. We don't want it to be 0. $version = $config['password_crypt_version'] ? $config['password_crypt_version'] : 1; - $new_salt = generate_salt(); - $password = crypt($password, $config['password_crypt'] . $new_salt . "$"); - return array($version, $password); + $hash = \password_hash($password, \PASSWORD_BCRYPT); + return [$version, $hash]; } -function test_password($password, $salt, $test) { +function test_password(string $db_hash, string|int $version, string $input_password): array { // Version = 0 denotes an old password hashing schema. In the same column, the // password hash was kept previously - $version = (strlen($salt) <= 8) ? (int) $salt : 0; - - if ($version == 0) { - $comp = hash('sha256', $salt . sha1($test)); + $version = (int)$version; + if ($version < 2) { + $ok = \hash_equals($db_hash, \crypt($input_password, $db_hash)); } else { - $comp = crypt($test, $password); + $ok = \password_verify($input_password, $db_hash); } - return array($version, hash_equals($password, $comp)); + return [$version, $ok]; } function generate_salt() { @@ -79,7 +77,7 @@ function login($username, $password) { list($version, $ok) = test_password($user['password'], $user['version'], $password); if ($ok) { - if ($config['password_crypt_version'] > $version) { + if ((int)$user['version'] < 2) { // It's time to upgrade the password hashing method! list ($user['version'], $user['password']) = crypt_password($password); $query = prepare("UPDATE ``mods`` SET `password` = :password, `version` = :version WHERE `id` = :id");