KHAGAN AYDIN

OWASP 2013 A2: Broken Authentication and Session Management

Attackers rarely break your password check. They walk around it.

· 11 min read

Broken Authentication and Session Management is a security vulnerability in how an application proves who a user is: how it stores passwords, how it remembers the user between requests, and how it lets them back in when they forget. It is number two on the 2013 OWASP Top 10.

It ranks this high because of what success gives the attacker. Injection hands over data. A broken login hands over a person. Once an attacker holds a valid session, every request they send is, as far as your application can tell, a request from your customer. The logs show a normal login and normal clicks.

What the bug is, in plain words

HTTP forgets everything between requests. So after a successful login, the server creates a session ID (a long random string), stores the user’s identity next to it, and gives the string to the browser in a cookie. From then on, whoever presents that string is that user. The session ID works like a cloakroom ticket: whoever holds it collects the coat.

So the item has two halves: protect the password, and protect the ticket. Real failures sit in the gaps: password tables that can be turned back into passwords, session IDs that leak or can be planted, sessions that never end, and reset or remember-me features weaker than the login they sit beside.

Four cases

LinkedIn, June 2012. About 6.5 million LinkedIn password hashes were posted on a Russian forum. They were hashed with SHA-1 (Secure Hash Algorithm 1) and no salt (a salt is a random value stored with each password and mixed in before hashing, so two users with the same password get different hashes). Roughly half had been cracked within days of the list appearing. Every hash on the list was unique, so duplicates had likely been stripped, and the real number of affected accounts was probably higher. Root cause: a fast, unsalted hash, which turns a stolen table into a list of passwords.

Adobe, October 2013. Adobe disclosed an attack on October 3 and put the number of affected customers at 2.9 million. By the end of the month it said attackers had taken encrypted passwords for about 38 million active users, and a file with more than 150 million records was circulating. The passwords were not hashed. Adobe confirmed Triple DES (Data Encryption Standard) encryption, and analysis of the file showed Electronic Codebook (ECB) mode with one key for every record, beside each user’s password hint in plain text. With one key and ECB, the same password always produces the same stored value. Researchers grouped identical values, read the hints beside them, and recovered the most common passwords without the key. The top one, 123456, belonged to nearly two million accounts. Root cause: reversible encryption where a salted one-way hash belonged, plus hints that gave the answers away.

Firesheep, October 2010. A free Firefox add-on turned session hijacking on open Wi-Fi into a click. It listened to traffic not protected by HTTPS (encrypted HTTP), picked out session cookies for 26 popular sites including Facebook, Twitter and Amazon, and let its user take over those sessions. It was downloaded more than 104,000 times in its first day. The add-on exposed a design many big sites shared: HTTPS for the login form, then the session cookie sent over plain HTTP on every page after it. Twitter and Facebook spent the next two years moving to HTTPS by default. Root cause: a session cookie on an unencrypted connection.

Apple, March 2013. On March 22, a flaw in Apple’s iForgot reset page let anyone reset an Apple ID password knowing only the account’s email address and the owner’s date of birth, by pasting a modified URL into the flow at the birth date step. Apple took the page offline that afternoon and restored it, fixed, that evening. Root cause: a reset flow that trusted a URL the user could edit, behind a birth date, which for many people is public.

Storing passwords

Vulnerable code

<?php
$hash = sha1($_POST['password']);
$stmt = $pdo->prepare('INSERT INTO users (email, password_sha1) VALUES (?, ?)');
$stmt->execute(array($_POST['email'], $hash));

SHA-1, MD5 and SHA-256 are designed to be fast, which is exactly wrong for passwords: a graphics card tests enormous numbers of guesses per second. Without a salt, one guess tests every account at once. Encryption is worse, because whoever gets the key gets every password, and the key usually lives next to the data.

Use a hash that is slow on purpose, salted per user, with a work factor you can raise as hardware gets faster: bcrypt, scrypt or PBKDF2 (Password-Based Key Derivation Function 2). PHP 5.5, released in June, wraps bcrypt in two simple functions.

Fixed code

<?php
// registration: bcrypt, with a random salt stored inside the result
$hash = password_hash($_POST['password'], PASSWORD_DEFAULT);

// login
$stmt = $pdo->prepare('SELECT id, password_hash FROM users WHERE email = ?');
$stmt->execute(array($_POST['email']));
$user = $stmt->fetch();
$ok = $user && password_verify($_POST['password'], $user['password_hash']);

On PHP 5.3.7 and later, the password_compat library provides the same functions. In Java, PBKDF2 ships with the platform:

import java.security.MessageDigest;
import java.security.SecureRandom;
import javax.crypto.SecretKeyFactory;
import javax.crypto.spec.PBEKeySpec;
import javax.xml.bind.DatatypeConverter;

public final class Passwords {
    private static final int ITERATIONS = 50000;

