Session Fixation Attacks
What Is This Vulnerability?
Session fixation is an attack where the adversary sets a known session ID for a victim before they authenticate. Once the victim logs in, the attacker uses the pre-set session ID to hijack the authenticated session. This is possible when the application does not regenerate the session identifier after successful authentication.
Why It Happens
Many session management implementations reuse the same session ID before and after login. If the session ID can be set via URL parameters, cookies, or hidden form fields, an attacker can force a known session ID onto the victim's browser. After the victim authenticates, the server associates that same session ID with the authenticated user.
Example Code
app.post("/login", async (req, res) => {
const { username, password } = req.body;
const user = await verifyCredentials(username, password);
if (!user) return res.status(401).send("Invalid credentials");
// Session ID is NOT regenerated after login
req.session.userId = user.id;
req.session.role = user.role;
res.redirect("/dashboard");
});app.post("/login", async (req, res) => {
const { username, password } = req.body;
const user = await verifyCredentials(username, password);
if (!user) return res.status(401).send("Invalid credentials");
// Regenerate session to prevent fixation
req.session.regenerate((err) => {
if (err) return res.status(500).send("Session error");
req.session.userId = user.id;
req.session.role = user.role;
res.redirect("/dashboard");
});
});How Hackers Exploit It
The attacker obtains a valid session ID from the target application, then tricks the victim into using it (via a crafted link with the session ID in the URL, or by injecting the session cookie through XSS). The victim logs in, and the server associates the known session ID with their account. The attacker then uses the same session ID to access the victim's authenticated session.
How to Fix It
Always regenerate the session ID immediately after successful authentication using req.session.regenerate() or your framework's equivalent. Reject session IDs provided in URL parameters. Set cookies with the Secure, HttpOnly, and SameSite attributes. Implement session expiration and absolute timeout to limit the window of opportunity.