Escaping is about context, not about the string
Why one escaping function never fits every place you print data, how auto-escaping templates still leave holes, the DOM-XSS source-to-sink model, mutation XSS and blind XSS, filter-bypass encodings, and why a Contributor-level stored XSS in a CMS is a privilege-escalation bug.
Ask a developer how to prevent cross-site scripting and the usual answer is “escape user input”. That answer is not wrong, but it hides the part that decides whether your page is safe: escape it for what?
The same string, x" onload="alert(1), is harmless between two <p> tags, dangerous inside a quoted HTML attribute, and dangerous in a different way inside a <script> block. No single function makes a string “safe”. There are only functions that make a string safe for one specific place in the document. XSS almost always comes from using the right function in the wrong place, or from forgetting that a place exists at all.
A little theory: the browser runs several parsers
A web page is not one language. When the browser reads your HTML, it hands pieces of it to different parsers, and each has its own special characters:
| Output context | Example | Characters that break out |
|---|---|---|
| HTML body | <p>DATA</p> |
<, & |
| Quoted attribute | <img class="DATA"> |
the matching quote, & |
| Unquoted attribute | <img class=DATA> |
space, >, =, quotes, backtick… |
| URL attribute | <a href="DATA"> |
everything above, plus the scheme: javascript: |
| JavaScript string | <script>var x = "DATA"</script> |
the quote, \, newline, and </script> |
| CSS | <div style="color: DATA"> |
;, }, (, url(, expression in old engines |
An HTML-body escaper turns < into <. That is enough for the first row and not enough for any other. It does nothing about a " inside an attribute, nothing about javascript:alert(1) in an href (there is not a single < in it), and nothing about ";alert(1);// inside a script string.
Contexts also nest. An onclick="..." handler is a JavaScript context inside an HTML attribute context: the browser HTML-decodes the attribute first, then runs it as JavaScript. So " in an event handler becomes a real " before the JS parser ever sees it. This is why “I HTML-escaped it” does not protect a value placed inside an inline event handler.
The WordPress toolbox, one function per context
WordPress is a useful example because its escaping API is named after contexts, not after “safety”:
esc_html()for text between tags.esc_attr()for the value of a quoted attribute. It encodes quotes, so the value cannot close the attribute.esc_url()forhref,srcand similar attributes. It restricts the scheme to an allowlist, which is what blocksjavascript:anddata:URLs.esc_attr()alone does not.wp_json_encode()(oresc_js()for small inline strings) for data going into JavaScript. JSON-encoding produces a valid JS literal; with theJSON_HEX_TAGflag it also encodes<and>, so the data cannot close the<script>element.wp_kses()/wp_kses_post()when you need to allow some HTML. This is sanitisation, not escaping: it parses the markup and keeps only allowed tags and attributes.
The sanitize_* family is missing from that list on purpose. sanitize_text_field() is an input filter. It strips tags and line breaks, but it does not encode quotes, because it does not know where the value will be printed. A value that passed sanitize_text_field() on save is still dangerous if you later echo it raw into an attribute. “Sanitise on input, escape on output” is the WordPress rule because the input side cannot know the output context.
Where auto-escaping stops
Modern templating engines (Twig, Blade, React’s JSX, Jinja2 as Flask configures it, and others) escape by default, which removes most body-context bugs. The remaining bugs cluster in a few predictable places, because the engine either does not know the context or cannot fix it:
- Unquoted attributes.
<div class={{ value }}>with an HTML-escaper still lets a space through, and a space starts a new attribute:x onmouseover=alert(1). Always quote attributes. - URL schemes. Auto-escaping encodes characters; it does not validate meaning.
<a href="{{ user.website }}">is correctly escaped and still runsjavascript:alert(1)on click. You need a scheme allowlist. - Inline event handlers and
<script>blocks. An engine that escapes for HTML is using the wrong encoder inside JavaScript. Pass data through a JSON-encoded data attribute or a<script type="application/json">block and read it from JS instead. - Explicit opt-outs.
|safe,|raw,{!! !!},Markup(),dangerouslySetInnerHTML. Each of these is a place where a human promised the value was safe. Grep for them. - The JavaScript side. Server-side escaping is irrelevant once client code does
el.innerHTML = location.hash.slice(1). That is DOM-based XSS: the payload never touches your template.
Stored, reflected, DOM: same bug, different delivery
The three classic labels describe how the payload reaches the vulnerable sink, not what the sink is:
- Reflected: the payload is in the request (a query parameter, a form field, a path segment) and echoed straight back in the response. The victim has to be tricked into sending that request, usually through a crafted link. One victim per link, and it dies when the tab closes.
- Stored: the payload is saved server-side (a comment, a profile field, a gallery setting, a filename) and rendered for everyone who views it later. No link-clicking needed, and it fires again on every view.
- DOM-based: client-side JavaScript reads attacker-influenced data (URL fragment,
postMessage,localStorage) and writes it into a dangerous sink. The payload may never touch the server, so server-side escaping and even server logs can miss it.
In all three, the base fix is the same: encode for the context at the sink. The blast radius differs, though, and stored XSS is the worst of the three, especially in a CMS. A reflected bug needs a fresh victim for every firing; a stored bug is planted once and then served by the trusted application to every reader, including the people with the most privilege. In a CMS the natural readers of attacker-stored content are editors and administrators reviewing it, so the normal editorial workflow becomes the delivery mechanism (see the Contributor section below).
DOM-XSS: the source-to-sink model
DOM-based XSS gets its own section because the whole bug lives in the browser, and server-side defences never run. Treat it as a dataflow problem: a source is any value an attacker can influence, and a sink is any API that turns a string into markup or code. A bug exists wherever a source reaches a sink without context-correct encoding in between.
| Common sources | Common sinks |
|---|---|
location.hash, location.search, location.pathname |
element.innerHTML, outerHTML |
location.href, document.URL, document.referrer |
document.write(), document.writeln() |
window.name |
insertAdjacentHTML() |
postMessage event data |
eval(), new Function(), setTimeout("string") |
localStorage / sessionStorage values |
jQuery $(...).html(), $(...).append(), $(html) |
| cookies, WebSocket messages | element.setAttribute('href'/'src', …), .src, location = |
The common one-liner is el.innerHTML = location.hash.slice(1): the fragment after # never leaves the browser, so nothing on the server sees it, yet it is parsed as HTML. jQuery often makes this worse, because $(userControlled) treats a string that looks like HTML as HTML, and .html() is a direct innerHTML wrapper. Assigning a source into href/src (or to location) is its own sink: a javascript: URL there executes on click or on load. setAttribute('href', source) is the same trap in attribute form; it writes the scheme without validating it.
The fix is not a string-escaping function. It is to stop feeding sources into HTML/JS sinks. Prefer textContent over innerHTML, build nodes with createElement/setAttribute (validating URL schemes), and where rich HTML is unavoidable, run it through a vetted sanitizer before it reaches the sink. At the browser level, Trusted Types turns the dangerous sinks into typed choke points that reject raw strings outright (covered under the fix).
Mutation XSS: when the browser rewrites your “safe” HTML
Mutation XSS (mXSS) is the reason you do not hand-roll an HTML sanitizer. The trap: you take untrusted HTML, run it through a filter that parses it and emits a string it believes is safe, then assign that string to innerHTML, and the browser re-parses it on assignment. The HTML parser does not round-trip. Error-correction, implied tags, namespace confusion (SVG/MathML vs HTML) and attribute re-serialisation quirks can mutate the “clean” markup into something that now contains an executable construct the sanitizer never approved.
The sanitizer and the browser disagree about what the string means, and the browser wins because it runs second. So use a well-tested, maintained sanitizer like DOMPurify, and keep it updated. mXSS vectors are found against these libraries and patched; a hand-written regex filter has no such process and falls to the first parser quirk its author did not know about. Sanitize as close to the sink as possible, and do not re-parse output you already sanitized.
Blind XSS: the payload you never see fire
Blind XSS is a stored bug whose sink is somewhere you cannot observe. It executes later, in a context the attacker never visits. A support-ticket subject, a User-Agent string, a delivery-address field or an error message gets stored and is then rendered unescaped in an internal tool: an admin dashboard, a log viewer, a CRM, an analytics backend. The attacker submits the payload and sees nothing in their own response; it fires minutes or days later in a staff member’s browser.
Because it fires late and out of band, it is easy to miss in testing, and the impact is high when it lands, since the victim is almost always a privileged internal user. The practical approach is an out-of-band callback: a payload that, when it executes, phones home to a collector with the URL and DOM where it fired, so you learn that and where it ran without seeing the page. For defenders: internal admin and log-viewing UIs are output contexts too, and fields you treat as “just logging” are sinks.
Getting past the filter: encodings and broken markup
Blocklist filters and naive sanitizers fail because there are many ways to spell the same payload. Both sides need to know the families: testers to test, defenders to understand why allowlisting beats blocklisting. Some recurring tricks:
| Technique | Example idea | Why it slips through |
|---|---|---|
| HTML-entity encoding | javascript: for javascript: |
filter matches the literal string; the browser decodes the entity first |
| URL / percent encoding | %6a%61vascript: in an href |
the URL parser decodes after the string filter ran |
| Case variation | <ScRiPt>, oNmOuSeOvEr= |
HTML tag/attribute names are case-insensitive, naive matches are not |
| Event handlers, no quotes | <img src=x onerror=alert(1)> |
no quotes or spaces to key a filter on; dozens of on* handlers exist |
| Scheme smuggling | javascript: and data:text/html,… URLs, iframe srcdoc |
the sink executes the scheme; entity/whitespace tricks hide the prefix |
| Broken / nested tags | <img src=1 onerror=…, <scr<script>ipt> |
browser error-correction completes the tag the filter thought it had neutralised |
| Null bytes / junk whitespace | java\x00script:, tabs/newlines inside the scheme |
parsers strip control characters the filter preserved |
You do not need to memorise payloads. A blocklist is a guess about the full input space, and the browser’s parser is the ground truth. That is why the defences in this post are to encode for the context (so the bytes can never become markup) and to allowlist what you keep (known-good tags, attributes and URL schemes) rather than trying to strip known-bad input.
Why “only a Contributor” is not a mitigation
In a CMS, stored XSS behind a low role is often dismissed as low impact: “the attacker needs an account”. That misses how CMS roles work. WordPress Contributors can write posts but deliberately cannot publish them, and cannot use unfiltered HTML. The editorial workflow exists so that someone more privileged reviews their content.
So a Contributor-level stored XSS turns the review workflow into the delivery mechanism. The Contributor saves a payload, an administrator opens the draft to review it, and the script runs in the administrator’s session. From there it can do anything the admin’s browser can: create a new administrator account, install a plugin, edit a theme file. The bug is not “XSS for Contributors”. It is a path from the lowest content role to full site control, and on many sites the Contributor role is handed out freely to guest authors.
A real one: Photoblocks and the class attribute
The Photoblocks stored XSS write-up shows a context mismatch in a few lines. The gallery plugin let a user with edit_posts (Contributor and above) save a gallery-level image_class setting. On save, it ran sanitize_text_field() over the settings, which strips tags but keeps double quotes. On render, it printed the value raw into a quoted class attribute:
<img
class="pb-image skip-lazy <?php echo $block->get_image_class(); ?>"
src="data:image/png;base64,...">A value like x" onload="alert(document.domain) closes the class attribute and adds an onload handler. Because the <img> has a valid inline src, the image always loads and the handler fires with no interaction, in the browser of anyone who views a page with the gallery, administrators included. I confirmed this on a local WordPress test site before reporting it. An earlier security update in the same file had already added esc_attr() to rel, target and the link href, but missed the class value. The issue was published as CVE-2026-107323 and fixed in version 1.3.6. The context-correct fix is a single escape for the attribute context:
<img
class="pb-image skip-lazy <?php echo esc_attr( $block->get_image_class() ); ?>"
src="data:image/png;base64,...">The full write-up covers the root cause and the incomplete earlier fix in detail.
How to find this in your own code
- List your sinks, not your inputs. Grep for raw output: in PHP,
echo $and<?=without anesc_*call; in templates,|safe,|raw,{!!; in JS,innerHTML,outerHTML,insertAdjacentHTML,document.write,dangerouslySetInnerHTML,eval,new Function, and jQuery.html()/.append()/$(…)fed from a URL,postMessageor storage. For DOM bugs, trace each source (location.*,window.name,postMessage) to the sink it reaches. - For every sink, name the context. Body, quoted attribute, URL, JS, CSS. Then check the escaper matches.
esc_html()insidehref="..."is a finding.esc_attr()on a URL is a finding.sanitize_text_field()on save with no escape on output is a finding. - Check the neighbours of fixed bugs. When a file has been patched for XSS on some fields, check every other field in that file. Patches are often applied to the reported parameter only.
- Test with context-breaking payloads, not just
<script>. Use",', a space,javascript:, and</script>. A payload with no angle brackets is the quickest way to find attribute and URL bugs.
CSP: a second line, not the first
A Content Security Policy is defence in depth for the day your encoding has a hole. A policy that drops 'unsafe-inline' and instead allowlists your own scripts by nonce or hash means an injected onload= handler or inline <script> does not run. The bug is still there, but it is no longer exploitable the easy way. That is useful, and it is also why CSP belongs after output encoding, never instead of it.
At an awareness level, know that a carelessly built CSP is routinely bypassed:
'unsafe-inline'(and'unsafe-eval'). The moment either is present, the policy stops blocking injected inline script. Many “we have a CSP” sites ship'unsafe-inline'for convenience and get almost no XSS protection from it.- Gadgets on trusted origins. If you allowlist a whole CDN or a domain that hosts a JSONP endpoint or a vulnerable framework, an attacker can often reach executable code through that allowed origin: a JSONP callback that reflects a parameter into script, or a known script-gadget in an allowlisted library. Host allowlists are much weaker than nonces/hashes for this reason.
- Nonce reuse / predictable nonces. A nonce must be unique and unguessable per response. A nonce reused across requests, or leaked into a place an attacker can read, lets injected script carry the valid nonce and execute.
The strong configuration is a strict, nonce-based policy (script-src 'nonce-…' 'strict-dynamic'), no 'unsafe-inline', and no blanket host allowlists.
The fix
- Escape late, at the point of output, for that exact context. Not on input, not “once at the top”. Context-aware output encoding is the primary control.
- Quote every attribute, so attribute escaping has a boundary to protect.
- Allowlist URL schemes (
http,https,mailto) for anything that ends up inhreforsrc. - For rich text, use an allowlist sanitizer, not a blocklist. Run untrusted HTML through a vetted, maintained library like DOMPurify that keeps only known-good tags and attributes, and keep it updated for mXSS fixes. Do not hand-roll it, and do not re-parse its output.
- Keep data out of executable contexts. Put it in JSON data attributes and read it with
textContent/dataset; usetextContentinstead ofinnerHTMLon the client. - Lock down DOM sinks with Trusted Types.
require-trusted-types-for 'script'makes the browser refuse a raw string atinnerHTML,document.write,evaland similar sinks, forcing all HTML through a policy you control (typically backed by DOMPurify). It changes DOM-XSS defence from “find every sink” to “every sink is enforced centrally”. - Restrict who can store markup. If a field is supposed to be a CSS class, validate it as one on save (in WordPress,
sanitize_html_class()on each token). Validation narrows what can be stored; it does not replace escaping on output. - Add a Content Security Policy as defence in depth (strict, nonce-based, no
'unsafe-inline', no blanket host allowlists), so the bug you missed is blocked rather than exploited.
Takeaway
There is no safe string.
There is only a string escaped for the place it is printed. Name the context at every sink, use the encoder built for it, and treat CSP as a second line rather than the first.