← Blog
November 29, 202611 min readAppSecVulnerability ResearchXSSSecurity Engineering

Why does mutation XSS keep slipping past HTML sanitizers?

In 2020 five lines of HTML passed DOMPurify and still ran script, because the browser parsed the sanitized output into a different tree. How mutation XSS works: the form-nesting, namespace and noscript rules behind it, what the 2025 attribute-escaping change fixed, the desanitization patterns apps add themselves, and the defenses that remove the second parse.

By The Xalgorix Team

Here are five lines of HTML that a well-maintained sanitizer once returned as safe:

<form>
<math><mtext>
</form><form>
<mglyph>
<style></math><img src onerror=alert(1)>

Michał Bentkowski of Securitum published this payload against DOMPurify, the most widely used client-side HTML sanitizer. DOMPurify parsed it, walked the resulting tree, found nothing executable and returned it. When the application assigned that output to innerHTML, the browser parsed it a second time, built a different tree, and the <img onerror> ran. It was tracked as CVE-2020-26870: “a serialize-parse roundtrip does not necessarily return the original DOM tree, and a namespace can change from HTML to MathML.”

That class of bug is mutation XSS, or mXSS. Mario Heiderich and co-authors formalized it in a 2013 ACM CCS paper, and it has kept producing sanitizer CVEs since, including a CVSS 10.0 DOMPurify advisory in October 2024. This article explains why it happens, the specific parser rules that cause it, the browser change in 2025 that closed one family of vectors, and the code patterns that still reopen the door in applications today.

One string, two parses

A DOM-based sanitizer does not inspect a string with regular expressions. It hands the string to an HTML parser, gets a tree back, removes every element and attribute that is not on its allowlist, and serializes the cleaned tree into a string again. The application then writes that string into the page, which means the browser parses it once more.

Untrusted string
Parse #1
sanitizer builds tree A
Allowlist walk
tree A looks safe
Serialize
tree A back to text
Parse #2
innerHTML builds tree B
Tree B runs script
The sanitizer approves tree A. The browser renders tree B. mXSS is any case where A and B differ in a way that matters.

If parsing and serializing were perfect inverses, the second parse would rebuild tree A and nothing could go wrong. They are not. The HTML parsing algorithm is built to recover from broken markup, and some of the trees it produces have no string form that parses back to the same tree. Serialize one of those, parse it again, and you get a cousin of the original. Every sanitizer bypass in this class is an attacker finding a cousin that carries script.

The parser rules that change a tree on reparse

The individual payloads look like noise, but nearly all of them combine a small number of parser behaviours.

Nesting the parser allows once

The HTML specification itself contains an example of markup whose tree cannot survive a round trip. Securitum's write-up quotes it: the input <form id="outer"><div></form><form id="inner"><input> produces a form nested inside a form, something you cannot write directly because the parser ignores a <form> start tag while another form is open. We ran the round trip in Chromium 158:

parse #1 -> serialize:
<form id="outer"><div><form id="inner"><input></form></div></form>

parse #2 -> serialize:
<form id="outer"><div><input></div></form>

The inner form disappears on the second parse, and every element after it is now attached somewhere else. On its own that is harmless. In the CVE-2020-26870 payload it is the lever. We parsed the opening payload twice in an inert document. After the first parse, the <img> is still text inside an HTML <style>. After the second, the inner form is gone and <mglyph> is a direct child of <mtext>, the one position where the parser treats mglyph as MathML rather than HTML. The <style> inside it follows into MathML, where it is an ordinary element, so </math> closes the math block and the image is real:

after parse #2 (Chromium 158):
<form>
<math><mtext>

<mglyph>
<style></style></mglyph></mtext></math><img src="" onerror="alert(1)"></form>

Raw text in HTML, markup in SVG and MathML

In the HTML namespace, <style> is a raw-text element. Everything up to </style> is text, so an <img> written inside it is just characters and the sanitizer correctly leaves it alone. Inside <svg> or <math>, the same <style> is foreign content and its children are parsed as ordinary elements. As Bentkowski puts it, HTML style “has only text content, while svg style is parsed just like an ordinary element.”

So a payload only has to make the sanitizer's parse put <style> in one namespace and the browser's reparse put it in the other. If the sanitizer sees HTML, the <img onerror> is inert text it has no reason to remove. If the browser then sees MathML, the closing tag the sanitizer read as text becomes real markup. That is what the form-nesting mutation above does to <mglyph> and <style>. After that fix, Gareth Heyes of PortSwigger bypassed the patch (7 October 2020) by hiding the closing tags in an HTML comment or a CDATA section, which the two namespaces also treat differently. That vector was patched in DOMPurify 2.1.

Parser flags that differ between contexts

