Memorizing XSS as “Reflected, Stored, and DOM-based” or reciting twenty -src directive names rarely helps when facing hex-entity relays inside onclick, public CDN allowlist gadgets, or <base> relative-path hijacking.
Following the browser parsing pipeline in order, the five split-screen scrollytelling stages below (inspired by R2D3’s A Visual Introduction to Machine Learning) and two interactive sandboxes connect all four XSS layers with the Content Security Policy matrix.
Layer 1: HTML Body
In plain element body text, everything hinges on whether < switches the HTML5 tokenizer out of data mode—and why filtering angle brackets alone misses more than seventy percent of real-world vectors.
Two Fates of Every Byte
To a reader, a webpage is formatted prose; to a browser engine, the network delivers a linear byte stream. Every character must be classified into either trusted code structure or inert user data.
Every XSS exploit tricks the parser into treating inert data as executable instructions. Hover any quadrant on the right or scroll down to trace the state machine.
Plain Text Inside HTML Body
Watch the HTML5 tokenizer needle sweep across the stream: outer <div> tags build the container element, while Alice keeps the lexer inside DATA_STATE, hanging a harmless #text leaf on the DOM tree.
Minting Elements with Angle Brackets
In HTML body text, < is the sole state-transition trigger. Striking < flips the lexer into TAG_OPEN_STATE, sprouting a live <img> branch whose failed src=x immediately fires onerror.
Disarming Angle Brackets via Entities
Encoding < into four literal characters < prevents the tokenizer from ever entering tag-open state. Modern frameworks ({x} in React, {{x}} in Vue) achieve the same guarantee via DOM text nodes.
Why Filtering < and > Fails Elsewhere
Beginners often conclude: "If I escape < and > everywhere, XSS is impossible." Testing 144 multi-context payloads on the right reveals the trap: only 28% are caught, while 72% cross boundaries without a single angle bracket.
Layer 2: Syntax Rooms
Once untrusted input enters HTML attributes, inline script variables, or URL attributes, the walls guarding data shift from angle brackets to quotes and URL schemes.
Different Rooms, Different Doors
Untrusted data rarely sits only between tags; templates routinely place it inside HTML attributes, JavaScript variables, or URL attributes. None of these three rooms are guarded by angle brackets.
Room A: Breaking Out with Quotes
Inside <input value="...">, the first injected " shuts value early and spills into the tag's attribute corridor to mount onfocus—zero angle brackets required. (Unquoted attributes are even weaker: a single space breaks out.)
Room B: Splitting the JS AST
Inside a <script> block, "; closes the string literal and appends a sibling CallExpression node to the AST while // comments out the trailing quote. Worse, a literal </script> closes the block regardless of JS quotes.
Room C: Symbol-Free javascript: Links
Count the special characters in javascript:alert(1): no angle brackets, no quotes, no slashes, no spaces. Character escaping cannot touch it because it flips the URL scheme switch straight into the JS engine.
Locking Each Room by Its Own Grammar
Encode quotes as " inside quoted attributes; serialize JS data via JSON.stringify plus \u003c; and parse URLs via new URL() to allowlist only http: and https:.
Layer 3: Parser Relays
Nesting one grammar inside another—most notoriously inside onclick—lets the browser’s automatic entity-decoding relay resurrect filtered quotes right inside memory.
Room Inside a Room: Inline Handlers
Inline event attributes nest a single-quoted JavaScript program inside an HTML attribute. Every payload passes sequentially through two distinct browser parsers.
Blocking Literal Quotes at the Gate
Suppose a WAF or backend filter blocks every literal ', ", <, and >. Naive quote breakouts crash into Chamber 01 and stop—creating a false sense of security.
How ' Resurrects Inside Memory
Watch the ribbon cross all three chambers (toggle 0.35x Slow to inspect): ' contains zero literal quotes so Chamber 01 passes it; Chamber 02 (HTML5 attribute parser) automatically decodes character references inside attributes, fusing ' back into a live ' that breaks open Chamber 03!
Severing the Parser Relay with dataset
b.addEventListener("click", () => greet(b.dataset.name));
Instead of manually stacking multi-layer encodings, decouple code from data: store input in data-* and pass dataset.name by variable reference. Even after HTML decoding, the string never enters the JS syntax parser.
Layer 4: SPA Runtime
React and Vue neutralize classic string concatenation by default, yet rich-HTML escape hatches (innerHTML / v-html) and global variable shadowing (DOM Clobbering) open client-side attack paths.
Why Modern Frameworks Still Get Hit
React and Vue bind text safely by default and bind events as function references rather than strings. Yet modern SPAs still suffer severe XSS through two client-side runtime paths.
Path 1: Raw HTML Escape Hatches
Rich-text comments, Markdown previews, or unvalidated :href="url" bindings bypass the Virtual DOM shield. When fed from location.hash or postMessage, payloads execute purely inside the browser without ever touching server logs.
Path 2: DOM Clobbering & Script Gadgets
Even when all scripts and event attributes are stripped, injecting a benign-looking tag with id="APP_CONFIG" shadows window.APP_CONFIG via legacy DOM Clobbering (or JS prototype pollution), tricking your own legitimate bundle.js into loading attacker code.
Engine-Level Type Lock on Sinks
Enabling Trusted Types turns raw string assignments to innerHTML into an immediate engine TypeError. Only TrustedHTML objects minted by a centralized DOMPurify policy are accepted.
Act 5: The CSP Matrix
When a code defect still slips through, Content Security Policy acts as the browser’s last-line capability firewall. Mastering CSP means reading it as a 2D matrix of Resource Channels × Trust Credentials—and shifting from host allowlists to per-response cryptographic nonce tokens plus 'strict-dynamic'.
What CSP Actually Is (and Isn't)
CSP is not a substitute for output encoding; it is a browser-enforced capability and egress mitigation layer. Even if HTML injection occurs, the browser validates script execution, plugin containers, base URLs, and network exfiltration against the HTTP response header.
Channels × Credentials & the 3 Non-Fallback Traps
Every CSP policy is a 2D matrix of Resource Channels × Trust Credentials. Standard -src fetch directives inherit from default-src, except the three amber rows on the right: base-uri, form-action, and frame-ancestors never fall back to default-src!
Why Host Allowlists Collapse in Practice
Policies like script-src 'self' https://cdn.jsdelivr.net block inline scripts and evil.test, yet allow any attacker-uploaded GitHub file mirrored on jsDelivr (or JSONP endpoints ?callback=alert(1) on allowlisted domains) to sail right through!
Cryptographic Nonces & Locking <base>
Per-request random nonce values block injected tags; 'strict-dynamic' lets nonced bundles load async chunks via createElement('script') while automatically disabling brittle host allowlists; and base-uri 'none' stops <base href="https://evil.test/"> from hijacking relative script URLs.
Five Interlocking Gates in Action
When context-aware escaping, scheme allowlists, dataset isolation, Trusted Types, and Strict CSP + HttpOnly work in concert, benign traffic renders at 100% fidelity while every exploit class is deterministically contained.
Reference Matrices
1. XSS Evolution Matrix
| Layer | Parsing Context | Core Breakout Mechanism | Engineering Remediation |
|---|---|---|---|
| Layer 1 | HTML Element Body | Injecting < > switches the HTML5 tokenizer into TAG_OPEN_STATE to mint new elements out of thin air | HTML entity encoding (or default text-node binding in React {x} / Vue {{x}}) |
| Layer 2 | Attributes / JS Strings / Links | Breaking out of quotes early, or injecting symbol-free javascript: schemes into URL attributes | Context-specific escaping per room; parse links and enforce an explicit http: / https: allowlist |
| Layer 3 | Nested Contexts (e.g., onclick) | Exploiting the automatic HTML-entity decode → URL decode → JS parse relay so ' resurrects as a live single quote | Never concatenate untrusted data into inline handlers or scripts; pass values via data-* attributes + dataset + addEventListener |
| Layer 4 | Modern SPA Runtime & Browser Gates | Misusing dangerous sinks like innerHTML / v-html, or using DOM Clobbering / prototype pollution as script gadgets | Sanitize rich HTML with DOMPurify + enforce engine-level Trusted Types + deploy Strict Nonce CSP |
2. CSP Bypass Matrix
| Directive | Controlled Channel | Falls Back to default-src? | Common Misconfigurations & Bypasses | Production Baseline |
|---|---|---|---|---|
default-src | Fallback gate for standard fetch directives | Root fallback itself | Assuming it covers base-uri, form-action, and frame-ancestors, leaving side doors wide open | 'none' or 'self' |
script-src | External scripts, inline blocks, event attributes, javascript:, and eval() | Yes | Allowing 'unsafe-inline' defeats XSS protection; trusting cdn.jsdelivr.net or JSONP hosts lets attackers load arbitrary scripts | 'nonce-<random>' 'strict-dynamic' |
base-uri | Restricts <base href="..."> relative-URL resolution | No (Frequently omitted) | Deploying nonces without base-uri: injecting <base href="https://evil.test/"> hijacks subsequent nonced relative scripts | 'none' or 'self' |
object-src | <object> / <embed> plugin and nested contexts | Yes | Leaving plugin containers open allows script execution via embedded data: documents | 'none' |
connect-src | fetch / XHR / WebSocket / sendBeacon endpoints | Yes | Overly broad origins allow executing scripts to exfiltrate tokens and responses silently | 'self' + explicit API origins |
img-src / style-src | Image loads and stylesheet rendering | Yes | img-src * enables beacon exfiltration; CSS attribute selectors enable character-by-character side channels | Restrict to 'self' data: and trusted CDNs |
form-action | Restricts <form action="..."> submission targets | No (No fallback) | HTML-only injection can plant a fake form that posts credentials or hidden inputs to an external host | 'self' |
frame-ancestors | Restricts parent <iframe> embedding (clickjacking defense) | No (Header only) | Ignored inside <meta http-equiv>; must be delivered via an HTTP response header | 'none' or 'self' |
require-trusted-types-for | Guards DOM XSS sinks such as innerHTML at the engine level | Independent directive | Nonce CSP alone cannot stop DOM XSS inside already-trusted bundles; require typed sanitization before innerHTML | 'script' |
Interactive Workbenches
Both deterministic sandboxes below run purely in memory without executing untrusted payloads, allowing you to test bypass conditions and CSP combinations directly:
2D CSP Matrix & Live Bypass Evaluator
Select a preset or click any cell in the 8×8 matrix to inspect inheritance and 6 live exploit probes.
A+ · Strict| Directive \ Source | 'none' | 'self' | cdn.jsdelivr | unsafe-inline | unsafe-eval | sha256-Hash | nonce-* | strict-dynamic |
|---|
Four-Layer Browser Parser X-Ray
Deterministic parser sandbox — inspect the exact string seen at each decoding stage safely.
DISCUSSION / COMMENTS
Comments
Powered by GitHub Discussions. Leave a comment below.