Cross-site scripting for defenders
Reflected, stored and DOM XSS, what an attacker can do with script in your origin, why the output context decides the encoding, how framework escape hatches reintroduce the bug, and a layered fix of auto-escaping, sanitisation, safe URLs and a strict CSP.
01Three ways script gets into your page
- Distinguish reflected, stored and DOM-based XSS and where each enters
- Explain the real impact of script running in your origin
- Choose the right encoding for each output context
- Find XSS through framework escape hatches and fix it in layers
Cross-site scripting (XSS) is injection into a web page: attacker-controlled data is rendered so that the browser runs it as script in your site's origin. The browser cannot tell that script from your own, so it gets your cookies (unless HttpOnly), your DOM, your APIs and the user's authenticated session.
| Type | Where the payload lives | Example | Who is hit |
|---|---|---|---|
| Reflected | In the request (query string, form field), echoed in the response | /search?q=<script>alert(1)</script> rendered into the results page | Users who follow a crafted link |
| Stored | Saved by the server: comments, profile names, support tickets | A display name containing markup, shown to every viewer | Everyone who views the content, including admins |
| DOM-based | Never reaches the server, or is handled only by client-side code | el.innerHTML = location.hash.slice(1) | Users who follow a crafted link; invisible to server logs |
Stored XSS is usually the most serious because it needs no lure and runs for every viewer. The Samy worm (2005) was stored XSS in MySpace profiles: each infected profile added the viewer as a friend and copied itself into their profile, reaching over a million accounts in about a day. Stored XSS that fires in an internal admin tool, such as a support dashboard rendering ticket text, can hand an attacker an administrator's session.
02What script in your origin can do
- Act as the user: call your APIs with the user's cookies, change their email address, then reset their password. This works even when session cookies are HttpOnly.
- Steal tokens stored where script can read them:
localStorage, non-HttpOnly cookies, values in the DOM. - Rewrite the page: a convincing fake login form on your real domain, served over your real TLS certificate.
- Capture input: keystrokes on payment or password fields on the same page.
- Spread: post content containing the payload, as Samy did.
Proof-of-concept payloads pop an alert box because it is harmless and obvious. Do not let that set the severity. Script in your origin can do anything the logged-in user can do, so an XSS on an admin page is effectively admin account takeover.
03The output context decides the encoding
There is no single "escape for the web" function. The same untrusted value needs different handling depending on where it lands, because each context has different characters that end the data and start code. This is why hand-rolled escaping fails and auto-escaping templates succeed: the template engine knows the context.
| Context | Example sink | What breaks out | Correct handling |
|---|---|---|---|
| HTML body | <p>{name}</p> | < starts a tag | HTML-encode & < > " ' |
| Quoted attribute | <input value="{name}"> | " ends the attribute, then onfocus=... | Attribute-encode; always quote attributes |
| URL attribute | <a href="{url}"> | javascript: scheme runs script without any special characters | Allow-list schemes (https:, mailto:), then attribute-encode |
| JavaScript | <script>var n = "{name}";</script> | " or </script> | Avoid. Pass data as JSON in a data attribute or a type="application/json" block |
| CSS | style="color: {c}" | url(...), expressions in old browsers | Avoid; allow-list values |
// React escapes text children and attribute values automatically:
<p>{comment.author}</p> // safe: rendered as text
// ...but these are the escape hatches where XSS comes back:
<div dangerouslySetInnerHTML={{ __html: comment.html }} /> // raw HTML: must be sanitised first
<a href={profile.website}>site</a> // "javascript:..." is a script URL: validate the scheme
// Fix for links: allow-list the scheme
function safeHref(raw: string): string {
try {
const u = new URL(raw);
return u.protocol === "https:" || u.protocol === "http:" ? u.href : "#";
} catch {
return "#";
}
}Vue v-html, Angular bypassSecurityTrustHtml, Jinja's |safe and Markup(), Django's mark_safe, Blade's {!! !!}, and plain innerHTML, outerHTML, insertAdjacentHTML and document.write in vanilla JavaScript. These are the lines to grep for in review.
04How XSS is found
- Review the escape hatches listed above and trace where their input comes from. Most modern XSS lives in a handful of these calls.
- Canary testing: submit a unique harmless string such as
xss7f3a<>"'into every field, then search rendered pages and API responses for where it appears and which characters survive unencoded. That tells you the context and whether encoding is applied. - DOM XSS needs client-side analysis: follow sources (
location,document.referrer,postMessagedata,window.name) to sinks (innerHTML,eval,setTimeoutwith strings,script.src). Browser devtools, DOM Invader in Burp Suite and SAST for JavaScript all help. - CSP violation reports in report-only mode show where inline script is being attempted, which sometimes reveals live injection attempts.
- Rendering surfaces outside the main app: email templates, PDF generators, admin dashboards and log viewers often skip the framework's escaping.
05Fixing XSS in layers
The primary fix is to render untrusted data through an auto-escaping template or framework and never bypass it with raw data. When the product genuinely needs user-supplied HTML (rich text comments, markdown), sanitise it with a maintained allow-list sanitiser such as DOMPurify, configured to permit only the tags and attributes you need. Sanitise at render time or on every output path, not only on input, so a change in the sanitiser or a new rendering path does not leave stored content unchecked.
A typical question: "we use React, so we are safe from XSS, right?". Say React escapes by default, then name the gaps: dangerouslySetInnerHTML, javascript: URLs in href, server-side templates and emails outside React, and DOM sinks in non-React code. Finish with CSP and Trusted Types as the backstop. That shows you know where the bug survives in modern stacks.
"XSS is untrusted data rendered as script in our origin, so its impact is whatever the user can do. The main control is auto-escaping in the framework with raw HTML sinks banned unless reviewed. Where we need user HTML, DOMPurify with a tight allow-list at render time; user links get a scheme allow-list. Behind that, a strict nonce-based CSP and Trusted Types catch what slips through, and session cookies are HttpOnly so script cannot read them directly."
A profile page renders `<a href={user.website}>` in React. The value is stored as `javascript:fetch('/api/email',{method:'POST',body:'x'})`. What is the best fix?
Q1Is HttpOnly a fix for XSS?+
No. It stops script reading the session cookie, but the injected script can still make authenticated requests as the user from the same page. It limits one impact, not the bug.
Q2Why sanitise at output rather than input?+
Content stored years ago was cleaned with an older sanitiser and older rules. Sanitising at render time applies today's rules to everything, and protects new rendering paths you have not thought of yet.
Q3Why is DOM XSS harder to detect?+
The payload may sit in the URL fragment, which browsers never send to the server, so server logs and WAFs never see it. You need client-side analysis and Trusted Types to catch it.