Some elements parse differently depending on the parser's state, not the markup. The best-known is <noscript>: when scripting is enabled its contents are raw text, and when it is disabled they are parsed as elements. A sanitizer that parses in an inert context, such as a <template> element, and an application that renders into a live page, where scripting is on, are using two different rules for the same string.

That is the mechanism behind the Google Search XSS that Masato Kinugawa reported in February 2019, as described by Acunetix. A September 2018 change in Google's Closure library removed a layer of sanitization, and this payload got through:

<noscript><p title="</noscript><img src=x onerror=alert(1)>">

Parsed with scripting off, it is a <p> with a long, harmless title attribute. Reparsed in the live page, <noscript> is raw text that ends at the first </noscript>, which sits inside the attribute value, so the <img> after it becomes a real element. Google reverted the change on 22 February 2019.

What the 2025 serializer change fixed

The noscript payload needs one more thing to work: when tree A is serialized, the < and > inside the title value must come out literally. For most of the web's history they did. On 20 May 2025 the HTML specification changed so that serializers always escape both characters in attribute values. Bentkowski announced it on the Chrome blog as a measure “helping prevent mutation XSS (mXSS) vulnerabilities”. It shipped in Chrome 138 (stable 24 June 2025) and Firefox 140, and was included in the Safari 26 beta.

In our Chromium 158 run, the same noscript payload parsed inside a <template> now serializes as title="&lt;/noscript&gt;&lt;img ...". The raw text in the live page never contains a literal </noscript>, so nothing breaks out. Vectors that smuggle markup inside attribute values stop working whenever the payload passes through a current browser's serializer, and DOMPurify, which serializes with the browser, picks that up without a code change. Comments and raw-text contents are still written literally, which is the route Heyes's comment and CDATA variant took.

The change is narrower than it looks. It alters what browsers write in innerHTML, outerHTML and getHTML(); it does nothing about structural mutations like form nesting and namespace switches, which still reproduce in the same Chromium build. It does not reach users on older browsers. And it does not apply to HTML serializers outside the browser: a server-side sanitizer writes strings with its own library's rules, so check what yours does.

Mutations the application adds itself

Sanitizer bypasses get the attention, but an equally common source of mXSS in application code is self-inflicted: the sanitizer does its job and the code around it changes the output or the context afterwards. DOMPurify's README warns that “if you first sanitize HTML and then modify it afterwards, you might easily void the effects of sanitization.” Yaniv Nizry's May 2024 research at Sonar calls this desanitization and catalogues the shapes it takes. Four come up repeatedly:

  • Post-processing the string. Decoding entities, applying emoji or mention replacements, or running a second formatter after sanitization. The sketch below is the simplest version, and we ran it against DOMPurify 3.5.0: the sanitizer correctly keeps the payload as text, then a well-meaning decode step turns it into an element.
  • Renaming elements. Sonar's example is code that rewrites svg to a custom tag name after sanitizing. Changing the name changes the namespace, and with it the parsing rules for everything inside.
  • Changing the context. Output sanitized as a fragment of HTML body content and then inserted inside an <svg>, a <textarea> or an HTML <template> is parsed under rules the sanitizer never applied.
  • Sanitizing on one parser, rendering on another. A server-side sanitizer whose parser is not the browser's is a standing parser differential. Sonar traced CVE-2023-33726 in the Electron note app Joplin to a sanitizer built on a parser that ignored namespaces; inside the Electron app, the XSS led to arbitrary command execution.
const clean = DOMPurify.sanitize('<p>&lt;img src=x onerror=alert(1)&gt;</p>');
// '<p>&lt;img src=x onerror=alert(1)&gt;</p>'   -- text, correctly kept

const pretty = clean.replace(/&lt;/g, '<').replace(/&gt;/g, '>');  // "fix" the entities
el.innerHTML = pretty;   // assigns '<p><img src=x onerror=alert(1)></p>'
// the browser builds a real <img> element and its onerror handler runs

None of these is a DOMPurify bug, and none will be fixed by upgrading it. They are usually visible once you trace the sanitized value to the sink.

Your sanitizer is a dependency with a CVE history

DOMPurify is maintained by people who wrote much of the mXSS research, and it still has a public record of parser-mutation fixes:

  • CVE-2019-16728: versions before 2.0.1 allowed “innerHTML mutation XSS (mXSS) for an SVG element or a MATH element.”
  • CVE-2020-26870: versions before 2.0.17, the form-nesting and MathML payload that opens this article. Heyes's comment and CDATA variant followed and was fixed in 2.1.
  • CVE-2024-47875 (GHSA-gx9m-whjm-85jf), published 11 October 2024: “nesting-based mXSS”, fixed in 2.5.0 and 3.1.3, rated CVSS 10.0 by GitHub.
  • CVE-2025-26791, published 14 February 2025: an incorrect template-literal regular expression when SAFE_FOR_TEMPLATES is enabled, “sometimes leading to mutation cross-site scripting (mXSS)”, fixed in 3.2.4. A reminder that optional modes add their own attack surface.

