Skip to content

GHSA-p98j-92pf-mc4p CVE-2026-109344

DOMPurify: IN_PLACE: node-removing afterSanitize hook leaves detached subtree event handlers armed, causing DOM XSS

Low npm
Severity
2.3 / 10
Low · CVSS 4.0
Exploit chance (EPSS)
0.19%
Chance of exploitation in the next 30 days. Higher than 8.47% 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')
Fix
3.4.16
Upgrade dompurify to this version or later

Description

Summary

In IN_PLACE mode DOMPurify sanitizes the caller's live DOM subtree directly. To close a known hazard (GHSA-55q2-fjhq-7xh7), the library neutralizes any node a hook detaches during sanitization by stripping its subtree's non-allow-listed attributes, but this neutralization is wired only into the beforeSanitizeElements and uponSanitizeElement hook sites. An afterSanitizeElements or afterSanitizeAttributes hook that removes a non-root element (a documented, supported pattern) detaches that element's subtree with no neutralization, so descendant on* handlers remain armed on the caller's live tree after sanitize() returns, yielding DOM XSS. No special privilege is required beyond supplying markup to an application that uses IN_PLACE together with a node-removing afterSanitize hook.

Root Cause

IN_PLACE sanitization mutates the caller's live document, so any element a hook detaches from that tree must have its subtree neutralized before sanitize() returns; otherwise a queued resource-event handler (for example an <img onerror> that began loading when the caller built the tree) fires in page scope even though the handler never reached the sanitized output. The guard helper _handleHookDetachedNode (which calls _neutralizeSubtree in IN_PLACE) is invoked only after beforeSanitizeElements and after uponSanitizeElement. It is never invoked from the afterSanitize return paths, and _sanitizeAttributes never calls it at all. The post-walk IN_PLACE neutralization pass iterates only DOMPurify.removed, and hook-detached nodes are intentionally not recorded there, so that pass cannot reach them either.

src/purify.ts
  _sanitizeElements: _handleHookDetachedNode present at lines 2142 and 2175
    (before/upon), absent after afterSanitizeElements at lines 2208 and 2249.
  _sanitizeAttributes: afterSanitizeAttributes fires at line 2670 with no
    detach re-check; the function never calls _handleHookDetachedNode.
  Post-walk IN_PLACE pass (lines 3081-3090) iterates DOMPurify.removed only,
    which by design (comment at lines 2096-2099) excludes hook-detached nodes.

Impact

An attacker who supplies markup processed by a victim application that runs DOMPurify.sanitize(node, { IN_PLACE: true }) and registers a node-removing afterSanitizeElements or afterSanitizeAttributes hook can retain arbitrary on* event handlers on descendants of a removed non-root element. Because IN_PLACE operates on the caller's live document, a queued resource-event handler on such a descendant fires in the page origin after the synchronous sanitize() call returns, giving script execution in the victim's session (DOM XSS). This defeats DOMPurify's IN_PLACE contract to neutralize handlers on subtrees removed from the live tree. The capability is script execution in the victim origin; exact confidentiality and integrity effects depend on the hosting application's session.

Proof of Concept

Dependencies: Node.js and jsdom. The harness builds a live tree, registers a
removal hook, runs IN_PLACE sanitize(), then inspects whether the attacker
onerror handler survives on the detached descendant. jsdom does not perform
real image loads, so the retained handler (rather than an actual fired event)
is the observed hazard; the retained on* attribute on a live detached node
after a synchronous sanitize() return is the neutralization failure.

Reproduction steps:

  1. Build a live subtree #root > section#wrap > img[onerror] where #root is the walk root and section#wrap is a non-root wrapper.
  2. Register an afterSanitizeElements (or afterSanitizeAttributes) hook that calls node.remove() on the wrapper.
  3. Call DOMPurify.sanitize(root, { IN_PLACE: true }).
  4. Observe that the descendant <img> retains its onerror handler, whereas the same removal performed in a beforeSanitizeElements/uponSanitizeElement hook strips it.
const { JSDOM } = require('jsdom');
const createDOMPurify = require('dompurify');
const { window } = new JSDOM('<!DOCTYPE html><body></body>');
const DOMPurify = createDOMPurify(window);

const root = window.document.createElement('div');
root.id = 'root';
root.innerHTML = '<section id="wrap"><img src="x" onerror="ATTACKER()"></section>';
window.document.body.appendChild(root);

DOMPurify.addHook('afterSanitizeElements', (node) => {
  if (node.id === 'wrap') node.remove();
});
DOMPurify.sanitize(root, { IN_PLACE: true });

// The detached <img> still carries its onerror handler:
console.log(root.querySelector('#wrap') === null,               // true (removed from live tree)
            !!window.document.querySelector('img[onerror]') ||  // handler survives on the detached node
            root.innerHTML);
PASS: beforeSanitizeElements detach neutralizes descendant onerror (control)
PASS: uponSanitizeElement detach neutralizes descendant onerror (control)
PASS: without a removal hook the descendant onerror is stripped normally
PASS: afterSanitizeElements detach LEAVES descendant onerror armed (GAP)
PASS: afterSanitizeAttributes detach LEAVES descendant onerror armed (GAP)
PASS: kept custom element removed in afterSanitizeElements leaves descendant onerror armed (GAP)

