Overview Attack Chain Techniques Tools Demo Detection Prevention Legal Resources

Session Hijacking Guide

What is Session Hijacking?

Session hijacking (also called cookie hijacking or session sidejacking) is a type of cyberattack where an attacker steals a user's session token (session ID, cookie, or JSON Web Token - JWT) to gain unauthorized access to their web application account. By capturing the session token, the attacker can impersonate the legitimate user without needing their password, bypassing multi-factor authentication (MFA). Session hijacking exploits weaknesses in session management, insecure cookie handling (no HttpOnly, Secure flags), lack of HTTPS encryption, or cross-site scripting (XSS) vulnerabilities.

Attack Prevalence: Session hijacking accounts for 25% of web application breaches (Verizon DBIR). 43% of organizations experienced session hijacking attacks in 2023. Average cost per incident: $500,000+ (data breach, unauthorized transactions, account takeover). Financial services (40%), e-commerce (25%), and social media (20%) are most targeted.

25%
of Web App Breaches
43%
Organizations Affected (2023)
$500K+
Average Cost per Incident

Common targets of session hijacking attacks:

How Session Hijacking Works (Attack Chain)

1. Session Token Capture

Attacker captures session token via packet sniffing (HTTP), XSS (JavaScript), MitM (ARP spoofing), or malware.

2. Token Extraction

Attacker extracts session ID (PHPSESSID, JSESSIONID) or JWT from captured traffic or browser storage.

3. Impersonation

Attacker injects stolen session token into their browser (Cookie Manager, Burp Suite, browser console).

4. Unauthorized Access

Attacker accesses victim's account without password, bypassing MFA.

// Session hijacking attack chain (technical flow) [Victim] → [Login] → [Web Server issues session cookie (PHPSESSID=abc123)] ↓ Attacker captures cookie via packet sniffing (HTTP only) ↓ Attacker injects cookie into browser (document.cookie) ↓ Attacker accesses victim account without password // Session hijacking via XSS (Cross-Site Scripting) // Victim visits malicious page with JavaScript // Session hijacking via packet sniffing (HTTP only - no HTTPS) // Attacker on same network (public Wi-Fi) captures HTTP traffic sudo tcpdump -i eth0 -A -s 0 | grep -E "Cookie:|PHPSESSID" // Session hijacking via Burp Suite (Proxy) // Attacker captures HTTP request, extracts Cookie header GET /profile HTTP/1.1 Host: victim.com Cookie: PHPSESSID=abc123def456ghi789 User-Agent: Mozilla/5.0 // Inject stolen cookie into attacker's browser (JavaScript console) document.cookie = "PHPSESSID=abc123def456ghi789; path=/" location.reload() // Attacker now logged in as victim // JWT hijacking (Bearer token in Authorization header) Authorization: Bearer eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9... // Attacker captures token, replays in their own requests

Session Hijacking Techniques & Attack Vectors

Packet Sniffing (Session Sidejacking)

Attacker captures HTTP traffic on unencrypted network (public Wi-Fi, ARP spoofing). Extracts session cookies (PHPSESSID, JSESSIONID) from HTTP headers. Tools: Wireshark, tcpdump, Bettercap, Ettercap. Mitigation: HTTPS (TLS) with HSTS, Secure cookie flag.

Network-based

Cross-Site Scripting (XSS)

Attacker injects malicious JavaScript into vulnerable website. Script steals document.cookie and sends to attacker server. Affects all users who view infected page. Mitigation: HttpOnly cookie flag (prevents JavaScript access), input sanitization, CSP (Content Security Policy).

Application

Session Fixation

Attacker forces victim to use known session ID (set by attacker). Victim logs in with attacker-controlled session ID. Attacker uses same session ID to access victim's account. Mitigation: Regenerate session ID after login (session_regenerate_id).

Application

Cross-Site Request Forgery (CSRF)

Attacker tricks victim into making unauthorized requests while authenticated (session hijacking limited to performing actions, not stealing token). Mitigation: CSRF tokens, SameSite cookie attribute (Lax/Strict), anti-CSRF headers.

Application

Session Token Prediction

Attacker predicts weak session IDs (sequential, predictable random number generators (RNG), time-based). Tools: Session ID brute force, token analysis. Mitigation: Cryptographically secure random session IDs (128+ bits), UUID v4.

