Skip to content
Module 3 of 8Injection
Estimated time: 25 min

Cross-Site Scripting (XSS) & Sanitization

Taxonomy of Reflected, Stored, and DOM XSS, and context-aware escaping.

Core Concept & Mental Model

Cross-Site Scripting (XSS) occurs when an application receives untrusted data and includes it in a web page without proper validation, context-aware encoding, or sanitization, allowing an attacker to execute arbitrary JavaScript in the victim's browser.

Threat Vector & Impact

Once arbitrary JavaScript executes in a victim's browser, the attacker can hijack session cookies (unless HttpOnly), capture keystrokes, make authenticated API calls on the user's behalf, or redirect to credential harvesters.

Defensive Architecture & Mitigation

Context-aware output encoding (HTML body, attributes, JavaScript context), HTML sanitization with DOMPurify, Content Security Policy (CSP), and avoiding unsafe sinks like innerHTML or dangerouslySetInnerHTML.

Technical Deep Dive

The Three Primary XSS Classes

  • Stored (Persistent) XSSMalicious payload is permanently saved in the database (e.g. comment forum, user profile) and delivered to all users who view the content.
  • Reflected (Non-Persistent) XSSPayload is delivered via URL parameters or form submissions and reflected immediately by the server in the response page.
  • DOM-based XSSAttack payload never leaves the browser. Client-side script reads from an untrusted source (location.hash, searchParams) and writes directly into a dangerous sink (innerHTML, eval).

Dangerous Sinks to Avoid in Modern Web Apps

Avoid `element.innerHTML`, `document.write()`, `window.eval()`, `new Function()`, `setTimeout(string)`, and React `dangerouslySetInnerHTML`. Always prefer `element.textContent` or pre-compile templates.

Interactive Mental Model Simulation

Live Visualizer
VISUALIZATION: REFLECTED XSS
Attacker
Victim
Vulnerable Server
BROWSER RENDERER
Waiting for response...
Attacker crafts a link containing a malicious script in the URL parameters.

Code Implementation & Patching

Vulnerable Code (Exploitable)
// Vulnerable DOM XSS in client router
const params = new URLSearchParams(window.location.search);
const userName = params.get('name'); // Source: untrusted query string

// Dangerous Sink: unescaped innerHTML
document.getElementById('welcome').innerHTML = "Welcome back, " + userName;
// Attacker URL: ?name=<img src=x onerror=alert(document.cookie)>
Secure Patched Code (Hardened)
// Secure implementation using safe DOM API and DOMPurify
import DOMPurify from 'dompurify';

const params = new URLSearchParams(window.location.search);
const userName = params.get('name') || 'Guest';

// Option A: Safe textContent (prevents all HTML parsing)
document.getElementById('welcome').textContent = "Welcome back, " + userName;

// Option B: If rich HTML is strictly necessary, sanitize thoroughly
const cleanHTML = DOMPurify.sanitize(userProvidedBio, {
  ALLOWED_TAGS: ['b', 'i', 'em', 'strong', 'a'],
  ALLOWED_ATTR: ['href']
});
document.getElementById('bio').innerHTML = cleanHTML;
Security Analysis & Core Architectural Rule

textContent treats all input strictly as text characters, rendering <script> as literal inert characters. When HTML is required, DOMPurify strips unsafe tags, attributes, and pseudo-protocols like javascript:.

Test Your Knowledge on Cross-Site Scripting (XSS) & Sanitization

Challenge yourself with realistic scenario questions in the Web Security Arena.

Launch Practice Arena