Migrating to password_verify

Written by Rob Allen - - Aggregated on Wednesday December 5, 2018

I've recently been updating a website that was written a long time ago that has not been touched in a meaningful way in many years. In addition to the actual work I was asked to do, I took the opportunity to update the password hashing routines.

This site is so old that the passwords are stored using MD5 hashes and that's not really good enough today, so I included updating to bcrypt hashing with password_hash() and password_verify() in my statement of work.

I've done this process before, but don't seem to have documented it, so thought I'd write it the steps I took in case it helps anyone else.

Updating existing passwords in the database

The first thing I did was hash all the passwords in the database to bcrypt with password_hash. As the current passwords are stored in hashed form, we don't have the original plain-text passwords, so we end up with bcrypt hashes containing the MD5 hashes. This is okay as we can handle this in the login process.

This update is a one-off PHP script:

$sql = 'SELECT id, password FROM user';
$rs = $database->execute($sql);
$rows = $rs->GetArray();
foreach ($rows as $row) {
    $sql = 'UPDATE user SET password = ? WHERE id = ?';
    $database->execute($sql, [
        password_hash($row['password'], PASSWORD_DEFAULT),
        $row['id'],
    ]);
}
echo "Passwords updated\n";

This website uses ADOdb so I just continued using it. The principles apply regardless of whether you're using PDO or any other database abstraction library.

I also had to update the database schema and change the password column from varchar(32) to varchar(255). The 255 characters is recommenced by the PHP manual page as it allows for the algorithm to change again.

Updating login

The authentication code needs updating to deal with bcrypt passwords. It currently looks like this:

$email = $_POST['email_address'];
$password = $_POST['password'];

$sql = "SELECT * FROM user where email = ? and password = ?";
$rs = $database->Execute($sql, array($email, md5($password)));
if ($rs->RecordCount() == 1) {
    // valid user
    $_SESSION['user'] = $rs->FetchRow();
}

In this code, there is a single step that only retrieves the user if and only if the email address and the MD5 of the plain text password match in the database record. If precisely one record is returned, it is assigned to the session.

To use password_verify(), we need a two step process:

  1. Retrieve the user via email address
  2. Check the retrieved hashed password against the password the user has supplied

Step 1

For the first step, I can retrieve the user by removing the password check from the SQL query:

$sql = "SELECT * FROM user where email = ?";
$rs = $database->Execute($sql, array($email));
if ($rs->RecordCount() == 1) {
    // ...

Step 2

I now need to check the password, which I do with password_verify():

if ($rs->RecordCount() == 1) {
    $user = $rs->FetchRow();
    $validPassword = password_verify($password, $user['password']);
    if ($validPassword) {
        // valid user
        $_SESSION['user'] = $user;
    }
}

This works great for all users who have an updated singly hashed plain text password, but none of my existing users can log in! This is because their bcrypt passwords are an MD5 hash of their plain text password.

To allow all users to log in, we need to also check for an MD5 hash if the password_verify() fails:

$validPassword = password_verify($password, $user['password']);
    if (!$validPassword) {
        // check for a legacy password
        $validPassword = password_verify(md5($password), $user['password']);
    }
    if ($validPassword) {
        // valid user
        $_SESSION['user'] = $user;

In this code, we MD5 the password supplied by the user and check again with password_verify against the database record. If it succeeds this time, then the credentials are verified.

Now all our users can successfully log in.

In place migrating

As the login process is the only time when we have the user's plain text password available to us, this is the ideal time to migrate the user's password in the database from a hashed MD5 string to a hashed plain text password.

I did this in the code where we checked for the MD5 version, but only if the check was successful:

$validPassword = password_verify($password, $user['password']);
    if (!$validPassword) {
        // check for a legacy password
        $validPassword = password_verify(md5($password), $user['password']);
        if ($validPassword) {
            // migrate user's record to bcrypt
            $sql = 'UPDATE user SET password = ? WHERE id = ?';
            $hashedPassword = password_hash($password, PASSWORD_DEFAULT);
            $database->Execute($sql, [$hashedPassword, $user['id']]);
        }
    }

Now, every time a user logs in with an MD5 hashed password, we will automatically re-hash their plain text password to bcrypt.

Updating password creation

Finally, I went through and fixed all the code that created a password in the database. This was in the user admin section and the user's change-password and reset-password pages.

In all cases, I changed:

$password = md5($new_password);

to

$password = password_hash($new_password, PASSWORD_DEFAULT);

password_hash() requires a second parameter which is the algorithm to use. Unless you have a specific reason not to, use PASSWORD_DEFAULT.

That's it

That's all the steps that I went though. I would expect that for applications actively maintained, that most if not all have been updated by now as PHP 5.5 came out in 2009! However it wouldn't surprise me if there's many sites out there that were built by an agency in the past where the client doesn't actively maintain it, but only asks for updates when changes are required – as in this case.


« Siblings Fighting - Eric L. Barnes

Laravel News - Laravel WebSockets Package Released »