Two practical consequences follow. Pin and update the sanitizer as you would an authentication library, and include vendored or bundled copies in that inventory, because a DOMPurify inlined into a third-party widget does not show up in your lockfile. And if you run DOMPurify on the server, its README says older jsdom versions “are known to be buggy in ways that result in XSS even if DOMPurify does everything 100% correctly”, so the DOM implementation is part of the dependency too.

Finding mXSS-prone code in a review

Fuzzing a sanitizer for new mutations is research. Finding the places where an application has given mutations room to work is ordinary code review, and it is where application-level findings usually come from. Trace every call to the sanitizer forward to the point where its output becomes DOM, and ask:

Between sanitize() and the sink, does anything…
Change the string?
Replacements, entity decoding, markdown or template passes after sanitizing. Treat as a finding.
Change the context?
Sanitized as body HTML but inserted into SVG, a textarea, a template, an attribute or another document.
Cross a parser boundary?
Sanitized on the server or in a worker with a different parser, rendered by the browser.
None of these
Sanitized at the sink, same parser, output used untouched. Check version and config, then move on.

When you want a quick signal on a specific output, check whether it survives a round trip. This catches structural mutations like the form-nesting case above. It cannot detect context changes or post-processing, and a stable result does not mean the markup is safe, only that one particular trick is not in play:

// Run in the browser you care about, on the sanitizer's string output.
// Parse in an inert document: in the live document, a detached <div> still
// loads <img> and fires onerror, so the check would run the payload.
function mutatesOnReparse(html) {
  const doc = document.implementation.createHTMLDocument('');
  const a = doc.createElement('div');
  a.innerHTML = html;
  const once = a.innerHTML;
  const b = doc.createElement('div');
  b.innerHTML = once;
  return once !== b.innerHTML;   // true = the tree changed shape on reparse
}

One caveat: that inert document parses with scripting off, so <noscript> behaves there as it would in a sanitizer, not as it does in the live page. Treat noscript content separately.

On the dynamic side, test with the application's real sanitizer version and the real sink, not a lab copy. The DOMPurify project keeps an attack-class and bypass history that is a better source of test cases than a generic XSS list, because it groups vectors by attack class: parser mutation, namespace confusion, DOM clobbering and raw-text breakouts. Black-box scanning, automated or manual, rarely finds mXSS by fuzzing alone; knowing which sanitizer and which post-processing sit in the path is what turns a payload list into a test.

Defenses that remove the second parse

Sonar's summary is blunt: “there is not one simple mitigation solution.” The controls that hold are the ones that shrink the gap between what the sanitizer checked and what the browser renders.

  • Insert the tree, not a string. DOMPurify can return a node instead of markup. Appending that node skips parse #2 entirely:
const frag = DOMPurify.sanitize(untrusted, { RETURN_DOM_FRAGMENT: true });
container.replaceChildren(frag);
  • Turn off what you do not need. Most user-generated HTML has no business containing SVG or MathML, and namespace confusion is the engine of most sanitizer bypasses. DOMPurify.sanitize(dirty, { USE_PROFILES: { html: true } }) restricts output to HTML; in our test, <svg> and <math> elements did not survive it.
  • Sanitize at the sink, in the renderer. Run the sanitizer in the browser, immediately before insertion, and use its output untouched. If markup must be transformed (markdown, mentions, link rewriting), do it before sanitizing, never after. Sonar recommends that apps using server-side rendering avoid rendering user-controlled HTML on the server where they can.
  • Use the platform sanitizer where it exists. The Sanitizer API's Element.setHTML() parses and sanitizes in one operation with safe defaults, then inserts the result, so there is no string to reparse. Firefox 148 was first to ship it on 24 February 2026, followed by Chrome and Edge 146 in March. Safari does not support it yet, so for now it is a progressive enhancement next to DOMPurify, not a replacement.
  • Keep a backstop. Trusted Types make every string-to-HTML sink go through a policy you control, and a strict CSP blocks inline handlers like onerror if something does slip through. Our guide to deploying a strict CSP with nonces and Trusted Types covers the rollout.

Mutation XSS is the same lesson as the ruby-saml parser differential in a different format: a security check is only as good as its agreement with the component that acts on the data. Every time sanitized HTML is turned back into a string, edited or moved to a new context, the browser gets a second opinion. The most reliable fix is to stop asking for one.

Ready to see it prove a bug?

Start scanning on Cloud →