TExcelTAD
Home › Security Foundations: Concepts, Law, Ethics & Your Lab › Session Hijacking and Credential Theft

Session Hijacking and Credential Theft

Passwords and MFA protect the moment of sign-in. After that, the server recognises you by a session: a random ID in a cookie, or a token the app sends with every request. Whoever presents that value is you, until it expires. Attackers have noticed: it is often easier to steal what a login produces than to break the login itself. This lesson covers both halves, taking over sessions and stealing credentials, with the detection and the fixes for each. How session stores and JWTs work is in the on-ramp lesson Sessions and Tokens.

Mechanism 1: session hijacking

A session can be taken in several ways:

Technique How the attacker gets the session What stops it
Sniffing reads the cookie from cleartext HTTP on the path (MITM) HTTPS everywhere, the Secure cookie flag, HSTS
Cross-site scripting (XSS) script injected into the page reads document.cookie or acts in the page output escaping, CSP, the HttpOnly flag (XSS)
Session fixation plants a session ID before the victim logs in, then uses it after a new session ID at login
Predictable IDs guesses IDs made from a counter, time or user name 128+ bits from a secure random generator
Token theft from the device malware or a malicious extension copies cookies and tokens from the browser profile endpoint protection, device-bound sessions, short lifetimes
Leaked tokens tokens in URLs, logs, screenshots, support tickets, public repositories keep tokens out of URLs and logs, secret scanning

Impact. The attacker acts as the user without ever seeing their password, and MFA has already been satisfied for that session. That is why stolen session cookies are a prized item and why "we have MFA" is not the end of the story.

Session fixation in ten lines

The program below is a toy session store. An attacker gets the victim to use a session ID the attacker chose (for example through a link on a site that accepts session IDs in the URL). The victim signs in. Does the attacker's copy of that ID now belong to a logged-in user?

python · try it yourself
import secrets

class SessionStore:
    def __init__(self, rotate_on_login):
        self.sessions, self.rotate = {}, rotate_on_login

    def new_anonymous(self, sid=None):
        sid = sid or secrets.token_urlsafe(32)
        self.sessions[sid] = {"user": None}
        return sid

    def login(self, sid, user):
        if self.rotate:                      # throw the old ID away, issue a fresh one
            self.sessions.pop(sid, None)
            sid = secrets.token_urlsafe(32)
        self.sessions[sid] = {"user": user}
        return sid

    def whoami(self, sid):
        s = self.sessions.get(sid)
        return s["user"] if s else "no session"

for rotate in (False, True):
    store = SessionStore(rotate_on_login=rotate)
    planted = store.new_anonymous("FIXED-ID-chosen-by-attacker")   # attacker gets the victim to use this ID
    victim_sid = store.login(planted, "alice")                      # the victim signs in
    print(f"rotate_on_login={rotate!s:5}  attacker using the planted ID is: {store.whoami(planted)}"
          f"  | victim is: {store.whoami(victim_sid)}")

print("fresh session ID length:", len(secrets.token_urlsafe(32)), "characters = 256 bits of randomness")
rotate_on_login=False  attacker using the planted ID is: alice  | victim is: alice
rotate_on_login=True   attacker using the planted ID is: no session  | victim is: alice
fresh session ID length: 43 characters = 256 bits of randomness

Without rotation the planted ID becomes Alice's logged-in session. With rotation it is dead the moment she signs in. The same rule applies to any change of privilege: issue a new session ID on login, on logout and when the user elevates (for example re-enters their password for an admin action). secrets.token_urlsafe(32) gives 256 random bits, so guessing an ID is hopeless.

Detecting a stolen session

A cookie copied to another machine is used from a different address, device and browser. The second program prints a hardened cookie header and then flags sessions whose source and user agent change in the middle of their life (a synthetic access log with lab and documentation addresses).

python · try it yourself
from http.cookies import SimpleCookie

c = SimpleCookie()
c["sid"] = "Zx9...lab-only..."
c["sid"].update({"path": "/", "secure": True, "httponly": True, "samesite": "Lax", "max-age": 3600})
print(c.output())

# Synthetic access log: (time, session id, source address, user agent)
log = [
    ("09:00:05", "s-41", "10.10.0.21", "Firefox/140 Linux"),
    ("09:02:10", "s-41", "10.10.0.21", "Firefox/140 Linux"),
    ("09:03:00", "s-77", "10.10.0.22", "Edge/141 Windows"),
    ("09:03:40", "s-41", "203.0.113.45", "curl/8.5"),
    ("09:04:02", "s-77", "10.10.0.22", "Edge/141 Windows"),
]
first_seen = {}
for t, sid, ip, ua in log:
    if sid not in first_seen:
        first_seen[sid] = (ip, ua)
    elif (ip, ua) != first_seen[sid]:
        print(f"ALERT {t} session {sid} moved from {first_seen[sid][0]} ({first_seen[sid][1]}) to {ip} ({ua})")
Set-Cookie: sid=Zx9...lab-only...; HttpOnly; Max-Age=3600; Path=/; SameSite=Lax; Secure
ALERT 09:03:40 session s-41 moved from 10.10.0.21 (Firefox/140 Linux) to 203.0.113.45 (curl/8.5)

