Here is the code which potentially can allow a timing attack
$user = getUserFromDatabase($input_username);
if ($user === false) { // potential timing attack
// user not exist
http_response_code(401);
echo json_encode(["message" => "invalid authentication"]);
exit;
}
if ( ! password_verify($input_password, $user["password_hash"])) { // potential timing attack
http_response_code(401);
echo json_encode(["message" => "invalid authentication"]);
exit;
}
ref. https://www.netguru.com/blog/authentication-with-login-and-password
I changed the code by checking the hash before checking if the user exists as suggested by above article.
I assigned an empty string as default hash in case the user doesn't exist.
The code works as expected but below post said empty hash is not a good idea.
Is using password_verify($password, "") to block access to an account secure?
$user = getUserFromDatabase($input_username);
$password_hash = $user["password_hash"] ?? "";
if ( ! password_verify($input_password, $password_hash) || $user === false) {
http_response_code(401);
echo json_encode(["message" => "invalid authentication"]);
exit;
}
Any suggestion how to fix this?