Application

Man-in-the-Middle (MitM) Session Hijacking

Attacker performs ARP spoofing or rogue access point to intercept traffic. Captures session tokens from HTTP/HTTPS (if HTTPS, attacker downgrades with SSLStrip or uses fake certificate).

Network-based

Session Token Leak via Referer Header

Session token leaked in URL (GET request with session ID in query string). Referer header sent to external sites (ad networks, analytics) exposes token. Mitigation: Store session tokens in HTTP-only cookies, not URLs.

Application

Session Hijacking Tools (Educational Context)

Burp Suite (Proxy + Repeater)

Web application security testing tool. Proxy captures HTTP requests/responses (including cookies). Repeater replays captured requests with stolen session tokens. Cookie Jar manages session tokens. Intruder brute-forces weak session IDs.

Wireshark (Packet Sniffing)

Network protocol analyzer for capturing HTTP traffic and extracting session cookies from unencrypted connections (HTTP only). Filters: http.cookie, http.request. Follow TCP stream to view full conversation.

Bettercap (MitM + Session Hijacking)

Framework for ARP spoofing (becoming MitM) and sniffing HTTP traffic. Extracts session cookies from captured packets. Includes HTTP/HTTPS proxy for session hijacking.

OWASP ZAP (Zed Attack Proxy)

Web application security scanner with session hijacking features (Cookie Manager, Session token analysis). Can replay requests with stolen session tokens.

Cookie Manager (Browser Extension)

Browser extensions (EditThisCookie, Cookie-Editor) for injecting stolen session tokens into browser. Allows modifying, adding, deleting cookies for session hijacking.

Fiddler (Web Debugging Proxy)

HTTP debugging proxy for capturing and modifying requests. Can extract session cookies and replay requests with stolen tokens. Supports HTTPS decryption (requires certificate installation).

Session Hijacking Simulation (Cookie Theft)

This demonstration simulates session hijacking by capturing session cookies and replaying them to gain unauthorized access:

Click "Simulate Session Hijacking" to see cookie theft and account takeover

This is a simulated demonstration for educational purposes. Real session hijacking can steal session tokens via XSS (JavaScript), packet sniffing (unencrypted HTTP), or MitM attacks. Protect yourself with HTTPS (TLS), HttpOnly/Secure cookie flags, and HSTS (HTTP Strict Transport Security).

Detecting Session Hijacking Attacks

Anomalous IP Address / Geolocation

Session used from different IP address or country than usual. Example: User logs in from US, session hijacked from Russia. Web application detects IP mismatch and invalidates session. Implement IP binding (session tied to IP address).

User-Agent Anomalies

Session used with different browser or device than login (e.g., Chrome on Windows vs Firefox on Linux). Check User-Agent consistency. Invalidate session on mismatched User-Agent.

Unusual Session Activity

Multiple concurrent sessions from same account (impossible for single user). Session active for unusually long duration (days vs hours). High request rate (automated script). Rapid sequential requests (API abuse).

Invalid Session Token Attempts

Multiple requests with invalid session IDs (session ID brute force). Session token replay attacks (same token used from multiple sources). Detect in logs: 401 Unauthorized responses.

// Session hijacking detection techniques // IP address binding (session tied to IP address) $_SESSION['ip_address'] = $_SERVER['REMOTE_ADDR']; // On each request, validate IP consistency if ($_SESSION['ip_address'] !== $_SERVER['REMOTE_ADDR']) { session_destroy(); // Invalidate session - possible hijacking header('Location: /login.php?error=session_hijack_detected'); exit(); } // User-Agent validation $_SESSION['user_agent'] = $_SERVER['HTTP_USER_AGENT']; if ($_SESSION['user_agent'] !== $_SERVER['HTTP_USER_AGENT']) { session_destroy(); // Log session hijacking attempt error_log("Session hijacking detected: IP mismatch for user {$_SESSION['user_id']}"); } // Detect multiple concurrent sessions // Store active session IDs in database for each user // Prevent more than N concurrent sessions (e.g., 3) // Detect session token replay attacks (same token from multiple IPs) // Log all session token accesses with IP/timestamp // Alert if same session token used from geographically distant IPs within minutes // Web server log analysis (detect session hijacking) sudo grep "PHPSESSID=" /var/log/nginx/access.log | awk '{print $1, $7}' | sort | uniq -c | sort -nr // Look for same session ID from multiple IP addresses // Real-time monitoring (SIEM) // Alert criteria: // - Same session ID from 2+ IP addresses within 5 minutes // - Session accessed from geographically impossible locations (e.g., US then China in 30 seconds) // - User-Agent changes mid-session // - Session active > 12 hours without re-authentication

