TExcelTAD
Home › Web Application Security: OWASP Top 10, APIs & Authentication › Sessions, Session IDs and Session Fixation

Sessions, Session IDs and Session Fixation

After a successful login the server has to remember the result, because HTTP won't. The usual way is a session: the server keeps a record ("this is alice, logged in at 10:02, MFA done") and gives the browser a long random session id in a cookie. From then on, whoever presents the id is alice. That makes the session id as valuable as the password, and every way of learning, guessing or choosing it is an account takeover. This lesson covers the session lifecycle and then the attack whose fix is a single line that is surprisingly often missing: session fixation, where the attacker doesn't steal the victim's session id but plants one they already know.

Definitions

  • Session id: an unguessable random value (OWASP's Session Management Cheat Sheet asks for at least 64 bits of entropy, and at least 128 bits from a CSPRNG if you generate ids yourself), meaningful only as a key into the server's session store.
  • Lifecycle: created (anonymous, e.g. for a shopping cart), elevated at login and at MFA, used, and ended by logout, idle timeout, absolute timeout or server-side revocation.
  • Session fixation: the attacker obtains a valid id from the site, gets the victim's browser to use it (a link with ?sessionid=… on sites that accept ids in URLs, a cookie set from a sibling subdomain, or a shared computer), waits for the victim to log in, then uses the same id. It works when the server keeps the same id across login.
  • Session hijacking: stealing an existing id (XSS without HttpOnly, cleartext HTTP, logs, Referer leaks); covered in Session Hijacking and Credential Theft.

The attack, on a toy app

The app on 127.0.0.1 (in your sandbox) gives every visitor an anonymous session cookie. With argument vulnerable it marks that same session as logged in at /login; with fixed it issues a new id at login and deletes the old record. Session ids are random, so the transcript prints only whether they changed. The victim's browser is given the attacker's id directly with -b, standing in for whatever planting trick the attacker used.

bash · try it yourself
cat > app.py <<'PY'
import secrets, sys
from http.cookies import SimpleCookie
from urllib.parse import parse_qs
from wsgiref.simple_server import make_server, WSGIRequestHandler

FIXED = sys.argv[1] == "fixed"
SESSIONS = {}                                      # sid -> {"user": None | name}
PASSWORDS = {"alice": "lab-pass-alice"}

class Quiet(WSGIRequestHandler):
    def log_message(self, *args):
        pass

def new_session(user=None):
    sid = secrets.token_urlsafe(16)                # 128 bits from the OS CSPRNG
    SESSIONS[sid] = {"user": user}
    return sid

def app(environ, start_response):
    cookie = SimpleCookie(environ.get("HTTP_COOKIE", ""))
    sid = cookie["sid"].value if "sid" in cookie else None
    if sid not in SESSIONS:                         # unknown or missing id: never adopt it, make a new one
        sid = new_session()
    path, headers = environ["PATH_INFO"], [("Content-Type", "text/plain")]
    if path == "/login" and environ["REQUEST_METHOD"] == "POST":
        form = parse_qs(environ["wsgi.input"].read(int(environ.get("CONTENT_LENGTH") or 0)).decode())
        user, pw = form.get("user", [""])[0], form.get("password", [""])[0]
        if PASSWORDS.get(user) == pw:
            if FIXED:
                del SESSIONS[sid]                   # the one-line fix: rotate the id on privilege change
                sid = new_session(user)
            else:
                SESSIONS[sid]["user"] = user
            body = f"welcome {user}\n"
        else:
            body = "invalid username or password\n"
    elif path == "/logout":
        SESSIONS.pop(sid, None)
        sid = new_session()
        body = "logged out\n"
    else:
        user = SESSIONS[sid]["user"]
        body = f"account page of {user}: card ending 4242\n" if user else "not logged in\n"
    headers.append(("Set-Cookie", f"sid={sid}; Path=/; HttpOnly; SameSite=Lax"))
    start_response("200 OK", headers)
    return [body.encode()]

make_server("127.0.0.1", 8000, app, handler_class=Quiet).serve_forever()
PY
sid_from() { awk -F'\t' '$6 == "sid" {print $7}' "$1"; }
for mode in vulnerable fixed; do
  python3 app.py $mode &
  for i in $(seq 50); do curl -s -o /dev/null http://127.0.0.1:8000/ && break; sleep 0.1; done
  echo "=== $mode"
  curl -s -c attacker.txt http://127.0.0.1:8000/ >/dev/null                      # 1. attacker gets an id
  PLANTED=$(sid_from attacker.txt)
  printf '  victim logs in with the planted id: '
  curl -s -b "sid=$PLANTED" -c victim.txt -d 'user=alice&password=lab-pass-alice' http://127.0.0.1:8000/login
  [ "$(sid_from victim.txt)" = "$PLANTED" ] && echo "  victim's id after login: unchanged" || echo "  victim's id after login: new"
  printf '  attacker reuses the planted id: '
  curl -s -b "sid=$PLANTED" http://127.0.0.1:8000/account
  printf '  attacker invents an id: '
  curl -s -b "sid=attacker-chosen-123" -c invented.txt http://127.0.0.1:8000/account
  [ "$(sid_from invented.txt)" = "attacker-chosen-123" ] && echo "  invented id adopted" || echo "  invented id replaced by the server"
  kill %1; wait 2>/dev/null
done
=== vulnerable
  victim logs in with the planted id: welcome alice
  victim's id after login: unchanged
  attacker reuses the planted id: account page of alice: card ending 4242
  attacker invents an id: not logged in
  invented id replaced by the server
=== fixed
  victim logs in with the planted id: welcome alice
  victim's id after login: new
  attacker reuses the planted id: not logged in
  attacker invents an id: not logged in
  invented id replaced by the server

In the vulnerable mode the attacker's request with the planted id lands on alice's account page: the victim did all the work of logging in, into a session the attacker already knew. In the fixed mode the victim's browser receives a new id at login, the planted one is deleted, and the attacker's copy is worthless. Both modes already refuse ids the server never issued (the invented id is replaced), which blocks the crudest form of fixation on servers that would otherwise adopt any value.

The session lifecycle, done right

Event What the server does
First visit create an anonymous session only if needed; random id, HttpOnly; Secure; SameSite cookie
Login, MFA, role change new id, old record deleted; record user, auth_time, mfa in the session
Each request look up the id; check idle timeout (OWASP's cheat sheet cites 2–5 min for high-value apps, 15–30 min for low-risk ones) and absolute timeout (e.g. 4–8 h for a working day)
Sensitive action require recent authentication (auth_time within minutes) or step-up MFA
Logout delete the server-side record, expire the cookie
Password change, "log out everywhere", admin revoke delete all the user's sessions

How session weaknesses are detected

  • Testing: note the session cookie before login, log in, compare. If it is unchanged, test fixation as above. Replay a cookie after logout and after a password change; send an invented id; look for ids in URLs (;jsessionid=, ?sid=).
  • Randomness: collect a few thousand ids and check them for structure (sequential parts, timestamps, user ids, short length). Burp's Sequencer does this statistically.
  • Logs: one session id used from two IP addresses or user agents at once; a session whose user changes; logins whose session id was created by a different client.

How it is fixed

  • Regenerate the id on every privilege change (most frameworks have one call: session.cycle_key() in Django, session.regenerate() in Express, request.changeSessionId() in Java Servlet 3.1+, session_regenerate_id(true) in PHP), and never accept ids from URLs.
  • Keep sessions server-side (or use signed, short-lived tokens with a revocation story, see JWT), enforce timeouts, and invalidate on logout and password change.
  • Use __Host- cookies so a sibling subdomain can't plant one.

Pitfalls

  • Regenerating but copying the old id's record without deleting it leaves the planted id valid.
  • Logout that only deletes the cookie in the browser: the server-side session lives on for anyone who copied the id.
  • Client-side "sessions" in a signed cookie can't be revoked before they expire unless the server keeps a denylist or version number.

Practice

1. A site uses a Domain=lab.test session cookie and hosts user blogs on *.blogs.lab.test. How could fixation happen even with ids only in cookies?

A blog page can set a cookie for lab.test (a parent domain) with JavaScript or a response header, planting the attacker's id in the victim's browser. Fix: rotate ids at login, use a __Host- cookie, and host user content on a separate registrable domain.

2. What should happen to alice's other sessions when she changes her password?

All of them except (optionally) the current one should be deleted server-side, so an attacker who had stolen a session id or planted one loses access.

Test yourself

What is the essential fix for session fixation?

  1. Longer session ids
  2. Issue a new session id at login (and other privilege changes) and invalidate the old one
  3. HTTPS
  4. SameSite=Strict

In the vulnerable mode, why did the attacker see alice's account?

  1. They guessed her password
  2. The server marked the attacker-known session as logged in when the victim used it to log in
  3. The cookie had no HttpOnly
  4. CSRF

Logout only deletes the cookie in the browser. What is the risk?

  1. None
  2. The server-side session stays valid for anyone who has a copy of the id
  3. The user can't log in again
  4. Cookies are sent twice