    public static String hash(char[] password) throws Exception {
        byte[] salt = new byte[16];
        new SecureRandom().nextBytes(salt);
        return ITERATIONS + ":" + DatatypeConverter.printHexBinary(salt) + ":"
            + DatatypeConverter.printHexBinary(derive(password, salt, ITERATIONS));
    }

    public static boolean verify(char[] password, String stored) throws Exception {
        String[] p = stored.split(":");
        byte[] salt = DatatypeConverter.parseHexBinary(p[1]);
        byte[] expected = DatatypeConverter.parseHexBinary(p[2]);
        return MessageDigest.isEqual(expected, derive(password, salt, Integer.parseInt(p[0])));
    }

    private static byte[] derive(char[] password, byte[] salt, int iterations) throws Exception {
        PBEKeySpec spec = new PBEKeySpec(password, salt, iterations, 160);
        return SecretKeyFactory.getInstance("PBKDF2WithHmacSHA1").generateSecret(spec).getEncoded();
    }
}

The iteration count is stored with each hash, so you can raise it later without breaking old records.

What most migration plans miss: you do not have to wait for every user to log in again. Wrap the old hashes tonight. A bcrypt hash of a SHA-1 hash is strong, and you can compute it from the values you already hold:

<?php
$rows = $pdo->query('SELECT id, password_sha1 FROM users WHERE password_sha1 IS NOT NULL')->fetchAll();
$upd = $pdo->prepare('UPDATE users SET password_hash = ?, legacy = 1, password_sha1 = NULL WHERE id = ?');
foreach ($rows as $r) {
    $upd->execute(array(password_hash($r['password_sha1'], PASSWORD_DEFAULT), $r['id']));
}

At login, for rows marked legacy, call password_verify(sha1($input), ...), and on success store a fresh password_hash($input) and clear the flag. The whole table is protected today, not over the next two years. Then purge old backups that still hold SHA-1 values, and stop storing password hints.

Three ways to steal or plant a session ID

In the URL. When a Java servlet container is not sure the browser accepts cookies, it appends ;jsessionid=... to every link passed through encodeURL, and PHP rewrites links the same way with session.use_trans_sid on. A session ID in a URL lands in server and proxy logs and browser history, travels to other sites in the Referer header (which tells a site which page linked to it), and gets pasted into emails. Turn it off.

Java (Servlet 3.0, web.xml):

<session-config>
    <session-timeout>15</session-timeout>
    <cookie-config>
        <http-only>true</http-only>
        <secure>true</secure>
    </cookie-config>
    <tracking-mode>COOKIE</tracking-mode>
</session-config>

PHP (php.ini):

session.use_only_cookies = 1
session.use_trans_sid = 0
session.cookie_httponly = 1
session.cookie_secure = 1
session.use_strict_mode = 1

session.use_strict_mode arrived in PHP 5.5.2 this year and is off by default. With it on, PHP refuses session IDs it did not create.

Planted before login (session fixation). The attacker visits your site and gets a valid, not yet logged in session ID. They get that ID into the victim’s browser, through a link if your site accepts IDs in URLs, or a cookie set from a sibling subdomain they control. The victim logs in, and your application marks the session as logged in without changing the ID. The attacker, who knew the ID all along, is now the victim.

The fix is a new ID at login and at every change of privilege.

Fixed code

<?php
if ($ok) {
    session_regenerate_id(true);   // new ID; true deletes the old session
    $_SESSION['user_id'] = $user['id'];
    $_SESSION['created'] = time();
    $_SESSION['last_seen'] = time();
    header('Location: /account');
    exit;
}

Pass true, or the old session survives on the server. In Java, on any servlet container:

HttpSession old = request.getSession(false);
if (old != null) {
    old.invalidate();
}
HttpSession session = request.getSession(true);
session.setAttribute("userId", user.getId());

Servlet 3.1, part of Java EE 7 released in June, adds request.changeSessionId() for the same job.

Read in transit or by script. Without the Secure flag, the browser sends the session cookie with any plain HTTP request to your domain. Without HttpOnly, any JavaScript on your page, including script injected through cross-site scripting, can read it.

This is the part teams miss. You moved the whole site to HTTPS and redirect every HTTP request. But a user who types your bare domain makes a first request over plain HTTP, and if the cookie lacks Secure, that request carries it before your redirect runs. An attacker on the same network can force that request by slipping an image pointing at http://yoursite.com/ into any unencrypted page the victim opens. The redirect protects the page, not the cookie. Set Secure, and add HTTP Strict Transport Security (HSTS), standardized in November 2012, which tells browsers to use only HTTPS for your domain:

Strict-Transport-Security: max-age=31536000

Chrome, Firefox and Opera honor it, and Safari has just added it. Internet Explorer does not, so Secure still does the real work.

Sessions that never end

A session needs two clocks on the server, an idle timeout and an absolute one, and logout must destroy the server session, not just the cookie:

