Session management vulnerabilities: how a session should start, change and end
After someone signs in, a single random value stands in for their password on every request.
This guide explains in plain English how that value should be issued, when it must change, when it must stop working and who should be able to end it, with the standard behind each rule. It comes with a session lifecycle state diagram and six local checks you can run with Node.js alone.
In this guide
Session lifecycle state diagram and local session checks
An illustration on an invented account. Part 1 is a session lifecycle state diagram in plain text, and Part 2 lists every transition with what must happen to the identifier and the requirement behind it.
How to use itHide the instructions
Parts 3 to 6 are a Node.js lab with no installs: a session service in a flawed and a fixed version with a clock the checks can move, six checks that print every request and result, a regression test that fails on the flawed version, and steps to point the checks at your own application. Run it on your own machine, and use the checks only on applications you own or are authorised in writing to test.
session-management.txt
Introduction14 lines
Part 1: The session lifecycle state diagram25 lines
Part 2: Every transition, what happens to the identifier, and why116 lines
Part 3: The lab files609 lines
Part 4: Run the six checks against both versions186 lines
Part 5: The regression test71 lines
Part 6: Point the checks at your own application5 lines
Whole template1,060 lines
SESSION LIFECYCLE STATE DIAGRAM AND LOCAL SESSION CHECKS
An illustration. The account, its password, the one-time code and the reset code are invented, and the lab runs only on your own machine against its own local server. Use the checks on applications you own or are authorised in writing to test, with test accounts.
Written and run on: Node.js 26.0.0, the only version it was run on. It uses node:http, node:crypto, node:test and node:assert, which ship with Node.js, and the fetch() function built into Node.js, so there is nothing to install. Every output below was copied from that run. Timings will differ on your machine, and the ports are picked by the system and never printed.
Source names used below:
ASVS OWASP Application Security Verification Standard 5.0.0, chapter V7 Session Management, and V8 Authorization for 8.3.2. The level follows each requirement number.
OWASP SM OWASP Session Management Cheat Sheet
OWASP FP OWASP Forgot Password Cheat Sheet
OWASP AUTH OWASP Authentication Cheat Sheet
WSTG-SESS OWASP Web Security Testing Guide v4.2, session management tests (SESS-01 to SESS-09)
CWE MITRE CWE version 5.0
NIST NIST SP 800-63B-4, section 5 Session Management, with sections 2.1.3, 2.2.3 and 2.3.3 for the timeouts at each assurance level
================================================================
PART 1: THE SESSION LIFECYCLE STATE DIAGRAM
ANONYMOUS ---sign-in---> SIGNED IN ---reauthentication---> ELEVATED
no session, or a new identifier, new identifier,
pre-sign-in session the old one refused the old one refused
A privilege change in SIGNED IN or ELEVATED: new identifier, old one refused.
From SIGNED IN or ELEVATED, each of these events ends the session:
sign-out ....................................... ENDED: SIGNED OUT
no request for the idle limit .................. ENDED: IDLE-EXPIRED
absolute limit since sign-in or reauthentication ENDED: ABSOLUTELY EXPIRED
the user ends it or signs out everywhere,
the remembered device it came from is removed,
an administrator ends it,
the account is disabled or deleted ............. ENDED: REVOKED
A password reset or other factor change ends the account's other
sessions (ENDED: REVOKED) when the user takes the option ASVS 7.4.3 asks
for, or by default, which is what this page recommends (see T8).
From any ENDED state: the server refuses that identifier from then on.
Signing in again starts at SIGNED IN with a new identifier.
The rule under every arrow: the server decides. Clearing a cookie,
closing a browser or a cookie's own expiry date changes nothing on the
server, so none of them counts as an ending.
================================================================
PART 2: EVERY TRANSITION, WHAT HAPPENS TO THE IDENTIFIER, AND WHY
T1 ANONYMOUS -> SIGNED IN
Event: sign-in succeeds, on every route that signs someone in
Identifier: issue a new one; destroy the pre-sign-in one so it is refused
Basis: ASVS 7.2.4 (Level 1); OWASP SM, renew the session ID after any
privilege level change; WSTG-SESS-03; CWE-384; NIST 5.1, the
secret is generated in direct response to an authentication event
Lab check: 1
T2 SIGNED IN -> ELEVATED
Event: the user re-authenticates, for example before changing sensitive
account attributes (ASVS 7.5.1, Level 2) or before a highly
sensitive transaction (ASVS 7.5.3, Level 3, which also accepts
secondary verification)
Identifier: issue a new one and terminate the current one; both timers restart
Basis: ASVS 7.2.4 (Level 1), a new session token on re-authentication;
NIST 5.2, a successful reauthentication SHALL reset both timeouts
Lab check: none
T3 SIGNED IN or ELEVATED -> the same state, new identifier
Event: a privilege change: a role granted or removed, a switch to an
administrator role, a password change
Identifier: renew it and destroy the old one
Basis: OWASP SM, renew after any privilege level change; ASVS 8.3.2
(Level 3), changes to the values behind authorisation decisions
applied immediately, or where they cannot be (such as data in
self-contained tokens), mitigating controls that alert on an action
the consumer is no longer authorised to do and revert the change
This page: when rights are removed, the change should reach sessions that
are already open, not only new ones
Lab check: none
T4 SIGNED IN or ELEVATED -> the same state, new identifier (optional)
Event: the renewal timeout passes, whatever the activity
Identifier: issue a new one; accept the previous one only for a short safety
interval, then invalidate it
Basis: OWASP SM, renewal timeout
Lab check: none
T5 SIGNED IN or ELEVATED -> ENDED: SIGNED OUT
Event: sign-out
Identifier: delete the session on the server; revoke every identifier of that
sign-in together, including rotated ones still in a grace period;
then clear the browser's copy
Basis: ASVS 7.4.1 (Level 1), 7.4.4 (Level 2); OWASP SM, logout button;
WSTG-SESS-06; CWE-1465; NIST 5.1, a readily accessible way to
log off (SHOULD)
Lab check: 2
T6 SIGNED IN or ELEVATED -> ENDED: IDLE-EXPIRED
Event: no request for the idle limit, measured on the server
Identifier: refuse and delete it; the user signs in again
Basis: ASVS 7.3.1 (Level 2); OWASP SM, idle timeout; WSTG-SESS-07;
NIST 5.2, when either timeout expires the session SHALL be
terminated; CWE-1463
Lab check: 4
T7 SIGNED IN or ELEVATED -> ENDED: ABSOLUTELY EXPIRED
Event: the absolute limit passes since sign-in or the last
reauthentication, however active the session is
Identifier: refuse and delete it
Basis: ASVS 7.3.2 (Level 2); OWASP SM, absolute timeout; NIST 5.2; CWE-1463
Lab check: 4
T8 every session of the account -> ENDED: REVOKED
Event: a password reset or change, or any other authentication factor
changed or removed
Identifier: end the other sessions (ASVS: offer the option; OWASP FP: ask the
user, or do it automatically; this page: end them by default);
the session making the change gets a new identifier
Basis: ASVS 7.4.3 (Level 2); OWASP FP; CWE-1466; OWASP SM, a password
change is a privilege change
Lab check: 3 (the lab ends every session and forgets every remembered
device after a reset)
T9 chosen sessions -> ENDED: REVOKED
Event: the user ends one session, or signs out everywhere, from the
account page
Identifier: delete the chosen sessions on the server, after the user
authenticates again with at least one factor
Basis: ASVS 7.5.2 (Level 2); OWASP SM, simultaneous session logons
Lab check: 5
T10 sessions started on a remembered device -> ENDED: REVOKED
Event: the user removes the remembered device
Identifier: refuse the device token and end every session started through it
Basis: ASVS 7.4.1 (Level 1) for each session ended; NIST 5.1,
remember-my-browser features SHALL NOT be used instead of
authentication, with one AAL2 reauthentication exception; OWASP
AUTH, remembered-device cookies are risk signals. Ending the
device's sessions is this page's design, not a numbered requirement.
Lab check: 6
T11 one user's sessions, or everyone's -> ENDED: REVOKED
Event: an administrator ends them
Basis: ASVS 7.4.5 (Level 2)
Lab check: none
T12 every session of the account -> ENDED: REVOKED
Event: the account is disabled or deleted
Basis: ASVS 7.4.2 (Level 1)
Lab check: none
T13 ANONYMOUS -> ANONYMOUS
Event: a request carries an identifier the server never issued
Identifier: do not accept it; issue a new one and raise an alert
Basis: OWASP SM, strict session management
Lab check: none
T14 any ENDED state, when the session is a self-contained token
Event: any ending above
Identifier: the token may otherwise remain valid until it expires, so it needs
a solution such as a list of terminated tokens, disallowing tokens
produced before a per-user date and time, or rotating a per-user
signing key
Basis: ASVS V7.4 and 7.4.1 (Level 1)
Lab check: none
================================================================
PART 3: THE LAB FILES
================================================================
Make an empty folder, save the four files below into it with the names shown, and open a terminal in that folder.
The lab's idle limit (20 minutes) and absolute limit (600 minutes) are values picked for the illustration. They are not a recommendation: set yours from your own documented risk analysis, as ASVS 7.3.1 and 7.3.2 ask.
================================================================
FILE 1 OF 4: session-lab-server.mjs
================================================================
// session-lab-server.mjs: a made-up account service whose sessions start,
// rotate, get listed, end and time out, in a flawed version and a fixed
// version. Illustration only. It listens on 127.0.0.1, keeps everything in
// memory and holds one invented account. Each mistake in the flawed version
// is marked FLAWED next to the fixed behaviour.
import { createServer } from 'node:http'
import { createHash, randomBytes, timingSafeEqual } from 'node:crypto'
// The lab's own limits, picked for the illustration. They are not a
// recommendation: set yours from your own documented risk analysis.
export const IDLE_LIMIT_MINUTES = 20
export const ABSOLUTE_LIMIT_MINUTES = 600
// The invented account. A real service stores a password hash, never the
// password. The code stands in for a one-time code from an authenticator
// app, and the reset code for the link a password reset would email.
export const LAB_ACCOUNT = {
email: 'sam@example.com',
password: 'correct horse lab',
code: '246810',
resetCode: 'reset-code-from-email',
}
// A clock the checks move forward, so timeouts are tested without waiting.
export function createLabClock() {
let minutes = 0
return {
now: () => minutes,
advance: (byMinutes) => { minutes = minutes + byMinutes },
}
}
const ROUTES = {
'GET /start': startAnonymousSession,
'POST /sign-in': signIn,
'POST /sign-out': signOut,
'GET /account': showAccount,
'GET /account/sessions': listSessions,
'POST /account/sessions/end': endSessionByHandle,
'GET /account/devices': listDevices,
'POST /account/devices/remove': removeDevice,
'POST /password-reset': resetPassword,
}
// version is 'flawed' or 'fixed'. The system picks a free port.
export function startSessionLab(version, clock) {
const lab = { version: version, clock: clock, account: Object.assign({}, LAB_ACCOUNT), sessions: new Map(), devices: new Map() }
const server = createServer((request, response) => {
answerRequest(lab, request, response).catch((error) => sendJson(response, 500, { error: String(error) }))
})
return new Promise((resolve) => {
server.listen(0, '127.0.0.1', () => {
lab.server = server
lab.port = server.address().port
resolve(lab)
})
})
}
async function answerRequest(lab, request, response) {
const handler = ROUTES[request.method + ' ' + request.url]
if (!handler) return sendJson(response, 404, { error: 'not-found' })
const body = request.method === 'POST' ? await readJson(request) : {}
const reply = handler(lab, request, body)
if (reply.cookies && reply.cookies.length) response.setHeader('Set-Cookie', reply.cookies)
sendJson(response, reply.status, reply.body)
}
// Tokens are 32 random bytes. The server keeps only a SHA-256 hash of each
// one, and the account page names sessions and devices by a separate public
// handle, so no page ever shows another session's token.
function newToken() {
return randomBytes(32).toString('base64url')
}
function newHandle() {
return randomBytes(6).toString('hex')
}
function hashOf(text) {
return createHash('sha256').update(text).digest()
}
function sameSecret(given, expected) {
return timingSafeEqual(hashOf(String(given)), hashOf(expected))
}
// Real deployments add Secure; it is left off so the lab runs over plain http.
function sessionCookie(token) {
return 'sid=' + token + '; Path=/; HttpOnly; SameSite=Lax'
}
function deviceCookie(token) {
return 'device=' + token + '; Path=/; HttpOnly; SameSite=Lax'
}
function clearedCookie(name) {
return name + '=; Path=/; Max-Age=0'
}
function createSession(lab, email, deviceHandle, request) {
const token = newToken()
const now = lab.clock.now()
const session = { handle: newHandle(), email: email, deviceHandle: deviceHandle, device: readUserAgent(request), createdAt: now, lastSeenAt: now, hidden: false }
lab.sessions.set(hashOf(token).toString('hex'), session)
return token
}
function hasTimedOut(session, now) {
const idleMinutes = now - session.lastSeenAt
const ageMinutes = now - session.createdAt
return idleMinutes >= IDLE_LIMIT_MINUTES || ageMinutes >= ABSOLUTE_LIMIT_MINUTES
}
// The live session named by this request's sid cookie, or null.
function findSession(lab, request) {
const key = hashOf(readCookie(request, 'sid')).toString('hex')
const session = lab.sessions.get(key)
if (!session) return null
// FLAWED: the server never times a session out.
if (lab.version === 'fixed' && hasTimedOut(session, lab.clock.now())) {
lab.sessions.delete(key)
return null
}
session.lastSeenAt = lab.clock.now()
return session
}
function findSignedInSession(lab, request) {
const session = findSession(lab, request)
return session && session.email ? session : null
}
function deleteSessions(lab, shouldDelete) {
for (const entry of lab.sessions) {
if (shouldDelete(entry[1])) lab.sessions.delete(entry[0])
}
}
function notSignedIn() {
return { status: 401, body: { error: 'not-signed-in' } }
}
function startAnonymousSession(lab, request) {
const token = createSession(lab, null, null, request)
return { status: 200, body: { result: 'anonymous-session' }, cookies: [sessionCookie(token)] }
}
function signIn(lab, request, body) {
const account = lab.account
if (body.email !== account.email || !sameSecret(body.password, account.password)) {
return { status: 401, body: { error: 'wrong-email-or-password' } }
}
const device = findDevice(lab, request)
if (!device && !sameSecret(body.code, account.code)) return { status: 401, body: { error: 'code-needed' } }
const cookies = []
let deviceHandle = device ? device.handle : null
if (!device && body.rememberDevice) {
const remembered = rememberDevice(lab, request)
deviceHandle = remembered.handle
cookies.push(deviceCookie(remembered.token))
}
return startSignedInSession(lab, request, deviceHandle, cookies)
}
function startSignedInSession(lab, request, deviceHandle, cookies) {
const earlier = findSession(lab, request)
if (lab.version === 'flawed' && earlier) {
// FLAWED: the identifier from before sign-in now carries the account.
earlier.email = lab.account.email
earlier.deviceHandle = deviceHandle
return { status: 200, body: { result: 'signed-in' }, cookies: cookies }
}
if (earlier) deleteSessions(lab, (session) => session === earlier)
const token = createSession(lab, lab.account.email, deviceHandle, request)
cookies.push(sessionCookie(token))
return { status: 200, body: { result: 'signed-in' }, cookies: cookies }
}
function signOut(lab, request) {
const session = findSession(lab, request)
// FLAWED: only the browser's cookie is cleared; the server keeps the session.
if (lab.version === 'fixed' && session) deleteSessions(lab, (each) => each === session)
return { status: 200, body: { result: 'signed-out' }, cookies: [clearedCookie('sid')] }
}
function showAccount(lab, request) {
const session = findSignedInSession(lab, request)
if (!session) return notSignedIn()
return { status: 200, body: { email: session.email } }
}
function listSessions(lab, request) {
const current = findSignedInSession(lab, request)
if (!current) return notSignedIn()
const now = lab.clock.now()
const rows = []
for (const session of lab.sessions.values()) {
if (session.email !== current.email || session.hidden) continue
if (lab.version === 'fixed' && hasTimedOut(session, now)) continue
rows.push({ handle: session.handle, device: session.device, current: session === current })
}
return { status: 200, body: { sessions: rows } }
}
// Ending a session asks for the password again (ASVS 5.0 requirement 7.5.2).
function endSessionByHandle(lab, request, body) {
const current = findSignedInSession(lab, request)
if (!current) return notSignedIn()
const isTarget = (session) => session.email === current.email && session.handle === body.handle
if (lab.version === 'flawed') {
// FLAWED: no password asked for, and the session is only hidden from the list.
for (const session of lab.sessions.values()) if (isTarget(session)) session.hidden = true
return { status: 200, body: { result: 'ended' } }
}
if (!sameSecret(body.password, lab.account.password)) return { status: 403, body: { error: 'password-needed' } }
deleteSessions(lab, isTarget)
return { status: 200, body: { result: 'ended' } }
}
function rememberDevice(lab, request) {
const token = newToken()
const device = { handle: newHandle(), email: lab.account.email, name: readUserAgent(request), hidden: false }
lab.devices.set(hashOf(token).toString('hex'), device)
return { token: token, handle: device.handle }
}
function findDevice(lab, request) {
return lab.devices.get(hashOf(readCookie(request, 'device')).toString('hex')) || null
}
function forgetDevices(lab, shouldForget) {
for (const entry of lab.devices) {
if (shouldForget(entry[1])) lab.devices.delete(entry[0])
}
}
function listDevices(lab, request) {
const current = findSignedInSession(lab, request)
if (!current) return notSignedIn()
const rows = []
for (const device of lab.devices.values()) {
if (device.email === current.email && !device.hidden) rows.push({ handle: device.handle, name: device.name })
}
return { status: 200, body: { devices: rows } }
}
function removeDevice(lab, request, body) {
const current = findSignedInSession(lab, request)
if (!current) return notSignedIn()
const isTarget = (device) => device.email === current.email && device.handle === body.handle
if (lab.version === 'flawed') {
// FLAWED: hidden from the list, but the device still skips the code and its sessions stay signed in.
for (const device of lab.devices.values()) if (isTarget(device)) device.hidden = true
return { status: 200, body: { result: 'removed' } }
}
forgetDevices(lab, isTarget)
deleteSessions(lab, (session) => session.email === current.email && session.deviceHandle === body.handle)
return { status: 200, body: { result: 'removed' } }
}
// How a reset is requested and how its link is protected belong to the
// sign-in flows; this lab covers what a reset must do to sessions.
function resetPassword(lab, request, body) {
const account = lab.account
if (body.email !== account.email || !sameSecret(body.resetCode, account.resetCode)) {
return { status: 403, body: { error: 'bad-reset-code' } }
}
account.password = body.newPassword
account.resetCode = newToken()
// FLAWED: the password changes, but every session stays signed in.
if (lab.version === 'fixed') {
deleteSessions(lab, (session) => session.email === account.email)
forgetDevices(lab, (device) => device.email === account.email)
}
return { status: 200, body: { result: 'password-changed' } }
}
function readCookie(request, name) {
const header = request.headers.cookie || ''
for (const part of header.split(';')) {
const pair = part.trim()
if (pair.startsWith(name + '=')) return pair.slice(name.length + 1)
}
return ''
}
function readUserAgent(request) {
return request.headers['user-agent'] || 'unknown device'
}
function readJson(request) {
return new Promise((resolve) => {
let text = ''
request.setEncoding('utf8')
request.on('data', (chunk) => { text = text + chunk })
request.on('end', () => {
try {
resolve(text ? JSON.parse(text) : {})
} catch (error) {
resolve({})
}
})
})
}
function sendJson(response, status, body) {
response.writeHead(status, { 'content-type': 'application/json', 'cache-control': 'no-store' })
response.end(JSON.stringify(body))
}
================================================================
FILE 2 OF 4: session-checks.mjs
================================================================
// session-checks.mjs: six checks that drive the lab the way test browsers
// would and record every request. Each check starts its own lab server, so
// one check's sign-ins and resets never touch another. The log names each
// identifier with a short label (S1, D1) and never prints a token.
import { ABSOLUTE_LIMIT_MINUTES, IDLE_LIMIT_MINUTES, LAB_ACCOUNT, createLabClock, startSessionLab } from './session-lab-server.mjs'
export const CHECKS = [
{ id: 1, title: 'The identifier changes at sign-in (no fixation)', run: checkRotationAtSignIn,
expected: 'sign-in issues a new sid, and the sid from before sign-in is refused' },
{ id: 2, title: 'Sign-out ends the session on the server', run: checkSignOut,
expected: 'a copy of the signed-out sid is refused' },
{ id: 3, title: 'A password reset ends every session', run: checkPasswordReset,
expected: 'after the reset, the sessions on both browsers are refused' },
{ id: 4, title: 'Idle and absolute timeouts end the session', run: checkTimeouts,
expected: 'refused after ' + IDLE_LIMIT_MINUTES + ' idle minutes, and after ' + ABSOLUTE_LIMIT_MINUTES + ' minutes however busy' },
{ id: 5, title: 'Sessions are listed and one can be ended from another', run: checkEndFromAnother,
expected: 'ending needs the password, and the ended session is refused' },
{ id: 6, title: 'Removing a remembered device ends what it holds', run: checkDeviceRemoval,
expected: 'the device session is refused and the device no longer skips the code' },
]
export async function runCheck(check, version) {
const clock = createLabClock()
const lab = await startSessionLab(version, clock)
const run = { lab: lab, clock: clock, steps: [], labels: new Map(), problems: [] }
try {
await check.run(run)
} finally {
lab.server.close()
}
const passed = run.problems.length === 0
return { steps: run.steps, passed: passed, reason: passed ? 'as expected' : run.problems.join('; ') }
}
function openBrowser(run, name) {
return { run: run, name: name, cookies: new Map() }
}
function labelOf(run, prefix, token) {
if (!run.labels.has(token)) run.labels.set(token, prefix + (countLabels(run, prefix) + 1))
return run.labels.get(token)
}
function countLabels(run, prefix) {
let count = 0
for (const label of run.labels.values()) if (label.startsWith(prefix)) count = count + 1
return count
}
function describeJar(browser) {
const names = []
for (const entry of browser.cookies) names.push(entry[0] + ' ' + labelOf(browser.run, entry[0] === 'sid' ? 'S' : 'D', entry[1]))
return names.length ? names.join(', ') : 'no cookie'
}
// Keeps cookies the way a browser would, and deletes one set with Max-Age=0.
function keepCookies(browser, setCookieHeaders) {
const changes = []
for (const header of setCookieHeaders) {
const pair = header.split(';')[0]
const name = pair.slice(0, pair.indexOf('='))
const value = pair.slice(pair.indexOf('=') + 1)
if (header.includes('Max-Age=0')) {
browser.cookies.delete(name)
changes.push('cleared ' + name)
} else {
browser.cookies.set(name, value)
changes.push('set ' + name + ' ' + labelOf(browser.run, name === 'sid' ? 'S' : 'D', value))
}
}
return changes
}
async function send(browser, method, path, body) {
const sent = describeJar(browser)
const options = { method: method, headers: { 'user-agent': browser.name } }
const jar = []
for (const entry of browser.cookies) jar.push(entry[0] + '=' + entry[1])
if (jar.length) options.headers.cookie = jar.join('; ')
if (body) {
options.headers['content-type'] = 'application/json'
options.body = JSON.stringify(body)
}
const response = await fetch('http://127.0.0.1:' + browser.run.lab.port + path, options)
const changes = keepCookies(browser, response.headers.getSetCookie())
const data = await response.json()
const outcome = [response.status + ' ' + summarise(data)].concat(changes).join(', ')
note(browser.run, browser.name.padEnd(7) + method + ' ' + path + describeBody(body))
note(browser.run, ''.padEnd(7) + 'sends ' + sent + ' -> ' + outcome)
return { status: response.status, data: data }
}
// Names the fields a request carries, never their values.
function describeBody(body) {
if (!body) return ''
const fields = Object.keys(body).filter((field) => field !== 'email')
return fields.length ? ' with ' + fields.join(', ') : ''
}
function summarise(data) {
if (data.error) return data.error
if (data.result) return data.result
if (data.email) return 'account of ' + data.email
if (data.sessions) return data.sessions.length + ' listed: ' + data.sessions.map((row) => row.device + (row.current ? ' (this one)' : '')).join(', ')
if (data.devices) return data.devices.length + ' listed: ' + data.devices.map((row) => row.name).join(', ')
return 'ok'
}
function note(run, text) {
run.steps.push(' ' + text)
}
function expect(run, isTrue, problem) {
if (!isTrue) run.problems.push(problem)
}
function signInBody(extra) {
return Object.assign({ email: LAB_ACCOUNT.email, password: LAB_ACCOUNT.password, code: LAB_ACCOUNT.code }, extra)
}
async function signedInBrowser(run, name) {
const browser = openBrowser(run, name)
await send(browser, 'POST', '/sign-in', signInBody())
return browser
}
async function checkRotationAtSignIn(run) {
const laptop = openBrowser(run, 'laptop')
await send(laptop, 'GET', '/start')
const before = laptop.cookies.get('sid')
const copy = openBrowser(run, 'copy')
copy.cookies.set('sid', before)
note(run, 'copy holds sid ' + labelOf(run, 'S', before) + ', standing in for anyone who saw it before sign-in')
await send(laptop, 'POST', '/sign-in', signInBody())
const replay = await send(copy, 'GET', '/account')
expect(run, laptop.cookies.get('sid') !== before, 'sign-in kept the sid issued before it')
expect(run, replay.status === 401, 'the sid from before sign-in opened the account')
}
async function checkSignOut(run) {
const laptop = await signedInBrowser(run, 'laptop')
const copy = openBrowser(run, 'copy')
copy.cookies.set('sid', laptop.cookies.get('sid'))
note(run, 'copy holds sid ' + labelOf(run, 'S', laptop.cookies.get('sid')) + ', standing in for a copy made before sign-out')
await send(laptop, 'POST', '/sign-out')
const replay = await send(copy, 'GET', '/account')
expect(run, replay.status === 401, 'the signed-out sid still opened the account')
}
async function checkPasswordReset(run) {
const laptop = await signedInBrowser(run, 'laptop')
const phone = await signedInBrowser(run, 'phone')
const resetter = openBrowser(run, 'reset')
await send(resetter, 'POST', '/password-reset', { email: LAB_ACCOUNT.email, resetCode: LAB_ACCOUNT.resetCode, newPassword: 'a new lab password' })
const laptopAfter = await send(laptop, 'GET', '/account')
const phoneAfter = await send(phone, 'GET', '/account')
expect(run, laptopAfter.status === 401, 'the laptop session survived the reset')
expect(run, phoneAfter.status === 401, 'the phone session survived the reset')
}
async function checkTimeouts(run) {
const laptop = await signedInBrowser(run, 'laptop')
run.clock.advance(IDLE_LIMIT_MINUTES + 1)
note(run, 'clock moves ' + (IDLE_LIMIT_MINUTES + 1) + ' minutes with no request (idle limit ' + IDLE_LIMIT_MINUTES + ')')
const idle = await send(laptop, 'GET', '/account')
expect(run, idle.status === 401, 'the session survived ' + (IDLE_LIMIT_MINUTES + 1) + ' idle minutes')
await send(laptop, 'POST', '/sign-in', signInBody())
const busy = await keepBusy(run, laptop, 18, ABSOLUTE_LIMIT_MINUTES + 18)
expect(run, busy.firstRefusal > 0, 'a session in use every 18 minutes was never ended')
expect(run, busy.firstRefusal === 0 || busy.firstRefusal >= ABSOLUTE_LIMIT_MINUTES, 'a busy session ended before the absolute limit')
}
// Sends one request every stepMinutes and logs one summary line, not each request.
async function keepBusy(run, browser, stepMinutes, untilMinutes) {
let minutes = 0
let lastAccepted = 0
let firstRefusal = 0
let requests = 0
while (minutes < untilMinutes && firstRefusal === 0) {
run.clock.advance(stepMinutes)
minutes = minutes + stepMinutes
requests = requests + 1
const response = await quietGet(browser, '/account')
if (response.status === 200) lastAccepted = minutes
else firstRefusal = minutes
}
const ending = firstRefusal ? ', then 401 at minute ' + firstRefusal : ', never refused'
note(run, browser.name.padEnd(7) + 'GET /account once every ' + stepMinutes + ' minutes, ' + requests + ' requests')
note(run, ''.padEnd(7) + '200 up to minute ' + lastAccepted + ending + ' (counted from this sign-in; absolute limit ' + ABSOLUTE_LIMIT_MINUTES + ')')
return { firstRefusal: firstRefusal }
}
async function quietGet(browser, path) {
const jar = []
for (const entry of browser.cookies) jar.push(entry[0] + '=' + entry[1])
const response = await fetch('http://127.0.0.1:' + browser.run.lab.port + path, { headers: { cookie: jar.join('; ') } })
await response.json()
return { status: response.status }
}
async function checkEndFromAnother(run) {
const laptop = await signedInBrowser(run, 'laptop')
const phone = await signedInBrowser(run, 'phone')
const listed = await send(laptop, 'GET', '/account/sessions')
const phoneRow = listed.data.sessions.find((row) => row.device === 'phone')
const withoutPassword = await send(laptop, 'POST', '/account/sessions/end', { handle: phoneRow.handle })
expect(run, withoutPassword.status === 403, 'a session was ended without the password')
await send(laptop, 'POST', '/account/sessions/end', { handle: phoneRow.handle, password: LAB_ACCOUNT.password })
const phoneAfter = await send(phone, 'GET', '/account')
await send(laptop, 'GET', '/account/sessions')
expect(run, phoneAfter.status === 401, 'the ended phone session still opened the account')
}
async function checkDeviceRemoval(run) {
const tablet = openBrowser(run, 'tablet')
await send(tablet, 'POST', '/sign-in', signInBody({ rememberDevice: true }))
await send(tablet, 'POST', '/sign-out')
const passwordOnly = { email: LAB_ACCOUNT.email, password: LAB_ACCOUNT.password }
await send(tablet, 'POST', '/sign-in', passwordOnly)
const laptop = await signedInBrowser(run, 'laptop')
const listed = await send(laptop, 'GET', '/account/devices')
await send(laptop, 'POST', '/account/devices/remove', { handle: listed.data.devices[0].handle })
const tabletAfter = await send(tablet, 'GET', '/account')
await send(tablet, 'POST', '/sign-out')
const signInAgain = await send(tablet, 'POST', '/sign-in', passwordOnly)
expect(run, tabletAfter.status === 401, 'the removed device kept its session')
expect(run, signInAgain.status === 401, 'the removed device still skipped the code')
}
================================================================
FILE 3 OF 4: run-checks.mjs
================================================================
// run-checks.mjs: runs all six checks against the flawed version and then
// the fixed version, and prints each request with its result.
// Run: node run-checks.mjs
import { CHECKS, runCheck } from './session-checks.mjs'
const VERSIONS = ['flawed', 'fixed']
async function main() {
const passes = { flawed: 0, fixed: 0 }
for (const check of CHECKS) {
console.log('CHECK ' + check.id + ': ' + check.title)
console.log('Expected: ' + check.expected)
for (const version of VERSIONS) {
const outcome = await runCheck(check, version)
console.log(version.toUpperCase() + ' VERSION')
for (const step of outcome.steps) console.log(step)
console.log(' Result: ' + (outcome.passed ? 'PASS' : 'FAIL') + ', ' + outcome.reason)
if (outcome.passed) passes[version] = passes[version] + 1
}
console.log('')
}
for (const version of VERSIONS) {
console.log(version + ' version: ' + passes[version] + ' of ' + CHECKS.length + ' checks passed')
}
}
main()
================================================================
FILE 4 OF 4: session-checks.test.mjs
================================================================
// session-checks.test.mjs: the six checks as a regression test.
// Run: node session-checks.test.mjs (fixed version: all six pass)
// node session-checks.test.mjs flawed (flawed version: all six fail)
// A failing test sets the exit code to 1, so a pipeline step running it fails.
import assert from 'node:assert/strict'
import { test } from 'node:test'
import { CHECKS, runCheck } from './session-checks.mjs'
const version = process.argv[2] || 'fixed'
if (version !== 'fixed' && version !== 'flawed') throw new Error('Use fixed or flawed')
for (const check of CHECKS) {
test(check.id + '. ' + check.title, async () => {
const outcome = await runCheck(check, version)
assert.ok(outcome.passed, outcome.reason)
})
}
================================================================
PART 4: RUN THE SIX CHECKS AGAINST BOTH VERSIONS
================================================================
Each step is two lines: the browser and the request, then the cookies it sent and what came back. S1, S2 and so on label session identifiers, and D1 labels a device token, so no real token is printed.
Command: node run-checks.mjs
CHECK 1: The identifier changes at sign-in (no fixation)
Expected: sign-in issues a new sid, and the sid from before sign-in is refused
FLAWED VERSION
laptop GET /start
sends no cookie -> 200 anonymous-session, set sid S1
copy holds sid S1, standing in for anyone who saw it before sign-in
laptop POST /sign-in with password, code
sends sid S1 -> 200 signed-in
copy GET /account
sends sid S1 -> 200 account of sam@example.com
Result: FAIL, sign-in kept the sid issued before it; the sid from before sign-in opened the account
FIXED VERSION
laptop GET /start
sends no cookie -> 200 anonymous-session, set sid S1
copy holds sid S1, standing in for anyone who saw it before sign-in
laptop POST /sign-in with password, code
sends sid S1 -> 200 signed-in, set sid S2
copy GET /account
sends sid S1 -> 401 not-signed-in
Result: PASS, as expected
CHECK 2: Sign-out ends the session on the server
Expected: a copy of the signed-out sid is refused
FLAWED VERSION
laptop POST /sign-in with password, code
sends no cookie -> 200 signed-in, set sid S1
copy holds sid S1, standing in for a copy made before sign-out
laptop POST /sign-out
sends sid S1 -> 200 signed-out, cleared sid
copy GET /account
sends sid S1 -> 200 account of sam@example.com
Result: FAIL, the signed-out sid still opened the account
FIXED VERSION
laptop POST /sign-in with password, code
sends no cookie -> 200 signed-in, set sid S1
copy holds sid S1, standing in for a copy made before sign-out
laptop POST /sign-out
sends sid S1 -> 200 signed-out, cleared sid
copy GET /account
sends sid S1 -> 401 not-signed-in
Result: PASS, as expected
CHECK 3: A password reset ends every session
Expected: after the reset, the sessions on both browsers are refused
FLAWED VERSION
laptop POST /sign-in with password, code
sends no cookie -> 200 signed-in, set sid S1
phone POST /sign-in with password, code
sends no cookie -> 200 signed-in, set sid S2
reset POST /password-reset with resetCode, newPassword
sends no cookie -> 200 password-changed
laptop GET /account
sends sid S1 -> 200 account of sam@example.com
phone GET /account
sends sid S2 -> 200 account of sam@example.com
Result: FAIL, the laptop session survived the reset; the phone session survived the reset
FIXED VERSION
laptop POST /sign-in with password, code
sends no cookie -> 200 signed-in, set sid S1
phone POST /sign-in with password, code
sends no cookie -> 200 signed-in, set sid S2
reset POST /password-reset with resetCode, newPassword
sends no cookie -> 200 password-changed
laptop GET /account
sends sid S1 -> 401 not-signed-in
phone GET /account
sends sid S2 -> 401 not-signed-in
Result: PASS, as expected
CHECK 4: Idle and absolute timeouts end the session
Expected: refused after 20 idle minutes, and after 600 minutes however busy
FLAWED VERSION
laptop POST /sign-in with password, code
sends no cookie -> 200 signed-in, set sid S1
clock moves 21 minutes with no request (idle limit 20)
laptop GET /account
sends sid S1 -> 200 account of sam@example.com
laptop POST /sign-in with password, code
sends sid S1 -> 200 signed-in
laptop GET /account once every 18 minutes, 35 requests
200 up to minute 630, never refused (counted from this sign-in; absolute limit 600)
Result: FAIL, the session survived 21 idle minutes; a session in use every 18 minutes was never ended
FIXED VERSION
laptop POST /sign-in with password, code
sends no cookie -> 200 signed-in, set sid S1
clock moves 21 minutes with no request (idle limit 20)
laptop GET /account
sends sid S1 -> 401 not-signed-in
laptop POST /sign-in with password, code
sends sid S1 -> 200 signed-in, set sid S2
laptop GET /account once every 18 minutes, 34 requests
200 up to minute 594, then 401 at minute 612 (counted from this sign-in; absolute limit 600)
Result: PASS, as expected
CHECK 5: Sessions are listed and one can be ended from another
Expected: ending needs the password, and the ended session is refused
FLAWED VERSION
laptop POST /sign-in with password, code
sends no cookie -> 200 signed-in, set sid S1
phone POST /sign-in with password, code
sends no cookie -> 200 signed-in, set sid S2
laptop GET /account/sessions
sends sid S1 -> 200 2 listed: laptop (this one), phone
laptop POST /account/sessions/end with handle
sends sid S1 -> 200 ended
laptop POST /account/sessions/end with handle, password
sends sid S1 -> 200 ended
phone GET /account
sends sid S2 -> 200 account of sam@example.com
laptop GET /account/sessions
sends sid S1 -> 200 1 listed: laptop (this one)
Result: FAIL, a session was ended without the password; the ended phone session still opened the account
FIXED VERSION
laptop POST /sign-in with password, code
sends no cookie -> 200 signed-in, set sid S1
phone POST /sign-in with password, code
sends no cookie -> 200 signed-in, set sid S2
laptop GET /account/sessions
sends sid S1 -> 200 2 listed: laptop (this one), phone
laptop POST /account/sessions/end with handle
sends sid S1 -> 403 password-needed
laptop POST /account/sessions/end with handle, password
sends sid S1 -> 200 ended
phone GET /account
sends sid S2 -> 401 not-signed-in
laptop GET /account/sessions
sends sid S1 -> 200 1 listed: laptop (this one)
Result: PASS, as expected
CHECK 6: Removing a remembered device ends what it holds
Expected: the device session is refused and the device no longer skips the code
FLAWED VERSION
tablet POST /sign-in with password, code, rememberDevice
sends no cookie -> 200 signed-in, set device D1, set sid S1
tablet POST /sign-out
sends device D1, sid S1 -> 200 signed-out, cleared sid
tablet POST /sign-in with password
sends device D1 -> 200 signed-in, set sid S2
laptop POST /sign-in with password, code
sends no cookie -> 200 signed-in, set sid S3
laptop GET /account/devices
sends sid S3 -> 200 1 listed: tablet
laptop POST /account/devices/remove with handle
sends sid S3 -> 200 removed
tablet GET /account
sends device D1, sid S2 -> 200 account of sam@example.com
tablet POST /sign-out
sends device D1, sid S2 -> 200 signed-out, cleared sid
tablet POST /sign-in with password
sends device D1 -> 200 signed-in, set sid S4
Result: FAIL, the removed device kept its session; the removed device still skipped the code
FIXED VERSION
tablet POST /sign-in with password, code, rememberDevice
sends no cookie -> 200 signed-in, set device D1, set sid S1
tablet POST /sign-out
sends device D1, sid S1 -> 200 signed-out, cleared sid
tablet POST /sign-in with password
sends device D1 -> 200 signed-in, set sid S2
laptop POST /sign-in with password, code
sends no cookie -> 200 signed-in, set sid S3
laptop GET /account/devices
sends sid S3 -> 200 1 listed: tablet
laptop POST /account/devices/remove with handle
sends sid S3 -> 200 removed
tablet GET /account
sends device D1, sid S2 -> 401 not-signed-in
tablet POST /sign-out
sends device D1, sid S2 -> 200 signed-out, cleared sid
tablet POST /sign-in with password
sends device D1 -> 401 code-needed
Result: PASS, as expected
flawed version: 0 of 6 checks passed
fixed version: 6 of 6 checks passed
Reading the evidence:
CHECK 1 Flawed: sign-in sets no new sid, so the copy of S1 opens the account. Fixed: sign-in sets S2 and S1 is refused.
CHECK 2 Flawed: sign-out clears the browser's cookie, and the copy of S1 still opens the account. Fixed: the server deleted S1.
CHECK 3 Flawed: the password changes and both sessions carry on. Fixed: the reset ends both.
CHECK 4 Flawed: the server never checks the time, so neither limit applies. Fixed: 21 idle minutes end S1, and S2 ends at the first request after minute 600 even though it was used every 18 minutes.
CHECK 5 Flawed: ending needs no password, and the phone row disappears from the list while the phone stays signed in. Fixed: ending without the password gets 403, and the ended session gets 401.
CHECK 6 Flawed: the tablet disappears from the device list, yet its session works and its device token still skips the code. Fixed: both are refused.
================================================================
PART 5: THE REGRESSION TEST
================================================================
The same six checks, run by Node's built-in test runner. Run it in the pipeline that deploys your application.
Command: node session-checks.test.mjs
✔ 1. The identifier changes at sign-in (no fixation) (23.005125ms)
✔ 2. Sign-out ends the session on the server (6.715458ms)
✔ 3. A password reset ends every session (4.221375ms)
✔ 4. Idle and absolute timeouts end the session (12.435833ms)
✔ 5. Sessions are listed and one can be ended from another (3.691125ms)
✔ 6. Removing a remembered device ends what it holds (4.636167ms)
ℹ tests 6
ℹ suites 0
ℹ pass 6
ℹ fail 0
ℹ cancelled 0
ℹ skipped 0
ℹ todo 0
ℹ duration_ms 57.872084
The process exits with code 0.
Command: node session-checks.test.mjs flawed
✖ 1. The identifier changes at sign-in (no fixation) (23.37375ms)
✖ 2. Sign-out ends the session on the server (6.998334ms)
✖ 3. A password reset ends every session (4.396917ms)
✖ 4. Idle and absolute timeouts end the session (14.464917ms)
✖ 5. Sessions are listed and one can be ended from another (4.714709ms)
✖ 6. Removing a remembered device ends what it holds (5.809583ms)
ℹ tests 6
ℹ suites 0
ℹ pass 0
ℹ fail 6
ℹ cancelled 0
ℹ skipped 0
ℹ todo 0
ℹ duration_ms 62.915291
✖ failing tests:
test at session-checks.test.mjs:13:3
✖ 1. The identifier changes at sign-in (no fixation) (23.37375ms)
AssertionError [ERR_ASSERTION]: sign-in kept the sid issued before it; the sid from before sign-in opened the account
(stack trace and error details removed here)
test at session-checks.test.mjs:13:3
✖ 2. Sign-out ends the session on the server (6.998334ms)
AssertionError [ERR_ASSERTION]: the signed-out sid still opened the account
(stack trace and error details removed here)
test at session-checks.test.mjs:13:3
✖ 3. A password reset ends every session (4.396917ms)
AssertionError [ERR_ASSERTION]: the laptop session survived the reset; the phone session survived the reset
(stack trace and error details removed here)
test at session-checks.test.mjs:13:3
✖ 4. Idle and absolute timeouts end the session (14.464917ms)
AssertionError [ERR_ASSERTION]: the session survived 21 idle minutes; a session in use every 18 minutes was never ended
(stack trace and error details removed here)
test at session-checks.test.mjs:13:3
✖ 5. Sessions are listed and one can be ended from another (4.714709ms)
AssertionError [ERR_ASSERTION]: a session was ended without the password; the ended phone session still opened the account
(stack trace and error details removed here)
test at session-checks.test.mjs:13:3
✖ 6. Removing a remembered device ends what it holds (5.809583ms)
AssertionError [ERR_ASSERTION]: the removed device kept its session; the removed device still skipped the code
(stack trace and error details removed here)
The process exits with code 1, so a pipeline step running the test fails.
================================================================
PART 6: POINT THE CHECKS AT YOUR OWN APPLICATION
================================================================
1. Copy session-checks.mjs and session-checks.test.mjs into your project's tests.
2. Replace startSessionLab with your application started on a test port, with a test account, and replace the paths with your own sign-in, sign-out, account, session list, device and reset routes.
3. Give the checks a way to move time: a clock your application reads through one function that a test can replace, or idle and absolute limits set very short in the test environment.
4. Keep the labels in the log in place of real identifiers.
5. Run it against a local or staging copy with test accounts, not against real customers' accounts. Reset checks change a password, so use an account made for the test.What a session is, and why whoever holds the identifier is the user
OWASP's Session Management Cheat Sheet starts from the fact that HTTP is stateless: each request and response pair is independent of the others.
So once someone signs in, the application needs a way to recognise their next request as theirs without asking for the password again. That is a session, which the cheat sheet defines as a sequence of HTTP request and response transactions associated with the same user.
The application tracks it with a session identifier: a value the browser sends back with every request, carried in a cookie in the design this page assumes.
The identifier is the whole proof. The cheat sheet says that once an authenticated session exists, the session ID is temporarily equivalent to the strongest authentication method the application uses, such as a password or a one-time password. Holding the identifier is worth as much as passing that sign-in.
NIST SP 800-63B-4 puts it in its own terms: the continuity of an authenticated session SHALL be based on possession of a session secret issued at the time of authentication. Whoever presents the identifier is treated as the user.
The cheat sheet lists how someone else comes to hold it: disclosure, capture, prediction, brute force or fixation of the session ID, each of which leads to session hijacking, where an attacker can fully impersonate the victim.
Session management is therefore a set of decisions about one value: how it is issued, when it must change, when it must die, and who can end it. A mistake in any of them is a session management vulnerability, and MITRE's weakness list now names them separately.
In CWE version 5.0, CWE-1462 Improper Session Management is the parent of CWE-384 Session Fixation, CWE-1463 Insufficient Session Timeout Value, CWE-1464 Improper Session Invalidation and CWE-1467 Use of Singular Authentication Artifact for Multiple User Sessions, and CWE-1464 has two children of its own: CWE-1465, for sessions not invalidated at logout, and CWE-1466, for sessions not invalidated after a credential change.
The older CWE-613, Insufficient Session Expiration, is marked deprecated in the same version and points to CWE-1463 and CWE-1464 instead.
The OWASP Top 10:2025 still lists CWE-613 among the weaknesses mapped to A07 Authentication Failures, and says sessions should be handled by a server-side, built-in session manager, with identifiers invalidated after logout and after idle and absolute timeouts.
This guide covers the session's life after sign-in. Five neighbouring guides take the rest: cookie security covers the cookie attributes themselves, JWT security covers token formats and signature checks, authentication failures covers the sign-up, sign-in and password reset flows, OAuth and OIDC security covers signing in through another provider and the tokens it issues, and sensitive data exposure covers what your responses reveal.
How a session identifier should be issued
The identifier has to be impossible to guess, and the sources set the floor in different terms.
The OWASP cheat sheet says session identifiers must have at least 64 bits of entropy and must come from a cryptographically secure pseudorandom number generator. It works an example: with 64 bits, an attacker trying 10,000 guesses per second against an application with 100,000 valid sessions at once would expect to spend about 585 years finding one.
For an identifier you create yourself rather than take from your framework, it asks for a generator size of at least 128 bits. ASVS 5.0 requirement 7.2.3, at Level 1, asks that reference tokens are unique, come from a cryptographically secure generator and have at least 128 bits of entropy.
NIST SP 800-63B-4 requires session secrets that come from an approved random bit generator, are at least 64 bits long and are generated by the session host in direct response to an authentication event.
The value itself should mean nothing. The cheat sheet says the session ID must be meaningless and must never include sensitive or personally identifiable information, and that what it stands for, such as the user, their role and their timeouts, belongs on the server.
NIST says a session cookie SHOULD contain only an opaque string and SHALL NOT contain cleartext personal information. WSTG-SESS-01, OWASP's test of the session management schema, calls putting specific data in the token instead of a generic value a common mistake.
The server should accept only identifiers it issued. The cheat sheet calls this strict session management, as opposed to permissive, which accepts any value the user sets and creates a session for it, and it notes that PHP defaults to permissive. Its rule is that an application should never accept a session ID it never generated; it should issue a new one instead and treat the attempt as suspicious.
ASVS 5.0 requirement 7.2.1, at Level 1, adds that all session token verification happens in a trusted backend service.
Use your framework's session handling rather than writing your own, as the cheat sheet recommends, keep it on the latest version and review its defaults. If the session store could leak, through a backup for example, the cheat sheet suggests storing a one-way verifier rather than the raw token, because high entropy protects against guessing and not against someone who can read the store.
The lab on this page keeps only a SHA-256 hash of each token for that reason, and gives each session a separate public handle so the account page can list sessions without showing their tokens.
Keep the identifier out of URLs. The cheat sheet says an ID in a URL can be disclosed in links and logs, browser history and bookmarks, the Referer header and search engines, and that a web application should use cookies to exchange session IDs.
WSTG-SESS-04, the test for exposed session variables, adds that in general the session ID should never be sent over unencrypted transport and should never be cached. For session cookie security, NIST says a session cookie SHALL be tagged to be accessible only on HTTPS sessions and SHALL be accessible to the minimum practical hostnames and paths; the cookie security guide covers those attributes and the rest in detail.
When the identifier must change: sign-in and privilege changes
The OWASP cheat sheet's rule is that the session ID must be renewed after any privilege level change, and the most common case, where renewal is mandatory, is sign-in, when the user moves from anonymous to authenticated.
It names password changes, permission changes and switching from a regular user role to an administrator role as other cases to consider, and says the old ID must be destroyed. ASVS 5.0 requirement 7.2.4, at Level 1, asks for a new session token on authentication, including re-authentication, and for the current token to be terminated.
Skipping that step is what makes session fixation possible. An application can start a session before sign-in, for a shopping cart or a language choice; WSTG-SESS-03 uses the cart as its example. That test says fixation is enabled by keeping the same session cookie value before and after authentication: if the value is not refreshed at login, whoever knew it before the user signed in now holds a signed-in session.
The cheat sheet explains how it differs from most other session attacks: the attacker sets the ID in the victim's browser rather than collecting the victim's ID.
CWE-384 describes the weakness as authenticating a user, or otherwise establishing a new session, without invalidating any existing session identifier, and its first mitigation is to invalidate existing identifiers before authorising a new session.
Frameworks that manage sessions do this on their own sign-in path. Django's documentation says its login() function calls cycle_key(), which creates a new session key while keeping the session data, to mitigate session fixation. The express-session README's login example calls req.session.regenerate() before storing the user, with a comment that this helps guard against forms of session fixation.
The exposure sits in any sign-in path that goes around those functions: a custom login route, a callback from another identity provider, a magic link, or an API login that writes the session itself. Each one needs the same rotation, and check 1 in the lab is the test for it.
Reauthentication should produce a new identifier too. ASVS 5.0 requirement 7.5.1, at Level 2, asks for full re-authentication before changes to sensitive account attributes which may affect authentication, such as the email address, phone number, multi-factor settings or other information used in account recovery, and requirement 7.5.3, at Level 3, asks for further authentication with at least one factor, or secondary verification, before highly sensitive transactions or operations.
Requirement 7.2.4 asks for a new session token on re-authentication, so a re-authentication done for either reason should issue one.
Privileges can also go down rather than up, for example when an administrator removes someone's role. ASVS requirement 8.3.2, at Level 3, asks that changes to the values behind authorisation decisions are applied immediately, and where they cannot be, such as when relying on data in self-contained tokens, that mitigating controls alert when a consumer performs an action they are no longer authorised to do and revert the change.
This page reads that as a rule for sessions too: a removed role has to stop working in sessions that are already open, not only in new ones.
When a session must end
ASVS 5.0 requirement 7.4.1, at Level 1, sets the standard for every ending: once termination is triggered, by logout or expiry for example, the application disallows any further use of the session, which for server-side sessions means invalidating the session data at the backend.
CWE-1464 states the same rule from the other side: invalidate sessions on the server for every security-related event relevant to the application, without relying on the client to delete anything, because identifiers and cookies can be captured for later reuse.
Clearing the cookie is not signing out. The browser's copy disappears, but any other copy still works while the server keeps the session. WSTG-SESS-06, OWASP's logout test, describes a common mistake in which the client-side token is set to a new value while the server-side state stays active and can be reused by setting the cookie back to its old value.
It also describes frameworks that keep no server-side record at all, so logging out removes the cookie from the browser but the server cannot tell the session has ended; its example is ASP.NET Forms Authentication.
CWE-1465 is the catalogue entry for the weakness, and the consequence it gives is more time for whoever has compromised the session.
Browser behaviour sharpens the point. MDN's Set-Cookie reference says a cookie without Expires or Max-Age is a session cookie, removed when the client shuts down, then warns that browsers with a session restore feature restore session cookies as well, as if the browser was never closed.
The OWASP cheat sheet draws the conclusion: do not rely on closing the browser to end an authenticated session, and deleting a cookie alone does not invalidate a stolen copy of the session ID.
- Delete the session on the server, so the old value is refused (ASVS 7.4.1).
- Revoke every identifier that belongs to that sign-in together, including values issued by earlier rotations and any old value still accepted during a grace period, as the cheat sheet requires.
- Give every authenticated page a visible sign-out control. ASVS 5.0 requirement 7.4.4, at Level 2, asks for it, and NIST says sessions SHOULD provide a readily accessible way to log off.
- Tidy the browser last. The cheat sheet suggests the Clear-Site-Data response header at logout, and MDN notes that its "cookies" directive clears cookies for the whole registered domain, subdomains included, so check what else lives on your domain before you send it.
An idle timeout ends a session nobody is using. An absolute timeout ends every session after a fixed time, however busy it is. The OWASP cheat sheet explains why both are needed. The idle timeout limits the chance to guess and use a valid identifier, but does nothing against someone who already holds a session and keeps it alive with periodic requests.
The absolute timeout limits how long a hijacked session can be used. WSTG-SESS-07 adds that the idle timeout can, in some circumstances, protect public computers from session reuse.
Both sources say the timeout must be enforced on the server, because time values the client holds can be changed to extend the session.
NIST SP 800-63B-4 sets the same two timers: an overall timeout from authentication or the last reauthentication, and an inactivity timeout. When either one expires, the session SHALL be terminated. Activity SHALL reset the inactivity timer, and a successful reauthentication SHALL reset both.
How long each should be is a decision the sources leave to you. ASVS 5.0 says no single pattern suits all applications; its requirements 7.3.1 and 7.3.2, both at Level 2, ask for an inactivity timeout and an absolute maximum lifetime set by risk analysis and documented security decisions, and requirement 7.1.1 asks that the documentation justifies any deviation from the re-authentication requirements in NIST SP 800-63B. The figures below are each source's own, with its conditions.
- OWASP Session Management Cheat Sheet: common idle timeout ranges of 2 to 5 minutes for high-value applications and 15 to 30 minutes for low-risk applications. For an application an office worker uses for a full day, it says an absolute timeout between 4 and 8 hours could be appropriate.
- WSTG-SESS-07: a 60 minute logout time can be acceptable for a public forum but would be too much for home banking, where it says a maximum timeout of 15 minutes is recommended.
- NIST SP 800-63B-4, whose abstract says it focuses on the authentication of subjects who interact with government information systems over networks, by authentication assurance level (AAL). AAL1: an overall timeout SHALL be set and SHOULD be no more than 30 days, and an inactivity timeout is optional. AAL2: an overall timeout SHALL be set and SHOULD be no more than 24 hours, and the inactivity timeout SHOULD be no more than 1 hour. AAL3: the overall timeout SHALL be no more than 12 hours, and the inactivity timeout SHOULD be no more than 15 minutes.
NIST says session cookies SHOULD expire at or soon after the session's validity period, and that this SHALL NOT be relied on to enforce session timeouts. WSTG-SESS-07 shows why: if the session cookie carries time data, such as a login time or an expiry date, the client may be involved in enforcing the timeout, and testers can try setting the expiry far in the future to see whether the session can be prolonged.
A copied identifier ignores the expiry the browser was told to apply.
The lab's flawed version shows the plainest form of the mistake, a server that never checks the time at all.
For sessions that must stay open a long time, the cheat sheet describes a third timer, the renewal timeout. It swaps the identifier for a new one partway through the session, whatever the activity, so a copied value stops working sooner while the real user stays signed in.
The previous value stays valid for a short safety interval while the browser picks up the new one, which is why logout has to revoke both.
A password reset can be the moment someone discovers their account was used by somebody else. The OWASP Forgot Password Cheat Sheet says a reset alone may not restore control, because an attacker may still have an active session or may have changed recovery details or multi-factor settings.
It says to ask the user whether to invalidate all existing sessions, or to invalidate them automatically, and, after recovering an account that may have been compromised, to invalidate existing sessions along with outstanding reset links and codes.
CWE-1466 names the weakness: users can change their password, but sessions authenticated before the change carry on. Its consequence spells out why that matters, since a session opened with a stolen password has to end when the password changes. ASVS 5.0 requirement 7.4.3, at Level 2, asks that after a successful change or removal of any authentication factor, including a password change through reset or recovery and a change to multi-factor settings, the application gives the option to terminate all other active sessions.
ASVS asks for the option; this page recommends ending the other sessions by default, which is the Forgot Password Cheat Sheet's second choice, and the lab's fixed version does that after a reset.
The session making the change is covered by the cheat sheet's renewal rule, since a password change is one of its privilege changes, so it gets a new identifier.
Django shows one way to build this. Its documentation says that for user models built on AbstractBaseUser, authenticated sessions carry an HMAC of the password field that is checked on every request, so changing the password logs out every session. Its default password change views update the session with the new hash so the person making the change stays signed in, and for custom views it offers update_session_auth_hash(), which also rotates the session key so a stolen cookie for that session stops working.
One more check belongs here. WSTG-SESS-08, the session puzzling test, gives a password reset page as its example: if the reset flow writes the username or email address into the session, and other pages read that value as proof of who is signed in, the reset flow becomes a way around sign-in.
Its fix is to use each session variable for one consistent purpose. The reset flow itself, including how its link is protected, is covered in the authentication failures guide.
Two endings come from outside the session. ASVS 5.0 requirement 7.4.2, at Level 1, asks that all active sessions end when an account is disabled or deleted, such as when an employee leaves the company. Requirement 7.4.5, at Level 2, asks that administrators can terminate active sessions for one user or for all users.
The OWASP cheat sheet asks that admin interfaces which manage active sessions are thoroughly protected, and says support staff frequently use them to impersonate users while solving problems.
Session revocation: what sign out everywhere has to reach
Sign out everywhere is only as complete as the list of things that can still act for the user.
With server-side sessions the job is direct: delete every session record for the account, as the lab's fixed version does after a reset. Four other things can outlive that deletion.
- Self-contained tokens. ASVS 5.0 says that for self-contained tokens, additional measures are required to revoke or block them, as they may otherwise remain valid until expiration. Its requirement 7.4.1 says applications using them will need a solution such as maintaining a list of terminated tokens, disallowing tokens produced before a per-user date and time, or rotating a per-user signing key. Django's documentation gives a concrete case: with its signed cookie session backend, sessions are not invalidated when the user logs out, so a stolen cookie keeps working until it is older than SESSION_COOKIE_AGE. Token formats and signature checks are covered in the JWT security guide.
- Access and refresh tokens. NIST SP 800-63B-4 says an access token and any associated refresh tokens could be valid long after the authentication session has ended, and that a relying party SHALL NOT treat the presence of an access token as a sign the user is present, in the absence of other signals. RFC 9700, the OAuth 2.0 security best current practice, says authorisation servers MAY revoke refresh tokens automatically in case of a security event, such as a password change or a logout at the authorisation server. A self-contained access token already issued falls under the previous point: without one of those measures it can stay usable until it expires, so its lifetime is how long sign out everywhere can take to reach it. The OAuth and OIDC security guide covers revoking delegated tokens.
- Federated sign-in. NIST says an identity provider and a relying party manage sessions separately, so ending one does not end the other, and a new assertion could be issued from a live identity provider session without the user signing in again. WSTG-SESS-06 makes the same point about single sign-on and expects a logout in the application or in the SSO system to end all sessions. ASVS 5.0 requirements 7.1.3 and 7.6.1, both at Level 2, ask that the systems in a federated sign-in setup are documented along with the controls that coordinate session lifetimes and termination, and that lifetime and termination between relying parties and identity providers behave as documented.
- Remembered devices. A remember-this-device option leaves a long-lived token in the browser that changes how the next sign-in works. NIST says cookies and similar remember-my-browser features SHALL NOT be used instead of authentication, except for reauthentication at AAL2 when the inactivity limit has passed but the overall limit has not. The OWASP Authentication Cheat Sheet says to use remembered-device cookies as risk signals, not substitutes for authentication, and its own example is an application that asks for multi-factor authentication on the first sign-in from a device but not on later ones. Whatever a device token unlocks, treat it as a credential: sign out everywhere, a password reset and removing the device from the account page all have to reach it, along with the sessions started on that device. Check 6 in the lab tests the last of these.
What a person should be able to see and end from their account page
People can only end sessions they can see.
ASVS 5.0 requirement 7.5.2, at Level 2, asks that users can view their active sessions and, after authenticating again with at least one factor, terminate any or all of them. The OWASP cheat sheet recommends letting users check the details of active sessions at any time, alerting them about concurrent logons, letting them end sessions remotely, and keeping an account activity history with details such as IP address, User-Agent, login date and time and idle time.
OWASP's Credential Stuffing Prevention Cheat Sheet adds that details of recent logins should be visible, and that where concurrent sessions are supported the user should be able to view all of them and terminate any that are not legitimate.
Whether one account may be signed in on several devices at once is a design decision, the cheat sheet says, and if it is not allowed, the application must act after each new sign-in, by ending the earlier session or asking the user which one stays.
ASVS requirement 7.1.2, at Level 2, asks that the documentation sets how many concurrent sessions one account may have and what happens when it reaches that number. Within those decisions, these are the parts of an account page that make session control usable.
- One row per session: the device or browser name, when it signed in, when it was last active, and a marker on the session the person is looking from.
- A handle for each row that is not the session's token, so nobody reading the page, and no script injected into it, can copy another session's identifier from it.
- End this session, and sign out of all other sessions, each asking for the password or another factor first, as ASVS 7.5.2 describes.
- A separate list of remembered devices, each with a remove action that also ends the sessions started on that device.
- Endings that take effect on the server. A row that disappears from the list while the session still works is the flaw check 5 in the lab catches.
Session hijacking: what limits a stolen identifier
Session hijacking is using someone else's identifier.
WSTG-SESS-09 puts it plainly: an attacker who gets access to a user's session cookies can impersonate them by presenting those cookies. Presenting the value is enough, which is why the controls on this page aim at limiting what a leaked identifier can do. The ways an identifier leaks each have their own coverage: injected script in the XSS guide, which also covers HttpOnly; cookies sent over plain HTTP in WSTG-SESS-09 and the cookie security guide; identifiers in URLs, logs and caches in WSTG-SESS-04; and predictable values in WSTG-SESS-01.
Several controls on this page shrink what a stolen identifier is worth. The absolute timeout caps how long it can be used, and the renewal timeout makes a copied value go stale while the real user stays signed in. Rotation at every privilege change means a value taken before sign-in or before reauthentication does not carry the new rights.
Reauthentication before changes to the email address or multi-factor settings (ASVS 7.5.1) means a stolen session alone cannot change them. Ending sessions on reset, on request and on device removal gives the owner a way to cut an intruder off.
Detection helps, within limits. The cheat sheet recommends binding the session to properties such as the client IP address or User-Agent and treating a change mid-session as a sign of hijacking, and warns that a skilled attacker can share the victim's IP address on the same network or copy the User-Agent.
NIST says session monitoring MAY be performed, evaluating characteristics such as usage patterns, device and browser characteristics, geolocation and IP address; that when it detects possible fraud the relying party SHOULD reauthenticate, terminate the session or notify support staff; and that collecting those characteristics SHALL be included in a privacy risk assessment.
NIST also names the emerging device bound session credentials specification as one way to prove possession of a session secret instead of presenting it as a bearer token.
Log the lifecycle, not the secret. The cheat sheet recommends recording when identifiers are created, renewed and destroyed, along with logins, logouts, privilege changes and timeouts, and logging a salted hash of the session ID rather than the ID itself, so the logs do not become one more place to find it.
How to test session management on an application you own
OWASP's Web Security Testing Guide v4.2 has nine session management tests, WSTG-SESS-01 to WSTG-SESS-09.
Run them only on an application you own or are authorised in writing to test, with test accounts you created for the purpose. Reset, lockout, disable and deletion checks run only on test accounts and test records, where the rules of engagement allow them.
- WSTG-SESS-01, session management schema: gather identifiers for the same user and, where possible, for different users, check there is enough randomness to stop forging, and look for unsigned cookies holding data that can be changed.
- WSTG-SESS-02, cookie attributes: review the session cookie's attributes and prefixes with an intercepting proxy or in the browser's cookie jar; the cookie security guide covers what to look for.
- WSTG-SESS-03, session fixation: follow the authentication flow, then present the cookies held before sign-in and see whether they now act for the signed-in user.
- WSTG-SESS-04, exposed session variables: check that the identifier only travels encrypted, is not cached, and is not sent in GET requests.
- WSTG-SESS-05, cross-site request forgery: covered in the CSRF guide.
- WSTG-SESS-06, logout: store the session cookie values, log out and try a page from the signed-in area; if logout set the cookies to a new value, restore the old values and reload. It should show nothing that only a signed-in user should see.
- WSTG-SESS-07, session timeout: confirm a timeout exists and that the server, not the cookie, enforces it.
- WSTG-SESS-08, session puzzling: list the session variables, then reach entry points such as password reset in an order the developers did not plan, and see whether values they set unlock other pages.
- WSTG-SESS-09, session hijacking: with two test accounts, find the session cookies that are not protected against travelling over plain HTTP and check whether presenting them is enough to act as the user.
- Beyond the WSTG list, from ASVS 5.0 chapter V7: reset a test account's password and confirm the option to end its other sessions is offered and, when taken, ends them (7.4.3); end one session from another and confirm it is refused (7.5.2); keep a session busy past the absolute limit (7.3.2); have an administrator end a test user's sessions and disable a test account, and confirm both take effect (7.4.5 and 7.4.2). Then remove a remembered device and confirm its token and its sessions stop working.
Running the session lifecycle checks on your own machine
The checks in the asset on this page are an illustration.
They run a small account service with one invented account in two versions: a flawed one with six deliberate mistakes, each marked FLAWED in the code, and a fixed one. The server binds to 127.0.0.1, lets the system pick a free port, keeps everything in memory and uses only modules that ship with Node.js plus its built-in fetch(), so there is nothing to install.
The service reads time from a clock the checks move forward, so the idle and absolute timeouts are tested in milliseconds rather than hours.
It was written and run on Node.js 26.0.0, and every output in the asset was copied from that run.
The checks only send HTTP requests, the way a browser would, so the same checks can later drive your own application. They are for applications you own or are authorised in writing to test.
- Save the four files into an empty folder and open a terminal there.
- Run node run-checks.mjs. It runs the six checks against the flawed version and then the fixed version, printing every request, the cookies it carried by label (S1 for a session identifier, D1 for a device token), the response and the result. The flawed version fails all six and the fixed version passes all six.
- Run node session-checks.test.mjs. Node's built-in test runner runs the six checks against the fixed version, and all pass. Run node session-checks.test.mjs flawed and all six fail with their reasons; when any test fails the runner sets the exit code to 1, so a pipeline step running the test fails.
Pointing the checks at your own application
Start your application on a test port with a test account, and replace the lab's paths with your own sign-in, sign-out, account, session list, device and reset routes. Then give the checks a way to move time: a clock your application reads through one function that a test can replace, or idle and absolute limits set very short in the test environment.
Keep the labels in the log in place of real identifiers, and run the checks against a local or staging copy, not against real customers' accounts.
Where an outside test fits
Your own checks cover the routes you know about.
A Clever Ops web application and API penetration test covers authentication and sessions alongside what each role can reach: whether sign-in replaces the session issued before it, whether a signed-out or timed-out session is still accepted when its old value is sent again, and whether suspending an account ends its open sessions.
Each finding comes with evidence, a fix written for your stack and the criteria the retest will use. If Clever Ops built or hosts your application, the work is a security review rather than an independent test, and the report says who built it and who hosts it.
Frequently asked questions
It is how an application keeps someone signed in between requests: issuing a random identifier at sign-in, recognising it on each request, changing it when privileges change, and ending it on sign-out, timeout, password reset or when the user or an administrator ends it. The OWASP Session Management Cheat Sheet says an authenticated session ID is temporarily equivalent to the strongest authentication method the application uses, which is why each step matters.
In hijacking, someone obtains an identifier the server already issued to the user and presents it. In fixation, the attacker knows an identifier first and the user's sign-in attaches to it; the OWASP cheat sheet describes the attacker setting the session ID in the victim's browser rather than collecting it. A new identifier at sign-in, as ASVS 5.0 requirement 7.2.4 asks, stops fixation. It does not stop the new identifier being stolen later.
ASVS 5.0 leaves it to a documented risk analysis, because no single pattern suits all applications. As examples, the OWASP cheat sheet gives common idle timeout ranges of 2 to 5 minutes for high-value applications and 15 to 30 minutes for low-risk ones, and NIST SP 800-63B-4 says that at AAL2 the inactivity timeout SHOULD be no more than 1 hour and the overall timeout SHOULD be no more than 24 hours. Enforce both limits on the server.
Only if the server ends it. Clearing the cookie removes the browser's copy, but WSTG-SESS-06 describes applications where the old cookie value still works after logout. Test it by keeping a copy of the identifier before signing out and sending it again afterwards: it should be refused.
The OWASP Forgot Password Cheat Sheet says to ask the user whether to invalidate all existing sessions, or to do it automatically, and after recovering a possibly compromised account to invalidate existing sessions and outstanding reset links. ASVS 5.0 requirement 7.4.3 asks that the option to end all other sessions is given after any authentication factor changes, and CWE-1466 is the weakness when sessions survive a credential change.
Not by deleting a server record alone, because a self-contained token carries its own validity. ASVS 5.0 says such tokens may otherwise remain valid until expiration, and its requirement 7.4.1 says applications using them will need a solution such as a list of terminated tokens, disallowing tokens produced before a per-user date and time, or rotating a per-user signing key.
It should not replace signing in. NIST SP 800-63B-4 says remember-my-browser features SHALL NOT be used instead of authentication, except for reauthentication at AAL2 after the inactivity limit has passed but the overall limit has not, and the OWASP Authentication Cheat Sheet treats remembered-device cookies as risk signals. Whatever the token allows, removing the device should revoke it and end the sessions it started.
Scope the right test for your application
Tell us what you have built, who uses it and when it needs to launch. You will get a plain-English recommendation: a website audit, a web application test or a referral to a specialist.