Security

Session Hijacking: How Attackers Steal Logins and How to Stop It

Session hijacking is when an attacker steals the token a website uses to keep you logged in, usually a session cookie, and uses it to act as you. Because the site sees a valid session, the attacker never needs your password or your two-factor code.

OWASP's session management guidance describes the consequence plainly: once a session ID is disclosed, captured, predicted, brute-forced or fixated, an attacker can "fully impersonate a victim user in the web application". That's why the session token deserves the same care as the password.

How a login session works

HTTP has no memory between requests. After you log in, the site creates a random session ID, stores it on the server next to your account, and sends it to your browser in a cookie:

Set-Cookie: __Host-session=FBSTuxevLee5x-JDlCXr-bmoTTjSPlyc0qMAL7QAte8; Secure; HttpOnly; SameSite=Lax; Path=/

Your browser sends that cookie back with every request to the site, and the server looks it up to know it's you. Whoever presents the cookie is treated as the logged-in user. Session hijacking is any way of getting a copy of that value.

How sessions get hijacked

Infostealer malware

MITRE ATT&CK's entry for stealing web session cookies (T1539) notes that "Cookies can be found on disk, in the process memory of the browser, and in network traffic". Malware on your computer can copy the browser's cookie store and send it off. One infection can capture sessions for every site the browser is logged into, including ones protected by 2FA.

Adversary-in-the-middle phishing

A phishing page that simply copies a login form only gets your password. Newer kits act as a proxy between you and the real site: you log in, complete 2FA, and the proxy keeps the session cookie the real site issues. MITRE names open-source tools such as Evilginx2 and Muraena that do this, and states that "Session cookies can be used to bypasses some multi-factor authentication protocols".

Cross-site scripting (XSS)

If a site has an XSS flaw, injected JavaScript runs in the context of that site and can read document.cookie, then send the value to the attacker. The HttpOnly cookie flag blocks exactly this read. See XSS explained for how the injection happens.

Sniffing unencrypted traffic

Over plain HTTP, the cookie travels in clear text, and anyone on the same network path can read it. This used to be the classic public Wi-Fi attack. HTTPS everywhere plus the Secure flag has largely closed it; is public Wi-Fi safe covers what remains.

Predictable or fixated session IDs

If session IDs are short or follow a pattern, an attacker can guess valid ones. In session fixation, the attacker plants a session ID they already know in your browser before you log in; if the site keeps the same ID after login, the attacker's copy becomes a logged-in session.

Defences for website builders

Most of the protection is in how the site issues and handles sessions. The OWASP cheat sheet sets these as baseline requirements:

ControlWhat it blocksOWASP / MDN wording
At least 64 bits of entropy from a secure random generatorGuessing and brute force"Session identifiers must have at least 64 bits of entropy"
New session ID on login and privilege changeSession fixation"The session ID regeneration is mandatory to prevent session fixation attacks"
HttpOnly cookieTheft through XSS"Forbids JavaScript from accessing the cookie"
Secure cookieSniffing over HTTPSent "only when a request is made with the https: scheme"
SameSite=Strict or LaxCross-site request abuse"Session cookies must explicitly set SameSite=Strict (preferred) or SameSite=Lax"
Idle and absolute timeoutsLong-lived stolen sessionsIdle: "2-5 minutes for high-value applications and 15-30 minutes for low risk applications"
Server-side invalidation on logoutReuse of a copied cookie after logout"the web application must invalidate the session at least on server side"

Generating a session ID with enough entropy is one line in most languages. In Python, the secrets module is built for this; its documentation says token_urlsafe returns Base64 text where "each byte results in approximately 1.3 characters", and that "32 bytes (256 bits) of randomness is sufficient for the typical use-case":

python -c "import secrets; t = secrets.token_urlsafe(32); print(t, len(t))"

Example output (yours will differ every run):

FBSTuxevLee5x-JDlCXr-bmoTTjSPlyc0qMAL7QAte8 43

That is 256 bits, four times OWASP's 64-bit minimum. For scale, even at 64 bits there are 264 ≈ 1.8 × 1019 possible values; at one billion guesses per second, trying them all would take about 585 years. Never build session IDs from timestamps, user IDs or counters.

The __Host- prefix in the cookie example above is an extra safeguard. MDN explains that such cookies must be set with Secure from an HTTPS page, with no Domain attribute and with Path=/, which "guarantees that such cookies are only sent to the host that set them". A compromised subdomain can't then overwrite your session cookie.

Binding sessions to the device

All of the above still leaves one gap: a cookie copied by malware works from any computer. Two approaches narrow it:

  • Checking client properties. OWASP recommends binding the session to properties such as the client IP address and User-Agent, as a detection signal. It also warns these "cannot be used by web applications to trustingly defend against session attacks", because IP addresses are shared behind NAT and User-Agent strings can be copied.
  • Device Bound Session Credentials (DBSC). A Chrome feature where the browser creates a key pair at login and keeps the private key "in secure hardware, such as a Trusted Platform Module (TPM), when available". The site issues short-lived cookies, and "Chrome proves possession of the private key before refreshing them". A stolen cookie expires quickly, and the thief can't refresh it without the key. Sites have to add support for it, and browsers without it fall back to normal cookies.

Defences for users

  • Keep malware off the device. Malware that reads the browser's cookie store bypasses every server-side control above, so browser and OS updates and caution with pirated software and unknown downloads protect every session at once.
  • Use passkeys or a security key where offered. MITRE lists hardware tokens that "bind to the login domain" as a mitigation, because a proxy phishing site on a different domain can't complete the login. See passkeys explained.
  • Log out on shared computers, and review the "active sessions" or "devices" page on important accounts. Signing out of all sessions there invalidates stolen cookies on the server.
  • Be wary of pasting code into the browser console or adding bookmarklets someone sent you; MITRE's mitigations include training users to avoid running untrusted JavaScript.
  • Use HTTPS-only mode in your browser so no session cookie is ever sent over plain HTTP.

Related attacks

Session hijacking is often confused with cross-site request forgery. In CSRF the attacker never sees your cookie; they trick your browser into sending a request that carries it. In hijacking the attacker has the cookie itself and can send any request from their own machine. The same thinking applies to API tokens: an OAuth bearer token works for whoever holds it, so a stolen one is effectively a hijacked session for that app.

Frequently asked questions

Does two-factor authentication stop session hijacking?
Mostly not. 2FA protects the login step, and a hijacked session starts after login. MITRE ATT&CK notes that stolen session cookies can be used to bypass some multi-factor authentication. Phishing-resistant methods such as passkeys and FIDO security keys do help against one route, the fake login page that proxies your session, because they are bound to the real site's domain.
How do I know if my session was hijacked?
Look at the account's list of active sessions or recent sign-ins, which most large services offer in their security settings. Sessions from devices or locations you don't recognise, settings you didn't change, or messages you didn't send are the usual signs. Sign out of all sessions from that page and change your password.
Does logging out protect me?
It does if the site invalidates the session on its server when you log out, which OWASP says is mandatory. Deleting the cookie in your browser alone would not stop a copy an attacker already holds. Well-built sites do both, which is why logging out on shared computers is worth the habit.
What is the difference between session hijacking and session fixation?
In hijacking, the attacker steals a session ID that the site issued to you. In fixation, the attacker gets you to log in using a session ID the attacker already knows, then uses it. Sites prevent fixation by issuing a new session ID at login, which OWASP describes as mandatory.

Sources