The rule is simple and noisy: phones change networks and addresses all the time. Real systems combine it with other signals (a new country, a different browser family, an automation tool like curl using a browser's cookie) and respond proportionately: ask for re-authentication rather than lock out.

The cookie flags each close one door: Secure never sends the cookie over HTTP, HttpOnly hides it from page scripts, SameSite=Lax (or Strict) keeps it off most cross-site requests, which also blunts CSRF, and a short Max-Age limits how long a stolen cookie works. The lab capture shows a cookie set without most of them. Scope: a sample file in your sandbox.

bash · try it yourself
tshark -r $SAMPLES/pcap/http.pcap -Y 'http.set_cookie or http.cookie' -T fields -E header=y \
  -e frame.number -e ip.dst -e http.set_cookie
frame.number	ip.dst	http.set_cookie
16	10.10.0.5	session=lab42; HttpOnly

session=lab42 was sent over plain HTTP on port 80, has no Secure flag, no SameSite and no lifetime, and its value is short enough to guess. A review that finds this writes four findings, not one.

Mechanism 2: credential theft

Credentials are stolen in bulk and one at a time:

  • Phishing pages and real-time relay kits that capture the password and the one-time code together (Phishing and Social Engineering).
  • Infostealer malware on a personal or work device, which copies saved browser passwords, cookies and tokens and sends them to the operator. (Explained here as a concept only; analysing such malware safely is a topic of Malware Analysis and Forensics.)
  • Database breaches at other services: the password hashes or, at badly run sites, plaintext passwords end up in "combo lists" that drive credential stuffing.
  • Secrets in the wrong places: API keys in source code and CI logs, passwords in wikis, chat and tickets, .env files in backups.
  • Credential dumping from a compromised machine's memory or credential stores, the step after an initial foothold, covered in Windows and Active Directory Security.
  • Shoulder surfing, keyloggers and help-desk pretexting in the physical and social world.

Warning signs: logins at unusual hours or from new locations, a sudden password-reset or MFA-change request, new mailbox forwarding rules, access tokens used from unexpected networks, and secret-scanning alerts in your repositories.

How it is detected

  • Identity-provider logs: sign-in risk (new device, country, impossible travel), failed then successful logins, MFA method changes, tokens refreshed from new addresses.
  • Session telemetry like the rule above, and server-side session lists that users can see ("signed in on 3 devices").
  • Breach-corpus monitoring: checking your users' passwords against known-breached lists, and alerts when your domain's accounts appear in a new breach.
  • Secret scanners on code, CI logs and container images; canary tokens (fake credentials that alert when used).

How it is prevented

  1. Phishing-resistant MFA (passkeys, FIDO2 keys): there is no shared secret to phish, and the credential is bound to the real site.
  2. Session hygiene: random 128+ bit IDs, rotation at login and privilege change, Secure; HttpOnly; SameSite, idle and absolute timeouts, server-side revocation on logout and on password change.
  3. Bind sessions to the device where the platform allows it: OAuth sender-constrained tokens (DPoP, mutual-TLS-bound tokens) and browser features that bind cookies to a device key make a copied token useless elsewhere. Classic "token binding" for TLS never became widely deployed; these newer mechanisms play its role.
  4. Short-lived access tokens with rotating refresh tokens, so a stolen refresh token used twice revokes the whole session. ExcelTAD's own sign-in works this way; see Web Application Security.
  5. Secrets hygiene: a password manager for people, a secrets manager for machines, no secrets in code or URLs, rotation after any suspected leak (Secrets Policy).
  6. Endpoint protection and managed browsers reduce infostealer infections; on suspicion, revoke every session and token of the user, not only the password.

Pitfalls

  • Resetting the password and stopping there. Existing sessions and refresh tokens keep working until they are revoked.
  • Session IDs in URLs. They leak through Referer headers, logs, bookmarks and shared links.
  • Logout that only deletes the cookie in the browser while the session stays valid on the server.
  • Binding sessions strictly to an IP address. It breaks mobile users; use it as a risk signal instead.

Practice

1. In the fixation program, rotation is on, but the server also accepts the old ID for 60 seconds "for convenience". What happens?

The attacker has a 60-second window in which the planted ID is a logged-in session. Rotation must invalidate the old ID immediately.

2. Which flags would you add to Set-Cookie: session=lab42; HttpOnly, and what else must change?

Add Secure, SameSite=Lax (or Strict), a Max-Age or expiry, and Path=/; serve the site over HTTPS with HSTS; and replace lab42 with a long random value, because a short value can be guessed whatever the flags say.

3. A user's laptop had an infostealer. List the response steps in order.

Isolate and clean (or reimage) the device; revoke all sessions and refresh tokens of the user; reset the password and any credentials saved in the browser, from a clean device; review MFA methods, mailbox rules and recent activity; rotate any API keys or secrets that were on the machine; check other users who might reuse those secrets.

Test yourself

Which server-side change defeats session fixation?

  1. Longer passwords
  2. Issuing a new session ID at login
  3. The HttpOnly flag
  4. Rate limiting

What does the HttpOnly cookie flag do?

  1. Sends the cookie only over HTTPS
  2. Hides the cookie from JavaScript in the page
  3. Blocks cross-site requests
  4. Encrypts the cookie

Why is a stolen session cookie dangerous even when the account uses MFA?

  1. Cookies contain the password
  2. The session was created after MFA had already been completed
  3. MFA codes are stored in cookies
  4. It is not dangerous

After a confirmed credential theft, which step is most often forgotten?

  1. Changing the password
  2. Revoking existing sessions and refresh tokens
  3. Telling the user
  4. Checking the logs