49

I'd like to add a "remember me" checkbox option before logging in.

What is the best way to securely store a cookie in the user's browser?

For example, Facebook have their "remember me" checkbox so that every time you enter facebook.com you are already logged in.

My current login uses simple sessions.

1
  • You may take a look at github.com/delight-im/PHP-Auth and its source to see how to implement a secure "remember me" feature. Basically, just store some very long (i.e. much entropy) string of random data in a cookie. When the user visits your page, check that "token" against your database where you track these tokens. If the token is valid, authenticate the user.
    – caw
    Commented Jul 13, 2016 at 0:01

1 Answer 1

68

Update (2017-08-13): To understand why we're separating selector and token, instead of just using a token, please read this article about splitting tokens to prevent timing attacks on SELECT queries.

I'm going to extract the strategy outlined in this blog post about secure long-term authentication since that covers a lot of ground and we're only interested in the "remember me" part.

Preamble - Database Structure

We want a separate table from our users' table that looks like this (MySQL):

CREATE TABLE `auth_tokens` (
    `id` integer(11) not null UNSIGNED AUTO_INCREMENT,
    `selector` char(12),
    `token` char(64),
    `userid` integer(11) not null UNSIGNED,
    `expires` datetime,
    PRIMARY KEY (`id`)
);

The important things here are that selector and token are separate fields.

After Logging In

If you don't have random_bytes(), just grab a copy of random_compat.

if ($login->success && $login->rememberMe) { // However you implement it
    $selector = base64_encode(random_bytes(9));
    $authenticator = random_bytes(33);

    setcookie(
        'remember',
         $selector.':'.base64_encode($authenticator),
         time() + 864000,
         '/',
         'yourdomain.com',
         true, // TLS-only
         true  // http-only
    );

    $database->exec(
        "INSERT INTO auth_tokens (selector, token, userid, expires) VALUES (?, ?, ?, ?)", 
        [
            $selector,
            hash('sha256', $authenticator),
            $login->userId,
            date('Y-m-d\TH:i:s', time() + 864000)
        ]
    );
}

Re-Authenticating On Page Load

if (empty($_SESSION['userid']) && !empty($_COOKIE['remember'])) {
    list($selector, $authenticator) = explode(':', $_COOKIE['remember']);

    $row = $database->selectRow(
        "SELECT * FROM auth_tokens WHERE selector = ?",
        [
            $selector
        ]
    );

    if (hash_equals($row['token'], hash('sha256', base64_decode($authenticator)))) {
        $_SESSION['userid'] = $row['userid'];
        // Then regenerate login token as above
    }
}

Details

We use 9 bytes of random data (base64 encoded to 12 characters) for our selector. This provides 72 bits of keyspace and therefore 236 bits of collision resistance (birthday attacks), which is larger than our storage capacity (integer(11) UNSIGNED) by a factor of 16.

We use 33 bytes (264 bits) of randomness for our actual authenticator. This should be unpredictable in all practical scenarios.

We store an SHA256 hash of the authenticator in the database. This mitigates the risk of user impersonation following information leaks.

We re-calculate the SHA256 hash of the authenticator value stored in the user's cookie then compare it with the stored SHA256 hash using hash_equals() to prevent timing attacks.

We separated the selector from the authenticator because DB lookups are not constant-time. This eliminates the potential impact of timing leaks on searches without causing a drastic performance hit.

22
  • 2
    Excellent work. Is it worth adding the expiry check in your code? Do you regenerate the token elsewhere in your code (e.g. 1 in 10 page loads)?
    – rybo111
    Commented Jun 13, 2015 at 10:19
  • Argh! This looks great and all, but I cannot get hash_equals to return true using any of these custom functions: php.net/hash_equals#115664
    – rybo111
    Commented Jun 13, 2015 at 18:13
  • 2
    @AgainMe Safe against any reasonable threat model. If someone can intercept/clone cookies (malware), there's nothing the server can or should do about that risk. See also: paragonie.com/blog/2016/03/… Commented Dec 12, 2016 at 5:03
  • 1
    Yes, they should only be used once. Commented Jun 11, 2018 at 17:07
  • 1
    I like this approach. The only thing I did differently was, rather than relying solely on $_SESSION['userid'], I also set a $_SESSION['selector'] to check against auth_tokens. This way I'm able to invalidate any active sessions (e.g. in the case of a password reset) without having to wait for the PHP session to expire. Commented Nov 9, 2019 at 6:18

Not the answer you're looking for? Browse other questions tagged or ask your own question.