Session Hijacking and Fixation: Why Django Rotates Your Session Key on Login — and How a Hand-Rolled Auth Flow Undoes It

Session Hijacking and Fixation: Why Django Rotates Your Session Key on Login — and How a Hand-Rolled Auth Flow Undoes It

Django Security Series — Post 12 | Series III: Authentication & Session
OWASP A07:2025 — Authentication Failures | Reading time: ~12 min

🧪 Run it yourself. This attack ships as a runnable lab in django-security-lab: two login views and a session the attacker fixes in advance. The hand-rolled view authenticates the user by writing to request.session directly — so the pre-login session id is never rotated, the attacker's known cookie becomes the victim's authenticated session, and a flag only the victim can see falls into the attacker's hands. The auth.login() view rotates the key on login, and the attacker is left holding an empty, anonymous session. Reproduce both from the command line with curl.

Post 11 was about the attacker at the door, guessing. This one is about the attacker who never guesses at all. Authentication proves who you are exactly once, at login; from then on, every request you make is trusted because it carries a small opaque value — the session cookie — that stands in for that proof. Steal it, or arrange in advance to know it, and you are the user. No password, no second factor, nothing to brute-force. The credential that matters after login is not the password. It is the session id, and most developers never think about it because Django manages it for them.

That is the whole tension of this post: Django manages the session id well, and the vulnerability is almost always something a developer did to step outside that management. This is the counter-intuitive part I want to land early: for most of this series the failure is a control Django doesn't provide (it won't throttle your login, it won't sanitise your HTML). Here the failure is a control Django already provides, silently, that a developer manages to switch off without realising it.

I learned to respect the session id building the password-reset flow for Petição Brasil. Resetting a password is the one moment you have to assume the account may already be compromised — that is why the user is resetting it — so the new password is not enough. I had to decide what happens to every session that was already open, and I chose to walk the whole session store, delete every session bound to that user, flush the current one, and refuse to auto-login afterwards. Only once I had written that did the model click: the reset does not "change the password," it revokes the sessions, because on a session-based app the live sessions are the credential and the password is just how you mint new ones. This post is about the attacker who gets one of those sessions by planting a known one before login (fixation), and why the defence is mostly a matter of not undoing what Django does for you.


The Attack: What It Is and How It Works

In session fixation, the attacker chooses the session id before the victim authenticates. Because a web app will happily create a session for an anonymous visitor — to hold a cart, a locale, a CSRF secret — an attacker can obtain a valid, empty session id of their own, then trick the victim's browser into adopting that same id (a crafted link, on an app that takes the session id from the URL — Django never does; an XSS write to document.cookie; a Set-Cookie on a shared subdomain). The victim then logs in normally. If the application authenticates the session it was handed — promoting that same id from anonymous to authenticated — the attacker's pre-chosen id is now a logged-in session for the victim, and the attacker, who has known the value all along, simply uses it. The victim typed their own password into their own browser and still handed their account to someone else.

The pivot that defeats fixation is trivial to state and easy to get wrong: rotate the session id at the privilege boundary. The moment an anonymous session becomes an authenticated one, throw away the old id and issue a fresh, random one. Any id the attacker fixed in advance is now stale — it was never promoted, so it stays anonymous — and the value the victim's browser now carries is one the attacker has never seen.

What makes this class quietly dangerous is that none of it involves malformed input. There is no payload, no injected syntax, no boundary to escape. Every request the attacker sends is a perfectly well-formed request carrying a perfectly valid session cookie. The server behaves exactly as designed. The defect is not in what the request contains; it is in whether the id in that cookie should still be trusted — a question the application answers implicitly, in the code it wrote around login, and usually never revisits.

The same id can also be lost after login. Session hijacking copies a session that is already live: on plain HTTP the cookie crosses the network in cleartext and anyone sharing the Wi‑Fi reads it off the packets (sidejacking), and a script injected through cross-site scripting (Post 2) can read it from document.cookie. The cookie flags Secure and HttpOnly close those two routes. And a session that never expires keeps a copied or fixed id working for as long as the attacker likes.


Real-World Incidents

Jenkins authentication plugins (2023)

