01 //Introduction
Session management is the backbone of web application authentication. Once a user logs in, the session is the only thing that keeps them authenticated across requests. Flaws in how sessions are created, maintained, and destroyed can give attackers full access to user accounts — without ever needing a password.
Session fixation is a particularly insidious attack because it doesn't require stealing a session — the attacker plants a session ID that the victim later authenticates. Combined with weak cookie configuration, missing expiration, and improper invalidation, session management vulnerabilities consistently appear in the OWASP Top 10.
- attacker sets the ID before login
- no need to steal anything
- works without XSS
- defense: session regeneration
- attacker steals an active ID
- requires XSS, sniffing, log access
- session already authenticated
- defense: secure cookie flags
- reuses expired / logged-out ID
- exploits weak invalidation
- works if server keeps sessions
- defense: server-side destroy
What makes session fixation different from session hijacking?
02 //Session Fixation Attacks
Session fixation occurs when an application accepts session identifiers from external sources — URL parameters, form fields, or injected cookies — and does not regenerate the session ID after authentication. The attacker obtains a valid session ID, tricks the victim into using it, and then shares the authenticated session.
1// VULNERABLE: Accepting session ID from URL
2app.get('/login', (req, res) => {
3 // Attacker sends: https://example.com/login?sessionId=ATTACKER_KNOWN_ID
4 if (req.query.sessionId) {
5 req.session.id = req.query.sessionId; // Using attacker-supplied ID!
6 }
7 res.render('login');
8});
9
10app.post('/login', async (req, res) => {
11 const { username, password } = req.body;
12 if (await authenticate(username, password)) {
13 // Session ID is NOT regenerated!
14 // The attacker-supplied ID is now authenticated
15 req.session.user = username;
16 req.session.authenticated = true;
17 res.redirect('/dashboard');
18 }
19});1# VULNERABLE: Django view without session regeneration
2from django.contrib.auth import authenticate, login
3
4def login_view(request):
5 if request.method == 'POST':
6 username = request.POST['username']
7 password = request.POST['password']
8 user = authenticate(request, username=username, password=password)
9 if user is not None:
10 # login() sets request.session['_auth_user_id']
11 # but if cycle_key() is not called, the session ID stays the same
12 login(request, user)
13 # Missing: request.session.cycle_key()
14 return redirect('/dashboard')
15 return render(request, 'login.html')
16
17# VULNERABLE: PHP session fixation
18# <?php
19# // Attacker visits: https://example.com/login.php?PHPSESSID=KNOWN_VALUE
20# session_start(); // Accepts the attacker's session ID
21# if (authenticate($username, $password)) {
22# $_SESSION['authenticated'] = true;
23# // session_regenerate_id(true) is NOT called!
24# }1// VULNERABLE: Cookie scoped too broadly
2app.use(session({
3 secret: process.env.SESSION_SECRET,
4 cookie: {
5 domain: '.example.com', // Any subdomain can set this cookie!
6 // attacker.example.com can inject: Set-Cookie: sessionId=KNOWN_VALUE; Domain=.example.com
7 }
8}));
9
10// If an attacker controls any subdomain (e.g. via subdomain takeover),
11// they can inject a session cookie for the parent domain.
12// When the victim visits the main app, they use the attacker's session ID.<meta http-equiv="Set-Cookie"> tags in injected HTML, or via document.cookie if they find an XSS vulnerability. Even cross-subdomain cookie injection is possible when the cookie's Domain attribute is set too broadly.Which of the following is NOT a session fixation attack vector?
03 //Session ID Generation
A session ID must be unpredictable enough that an attacker cannot guess or brute-force it. Weak session IDs — based on timestamps, sequential counters, or weak random number generators — make session prediction and fixation attacks trivial.
1// VULNERABLE: Timestamp-based session ID
2function generateSessionId() {
3 return Date.now().toString(36); // Predictable: based on current time
4}
5
6// VULNERABLE: Sequential session IDs
7let counter = 1000;
8function generateSessionId() {
9 return 'sess_' + (++counter); // Trivially guessable
10}
11
12// VULNERABLE: Math.random() is not cryptographically secure
13function generateSessionId() {
14 return Math.random().toString(36).substring(2);
15 // Internal state can be recovered from outputs
16}
17
18// VULNERABLE: Weak entropy
19function generateSessionId() {
20 const pid = process.pid;
21 const time = Date.now();
22 return require('crypto').createHash('md5')
23 .update(pid + ':' + time).digest('hex');
24 // Only two inputs, both guessable
25}1const crypto = require('crypto');
2
3// SECURE: Cryptographically random session ID
4function generateSessionId() {
5 return crypto.randomBytes(32).toString('hex');
6 // 256 bits of entropy — infeasible to brute-force
7}
8
9// SECURE: Using uuid v4 (backed by crypto.randomUUID)
10function generateSessionId() {
11 return crypto.randomUUID();
12}
13
14// SECURE: Custom format with sufficient entropy
15function generateSessionId() {
16 const bytes = crypto.randomBytes(32);
17 return 'sess_' + bytes.toString('base64url');
18 // base64url encoding: URL-safe, no padding
19}
20
21// The session ID should have at least 128 bits of entropy.
22// OWASP recommends a minimum of 128 bits (16 bytes).
23// Using 256 bits (32 bytes) provides a strong safety margin.Session ID Entropy Requirements
| Method | Entropy | Security Level |
|---|---|---|
| Date.now() | ~40 bits | Trivially predictable |
| Math.random() | ~52 bits | Not cryptographic |
| UUID v1 (time-based) | ~60 bits unique | Partially predictable |
| crypto.randomBytes(16) | 128 bits | OWASP minimum |
| crypto.randomBytes(32) | 256 bits | Recommended |
Why is Math.random() unsuitable for session ID generation?
05 //Session Lifecycle
Proper session management requires attention at every stage: creation, authentication binding, validation, privilege changes, and destruction. Many vulnerabilities arise from skipping steps in this lifecycle — particularly session regeneration and server-side invalidation.
1// VULNERABLE: No session regeneration on login
2app.post('/login', async (req, res) => {
3 if (await authenticate(req.body.username, req.body.password)) {
4 req.session.user = req.body.username;
5 req.session.role = 'user';
6 // Session ID stays the same! Fixation possible.
7 res.redirect('/dashboard');
8 }
9});
10
11// VULNERABLE: No regeneration on privilege escalation
12app.post('/admin/elevate', (req, res) => {
13 if (req.session.role === 'user' && verifyAdminCode(req.body.code)) {
14 req.session.role = 'admin';
15 // Same session ID now has admin privileges!
16 // If it was fixated or leaked as user-level, attacker gets admin
17 res.redirect('/admin');
18 }
19});
20
21// VULNERABLE: Client-side only logout
22app.post('/logout', (req, res) => {
23 res.clearCookie('sessionId');
24 // Session data still exists on the server!
25 // If attacker captured the session ID, it's still valid
26 res.redirect('/login');
27});
28
29// VULNERABLE: No absolute timeout
30app.use(session({
31 cookie: { maxAge: null }, // Never expires!
32 rolling: true, // Activity keeps extending it forever
33}));1// SECURE: Regenerate session ID on authentication
2app.post('/login', async (req, res) => {
3 if (await authenticate(req.body.username, req.body.password)) {
4 // Regenerate session — new ID, old data preserved
5 req.session.regenerate((err) => {
6 if (err) return res.status(500).send('Session error');
7 req.session.user = req.body.username;
8 req.session.role = 'user';
9 req.session.loginTime = Date.now();
10 req.session.lastActivity = Date.now();
11 res.redirect('/dashboard');
12 });
13 }
14});
15
16// SECURE: Regenerate on privilege change
17app.post('/admin/elevate', (req, res) => {
18 if (verifyAdminCode(req.body.code)) {
19 req.session.regenerate((err) => {
20 if (err) return res.status(500).send('Session error');
21 req.session.role = 'admin';
22 req.session.elevatedAt = Date.now();
23 res.redirect('/admin');
24 });
25 }
26});
27
28// SECURE: Server-side session destruction on logout
29app.post('/logout', (req, res) => {
30 req.session.destroy((err) => {
31 if (err) return res.status(500).send('Logout error');
32 res.clearCookie('__Host-sid');
33 res.redirect('/login');
34 });
35});
36
37// SECURE: Idle timeout AND absolute timeout
38function sessionTimeoutMiddleware(req, res, next) {
39 if (!req.session.loginTime) return next();
40
41 const now = Date.now();
42 const IDLE_TIMEOUT = 30 * 60 * 1000; // 30 minutes
43 const ABSOLUTE_TIMEOUT = 8 * 60 * 60 * 1000; // 8 hours
44
45 if (now - req.session.lastActivity > IDLE_TIMEOUT) {
46 return req.session.destroy(() => res.redirect('/login?reason=idle'));
47 }
48
49 if (now - req.session.loginTime > ABSOLUTE_TIMEOUT) {
50 return req.session.destroy(() => res.redirect('/login?reason=expired'));
51 }
52
53 req.session.lastActivity = now;
54 next();
55}req.session.regenerate() in Express, request.session.cycle_key() in Django). Don't manually delete and recreate — race conditions can cause the old session to persist briefly, and you may lose session data needed during the transition.When should you regenerate the session ID?
06 //Prevention Techniques
Preventing session management vulnerabilities requires a defense-in-depth approach. No single measure is sufficient — combine session regeneration, secure cookies, server-side storage, timeouts, and monitoring to build a robust session management system.
- Regenerate session ID on auth changes: Always call session regeneration on login, logout, privilege escalation, and password changes.
- Use secure cookie attributes: Set
HttpOnly,Secure,SameSite=Lax(or Strict), and use the__Host-prefix. - Generate cryptographically random IDs: Use
crypto.randomBytes(32)or framework defaults that use CSPRNGs. Never accept session IDs from URL parameters. - Implement server-side session storage: Store session data in Redis, Memcached, or a database — never in the cookie itself (signed cookies still leak data).
- Enforce idle and absolute timeouts: Set an idle timeout (15-30 minutes) and an absolute timeout (4-8 hours). Don't let rolling sessions live forever.
- Destroy sessions server-side on logout: Clear the server-side session data AND the client cookie. Never rely on client-side deletion alone.
- Reject session IDs from URLs: Never accept
?sessionId=or?PHPSESSID=parameters. Disable URL-based session tracking in framework config. - Bind sessions to client fingerprint: Optionally bind sessions to User-Agent or IP range to detect session migration between clients.
1// Session management security checklist as middleware
2const sessionSecurityMiddleware = {
3 // 1. Reject session IDs from URL parameters
4 rejectUrlSessions(req, res, next) {
5 if (req.query.sessionId || req.query.sid || req.query.PHPSESSID) {
6 return res.status(400).send('Session IDs in URLs are not accepted');
7 }
8 next();
9 },
10
11 // 2. Validate session integrity on each request
12 validateSession(req, res, next) {
13 if (!req.session || !req.session.user) return next();
14
15 // Check idle timeout
16 const idleLimit = 30 * 60 * 1000;
17 if (Date.now() - req.session.lastActivity > idleLimit) {
18 return req.session.destroy(() => res.redirect('/login'));
19 }
20
21 // Check absolute timeout
22 const absoluteLimit = 8 * 60 * 60 * 1000;
23 if (Date.now() - req.session.createdAt > absoluteLimit) {
24 return req.session.destroy(() => res.redirect('/login'));
25 }
26
27 // Update activity timestamp
28 req.session.lastActivity = Date.now();
29 next();
30 },
31
32 // 3. Concurrent session limiting
33 async limitConcurrentSessions(req, res, next) {
34 if (!req.session.user) return next();
35
36 const activeSessions = await sessionStore.findByUser(req.session.user);
37 const MAX_SESSIONS = 3;
38
39 if (activeSessions.length > MAX_SESSIONS) {
40 // Destroy oldest sessions
41 const toDestroy = activeSessions
42 .sort((a, b) => a.lastActivity - b.lastActivity)
43 .slice(0, activeSessions.length - MAX_SESSIONS);
44
45 for (const s of toDestroy) {
46 await sessionStore.destroy(s.id);
47 }
48 }
49 next();
50 }
51};Session Security Configuration Checklist
| Setting | Secure Value | Why It Matters |
|---|---|---|
| Cookie HttpOnly | true | Blocks XSS-based session theft |
| Cookie Secure | true | Prevents HTTP interception |
| Cookie SameSite | Lax or Strict | Blocks CSRF token reuse |
| Cookie Name Prefix | __Host- | Prevents subdomain injection |
| Session Storage | Server-side (Redis) | Client can't tamper with data |
| Idle Timeout | 15-30 minutes | Limits window for stolen sessions |
| Absolute Timeout | 4-8 hours | Forces periodic re-authentication |
| Session Regeneration | On every auth change | Defeats fixation attacks |
| URL Session IDs | Disabled | Prevents fixation via URL |
| Concurrent Sessions | Limited (2-3) | Detects session sharing/theft |
07 //Framework-Specific Patterns
Each web framework handles session management differently. Knowing the framework-specific APIs and their default security posture is critical for effective code review. Some frameworks regenerate sessions automatically on login, while others require explicit calls.
1const session = require('express-session');
2const RedisStore = require('connect-redis').default;
3const redis = require('redis');
4
5const redisClient = redis.createClient({
6 url: process.env.REDIS_URL,
7});
8
9app.use(session({
10 store: new RedisStore({ client: redisClient }),
11 name: '__Host-sid',
12 secret: process.env.SESSION_SECRET,
13 resave: false,
14 saveUninitialized: false,
15 cookie: {
16 httpOnly: true,
17 secure: true,
18 sameSite: 'lax',
19 maxAge: 1800000,
20 },
21}));
22
23// Regeneration pattern for Express
24function regenerateSession(req, userData) {
25 return new Promise((resolve, reject) => {
26 const oldSession = { ...req.session };
27 req.session.regenerate((err) => {
28 if (err) return reject(err);
29 // Restore non-auth data if needed
30 req.session.user = userData;
31 req.session.createdAt = Date.now();
32 req.session.lastActivity = Date.now();
33 resolve();
34 });
35 });
36}1# settings.py — Secure session configuration
2SESSION_ENGINE = 'django.contrib.sessions.backends.cache'
3SESSION_CACHE_ALIAS = 'sessions' # Use a dedicated Redis cache
4
5SESSION_COOKIE_HTTPONLY = True
6SESSION_COOKIE_SECURE = True
7SESSION_COOKIE_SAMESITE = 'Lax'
8SESSION_COOKIE_AGE = 1800 # 30 minutes
9SESSION_COOKIE_NAME = '__Host-sessionid'
10
11SESSION_EXPIRE_AT_BROWSER_CLOSE = True
12SESSION_SAVE_EVERY_REQUEST = True # Updates expiry on activity
13
14# Django's login() calls cycle_key() automatically since Django 1.0
15# but VERIFY this in your version and custom auth backends!
16
17from django.contrib.auth import login, logout
18
19def login_view(request):
20 form = AuthenticationForm(request, data=request.POST)
21 if form.is_valid():
22 user = form.get_user()
23 login(request, user) # cycle_key() called internally
24 return redirect('/dashboard')
25
26def privilege_escalation_view(request):
27 if verify_admin_token(request.POST['token']):
28 request.session.cycle_key() # Manual regeneration needed!
29 request.session['is_admin'] = True
30 return redirect('/admin')
31
32def logout_view(request):
33 logout(request) # Flushes session data + deletes cookie
34 return redirect('/login')1// Spring Security handles session fixation automatically
2// but you MUST verify the configuration
3
4@Configuration
5@EnableWebSecurity
6public class SecurityConfig {
7
8 @Bean
9 public SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
10 http
11 .sessionManagement(session -> session
12 // Default: migrateSession (copies attributes, new ID)
13 // Options: newSession, migrateSession, changeSessionId, none
14 .sessionFixation().changeSessionId()
15
16 // Limit concurrent sessions
17 .maximumSessions(2)
18 .maxSessionsPreventsLogin(false) // Expire oldest
19 .expiredUrl("/login?expired")
20 )
21 .rememberMe(remember -> remember
22 .tokenValiditySeconds(86400)
23 .useSecureCookie(true)
24 );
25
26 return http.build();
27 }
28}
29
30// DANGEROUS: Disabling session fixation protection
31// .sessionFixation().none() // NEVER DO THIS!
32
33// Cookie configuration in application.properties:
34// server.servlet.session.cookie.http-only=true
35// server.servlet.session.cookie.secure=true
36// server.servlet.session.cookie.same-site=lax
37// server.servlet.session.timeout=30m1from flask import Flask, session, redirect, request
2from flask_session import Session
3import redis
4import secrets
5
6app = Flask(__name__)
7
8# SECURE: Server-side session with Redis
9app.config['SESSION_TYPE'] = 'redis'
10app.config['SESSION_REDIS'] = redis.from_url(os.environ['REDIS_URL'])
11app.config['SESSION_COOKIE_HTTPONLY'] = True
12app.config['SESSION_COOKIE_SECURE'] = True
13app.config['SESSION_COOKIE_SAMESITE'] = 'Lax'
14app.config['SESSION_COOKIE_NAME'] = '__Host-session'
15app.config['PERMANENT_SESSION_LIFETIME'] = timedelta(minutes=30)
16
17Session(app)
18
19# Flask does NOT auto-regenerate sessions on login!
20# You must clear and recreate manually.
21
22@app.route('/login', methods=['POST'])
23def login():
24 if authenticate(request.form['username'], request.form['password']):
25 # Clear old session data
26 session.clear()
27 # Force a new session ID by modifying session
28 session['user'] = request.form['username']
29 session['created_at'] = datetime.utcnow().isoformat()
30 session.modified = True
31 return redirect('/dashboard')
32
33@app.route('/logout', methods=['POST'])
34def logout():
35 session.clear() # Removes data AND invalidates server-side
36 return redirect('/login')login(), Spring Security defaults to changeSessionId, but Express and Flask require manual regeneration. During code review, always check whether the framework handles regeneration automatically or if it needs explicit code.08 //Advanced Token Binding
Token binding adds an additional layer of security by tying a session to a specific client. If an attacker steals a session ID, they can't use it from a different browser or device because the session is bound to properties of the original client.
1const crypto = require('crypto');
2
3// Generate a fingerprint from stable client properties
4function generateFingerprint(req) {
5 const components = [
6 req.headers['user-agent'] || '',
7 req.headers['accept-language'] || '',
8 // Don't include full IP — it changes on mobile networks
9 // Use first two octets for rough geo-binding
10 req.ip.split('.').slice(0, 2).join('.'),
11 ];
12
13 return crypto
14 .createHash('sha256')
15 .update(components.join('|'))
16 .digest('hex');
17}
18
19// Bind session to fingerprint on creation
20app.post('/login', async (req, res) => {
21 if (await authenticate(req.body.username, req.body.password)) {
22 await regenerateSession(req, {
23 user: req.body.username,
24 fingerprint: generateFingerprint(req),
25 });
26 res.redirect('/dashboard');
27 }
28});
29
30// Validate fingerprint on each request
31function fingerprintMiddleware(req, res, next) {
32 if (!req.session.user) return next();
33
34 const currentFingerprint = generateFingerprint(req);
35 if (req.session.fingerprint !== currentFingerprint) {
36 console.warn('Session fingerprint mismatch', {
37 userId: req.session.user,
38 sessionId: req.sessionID,
39 expected: req.session.fingerprint,
40 actual: currentFingerprint,
41 });
42 return req.session.destroy(() => {
43 res.status(401).json({ error: 'Session invalidated' });
44 });
45 }
46 next();
47}1// Double-submit pattern: session ID in cookie + header must match
2// This prevents CSRF and verifies the client has read access to the cookie
3
4// On login, set both a session cookie and return a token
5app.post('/login', async (req, res) => {
6 if (await authenticate(req.body.username, req.body.password)) {
7 const sessionToken = crypto.randomBytes(32).toString('hex');
8
9 req.session.regenerate((err) => {
10 req.session.user = req.body.username;
11 req.session.csrfToken = sessionToken;
12
13 // Return the token — client must send it in X-Session-Token header
14 res.json({ csrfToken: sessionToken });
15 });
16 }
17});
18
19// Validate both cookie and header on each request
20function doubleSubmitMiddleware(req, res, next) {
21 if (!req.session.user) return next();
22
23 const headerToken = req.headers['x-session-token'];
24 if (!headerToken || headerToken !== req.session.csrfToken) {
25 return res.status(403).json({ error: 'Invalid session token' });
26 }
27 next();
28}09 //Distributed Session Management
In distributed systems with multiple application servers, session management becomes significantly more complex. Sessions must be shared across instances, invalidation must propagate quickly, and race conditions during regeneration can create security gaps.
1const session = require('express-session');
2const RedisStore = require('connect-redis').default;
3const { createClient } = require('redis');
4
5// Redis cluster for high availability
6const redisClient = createClient({
7 url: process.env.REDIS_CLUSTER_URL,
8 socket: {
9 reconnectStrategy: (retries) => Math.min(retries * 100, 5000),
10 },
11});
12
13const sessionStore = new RedisStore({
14 client: redisClient,
15 prefix: 'sess:',
16 ttl: 1800, // 30 minutes — Redis handles expiry
17});
18
19app.use(session({
20 store: sessionStore,
21 name: '__Host-sid',
22 secret: process.env.SESSION_SECRET,
23 resave: false,
24 saveUninitialized: false,
25 cookie: {
26 httpOnly: true,
27 secure: true,
28 sameSite: 'lax',
29 maxAge: 1800000,
30 },
31}));
32
33// Atomic session regeneration for distributed environments
34async function atomicRegenerate(req, userData) {
35 const oldSessionId = req.sessionID;
36
37 return new Promise((resolve, reject) => {
38 req.session.regenerate(async (err) => {
39 if (err) return reject(err);
40
41 // Explicitly destroy old session in Redis
42 // (regenerate creates new one but old may linger briefly)
43 await redisClient.del('sess:' + oldSessionId);
44
45 req.session.user = userData;
46 req.session.createdAt = Date.now();
47 req.session.lastActivity = Date.now();
48 resolve();
49 });
50 });
51}1// Global session invalidation (e.g., password change, security event)
2// Uses Redis pub/sub to notify all instances
3
4const INVALIDATION_CHANNEL = 'session:invalidate';
5
6// Subscribe all instances to invalidation events
7redisClient.subscribe(INVALIDATION_CHANNEL, (message) => {
8 const { userId, reason } = JSON.parse(message);
9 console.log(`Invalidating sessions for user ${userId}: ${reason}`);
10});
11
12// Invalidate all sessions for a user across all instances
13async function invalidateAllUserSessions(userId, reason) {
14 // Find all sessions for this user
15 const keys = await redisClient.keys('sess:*');
16
17 for (const key of keys) {
18 const sessionData = await redisClient.get(key);
19 if (!sessionData) continue;
20
21 const parsed = JSON.parse(sessionData);
22 if (parsed.user === userId) {
23 await redisClient.del(key);
24 }
25 }
26
27 // Notify all instances
28 await redisClient.publish(
29 INVALIDATION_CHANNEL,
30 JSON.stringify({ userId, reason, timestamp: Date.now() })
31 );
32}
33
34// Usage: on password change, force all other sessions to re-auth
35app.post('/change-password', async (req, res) => {
36 await updatePassword(req.session.user, req.body.newPassword);
37
38 const currentSessionId = req.sessionID;
39 await invalidateAllUserSessions(req.session.user, 'password_change');
40
41 // Regenerate current session so user stays logged in
42 await atomicRegenerate(req, { user: req.session.user });
43 res.json({ message: 'Password changed, other sessions logged out' });
44});10 //Real-World Case Studies
Session management vulnerabilities have caused major security breaches across the industry. These real-world cases illustrate why session security is critical and how subtle mistakes lead to serious compromise.
github.com via a subdomain they controlled. Because GitHub allowed broad cookie domains, the attacker planted a known session ID via a crafted page on a GitHub Pages site. When the victim logged in, GitHub did not regenerate the session, and the attacker gained access to the victim's account. GitHub fixed this by implementing strict session regeneration on login and restricting cookie scope.HttpOnly and overly broad cookie scope — 22 million users were affected.- Common theme: All three breaches could have been prevented by following basic session management best practices — regeneration, secure cookie attributes, and server-side invalidation.
- Detection is hard: Session management flaws are rarely caught by automated scanners. They require manual code review and understanding of authentication flow.
- Impact is severe: Session vulnerabilities lead directly to account takeover — the attacker becomes the victim with full access to their data and actions.
11 //Security Tools
Use these tools during code review and testing to identify session management vulnerabilities.
Session Security Testing Tools
| Tool | Purpose | Use Case |
|---|---|---|
| Burp Suite | Session analysis and manipulation | Test session fixation, cookie attributes, token entropy |
| OWASP ZAP | Automated session scanning | Detect missing cookie flags, session ID in URLs |
| Browser DevTools | Cookie inspection | Verify HttpOnly, Secure, SameSite attributes |
| Semgrep | Static analysis | Find missing session regeneration in code |
| curl | Manual HTTP testing | Test session behavior across login/logout flows |
| jwt.io | JWT debugging | Inspect token-based sessions for misconfigurations |
1# Step 1: Get a session ID (pre-authentication)
2curl -v https://example.com/login 2>&1 | grep 'Set-Cookie'
3# Note the session ID, e.g., sid=abc123
4
5# Step 2: Authenticate using that session ID
6curl -v -X POST https://example.com/login \
7 -H "Cookie: sid=abc123" \
8 -d "username=victim&password=password123" \
9 2>&1 | grep 'Set-Cookie'
10
11# Step 3: Check if the session ID changed after login
12# If the response does NOT contain a new Set-Cookie with a different sid,
13# the application is vulnerable to session fixation!
14
15# Step 4: Try accessing protected resource with the old session ID
16curl -v https://example.com/dashboard \
17 -H "Cookie: sid=abc123"
18# If this returns the dashboard, session fixation is confirmed.
19
20# Testing session invalidation on logout:
21curl -v -X POST https://example.com/logout \
22 -H "Cookie: sid=abc123"
23
24# Try reusing the session after logout:
25curl -v https://example.com/dashboard \
26 -H "Cookie: sid=abc123"
27# If this still works, server-side invalidation is broken.12 //Conclusion
When reviewing session management code, trace the entire lifecycle: how is the session created, how is the ID generated, what happens at login and logout, how are cookies configured, and what happens when a session expires. A single gap in this chain — a missing regeneration call, a missing cookie flag, or client-only logout — can hand over full account access to an attacker.