Skip to main content

Free 30-min security demo  — We'll scan your real code and show live findings, no commitment Book Now

Offensive360
Academy Session Fixation
Intermediate · 15 min

Session Fixation

Learn how attackers plant a known session ID before login and why regenerating it on auth is critical.

1 How Session Fixation Works

In a session fixation attack, the attacker tricks a victim into using a session ID that the attacker already knows — then after the victim logs in, the attacker uses that same ID to take over the authenticated session.

Attack steps:

  1. Attacker obtains a valid (unauthenticated) session ID from the server
  2. Attacker sends victim a link: https://example.com/login?sessionid=KNOWN_SESSION_ID
  3. Victim logs in — server authenticates but reuses the same session ID
  4. Attacker uses KNOWN_SESSION_ID and is now authenticated as the victim

Vulnerable code (PHP):

session_start();
// User logs in successfully
$_SESSION["user_id"] = $user["id"];
// BUG: session ID not regenerated after login!
// Attacker who set sessionid= before login now owns the session

This vulnerability is particularly dangerous when session IDs can be set via URL parameters or cookie injection.

2 Fix: Regenerate Session ID on Authentication

The definitive fix is to regenerate the session ID immediately after successful authentication. The old session ID is invalidated, so even if the attacker knew it, it is no longer valid.

Safe fix (PHP):

session_start();
if (authenticate($username, $password)) {
    // CRITICAL: regenerate session ID on login
    session_regenerate_id(true); // true = delete old session
    $_SESSION["user_id"] = $user["id"];
    $_SESSION["authenticated"] = true;
}

Node.js (express-session):

app.post("/login", (req, res) => {
  if (authenticate(req.body.username, req.body.password)) {
    req.session.regenerate((err) => {  // New session ID
      req.session.userId = user.id;
      req.session.authenticated = true;
      res.json({ success: true });
    });
  }
});

Defense checklist:

  • Always call session_regenerate_id / session.regenerate on successful login
  • Never accept session IDs from URL parameters
  • Set SameSite and HttpOnly on session cookies
  • Invalidate old session on regeneration

Knowledge Check

0/3 correct
Q1

In a session fixation attack, when does the attacker become authenticated?

Q2

What is the primary defense against session fixation?

Q3

Why is accepting session IDs from URL parameters especially dangerous?

Code Exercise

Regenerate Session on Login

The login handler authenticates users but does not regenerate the session ID, making it vulnerable to session fixation. Add session regeneration after authentication.

javascript