Preventing Session Hijacking (Secure Session Management)

HTTPS with HSTS (HTTP Strict Transport Security)

Always use HTTPS (TLS 1.2+) for entire application, not just login page. Prevents packet sniffing (session cookie theft over HTTP). Enable HSTS (Strict-Transport-Security header) to force browser to use HTTPS. Preload HSTS (hstspreload.org).

Secure Cookie Flags (HttpOnly, Secure, SameSite)

HttpOnly cookie flag prevents JavaScript access (mitigates XSS theft). Secure flag forces cookie over HTTPS only (prevents HTTP transmission). SameSite=Lax/Strict prevents CSRF and session fixation. Set in Set-Cookie header.

Regenerate Session ID After Login

Regenerate session ID after successful authentication (prevents session fixation). Use session_regenerate_id(true) (PHP), request.getSession().changeSessionId() (Java), or flask.session.regenerate() (Python).

Short Session Timeout (Idle & Absolute)

Implement idle timeout (15-30 minutes inactivity) and absolute timeout (8-12 hours regardless of activity). Invalidate session on logout and after timeout. Reduces window for session hijacking.

IP Address & User-Agent Binding

Bind session to client's IP address (IPv4) and User-Agent. Invalidate session if IP or User-Agent changes (potential hijacking). Allowlist for mobile carriers (dynamic IP).

Content Security Policy (CSP)

Deploy CSP to prevent XSS (cross-site scripting) attacks that steal session cookies. Header: Content-Security-Policy: script-src 'self'. Blocks inline JavaScript and external malicious scripts.

Multi-Factor Authentication (MFA)

Require MFA for sensitive actions (password change, money transfer). Session hijacking cannot bypass MFA challenge (TOTP, SMS). Time-based One-Time Password (TOTP) with 30-second window.

Session Activity Monitoring & Anomaly Detection

Monitor session activity for anomalies: multiple IPs per session, geographic impossible travel, unusual request patterns. Implement rate limiting (block automated session abuse). Alert on suspicious session activity.

Best Practice - Defense-in-Depth for Session Security: Always use HTTPS with HSTS preloading (prevents packet sniffing), set HttpOnly+Secure+SameSite cookie flags (prevents XSS theft and CSRF), regenerate session ID after login (prevents session fixation), implement short session timeouts (15-30 minutes idle), bind session to IP/User-Agent, and deploy CSP to prevent XSS. No single control prevents all session hijacking - layered defense is essential. Regular security audits (penetration testing) identify session management vulnerabilities.

Further Session Hijacking Resources & Information

OWASP Session Management Cheat Sheet

OWASP (Open Web Application Security Project) session management best practices: secure session ID generation, cookie flags (HttpOnly/Secure/SameSite), session timeout, session fixation prevention, and session hijacking detection.

Mozilla Observatory (Session Security Scanner)

Mozilla Observatory scans web applications for session security headers: HSTS, CSP, X-Frame-Options, X-Content-Type-Options, Referrer-Policy, and cookie flags (HttpOnly, Secure, SameSite).

MITRE ATT&CK - Session Hijacking Techniques

MITRE ATT&CK framework tactics: T1189 (Drive-by Compromise - XSS cookie theft), T1557 (Adversary-in-the-Middle - session sniffing), T1539 (Steal Web Session Cookie).

SANS SEC542 (Web App Penetration Testing)

Course covering session hijacking detection, session management vulnerabilities, XSS cookie theft, and session fixation attacks.

PortSwigger Web Security Academy (Session Hijacking)

Free Burp Suite Academy labs on session hijacking: session fixation, cross-site scripting (XSS) cookie theft, CSRF, and session token prediction.

Session Hijacking Detection Scripts

Community-maintained scripts for detecting session hijacking (IP binding, User-Agent validation, concurrent session detection, anomaly detection). Example implementations in PHP, Python, Node.js, Java.

← Back to Knowledge Base