On January 24, 2023, the Jenkins project published a security advisory with five entries that read almost word for word alike. The OpenId Connect, Azure AD, Bitbucket OAuth, Keycloak and OpenID authentication plugins each did "not invalidate the existing session on login", and for each the advisory gave the consequence: "This allows attackers to use social engineering techniques to gain administrator access to Jenkins." All five were rated High, and two had no fix when the advisory went out. Jenkins core invalidates the session on its own login; it had fixed a regression of exactly this bug in 2021 (CVE-2021-21671). Each plugin replaces that login with an OAuth or OpenID flow and, at the end of it, marks the user authenticated itself. In the OpenId Connect plugin (CVE-2023-24424) that last step wrote the authentication straight into Spring Security's context, and version 2.5 added what was missing just before it: invalidate the old session, create a new one.

The advisory does not report exploitation; the lesson is in the shape of the bug. In ATT&CK terms, using a known session cookie in place of the victim's credentials is T1550.004 (Use Alternate Authentication Material: Web Session Cookie); ATT&CK has no technique for the fixation step itself. For Django developers the parallel is exact. login() rotates the key the way Jenkins core invalidates its session, and an OAuth callback, an SSO handler or an impersonation feature that marks the session authenticated by hand skips the rotation, as all five plugins did.

Source: Jenkins Security Advisory 2023-01-24


Django's Default Protections

Django's session framework is one of the strongest defaults in the framework, and the fixation defence in particular is something most developers benefit from without ever knowing it exists.

Session-key rotation on login. When you call django.contrib.auth.login(request, user), Django replaces the session key. Internally, login() inspects the current session: if it is anonymous — the common case — it calls request.session.cycle_key(), which generates a brand-new random session key while carrying the existing session data across; if it is already authenticated as a different user, or under a session-auth hash that no longer matches, it flushes it entirely. Only a repeat login as the same user keeps the key, and that session was authenticated already. This is precisely the anti-fixation pivot described above — and it happens automatically, on the one line every Django tutorial tells you to write. login() also calls rotate_token() to cycle the CSRF secret at the same boundary, for the same reason.

What Django cannot do for you is rotate a key you route around. The cycle_key() protection lives inside login(). A hand-rolled auth flow that marks a session authenticated by writing to request.session directly, or an "impersonate user" / "switch account" feature that changes who the session belongs to without calling login(), never triggers the rotation — and reopens fixation exactly where Django had closed it.


The Vulnerable Pattern and the Fix

A hand-rolled login that never rotates the session

The canonical footgun is authenticating a user without going through login(). It usually appears when someone wants "more control" over the login response, or is porting an auth flow, and reconstructs by hand what login() does — but leaves out the part they could not see, the key rotation. The lab's vulnerable view writes the three session keys login() writes, after the same authenticate() call; the secure view replaces them with the call itself:

 def login_view(request):
     ...
     if user is None:
         return HttpResponse("invalid credentials\n", status=401)
-    # DANGER: these are the writes login() makes — but NOT its cycle_key()
-    # rotation. The session id the browser arrived with is promoted in place.
-    request.session["_auth_user_id"] = str(user.pk)
-    request.session["_auth_user_backend"] = "django.contrib.auth.backends.ModelBackend"
-    request.session["_auth_user_hash"] = user.get_session_auth_hash()
-    return HttpResponse(f"logged in as {user.username} (session NOT rotated)\n")
+    login(request, user)  # cycle_key(): new random session id, data preserved
+    return HttpResponse(f"logged in as {user.username} (session rotated)\n")

The vulnerable side "works" — the user is logged in, request.user resolves on the next request, every test that only checks whether login succeeds passes. What it silently drops is the rotation: the id the victim arrived with is promoted in place instead of being replaced, so an attacker who fixed it beforehand now holds an authenticated session. Nothing here looks like a vulnerability; it looks like a login view. The bug is the line that is not there. The fix is the one call: login() replaces the key, carries the session data across, and writes the _auth_* keys, including the session-auth hash that ties the session to the password so a password change can end it. Both views are in the lab: views_vulnerable.py and views_secure.py.

Every other privilege change

