auth.php: use password_hash with bcrypt and password_verify for login

This commit is contained in:
fowr 2025-04-16 12:31:18 -03:00 committed by Zankaria
parent 24e43a5aa1
commit 3510f05fe8

View file

@ -46,22 +46,20 @@ function crypt_password($password) {
global $config; global $config;
// `salt` database field is reused as a version value. We don't want it to be 0. // `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; $version = $config['password_crypt_version'] ? $config['password_crypt_version'] : 1;
$new_salt = generate_salt(); $hash = \password_hash($password, \PASSWORD_BCRYPT);
$password = crypt($password, $config['password_crypt'] . $new_salt . "$"); return [$version, $hash];
return array($version, $password);
} }
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 // Version = 0 denotes an old password hashing schema. In the same column, the
// password hash was kept previously // password hash was kept previously
$version = (strlen($salt) <= 8) ? (int) $salt : 0; $version = (int)$version;
if ($version < 2) {
if ($version == 0) { $ok = \hash_equals($db_hash, \crypt($input_password, $db_hash));
$comp = hash('sha256', $salt . sha1($test));
} else { } 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() { function generate_salt() {
@ -79,7 +77,7 @@ function login($username, $password) {
list($version, $ok) = test_password($user['password'], $user['version'], $password); list($version, $ok) = test_password($user['password'], $user['version'], $password);
if ($ok) { if ($ok) {
if ($config['password_crypt_version'] > $version) { if ((int)$user['version'] < 2) {
// It's time to upgrade the password hashing method! // It's time to upgrade the password hashing method!
list ($user['version'], $user['password']) = crypt_password($password); list ($user['version'], $user['password']) = crypt_password($password);
$query = prepare("UPDATE ``mods`` SET `password` = :password, `version` = :version WHERE `id` = :id"); $query = prepare("UPDATE ``mods`` SET `password` = :password, `version` = :version WHERE `id` = :id");