<?php
session_start();
$now = time();
if (isset($_SESSION['user_id']) &&
    ($now > $_SESSION['last_seen'] + 900 || $now > $_SESSION['created'] + 28800)) {
    $_SESSION = array();
    session_destroy();
    header('Location: /login');
    exit;
}
$_SESSION['last_seen'] = $now;

Deleting the cookie only makes one browser forget. Anyone who copied the ID keeps using it. When a user changes their password, end their other sessions too: keep a counter on the user record, copy it into the session at login, compare it on every request, and increase it on password change.

Password reset is a second login

  • Generate the token from a secure random source: bin2hex(openssl_random_pseudo_bytes(32)) in PHP, SecureRandom in Java. Never md5($email . time()).
  • Store only a hash of the token, so a database leak does not hand out working reset links.
  • Expire it within an hour and accept it once.
  • Find the account from the token. Never take a user ID or email from the reset request.
  • Show the same message whether or not the email has an account.
  • After a reset, end all sessions and remember-me tokens, and email the user.
  • Birth dates and maiden names are lookups, not secrets.

One leak almost nobody checks: the token sits in the URL, and if the reset page loads third-party scripts, images or analytics, the browser sends that full URL to them in the Referer header. Keep the reset page free of outside content, and once the token checks out, move it into the server session and redirect to a clean URL.

Remember-me cookies

Vulnerable code

setcookie('remember', $user['id'] . ':' . md5($user['email']), time() + 31536000);

Anyone who knows a user’s ID and email can build that cookie. It works for a year, survives password changes, and cannot be revoked. A remember-me cookie is a long-lived password.

Fixed code

<?php
// at login, when the box is ticked
$token = bin2hex(openssl_random_pseudo_bytes(32));
$pdo->prepare('INSERT INTO remember_tokens (user_id, token_hash, expires_at)
               VALUES (?, ?, DATE_ADD(NOW(), INTERVAL 30 DAY))')
    ->execute(array($user['id'], hash('sha256', $token)));
setcookie('remember', $token, time() + 2592000, '/', '', true, true);

On a later visit, look the token up by its hash, delete it, start a fresh session with session_regenerate_id(true), and issue a new token. Ask for the password again before sensitive actions, and delete all tokens at logout and on password change.

Around all of this, slow down guessing: count failed logins per account and per address, add a growing delay, and give the same error for an unknown email and a wrong password. Hard lockouts let anyone lock out your customers, so prefer delays.

The fix, in short

Each part of this bug has its own fix, covered above. Together they come to five:

  1. Passwords. Store them with a slow, salted hash (bcrypt, scrypt or PBKDF2), and wrap any old fast hashes now.
  2. Session IDs. Keep them in cookies only, never in the URL, and issue a new one at login.
  3. Cookies. Mark them Secure and HttpOnly, and serve every page over HTTPS with HSTS.
  4. Session life. Set an idle timeout and an absolute timeout on the server, and make logout destroy the session.
  5. Reset and remember-me. Use random tokens that are stored hashed, expire quickly, work once and can be revoked.

How to test your own application

Use an intercepting proxy such as Burp Suite and two different browsers.

  1. Log in and compare the session cookie before and after. It must change.
  2. Copy browser A’s pre-login session ID into browser B, log in with B, then reload in A. If A is now logged in, you have fixation. Also send an invented ID; if the server adopts it, strict mode is off.
  3. Read every Set-Cookie header for session and remember-me cookies. Each needs Secure and HttpOnly.
  4. While logged in, type the plain http:// address and watch the proxy. If the session cookie rides on that request, it lacks Secure.
  5. Copy the session cookie, log out, and replay it:
curl -s -o /dev/null -w "%{http_code}\n" -H "Cookie: PHPSESSID=PASTE_VALUE" https://app.example.com/account

A 200 means logout did not end the session. Repeat after the idle timeout, and after changing the password in the other browser.

  1. Request two reset emails. The tokens should look random, work once and expire. List the outside hosts the reset page loads.
  2. Decode the remember-me cookie. If you can read an ID or email in it, you can probably forge it.
  3. In a test copy of the database, look at a stored password. $2y$10$ is bcrypt. Forty hex characters is SHA-1. Anything you can decrypt is a breach waiting for a date.

Checklist

  • Slow, salted hashing. Wrap legacy hashes now. No password hints.
  • Session IDs in cookies only, regenerated at login, marked Secure and HttpOnly.
  • HTTPS on every page, HSTS on top.
  • Server-side timeouts, and a logout that destroys the session.
  • Reset and remember-me tokens random, hashed, short-lived and revocable.

Your login form is the front door, and it is usually the best-guarded part of the house. The session cookie is the key everyone carries afterwards, the reset link is a spare key under the mat, and the password table is the copy you hope nobody finds. Attackers try whichever is easiest. Make all of them as hard as the door.