The rotation belongs at every boundary where the session changes owner or privilege, not only at login: impersonation start and stop, "switch account", step-up authentication. A change of user goes through login(), never through edits to the session. Step-up is the exception: login() for a user who is already logged in, under the same password hash, keeps the key, so once the extra check succeeds, call request.session.cycle_key() yourself, before granting the elevated state. A switch that only reassigns _auth_user_id does not even work — on the next request get_user() compares the stored session-auth hash with the new user's, finds the old one, and flushes the session — so a hand-rolled switch that does work has to rewrite all three keys, which is the hand-rolled login's mistake again: same id, new owner. login(request, target) flushes the old session and issues a new id instead; pass backend= when more than one authentication backend is configured, because target did not come from authenticate().


The Analyst's View

For a CySA+ analyst, session fixation is the cleanest case in the series of a vulnerability that is an absence. Rotation on login (cycle_key()) is a preventive control: it removes the attacker's foreknowledge of the id, so a value fixed before login is worthless after it. Nothing in the attack is malformed, so no input validation, WAF rule or log signature has anything to match. The one trace it leaves is a session id that was in use before a login and is still in use after it, and you can see that only if something records which session served each request.

The habit the attack rewards is treating login as a privilege boundary rather than a line of code. Every place where a session changes owner or gains privilege (the login view, an OAuth or SSO callback, impersonation, a step-up check) has to issue a fresh id, and the cheapest way to guarantee it is to cross that boundary through one function: login(), plus cycle_key() for a same-user step-up. When you review an auth flow, list every line that writes _auth_user_id and every call to login(); a session that becomes authenticated through anything else is the finding.


Catching It Automatically

Testing Your Defence

The fixation defence has a property that makes it unusually testable: the session key must change across login(), and the user must still be logged in afterwards — a check the test needs, because a view that flushed the session would change the key too. This is the lab's test:

def test_login_rotates_the_session_key_on_secure_view(self):
    # The session id must CHANGE across login() — and bob must stay logged in.
    c = Client()
    c.get("/session/whoami/")  # establish a pre-login session
    before = c.session.session_key
    self.assertIsNotNone(before)
    c.post("/session/secure/login/", {"username": "bob", "password": PASSWORD})
    self.assertNotEqual(before, c.session.session_key)  # cycle_key() rotated it
    self.assertIn(FLAG, c.get("/session/secret/").content.decode())  # still bob

Point it at /session/vulnerable/login/ and it fails: the key comes back unchanged. The lab's tests.py also runs the attack end to end — the attacker's fixed id reads bob's flag through the vulnerable view and is bounced by @login_required on the secure one.

Scanning It

The SAST tools come up empty here, and for a sharper reason than in the other posts where they miss: the flaw is not a dangerous call but a missing one. Bandit reports zero on the lab: there is no dangerous call anywhere in a login that skips login() (and none of the test-password noise other labs show, because this lab imports the shared cast's password instead of hard-coding one). Semgrep's community packs (p/django, p/python, p/owasp-top-ten) report zero too, and the registry/audit tier surfaces only unrelated findings (the XSS audit rule direct-use-of-httpresponse on the lab's plain HttpResponse views, and one maintainability rule) — nothing about session rotation. The missing cycle_key() call is not itself something a rule can point at, but a hand-rolled login has to write Django's private _auth_user_id key by hand, so a narrow custom rule matching request.session["_auth_user_id"] = ... would fire on the vulnerable view and stay silent on the secure one. This lab does not ship one; the test above is its gate.

Nothing we ran checks the rotation, and that is the honest CySA+ lesson of the post: some controls are verified by a test, not a tool. The session_key-must-change-across-login() assertion in the lab's tests.py is deterministic and fails the instant a hand-rolled login creeps back in; the dynamic other half is the curl probe — fix an id, ride it to the flag on the vulnerable view, watch it die (a 302) on the secure one. The captured scanner runs are committed under scans/; tests.py is the runnable proof.


The habit this post left me with: every change of user goes through login(), and every same-user elevation calls cycle_key().

Post 13 continues Series III with Weak Passwords and Validators, where the failure moves back to the credential itself — the app that accepts 123456, or the user's own email, as a password — and Django's AUTH_PASSWORD_VALIDATORS catch it only when every registration and change path actually calls them.

Further Reading

← Back to the series