Lesson 1 of 9 · 20m
How XSS Actually Happens
The browser does not know which bytes were trusted — the only model that predicts XSS is input, sink, parser context, and output encoding.
Most developers can recite "validate input" and still ship XSS. The reason is simple: XSS is not primarily an input-validation failure. It is an output-context failure. The browser receives one byte stream, parses HTML, then switches into JavaScript, CSS, URLs, and attributes according to context. If attacker-controlled text lands in the wrong grammar, it executes.
The four-part model
Every XSS bug has four parts:
- Source — where the attacker controls data: query string, post body, JSON API, localStorage, postMessage, uploaded filename.
- Transport — how it reaches the page: immediate HTML response, database retrieval, client-side routing, another user viewing stored content.
- Sink — the exact place it enters the document:
innerHTML, an attribute, a script block,eval, a template interpolation. - Context — what parser state the bytes land in: text node, quoted attribute, unquoted attribute, JavaScript string, URL, CSS, HTML markup.
If you cannot name all four, you are guessing. "The input had a script tag" is not analysis; it is payload trivia.
A minimal reflected example
// search.php — the classic bug
<p>Results for <?= $_GET["q"] ?></p>Request:
GET /search.php?q=%3Csvg%20onload%3Dalert(1)%3E HTTP/1.1
Host: shop.internalThe server does not execute anything. It merely returns attacker bytes inside an HTML document. The victim's browser builds a new SVG element and runs the onload handler. Server-side code can look completely ordinary while producing a client-side code-injection primitive.
Why encoding beats filtering
You cannot reliably enumerate dangerous strings. <script> is only one payload among hundreds; event handlers, SVG, javascript URLs, malformed tags, template syntax, and browser mutation all mutate the search space. Correct defense is contextual: encode text as HTML text, encode attributes as attribute values, and never treat URLs or markup as plain strings.
Field notes
- The attacker does not need to inject a full
<script>tag; one attribute or parser mutation can be enough. - HTTPS, authentication, CSRF tokens, and same-site cookies do not prevent XSS.
- A payload firing in your browser is proof of exploitability only when it executes in the victim's expected origin and session.
- Read the response body, not just the request — reflection without execution context is often harmless.
Was this lesson helpful?