Attack Chain

  1. Exposure: The victim application calls DOMPurify.sanitize(liveNode, { IN_PLACE: true }) on attacker-influenced markup and has registered a node-removing afterSanitizeElements or afterSanitizeAttributes hook per an application policy (src/purify.ts:3026 walk, 2136 element pass, 2522 attribute pass).
  2. Control: The attacker controls the markup, including a non-root wrapper element and, inside it, a descendant carrying an on* resource-event handler such as <img src=x onerror=...>.
  3. Path: The pre-order walk visits the wrapper before its descendants. During the wrapper's element or attribute pass the application hook detaches the wrapper from the live tree.
  4. Guard: The detach-neutralization guard _handleHookDetachedNode runs only after beforeSanitizeElements (2142) and uponSanitizeElement (2175); it is absent after afterSanitizeElements (2208, 2249) and is never called by _sanitizeAttributes (afterSanitizeAttributes at 2670). The NodeIterator advances past the detached subtree, so the descendants are never revisited, and the post-walk pass iterates only DOMPurify.removed, which excludes hook-detached nodes.
  5. Primitive: The descendant retains its on* handler on the caller's live document after sanitize() returns.
  6. Result: The queued resource event fires the attacker handler in the victim page origin, achieving DOM XSS despite IN_PLACE sanitization.

Bypass Evidence

The relevant prior fix is GHSA-55q2-fjhq-7xh7 ("IN_PLACE hook removal leaves a detached subtree executable, causing XSS"), whose change (#1557) added _neutralizeSubtree at the beforeSanitizeElements and uponSanitizeElement detach sites. Inspection of that change shows it touches no afterSanitize site: the diff adds the neutralization only at the before/upon locations, later refactored into _handleHookDetachedNode at src/purify.ts:2142 and 2175. A subsequent hardening change (#1616) added a rootWasRemoved throw and a neutralization sweep over DOMPurify.removed, but that sweep still iterates only DOMPurify.removed, which by design excludes hook-detached non-root nodes, so it does not close this gap. The afterSanitizeElements-on-kept-custom-element site at 2208 was itself introduced by the fix for GHSA-c2j3-45gr-mqc4 (#1527), adding another uncovered hook site.

Disproof attempts, all failed: (a) that a later release closed the afterSanitize gap, refuted by inspecting the published 3.4.13, 3.4.14, and 3.4.15 artifacts; (b) that detached descendants are revisited or re-sanitized, refuted at runtime (the onerror is retained only at the afterSanitize sites and stripped at the before/upon sites and with no removal hook); (c) that the post-walk pass catches hook-detached nodes, refuted by the design that excludes them from DOMPurify.removed; (d) that the precondition is contrived, refuted by parity with the accepted GHSA-55q2 threat model and the library's own supported pattern of removing a node inside afterSanitizeElements. The only edge not directly executed is the browser resource-event dispatch (jsdom performs no real image load); it is established by the proven retention of the live handler after a synchronous return, the library's own comments describing exactly this hazard, and parity with the accepted GHSA-55q2 mechanism.

Affected Versions

  • Ecosystem: npm
  • Package: dompurify
  • Confirmed affected range: >= 3.4.13, <= 3.4.15
  • Latest release checked: 3.4.15 (npm registry)
  • Fix status: fixed in 3.4.16

The before/upon detach neutralization introduced for GHSA-55q2-fjhq-7xh7 first shipped in 3.4.13; the residual afterSanitize gap was verified by reproducing it against the published npm artifacts for 3.4.13, 3.4.14, and 3.4.15. The 3.4.12 artifact predates that neutralization and behaves differently at the before/upon sites, so it is outside this specific incomplete-fix range. No release through 3.4.15 neutralizes detached subtrees at the afterSanitize sites, so no fixed version is established.

Suggested Fix

Enforce the same IN_PLACE detach-neutralization invariant at every hook site that can detach a node, not only the before/upon sites. Concretely, apply a _handleHookDetachedNode(currentNode, root) re-check after afterSanitizeElements at both src/purify.ts:2208 and 2249 (returning as removed when the node was detached), and add an equivalent IN_PLACE detach check plus _neutralizeSubtree after afterSanitizeAttributes at 2670. As an interim mitigation without a code change, applications using IN_PLACE can avoid removing nodes inside afterSanitizeElements/afterSanitizeAttributes hooks and instead perform such removals in beforeSanitizeElements/uponSanitizeElement, or avoid IN_PLACE for attacker-influenced content.

Reported by zx (GitHub: @manus-pi).

Affected versions

npm

PackageVulnerableFixed in
dompurify
>= 3.4.13, <= 3.4.15
No fix yet
dompurify
>= 3.4.13, < 3.4.16
3.4.16

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.16

npm
npm install dompurify@3.4.16
yarn
yarn add dompurify@3.4.16
pnpm
pnpm add dompurify@3.4.16

Severity breakdown

CVSS 4.0 2.3

CVSS:4.0/AV:N/AC:L/AT:P/PR:N/UI:P/VC:L/VI:L/VA:N/SC:N/SI:N/SA:N

Attack vector
Network
Attack complexity
Low
Attack requirements
Present
Privileges required
None
User interaction
Passive
Confidentiality (vulnerable system)
Low
Integrity (vulnerable system)
Low
Availability (vulnerable system)
None
Confidentiality (subsequent systems)
None
Integrity (subsequent systems)
None
Availability (subsequent systems)
None

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.

References

Timeline

  1. Published
  2. Last updated by the source
  3. Latest EPSS score
AdvisorySeverityWhy 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-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
GHSA-vxr8-fq34-vvx9
DOMPurify: Trusted Types policy survives `clearConfig()` and can poison later `RETURN_TRUSTED_TYPE` output
Low Also affects dompurify

Credits: manus-pi

Is this in your code?

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