Session Fixation

Difficulty: Advanced

Question

What is a session fixation attack and how do you prevent it in a web application?

Answer

Session fixation is an attack where the attacker plants a session ID they already know into the victim's browser, waits for the victim to log in, and then uses that same ID to act as the victim. It works when the server keeps the pre-login session ID after authentication. The fix is to issue a brand new session ID at every privilege change, especially immediately after a successful login, and destroy the old one.

How the attack works

  1. The attacker visits the site and gets a valid anonymous session ID, say sid=abc123.
  2. They get the victim's browser to use abc123. Common ways: a link with the ID in the URL (?PHPSESSID=abc123) on apps that accept URL session IDs, a cookie set from a compromised or attacker-controlled subdomain, or an XSS bug that writes document.cookie.
  3. The victim logs in normally. The server marks session abc123 as authenticated for that user but does not change the ID.
  4. The attacker, who still holds abc123, is now logged in as the victim.

The difference from session hijacking: in hijacking the attacker steals an ID after login; in fixation the attacker chooses the ID before login, so they never need to steal anything.

The core defence: regenerate on login

After verifying credentials, create a fresh session with a new random ID, copy over only what you need, and invalidate the old one. Most frameworks have a single call:

StackHow to rotate
Express (express-session)req.session.regenerate(cb)
PHPsession_regenerate_id(true)
Spring SecurityDone by default (changeSessionId strategy)
DjangoDone automatically by login() via cycle_key()
ASP.NET CoreIssue a new auth cookie on sign-in

Also rotate when privileges change: switching to an admin role, completing step-up MFA, or after a password change. On logout, destroy the session server side, not just the cookie.

Defence in depth

  • Never accept session IDs from URLs. Only read them from cookies. Disable session.use_trans_sid in PHP.
  • Strict mode: reject session IDs the server did not generate (session.use_strict_mode=1 in PHP). Express-session already ignores unknown IDs and creates a new session.
  • Cookie attributes: HttpOnly, Secure, SameSite=Lax or Strict, and the __Host- name prefix, which requires Secure, Path=/ and no Domain, so a sibling subdomain cannot overwrite it.
  • Timeouts: idle and absolute expiry limit how long a planted or stolen ID stays useful.
  • Fix XSS: an XSS bug lets an attacker set cookies and makes most session defences moot.

Where it still shows up

Custom auth code is the usual culprit: a developer sets req.session.userId = user.id after a password check and forgets to regenerate. It also appears in SSO callbacks and in apps that keep a guest cart session and then "upgrade" it at login. Merge the cart into the new session instead of promoting the old one.

Session fixation attack. The attack only works because the server keeps the same session ID after login.
  1. Attacker → Web server: Get anonymous session sid=abc123
  2. Attacker → Victim browser: Plant sid=abc123 via link or cookie
  3. Victim browser → Web server: Log in using sid=abc123
  4. Web server → Victim browser: Marks abc123 as authenticated
  5. Attacker → Web server: Request with sid=abc123 as the victim

Code examples

Regenerating the session after login in Express

import session from 'express-session';

app.use(session({
  name: '__Host-sid',
  secret: process.env.SESSION_SECRET,
  resave: false,
  saveUninitialized: false,
  cookie: { httpOnly: true, secure: true, sameSite: 'lax', path: '/' },
}));

app.post('/login', async (req, res, next) => {
  const user = await verifyCredentials(req.body.email, req.body.password);
  if (!user) return res.status(401).json({ error: 'Invalid credentials' });

  const cart = req.session.cart; // keep only what you need
  req.session.regenerate((err) => { // new ID, old one destroyed
    if (err) return next(err);
    req.session.userId = user.id;
    req.session.cart = cart;
    req.session.save((err) => (err ? next(err) : res.json({ ok: true })));
  });
});

regenerate() discards the pre-login session and issues a new random ID. The __Host- prefix stops subdomains from planting a cookie with the same name.

Key points

  • Fixation: attacker chooses the ID before login; hijacking: attacker steals it after login
  • Always regenerate the session ID on login and on any privilege change
  • Never accept session IDs from URL parameters
  • Use HttpOnly, Secure, SameSite and the __Host- prefix on session cookies
  • Destroy the server-side session on logout, not just the cookie

Common follow-up questions

  • How is session fixation different from session hijacking?
  • What does the __Host- cookie prefix guarantee?
  • Does using JWTs instead of server sessions remove this risk?
  • How would you test an application for session fixation?

Interview tips

  • Walk through the attack in four steps before giving the fix; it shows you understand why rotation works
  • Name the framework call you would use, such as req.session.regenerate or session_regenerate_id(true)
  • Mention rotating on privilege escalation too, not only on login

Concepts covered

Session Fixation, Session ID Regeneration, Session Hijacking, Cookie Attributes

More Web Security (OWASP, JWT, XSS, CSRF) questions