Protect log in against timing attacks


Nov '15

May '16

2

823

1


Ole
2.4k

When doing log in scripts, it's easy to be vulnerable to timing attacks used to enumerate valid usernames. This is something you really do not want to happen.

When using the example in the documentation...

<?php

use Phalcon\Mvc\Controller;

class SessionController extends Controller
{
    public function loginAction()
    {
        $login    = $this->request->getPost('login');
        $password = $this->request->getPost('password');

        $user = Users::findFirstByLogin($login);
        if ($user) {
            if ($this->security->checkHash($password, $user->password)) {
                // The password is valid
            }
        }

        // The validation has failed
    }
}

... you are prone to this attack. The time it takes to load the page will be longer if the username is correct. This happens because it's now validating the password.

The defense against this attack is very easy though. By adding an else condition to the script if the username was not found, and do a dummy hash the page loading time, will be the same no matter if the user exists or not.

<?php

use Phalcon\Mvc\Controller;

class SessionController extends Controller
{
    public function loginAction()
    {
        $login    = $this->request->getPost('login');
        $password = $this->request->getPost('password');

        $user = Users::findFirstByLogin($login);
        if ($user) {
            if ($this->security->checkHash($password, $user->password)) {
                // The password is valid
            }
        } else {
            $this->security->hash(rand());
        }

        // The validation has failed
    }
}

This is very useful. Thanks.


Ole
2.4k

You're welcome :)

This is very useful. Thanks.

I have a question,

Is Throttling user login attempts removes timing attacks thread?

I have such check() method for checking logins:

public function check($credentials)
{
    // Check if the user exist
    $user = Users::findFirstByEmail($credentials['email']);
    if ($user == false) {
        $this->registerUserThrottling(0);
        throw new Exception('Wrong email/password combination');
    }

    // Check the password
    if (!$this->security->checkHash($credentials['password'], $user->password)) {
        $this->registerUserThrottling($user->id);
        throw new Exception('Wrong email/password combination');
    }

    $this->_setSession($this->_getIdentityRecord($user));
}

Is this safe against timing attacks?

Thanks