Where
-Infinity
0
Severity
8.7
XSS
AV:N/AC:L/AT:N/PR:N/UI:N/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

Summary

Document.createProcessingInstruction() in @xmldom/xmldom performs no validation on the target parameter. The requireWellFormed: true serializer option validates only for : in the target and a case-insensitive xml prefix, but does not check for > characters. A > in the target breaks the processing instruction boundary (<?...?>), allowing injection of arbitrary content into the serialized XML output.

Details

Document.createProcessingInstruction(target, data) at lib/dom.js around line 2413 accepts any string as the target parameter and stores it on the PI node without validation.

During serialization, the requireWellFormed code path (around line 3286) performs two checks on PI targets:

1. Rejects targets containing : (namespace prefix check) 2. Rejects targets matching xml case-insensitively (reserved prefix)

However, it does NOT validate that the target conforms to the XML Name production, and critically does NOT check for > characters. Since processing instructions are serialized as <?target data?>, a > in the target prematurely closes the PI, causing the remaining content to be interpreted as document content by any downstream XML parser.

Root Cause

1. createProcessingInstruction() performs no validation on target 2. The serializer's requireWellFormed check is incomplete -- it only checks for : and xml, missing characters that break PI syntax (>, ?, whitespace) 3. The serializer emits the target verbatim: <?${target} ${data}?>

Proof of Concept

javascript const { DOMImplementation, XMLSerializer } = require('@xmldom/xmldom');

const impl = new DOMImplementation(); const serializer = new XMLSerializer(); const doc = impl.createDocument(null, 'root', null);

// PI target containing > breaks the PI boundary const pi = doc.createProcessingInstruction('a>', 'data'); doc.documentElement.appendChild(pi);

const output = serializer.serializeToString(doc, { requireWellFormed: true }); console.log(output); // Output: <root><?a> data?></root> // // The > in the target closes the PI prematurely. // A downstream XML parser sees: // - Processing instruction: <?a?> (target "a", no data) // - Text content: " data?>" // // requireWellFormed: true did NOT prevent the injection.

Injecting elements via PI target

javascript const pi2 = doc.createProcessingInstruction( 'a?><script xmlns="http://www.w3.org/1999/xhtml">alert(1)</script><?b', '' ); doc.documentElement.appendChild(pi2);

const output2 = serializer.serializeToString(doc, { requireWellFormed: true }); console.log(output2); // Output includes: // <?a?><script xmlns="http://www.w3.org/1999/xhtml">alert(1)</script><?b ?> // // The injected <script> element is valid XHTML that a browser would execute.

Impact

Applications that create processing instructions with user-controlled target strings and serialize the result are vulnerable to XML injection. This enables:

- XML structure injection: Breaking the PI boundary to inject arbitrary elements, text, or additional processing instructions into the output - XSS via XHTML: If the serialized output is served as XHTML or processed by a browser-based XML parser, injected script elements will execute - XXE chain: Injected DOCTYPE declarations or entity references could trigger XXE in downstream XML parsers that consume the output - requireWellFormed bypass: The existing well-formedness checks are incomplete and provide a false sense of security

Fix Applied

Under requireWellFormed, the serializer validates a processing-instruction target as an XML NCName (a Name with no colon) and rejects a case-insensitive xml, throwing InvalidStateError when the target is ill-formed — so a >, ?, or whitespace in the target is now refused.\ On 0.9.12 this replaces an earlier check that already rejected a colon or xml, so the no-colon rule is preserved.\ 0.8.15 had no processing-instruction target check at all, so the whole target validation is new there.\ Non-breaking and opt-in. See the XML Name production. ⚠ Opt-in required. Protection is not automatic. Existing serialization calls remain vulnerable unless { requireWellFormed: true } is explicitly passed. Applications that serialize untrusted DOM content should audit all serializeToString() call sites and add it.

Proof of Concept - fixed path

javascript const { DOMImplementation, XMLSerializer } = require('@xmldom/xmldom');

const impl = new DOMImplementation(); const serializer = new XMLSerializer(); const doc = impl.createDocument(null, 'root', null);

// PI target containing > breaks the PI boundary const pi = doc.createProcessingInstruction('a>', 'data'); doc.documentElement.appendChild(pi);

// Default path: emits the ill-formed target verbatim. console.log(serializer.serializeToString(doc)); // Output: <root><?a> data?></root>

// Opt-in path: the target check now rejects the break-out character. try { serializer.serializeToString(doc, { requireWellFormed: true }); } catch (e) { console.log(e.name); // InvalidStateError }

Why the default stays verbatim

W3C DOM Parsing's require-well-formed flag defaults to false, and the browser XMLSerializer emits the target verbatim in that default mode. Unconditionally throwing on an ill-formed PI target would diverge from that platform behavior and would be an unjustified breaking change, so the stricter validation is gated behind { requireWellFormed: true }. (See the W3C XML Name production and XML Processing Instructions.)

Residual limitation

The default serialization path still emits the ill-formed target verbatim -- only the opt-in requireWellFormed path is protected. Creation-time validation of the target in createProcessingInstruction() is breaking and is deferred to the next breaking release, tracked at xmldom/xmldom#1073.

1 / 3
Source: GitHub
First published (updated )
Severity
8.7
AV:N/AC:L/AT:N/PR:N/UI:N/VC:N/VI:N/VA:H/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

Summary

When an element declares a namespace prefix, xmldom copies the entire in-scope namespace map into a fresh object and keeps that copy on the element while it is open on the parse stack. A crafted document that nests N elements, each declaring one unique prefix, therefore drives the parser to hold on the order of N(N+1)/2 = O(N²) namespace-map entries at its peak, so a small, highly compressible input exhausts the heap. Parsing runs under default options on untrusted, network-delivered XML, so a sub-megabyte payload can OOM-crash the process before any application-level validation runs — an unauthenticated denial of service.

Details

appendElement performs the copy: copy clones the current namespace map into a fresh object for each prefix-declaring element, and the copy is retained on that element's parse-stack entry:

js if (localNSMap == null) { localNSMap = Object.create(null); copy(currentNSMap, (currentNSMap = Object.create(null))); // full copy of all ancestor prefixes } currentNSMap[nsPrefix] = localNSMap[nsPrefix] = value; ... el.currentNSMap = currentNSMap; // retained while the element is open on the parse stack

https://github.com/xmldom/xmldom/blob/08a22d78e4bc50f12ce9f5090b8d96ee6031ac7b/lib/sax.js#L467-L540

The copies stack: the element at depth i copies a map of size ~i, and every ancestor stays live on the parse stack until it closes, so at the deepest point Σi namespace entries are held at once. That peak is transient — the completed DOM retains only O(N), one small namespace map per node — but it is reached during parsing, which is what OOM-crashes the process.

Proof of Concept

A minimal document — N nested elements, each declaring one unique namespace prefix (no SAML wrapper needed):

js const { DOMParser } = require('@xmldom/xmldom');

function build(n) { let open = '', close = ''; for (let i = 0; i < n; i++) { open += <a xmlns:p${i}="urn:${i}">; close = '</a>' + close; } return <r>${open}${close}</r>; // <r><a xmlns:p0="urn:0">...<a xmlns:p{n-1}="urn:{n-1}">...</a>...</r> }

for (const n of [2000, 4000, 8000, 16000]) { const src = build(n); new DOMParser().parseFromString(src, 'text/xml'); // peak memory ~ O(n^2) console.log(n, (src.length / 1024).toFixed(0) + ' KB in', (process.resourceUsage().maxRSS / 1024).toFixed(0) + ' MB peak RSS'); }

Measured on Node.js v24 (peak RSS ~quadruples per doubling of depth; absolute numbers vary by host):

| depth | input | peak RSS | | -----: | ------: | ------------------------------- | | 2,000 | 56 KB | 266 MB | | 4,000 | 115 KB | 622 MB | | 8,000 | 232 KB | 1.9 GB | | 16,000 | ~470 KB | OOM crash (default ~4 GB heap) |

About 470 KB of trivially-generated, highly-compressible input crashes a default Node.js process; larger depths scale as O(N²) into the tens of GB, crashing larger hosts (as first measured by the reporter with a SAML-shaped payload).

Impact

Unauthenticated denial of service against any service that parses attacker-influenced XML with xmldom under default options. A single sub-megabyte request drives multi-gigabyte peak memory and can OOM-crash the process before any application-level validation (e.g. schema checks or a SAML signature verification) runs. The payload is a plain namespace-nesting document and highly compressible, so it is effective over compressed transports (e.g. an HTTP-Redirect / DEFLATE binding, not only POST bindings).

Severity note

The CVSS 4.0 vector scores availability only (VC:N/VI:N/VA:H): the flaw neither discloses nor alters data, it exhausts the heap. VA:H is justified because a single unauthenticated, network-delivered request (AV:N/PR:N/UI:N) of trivial complexity (AC:L/AT:N) drives the parser to multi-gigabyte peak memory and OOM-crashes the process before any application-level logic runs — a full loss of availability for the affected service.

Fix Applied

Inherit each element's in-scope namespace map through the prototype chain instead of copying it for every prefix-declaring element, so a deeply namespaced document holds O(N) namespace entries instead of O(N²) at peak. Behavior-preserving: serialized output is byte-identical, only the memory cost drops. Non-breaking and independent of requireWellFormed; ships on both maintained versions.

1 / 3
Source: GitHub
First published (updated )
Severity
8.7
CVSS:4.0/AV:N/AC:L/AT:N/PR:N/UI:N/VC:N/VI:N/VA:H/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

Summary

xmldom's malformed-input error-recovery path has two quadratic-time (O(n²)) behaviors that a single crafted input triggers together, so a tiny, highly compressible document (tens of KB) stalls the Node.js event loop for multiple seconds. It is reachable from DOMParser.parseFromString under default options — i.e. from unauthenticated, network-delivered XML — making this an unauthenticated denial of service. One of the two behaviors, the normalize() adjacent-text merge, is additionally reachable programmatically — via a plain normalize() call on a DOM built with adjacent text nodes, independent of the parser — so its fix must live in normalize(), not only in a parser bound.

Details

Finding A — parseElementStartPart quadratic re-scan

A < character is not a delimiter in any tag-parsing state, so parseElementStartPart scans forward character-by-character over any embedded < until it reaches the next > (or end of input), then validates the accumulated slice as a tag name and throws invalid tagName: on failure. The main loop catches this, reports an error, sets end = -1, and recovers by advancing a single character (appendText(Math.max(tagStart, start) + 1)). With a long run of < and a distant >, each of the O(n) recovery retries performs an O(n) scan plus an O(n) anchored regex validation over the growing candidate ⇒ O(n²).

Code (0.9.x, bb7a085dc5ba1eea3212388509b97bb4b4af32b9):

- parseElementStartPart character scan — https://github.com/xmldom/xmldom/blob/bb7a085dc5ba1eea3212388509b97bb4b4af32b9/lib/sax.js#L263-L461 - tag-name validation (setTagName → throws invalid tagName) — https://github.com/xmldom/xmldom/blob/bb7a085dc5ba1eea3212388509b97bb4b4af32b9/lib/sax.js#L886-L891 - main-loop catch → error + end = -1 — https://github.com/xmldom/xmldom/blob/bb7a085dc5ba1eea3212388509b97bb4b4af32b9/lib/sax.js#L234-L242 - single-character recovery fallback — https://github.com/xmldom/xmldom/blob/bb7a085dc5ba1eea3212388509b97bb4b4af32b9/lib/sax.js#L247

Code (0.8.x, e5c14802592685bb872c042c54c3f73758875c85):

- parseElementStartPart — https://github.com/xmldom/xmldom/blob/e5c14802592685bb872c042c54c3f73758875c85/lib/sax.js#L227 - catch → error + end = -1 — https://github.com/xmldom/xmldom/blob/e5c14802592685bb872c042c54c3f73758875c85/lib/sax.js#L202-L208 - recovery fallback — https://github.com/xmldom/xmldom/blob/e5c14802592685bb872c042c54c3f73758875c85/lib/sax.js#L213 - setTagName validation — https://github.com/xmldom/xmldom/blob/e5c14802592685bb872c042c54c3f73758875c85/lib/sax.js#L616-L621

Finding B — normalize() adjacent-text O(K²) merge

endDocument() calls document.normalize(). For a parent with K adjacent text nodes (produced by the one-character recovery of Finding A), normalize() performs K−1 merges. Each merge does a removeChild — which re-indexes all child nodes of the parent (O(K)) — and an appendData — which rebuilds the accumulator string this.data + text (O(K)). Total: O(K²).

Well-formed XML cannot produce adjacent text-node siblings through the parser (each text run is one node; comments, CDATA, PIs, and elements sit between runs), so the parse-path trigger for Finding B is the malformed-input recovery that emits single-character text nodes. The same O(K²) merge is, however, independently reachable via the public normalize() API on a programmatically built tree (see "Finding B is additionally reachable programmatically" below).

Code (0.9.x, bb7a085dc5ba1eea3212388509b97bb4b4af32b9):

- endDocument → normalize() — https://github.com/xmldom/xmldom/blob/bb7a085dc5ba1eea3212388509b97bb4b4af32b9/lib/dom-parser.js#L418-L420 - normalize() adjacent-text merge — https://github.com/xmldom/xmldom/blob/bb7a085dc5ba1eea3212388509b97bb4b4af32b9/lib/dom.js#L1336-L1356 - removeChild re-index-all branch — https://github.com/xmldom/xmldom/blob/bb7a085dc5ba1eea3212388509b97bb4b4af32b9/lib/dom.js#L1788-L1798 - appendData string rebuild — https://github.com/xmldom/xmldom/blob/bb7a085dc5ba1eea3212388509b97bb4b4af32b9/lib/dom.js#L2786-L2790

Code (0.8.x, e5c14802592685bb872c042c54c3f73758875c85):

- endDocument → normalize() — https://github.com/xmldom/xmldom/blob/e5c14802592685bb872c042c54c3f73758875c85/lib/dom-parser.js#L213-L214 - normalize() merge — https://github.com/xmldom/xmldom/blob/e5c14802592685bb872c042c54c3f73758875c85/lib/dom.js#L529-L549 - removeChild re-index-all branch — https://github.com/xmldom/xmldom/blob/e5c14802592685bb872c042c54c3f73758875c85/lib/dom.js#L756-L773 - appendData string rebuild — https://github.com/xmldom/xmldom/blob/e5c14802592685bb872c042c54c3f73758875c85/lib/dom.js#L1533

Finding B is additionally reachable programmatically (no parser involved)

Node.prototype.normalize() is public API on every Document/Element. A tree built entirely through the ordinary DOM API — new DOMImplementation().createDocument(...), then K× createTextNode + appendChild on one parent — reaches the same O(K²) merge when the application calls normalize(), with no parsing and no error-recovery. The parser is only one of the two callers of the vulnerable merge:

- the parser's automatic endDocument() → document.normalize() (the parse-path trigger above), and - any explicit application call to the public normalize() on a tree with adjacent text nodes.

XMLSerializer does not call normalize(), so serializing an un-merged tree is O(total text), not O(K²); the O(K²) surface is exactly those two normalize() callers. Consequently a parser-side bound alone cannot remediate Finding B — the fix must live in normalize().

Affected Versions

Both findings are present across the full published @xmldom/xmldom history — both currently-maintained versions (0.8.x and 0.9.x) are affected — and across the retired unscoped xmldom line. Finding B's normalize() merge is additionally reachable programmatically: a direct normalize() call on a DOM built with adjacent text nodes hits the same O(K²) merge, independent of the parser — so, unlike Finding A, it does not require the malformed-input recovery path.

Proof of Concept

Default DOMParser, no options. The input is trivially compressible (a< / a<> repeated) and never throws — it is parsed via the recovery path.

js const { DOMParser } = require('@xmldom/xmldom');

// Silence the expected error-level recovery reports (default handler logs // them to console.error without throwing; only fatalError throws). console.error = function () {};

function timeParse(label, xml, mime) { const t0 = process.hrtime.bigint(); new DOMParser().parseFromString(xml, mime); // completes; no exception const ms = Number(process.hrtime.bigint() - t0) / 1e6; console.log(label + ' bytes=' + Buffer.byteLength(xml) + ' time=' + ms.toFixed(1) + ' ms'); }

for (const N of [4000, 8000, 16000, 32000]) { // Finding A: long re-scans, O(n^2) during parse. timeParse('A N=' + N, '<r>' + 'a<'.repeat(N) + '</r>', 'text/xml'); // Finding B: short re-scans (cheap parse) but K adjacent text nodes -> O(K^2) in normalize(). timeParse('B N=' + N, '<r>' + 'a<>'.repeat(N) + '</r>', 'text/html'); // Combined: ONE input hits both A and B under the default parser. timeParse('C N=' + N, '<r>' + 'a<'.repeat(N) + '</r>', 'text/xml'); }

Measured on Node v18.20.8 (absolute ms vary by host; the load-bearing fact is that doubling the input ~quadruples the time — canonical O(n²)):

Finding A, isolated ("<r>" + "a<"×N + "</r>", normalize disabled to isolate the re-scan):

| N | input bytes | @xmldom/xmldom 0.9.10 | 0.8.13 | |--:|--:|--:|--:| | 2000 | 4007 | 43 ms | 37 ms | | 4000 | 8007 | 129 ms | 106 ms | | 8000 | 16007 | 434 ms | 424 ms | | 16000 | 32007 | 1629 ms | 1611 ms |

Finding B, isolated ("<r>" + "a<>"×N + "</r>", time attributable to normalize()):

| K (N) | input bytes | 0.9.10 | 0.8.13 | |--:|--:|--:|--:| | 4000 | 12007 | 120 ms | 165 ms | | 8000 | 24007 | 589 ms | 771 ms | | 16000 | 48007 | 3142 ms | 4448 ms | | 32000 | 96007 | 12127 ms | 12951 ms |

Combined (default parser, both findings; "<r>" + "a<"×N + "</r>"):

| N | input bytes | 0.9.10 | 0.8.13 | |--:|--:|--:|--:| | 4000 | 8007 | 341 ms | 397 ms | | 8000 | 16007 | 1894 ms | 1641 ms | | 16000 | 32007 | 4398 ms | 7661 ms |

~32 KB of input → several seconds of single-threaded event-loop stall.

Finding B via the public normalize() API (no parser)

js const { DOMImplementation } = require('@xmldom/xmldom');

function timeNormalize(K) { const doc = new DOMImplementation().createDocument(null, 'r', null); const el = doc.documentElement; for (let i = 0; i < K; i++) el.appendChild(doc.createTextNode('x')); // K adjacent text nodes const t0 = process.hrtime.bigint(); doc.normalize(); // O(K^2) merge — no parsing involved const ms = Number(process.hrtime.bigint() - t0) / 1e6; console.log('K=' + K + ' time=' + ms.toFixed(1) + ' ms'); } for (const K of [2000, 4000, 8000, 16000, 32000]) timeNormalize(K);

Measured on Node v18.20.8 (doubling K ~quadruples the time — O(K²)):

| K | 0.9.10 | 0.8.13 | |--:|--:|--:| | 2000 | 5.7 ms | 5.6 ms | | 32000 | 1263 ms | 1704 ms |

This path is reachable by any application that builds a DOM from attacker-influenced data and calls normalize(), entirely independent of DOMParser.

Impact

Availability only: a single parse of a small crafted document blocks the Node.js event loop for the duration of the quadratic work (multiple seconds at tens of KB; larger inputs scale as O(n²)). No memory blow-up beyond transient strings, no data exposure, no integrity impact. Because XML is routinely accepted from untrusted sources and parsed with default options, one request can stall a server. The payloads are highly compressible, so any endpoint accepting compressed XML faces additional amplification. Finding B is additionally reachable via an explicit normalize() call on a programmatically built DOM (see Proof of Concept), so applications that construct a document from attacker-influenced data and normalize it are exposed even without parsing.

Severity note

The complexity is quadratic, not exponential, so a multi-second stall requires tens-to-hundreds of KB of input. VA:H reflects that xmldom applies no input-size limit and the path runs on default-options parsing, so a single unbounded parse can fully stall the event loop.

Fix Applied

Two independent, non-breaking fixes shipped together — each alone leaves the other's quadratic cost dominating the default parse. Finding A — terminate the malformed tag-name scan at an embedded <, so error recovery is linear instead of O(n²). DOM output is unchanged; only the reported error-message text differs (error strings are not a semver contract). Finding B — merge adjacent text nodes in normalize() in O(K) instead of O(K²), which also closes the same slowdown reachable programmatically through a direct normalize() call. Both ship on both maintained versions.

1 / 3
Source: GitHub
First published (updated )
Severity
8.7
AV:N/AC:L/AT:N/PR:N/UI:N/VC:N/VI:N/VA:H/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

Summary

xmldom builds the attribute collection of every parsed element by inserting attributes one at a time into a DOM NamedNodeMap. Each insertion first performs a linear scan of all already-inserted attributes to enforce the DOM uniqueness rule (no two attributes with the same qualified name / namespace+local-name). Parsing an element that carries M distinct attributes therefore costs 1 + 2 + … + M = O(M²) comparisons.

Because the trigger is simply "one element with many attributes", the attack payload is a fully well-formed XML document. No malformed markup, no error recovery, and no non-default parser options are involved — parsing completes silently with zero warning/error/fatalError events. An attacker who can submit a modest, highly compressible document (a single element with tens of thousands of attributes, ~340 KB uncompressed) can consume seconds of single-threaded CPU per request, enabling an unauthenticated denial of service.

This is distinct from the known quadratic-memory namespace-map issue: it burns CPU and it does not require any namespace declarations or nesting.

Details

The DOM content handler adds each attribute of a starting element by calling el.setAttributeNode(attr) in a loop:

js // DOMHandler.startElement for (var i = 0; i < len; i++) { var namespaceURI = attrs.getURI(i); var value = attrs.getValue(i); var qName = attrs.getQName(i); var attr = doc.createAttributeNS(namespaceURI, qName); attr.value = attr.nodeValue = value; el.setAttributeNode(attr); // O(existing attrs) each — see below }

https://github.com/xmldom/xmldom/blob/bb7a085dc5ba1eea3212388509b97bb4b4af32b9/lib/dom-parser.js#L370-L387

setAttributeNode delegates to NamedNodeMap.setNamedItem, which calls getNamedItemNS to look for an existing attribute with the same namespace URI and local name before appending:

js setNamedItem: function (attr) { var el = attr.ownerElement; if (el && el !== this.ownerElement) { throw new DOMException(DOMException.INUSEATTRIBUTEERR); } var oldAttr = this.getNamedItemNS(attr.namespaceURI, attr.localName); // linear scan if (oldAttr === attr) { return attr; } addNamedNode(this.ownerElement, this, attr, oldAttr); return oldAttr; },

https://github.com/xmldom/xmldom/blob/bb7a085dc5ba1eea3212388509b97bb4b4af32b9/lib/dom.js#L612-L623

getNamedItemNS walks the whole list on every call:

js getNamedItemNS: function (namespaceURI, localName) { if (!namespaceURI) { namespaceURI = null; } var i = 0; while (i < this.length) { var node = this[i]; if (node.localName === localName && node.namespaceURI === namespaceURI) { return node; } i++; } return null; },

https://github.com/xmldom/xmldom/blob/bb7a085dc5ba1eea3212388509b97bb4b4af32b9/lib/dom.js#L702-L715

For the i-th attribute the scan visits i-1 entries, so inserting M distinct attributes performs Θ(M²) comparisons. There is no hash index or set keyed by name; the map is a plain array-backed structure.

The same structure exists on 0.8.x. There setNamedItem dedups via getNamedItem(attr.nodeName) instead of getNamedItemNS, but that method is likewise a full linear scan, so the complexity is identical:

- startElement loop / setAttributeNode: https://github.com/xmldom/xmldom/blob/e5c14802592685bb872c042c54c3f73758875c85/lib/dom-parser.js#L159-L176 - setNamedItem → linear getNamedItem: https://github.com/xmldom/xmldom/blob/e5c14802592685bb872c042c54c3f73758875c85/lib/dom.js#L286-L308

The linear-scan NamedNodeMap predates the @xmldom/xmldom fork and is present unchanged in the unscoped xmldom package back to its earliest published release. In xmldom@0.1.0, parsing already inserts each attribute one at a time (DOMHandler.startElement loops calling setAttributeNS → setAttributeNode → NamedNodeMap.setNamedItem), and setNamedItem dedups by calling getNamedItemNS, which is a full linear while (i--) scan of the already-inserted attributes — the identical O(M²) structure. The whole unscoped line (0.1.0 … 0.6.0) is therefore affected; the earliest published tag (0.1.0) was verified to contain the per-insert linear dedup scan.

Proof of Concept

A single well-formed element with M distinct attributes. No malformed markup and no options:

js 'use strict'; var DOMParser = require('@xmldom/xmldom').DOMParser;

function buildDoc(m) { var parts = new Array(m); for (var i = 0; i < m; i++) parts[i] = 'a' + i + '="x"'; return '<r ' + parts.join(' ') + '/>'; // <r a0="x" a1="x" ... a{M-1}="x"/> }

for (var i = 0, sizes = [2000, 4000, 8000, 16000, 32000]; i < sizes.length; i++) { var m = sizes[i]; var xml = buildDoc(m); var t0 = process.hrtime.bigint(); var doc = new DOMParser().parseFromString(xml, 'text/xml'); // silent: no error events var ms = Number(process.hrtime.bigint() - t0) / 1e6; console.log(m + ' attrs, ' + xml.length + ' bytes -> ' + ms.toFixed(1) + ' ms; parsed=' + doc.documentElement.attributes.length); }

Measured with Node.js v18.20.8 (wall-clock; absolute numbers vary by host, the scaling is the load-bearing fact):

@xmldom/xmldom 0.9.10:

| M (attributes) | input bytes | time (ms) | ratio vs prev | |---:|---:|---:|---:| | 2000 | 18,894 | 13.4 | — | | 4000 | 38,894 | 38.7 | ×2.9 | | 8000 | 78,894 | 100.8 | ×2.6 | | 16000 | 164,894 | 406.2 | ×4.0 | | 32000 | 340,894 | 2149.5 | ×5.3 |

@xmldom/xmldom 0.8.13:

| M (attributes) | input bytes | time (ms) | |---:|---:|---:| | 2000 | 18,894 | 10.6 | | 4000 | 38,894 | 19.9 | | 8000 | 78,894 | 75.9 | | 16000 | 164,894 | 657.7 | | 32000 | 340,894 | 1643.2 |

xmldom (unscoped) 0.6.0: 4000 → 28.2 ms, 8000 → 131.8 ms, 16000 → 545.2 ms (≈ ×4 per doubling).

Time grows ≈ ×4 per doubling of M — quadratic. About 340 KB of well-formed input costs ~1.6–2.1 s of single-threaded CPU, and it keeps scaling: doubling the attribute count quadruples the cost. The document is trivially generated and compresses to a few kilobytes on the wire.

Impact

Unauthenticated, remotely triggerable denial of service against any service that parses attacker-influenced XML/HTML with xmldom. A single request holds one event-loop thread for seconds; a handful of concurrent requests can saturate CPU and stall the process. Because the payload is a plain well-formed document (one element, many attributes), it passes any "must be well-formed" gate and reaches the parser before any application-level validation (e.g. schema checks or signature verification) can run. The payload is highly compressible, so it is effective over compressed transports.

Fix Applied

Replaced the per-insert linear duplicate scan on the parse-time dedup path with a name-keyed index, so de-duplicating an element's attributes during parse is O(M) instead of O(M²) — a well-formed-but-hostile attribute list can no longer wedge the parse. Behavior-preserving: attribute order and duplicate resolution (last value wins, first position kept) are byte-identical. Non-breaking and independent of requireWellFormed; ships on both maintained versions.

1 / 3
Source: GitHub
First published (updated )
Severity
8.7
CVSS:4.0/AV:N/AC:L/AT:N/PR:N/UI:N/VC:N/VI:N/VA:H/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

Summary

In HTML mode (text/html), a raw-text element (script, style, textarea, title) whose closing tag differs in case from its opening tag (e.g. </ScRiPt> for <script>) is mishandled by the parser, producing quadratic (O(n²)) output growth — a small crafted document parses and serializes into output orders of magnitude larger, exhausting CPU and memory. A modest input of tens of KB can therefore cause a denial of service in any service that parses untrusted HTML with xmldom. Only HTML mode is affected.

Details

The parser calls parseHtmlSpecialContent for each raw-text element in HTML mode, matched via isHTMLRawTextElement / isHTMLEscapableRawTextElement (so all four types — script, style, textarea, title — are in scope). It searches for the element's closing tag with source.indexOf('</' + tagName + '>', elStartEnd), a byte-for-byte case-sensitive match. A mixed-case closing tag never matches, so the search returns -1, and the following source.substring(elStartEnd + 1, -1) extracts text backwards from the start of the document instead of the element's content. The function then returns -1 to the parse loop, which cannot advance normally and falls back to character-by-character reprocessing. Every raw-text element re-captures all source text preceding it, so output grows as O(n²) in the number of such elements.

Root Cause

1. Case-sensitive close-tag search (lib/sax.js:549): source.indexOf('</' + tagName + '>', elStartEnd) does not fold case, contrary to the WHATWG HTML RAWTEXT end-tag-name rule. 2. Unguarded -1 (lib/sax.js:550): source.substring(elStartEnd + 1, elEndStart) runs even when elEndStart === -1, extracting text backwards from position 0. 3. Unstable progression (lib/sax.js:556): the function returns elEndStart (-1), driving repeated character-by-character fallback in the parse loop.

Affected Versions

Only the 0.9.x line is affected — the amplification was introduced in 0.9.0-beta.1 when parseHtmlSpecialContent was refactored, and remains through 0.9.11. The 0.8.x line is not affected: its older parseHtmlSpecialContent does not amplify, despite sharing the same case-sensitive indexOf.

Proof of Concept

js const { DOMParser, XMLSerializer } = require('@xmldom/xmldom');

const n = 1000; const payload = '<html><body>' + '<script>x</ScRiPt>'.repeat(n) + '</body></html>'; const doc = new DOMParser().parseFromString(payload, 'text/html'); const out = new XMLSerializer().serializeToString(doc); console.log(payload.length, out.length, (out.length / payload.length).toFixed(1) + 'x'); // 18026 9037063 501.3x — an 18 KB input yields ~9 MB of output

Output size grows quadratically with the number of case-mismatched raw-text elements:

Repeats | Input len | Output len | Ratio 1 | 44 | 109 | 2.5x 100 | 1826 | 93763 | 51.3x 500 | 9026 | 2268563 | 251.3x 1000 | 18026 | 9037063 | 501.3x 2000 | 36026 | 36074063 | 1001.3x

Proof of Concept from @KarimTantawey (tested with script); the same amplification occurs for style, textarea, and title.

Impact

Small attacker payloads can force disproportionate CPU and memory usage in services that parse and serialize untrusted HTML via xmldom. The quadratic growth means a modest-sized input (tens of kilobytes) can produce output in the tens or hundreds of megabytes, potentially exhausting memory or causing timeouts.

The attack only requires HTML mode (text/html MIME type) and mixed-case closing tags for any of the four raw-text element types. No special configuration or error handler setup is needed.

Severity note

The CVSS 4.0 vector scores availability only (VA:H, with VC:N/VI:N): the flaw neither discloses nor corrupts data, but a small untrusted HTML input (tens of KB) can force output and memory in the tens to hundreds of MB, enough to exhaust a service's heap or stall its event loop. It is reachable with no authentication, configuration, or error-handler setup — only that the application parses untrusted text/html and serializes the result.

Fix Applied

The raw-text closing tag is now matched case-insensitively in HTML raw-text mode (per the WHATWG HTML RAWTEXT end-tag rule), and a missing closing tag is handled explicitly, removing the quadratic output amplification. Output for well-formed input is unchanged. Non-breaking; 0.9.x-only.

1 / 2
Source: GitHub
First published (updated )
Severity
6.9
AV:N/AC:L/AT:N/PR:N/UI:N/VC:N/VI:L/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

Summary

xmldom's parser silently accepts a not-well-formed end tag whose valid name is followed by trailing content — e.g. </a⏎junk>. The element is closed, the trailing content is discarded, and no error is reported, even though the XML end-tag production allows only optional whitespace after the name and both Chromium and Firefox reject such input as application/xml. An application that relies on xmldom to reject not-well-formed input therefore receives a false "valid" result for a document the specification and browsers consider malformed.

Details

Across every affected version, an end tag whose valid Name is followed by trailing content before > is silently accepted: the element is closed, the residue is dropped, and no error is reported. How much leaks differs by line (see Affected Versions), but the observable weakness is the same.

On the current (0.9.x) line, the parser validates the end-tag name against the XML ETag production with an anchored regular expression (^ QName S? $). That expression is compiled with the m (multiline) flag by a shared builder, so $ matches at an interior line terminator: a valid name on the first line satisfies the anchored production and any content after the line break escapes the check. On 0.9.x the whitespace-separated variant (</a junk>) is already rejected; only the line-terminator variant leaks. Older lines have no anchored end-tag validator at all, so they accept both the line-terminator and the whitespace variant.

This is not content injection — the trailing content is dropped, and the resulting DOM is a normal single-root document (<a/>). The security-relevant property is the silent acceptance of not-well-formed input: xmldom's parse result disagrees with the specification and with browser XML parsers, so any control that treats "xmldom parsed it without error" as "well-formed" is bypassed.

Root Cause

On the 0.9.x line, where the line-terminator variant specifically leaks:

1. A shared regexp builder compiles anchored productions with the m flag. 2. ^…$ under m are line anchors, not string anchors. 3. The anchored end-tag production ^ QName S? $ is therefore satisfied by the first line alone, so trailing content after a line terminator is neither matched nor rejected — the malformed end tag is accepted and the residue silently discarded.

The triggering line terminators are the ECMAScript LineTerminator set: U+000A, U+000D, U+2028, U+2029. U+2028 and U+2029 are not XML whitespace, so they are non-conforming trailing content that nonetheless leaks because the JavaScript $ anchor treats them as line boundaries under m.

Affected Versions

Both maintained versions are affected and fixed:

- 0.9.x (>= 0.9.0, <= 0.9.11) → 0.9.12: the anchored end-tag validator's m flag leaks the line-terminator variant. The whitespace variant (</a junk>) is already rejected on this line. - 0.8.x (>= 0.8.0, <= 0.8.14) → 0.8.15: no anchored end-tag validator at all — both the line-terminator and the whitespace variant are silently accepted; the fix adds a residue check.

release-0.7.x (<= 0.7.13) and the unscoped xmldom package (range , last release 0.6.0) are affected but will not be patched — they are end-of-life / unmaintained. They share the older-line behavior (both variants silently accepted, residue dropped).

Proof of Concept

js const { DOMParser, XMLSerializer } = require('@xmldom/xmldom'); const doc = new DOMParser().parseFromString('<a></a\njunk>', 'text/xml'); // no error console.log(new XMLSerializer().serializeToString(doc)); // Observed: <a/> — the malformed end tag is accepted, "junk" silently discarded, no error reported. // Expected (per XML spec / Chromium / Firefox): a parse error — the input is not well-formed.

Impact

- Silent acceptance of not-well-formed XML: a document the specification and browser XML parsers reject is parsed without error. - Bypass of a well-formedness / parse-before-trust gate: an application relying on xmldom to reject malformed input treats such a document as valid. Note this is an input-validation / parser-differential issue, not content injection — the trailing content is discarded.

Fix Applied

The parser now reports a not-well-formed end tag whose valid name is followed by trailing content, on both 0.9.12 and 0.8.15 — previously it was accepted silently — and parsing recovers to the byte-identical DOM as before.\ On 0.9.12 the anchored end-tag validator is corrected so a line break followed by trailing content no longer satisfies it, reported as a recoverable error when parsing as XML and a warning when parsing as HTML.\ On 0.8.15, which previously performed no end-tag residue validation, an equivalent residue check is added, reported as a recoverable error in both XML and HTML.\ Well-formed documents are unaffected.

Because the report is recoverable, the fix is non-breaking: no previously-parsed document begins to throw and no serialized output changes. Consumers that want strict rejection can escalate the reported error to a fatal one via the parser's error handler (onError in 0.9.12, errorHandler in 0.8.15). The two versions also differ in the whitespace-separated variant (</a junk>): 0.9.12 already rejected it with a fatal error in XML and continues to, while 0.8.15 — which validated neither variant — now emits the same recoverable report for both the whitespace and line-break variants.

Residual limitation

By default the parser still recovers (it does not reject the document); the reported condition is a recoverable error/warning, not a fatal error, to avoid changing the parsed output in a patch release. Converting this and the other not-well-formed-acceptance cases to a consistent fatalError — including the broader end-tag leniency on the older versions — is deferred to the next breaking release, tracked at xmldom/xmldom#1074.

1 / 3
Source: GitHub
First published (updated )
Severity
6.3
CVSS:4.0/AV:N/AC:L/AT:P/PR:N/UI:N/VC:N/VI:L/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

Summary

An EntityReference node can be created with an invalid, attacker-controlled name through Document.createEntityReference(name). When this node is serialized directly with:

js serializer.serializeToString(ref, { requireWellFormed: true })

the invalid nodeName is emitted into the serialized XML fragment without validation or escaping.

This can produce real XML markup in the serialized output. In the proof of concept below, the serialized fragment contains <injected/>, and reparsing the fragment creates a real injected element.

---

Details

The issue appears to be in the serialization path for ENTITYREFERENCENODE.

For several other node types, requireWellFormed: true performs specific validation checks before serialization. For example, comments, processing instructions, document types, and some character data cases are checked before being emitted.

However, for ENTITYREFERENCENODE, the serializer appears to emit the node name directly in entity reference form:

js case ENTITYREFERENCENODE: buf.push('&', n.nodeName, ';'); return null;

As a result, if nodeName contains characters that break out of the intended &name; structure, the serializer can emit additional XML markup.

For example, an entity reference created with the name:

text safe; <injected/> &x

is serialized as:

xml &safe; <injected/> &x;

When this fragment is later parsed in an XML context, <injected/> becomes a real element.

This is especially surprising when { requireWellFormed: true } is used, because applications may reasonably treat this mode as the stricter or safer XML serialization mode.

---

Proof of Concept

Tested with:

text @xmldom/xmldom@0.9.10 Node.js v24.18.0 Windows 10 / PowerShell

js 'use strict';

const { DOMImplementation, XMLSerializer, DOMParser } = require('@xmldom/xmldom');

const impl = new DOMImplementation(); const doc = impl.createDocument(null, 'root', null); const serializer = new XMLSerializer();

function countInjected(fragment) { try { const parsed = new DOMParser().parseFromString(<root>${fragment}</root>, 'application/xml'); return parsed.getElementsByTagName('injected').length; } catch (e) { return PARSETHROW ${e.name}: ${e.message}; } }

for (const name of [ 'safe', 'safe; <injected/> &x', 'x<injected', 'x y' ]) { try { const ref = doc.createEntityReference(name); const xml = serializer.serializeToString(ref, { requireWellFormed: true });

console.log([SERIALIZED] ${JSON.stringify(name)}: ${xml}); console.log([INJECTEDCOUNT] ${JSON.stringify(name)}: ${countInjected(xml)}); } catch (e) { console.log([THROW] ${JSON.stringify(name)}: ${e.name}: ${e.message}); } }

Observed output:

text [SERIALIZED] "safe": &safe; [INJECTEDCOUNT] "safe": 0

[SERIALIZED] "safe; <injected/> &x": &safe; <injected/> &x; [INJECTEDCOUNT] "safe; <injected/> &x": 1

[SERIALIZED] "x<injected": &x<injected; [INJECTEDCOUNT] "x<injected": 0

[SERIALIZED] "x y": &x y; [INJECTEDCOUNT] "x y": 0

---

Impact

An application that creates an EntityReference from attacker-controlled input and then serializes that node or XML fragment with requireWellFormed: true may produce XML containing attacker-controlled markup.

The impact is limited by two observations:

1. The parser does not create EntityReference nodes from ordinary XML entity references. 2. Appending an EntityReference node as an element child is rejected with a HierarchyRequestError.

The main affected scenario is applications that directly use createEntityReference(name) and then serialize the resulting node or fragment.

Fix Applied

Two complementary, non-breaking fixes. (1) document.createEntityReference(name) rejects an invalid Name at creation, closing the reachable creation vector by default — the opt-in serializer check alone cannot, since a later nodeName mutation would bypass a creation-only guard. (2) Under requireWellFormed, the serializer validates the EntityReference nodeName as a well-formed XML Name and throws InvalidStateError when it is not; a valid reference still serializes as &name;. Both ship on both maintained versions. The EntityReference / createEntityReference docs note that under requireWellFormed the nodeName is validated as an XML Name, and that xmldom does not expand entities. See the XML Name production. ⚠ Opt-in required. Protection is not automatic. Existing serialization calls remain vulnerable unless { requireWellFormed: true } is explicitly passed. Applications that serialize untrusted DOM content should audit all serializeToString() call sites and add it.

Proof of Concept - fixed path

js 'use strict';

const { DOMImplementation, XMLSerializer } = require('@xmldom/xmldom');

const impl = new DOMImplementation(); const doc = impl.createDocument(null, 'root', null); const serializer = new XMLSerializer();

// Creation-time anchor (applied by default): an invalid XML Name is rejected at creation. try { doc.createEntityReference('safe; <injected/> &x'); } catch (e) { console.log(${e.name}); // rejected at creation }

// Default path (requireWellFormed omitted): because creation now rejects an ill-formed name, // an ill-formed nodeName is only reachable via a post-creation mutation — and is emitted verbatim. const ref = doc.createEntityReference('safe'); ref.nodeName = 'safe; <injected/> &x'; console.log(serializer.serializeToString(ref)); // -> &safe; <injected/> &x; (injection present on the default path)

// Opt-in path: throws on the invalid nodeName. try { serializer.serializeToString(ref, { requireWellFormed: true }); } catch (e) { console.log(${e.name}); // InvalidStateError }

// A valid name still serializes as &name; under requireWellFormed. const ok = doc.createEntityReference('valid'); console.log(serializer.serializeToString(ok, { requireWellFormed: true })); // -> &valid;

Why the default stays verbatim

The creation-time anchor is applied by default, because it is classified non-breaking. The serializer check, by contrast, stays gated behind { requireWellFormed: true }: W3C DOM Parsing's require-well-formed flag defaults to false, and the browser XMLSerializer emits the nodeName verbatim in that default mode, so unconditionally throwing for an ill-formed EntityReference.nodeName would be an unjustified breaking change — which is why the default serialization path stays verbatim.

Residual limitation

The creation vector is closed by default — the non-breaking creation-time anchor — with no further deferred work. The residual is at serialization: the default path still emits an ill-formed nodeName verbatim, because the serializer check is opt-in via { requireWellFormed: true }.

1 / 3
Source: GitHub
First published (updated )
Severity
8.7
XSS
CVSS:4.0/AV:N/AC:L/AT:N/PR:N/UI:N/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

Summary

An embedded line terminator bypasses xmldom's always-on, WHATWG-mandated creation-time name validation. createElementNS, createAttributeNS, createDocumentType, and createAttribute should reject a malformed qualified name with InvalidCharacterError, but a name whose first line is well-formed slips through and enters the DOM. On serialization it is emitted verbatim, so the characters after the line terminator inject markup into the output. The injection reaches the default serialization path, and enabling requireWellFormed does not prevent it.

Details

createElementNS, createAttributeNS, and createDocumentType route through validateQualifiedName, and createAttribute performs the analogous check; each validates the name with g.QNameexact.test(name). QNameexact = reg('^', QName, '$') inherits the m flag from xmldom's shared regexp builder, so the matcher accepts any name whose first line is a valid QName and leaves the remaining lines unconstrained (see Root Cause).

Root Cause

1. A shared regexp builder compiles anchored productions with the m flag. 2. ^…$ under m are line anchors, not string anchors. 3. validateQualifiedName / createAttribute validate with .test() against such a production, so a line terminator followed by breakout markup passes and the malformed name is stored.

The triggering line terminators are the ECMAScript LineTerminator set: U+000A, U+000D, U+2028, U+2029.

Proof of Concept

js const { DOMImplementation, XMLSerializer } = require('@xmldom/xmldom'); const impl = new DOMImplementation();

const doc = impl.createDocument('urn:x', 'root', null); const el = doc.createElementNS('urn:x', 'a\n><script>x</script'); // ACCEPTED (no throw) doc.documentElement.appendChild(el);

// DEFAULT serialization — requireWellFormed NOT set: console.log(new XMLSerializer().serializeToString(doc)); // Observed: <root xmlns="urn:x"><a // ><script>x</script/></root> <-- injected element on the default path // Control: createElementNS('urn:x', 'bad>name') throws InvalidCharacterError, confirming the check is // active and specifically bypassed by the line terminator.

Impact

- Bypass of the always-on WHATWG creation-time name validation (InvalidCharacterError): a malformed name the standard requires be rejected at creation is instead admitted to the DOM. - Markup / structure injection. An application relying on the create APIs to reject malformed names (the standard behavior) as a trust boundary is exposed; where the serialized output reaches an HTML context, downstream XSS. - No serializer option mitigates it. The admitted name is emitted verbatim under both the default path and requireWellFormed: true — the strict serializer shares the same m-flagged blind spot (the subject of the sibling serializer advisories) — so the bypassed creation-time check was the only layer that could have stopped it. Demonstrated for all four create sites in poccreationstrictserializationbypass.cjs.

Fix Applied

createElementNS, createAttributeNS, createDocumentType, and createAttribute now reject a name containing a line terminator with InvalidCharacterError — the same result they already give for other malformed names — because name validation now applies to the whole string. The requireWellFormed serializer's name checks are corrected by the same change. The fix is non-breaking: such a name was already invalid, and no previously-accepted well-formed name is affected.

1 / 2
Source: GitHub
First published (updated )
Severity
8.7
XSS
AV:N/AC:L/AT:N/PR:N/UI:N/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

Summary

The @xmldom/xmldom serializer emits DocumentType.name verbatim into the <!DOCTYPE …> declaration with no well-formedness guard. GHSA-f6ww-3ggp-fr8h (CVE-2026-41674) hardened the serializer's requireWellFormed path for a DocumentType's sibling fields — publicId, systemId, and internalSubset — but it did not add any check for name. A > (or whitespace) in the name terminates the doctype declaration early, letting the remaining characters become sibling markup in the serialized output.

Because requireWellFormed: true — the recommended mitigation for the prior xmldom injection CVEs — performs no validation on the DocType name, this is a bypass of that control, in the same family as the open element-name (GHSA-w2rr-34g9-rvrj) and attribute-name (GHSA-4w3w-2rp5-g8jm) name-injection advisories.

Details

The serializer's DOCUMENTTYPENODE case runs the requireWellFormed block only against publicId, systemId, and internalSubset, then pushes n.name directly into the buffer between the <!DOCTYPE prefix and the closing >:

- 0.9.x (v0.9.10, bb7a085): serializer DocType case, lib/dom.js#L3256-L3283 — the requireWellFormed block (#L3259-L3269) validates publicId/systemId/internalSubset but not name, which is emitted verbatim at #L3270. - 0.8.x (v0.8.13, e5c1480): serializer DocType case, lib/dom.js#L1914-L1946 — same structure; name is emitted verbatim at #L1928. - unscoped xmldom (v0.6.0, c80a161): lib/dom.js#L1105 emits node.name verbatim; this line predates requireWellFormed, so there is no well-formedness path at all.

Enabling write paths

DocumentType.name is a plain, writable own-property, so the enabling vector differs by line:

- 0.9.x — createDocumentType() validates the name via validateQualifiedName (lib/dom.js#L925-L936, validation at #L926), so the deliverable vector is a direct property write (dt.name = 'html><script>…') to the unguarded own-property. - 0.8.x — createDocumentType() does not validate the name (lib/dom.js#L456-L464), so the malicious name is reachable directly through createDocumentType() as well as via direct property write. - unscoped xmldom (<= 0.6.0) — createDocumentType() does not validate the name (lib/dom.js#L286), same as 0.8.x.

This is the same structural root cause the sibling name-injection advisories share: the serializer's requireWellFormed path validates content delimiters but no name field, and every name-like field is a plain writable property, so mutation / direct property-write bypasses any creation-time check.

Root Cause

1. The serializer's requireWellFormed DocType block checks publicId, systemId, and internalSubset (the fields hardened by GHSA-f6ww-3ggp-fr8h) but has no check for name. 2. DocumentType.name is a plain writable own-property; on 0.8.x and the unscoped package createDocumentType() does not validate it either. 3. The serializer emits name directly between the doctype delimiters: <!DOCTYPE ${name}…>.

Proof of Concept

Run against @xmldom/xmldom v0.9.10 (commit bb7a085):

javascript const { DOMImplementation, XMLSerializer, DOMParser } = require('@xmldom/xmldom');

const impl = new DOMImplementation(); const serializer = new XMLSerializer();

// 0.9.x createDocumentType validates the name, so overwrite it via direct property write const dt = impl.createDocumentType('html', '', ''); dt.name = 'html><script xmlns="http://www.w3.org/1999/xhtml">alert(1)</script'; const doc = impl.createDocument(null, 'r', dt);

const output = serializer.serializeToString(doc, { requireWellFormed: true }); console.log(output); // Output: <!DOCTYPE html><script xmlns="http://www.w3.org/1999/xhtml">alert(1)</script><r/> // // requireWellFormed: true did NOT prevent the injection (no exception thrown). // The injected <script> is well-formed XHTML that a browser would execute.

Confirmed runtime behavior:

- 0.9.x — createDocumentType() rejects the malicious name at creation (InvalidCharacterError); a direct write to dt.name bypasses that, and serializeToString(…, { requireWellFormed: true }) emits the breakout with no exception. - Re-parse confirmation — re-parsing the output shows the injected <script> is a real second top-level element originating entirely from the DocType name: the parser rejects it with HierarchyRequestError: Only one element can be added and only after doctype. A comment-injection variant (dt.name = 'html><!--INJECTED--', output <!DOCTYPE html><!--INJECTED--><r/>) re-parses cleanly and the injected comment node is enumerable, confirming the injected node is structurally live. - 0.8.x (v0.8.13, e5c1480) — createDocumentType('html><script>…', '', '') accepts the malicious name directly (no creation-time validation), and serializeToString(doc, null, null, { requireWellFormed: true }) produces <!DOCTYPE html><script>alert(1)</script><r/> with no exception.

A browser reproduction does not apply: browsers keep DocumentType.name readonly, so the direct-write vector cannot be reproduced in a browser DOM. The injection is specific to xmldom exposing name as writable and serializing it without a guard.

Impact

Applications that build a DocumentType node with an attacker-influenced name — via direct property write on any affected line, or via createDocumentType() on 0.8.x and the unscoped package — and serialize the document are vulnerable to XML/markup injection:

- XML structure injection — breaking out of the <!DOCTYPE …> declaration to inject arbitrary sibling elements, comments, or additional markup into the output. - XSS via XHTML — if the serialized output is served as XHTML or processed by a browser-based XML parser, an injected <script> element (in the XHTML namespace) executes. - requireWellFormed bypass — applications that adopted requireWellFormed: true as a mitigation for the prior injection CVEs (including the sibling DocType fields fixed by GHSA-f6ww-3ggp-fr8h) remain vulnerable through the DocType name.

Fix Applied

Under requireWellFormed, the serializer validates the DocType name as a well-formed XML Name and throws InvalidStateError when it is not — matching the sibling publicId/systemId/internalSubset checks. Non-breaking and opt-in; ships on both maintained versions. No creation-time change is made: 0.9.x already validates the name at createDocumentType, and the 0.8.x/unscoped creation gap cannot be closed without a breaking change, so it is left unfixed. See the XML Name production. ⚠ Opt-in required. Protection is not automatic. Existing serialization calls remain vulnerable unless { requireWellFormed: true } is explicitly passed. Applications that serialize untrusted DOM content should audit all serializeToString() call sites and add it.

Proof of Concept - fixed path

javascript const { DOMImplementation, XMLSerializer } = require('@xmldom/xmldom');

const impl = new DOMImplementation(); const serializer = new XMLSerializer();

const dt = impl.createDocumentType('html', '', ''); dt.name = 'html><script xmlns="http://www.w3.org/1999/xhtml">alert(1)</script'; const doc = impl.createDocument(null, 'r', dt);

// Default path: the ill-formed name is still emitted verbatim (injection present). console.log(serializer.serializeToString(doc)); // <!DOCTYPE html><script xmlns="http://www.w3.org/1999/xhtml">alert(1)</script><r/>

// Opt-in path: serialization throws instead of emitting the breakout. serializer.serializeToString(doc, { requireWellFormed: true }); // throws InvalidStateError

Why the default stays verbatim

W3C DOM Parsing's require-well-formed flag defaults to false, and the browser XMLSerializer emits the name verbatim in that default mode. Unconditionally throwing would be an unjustified breaking change against that specified default, so the guard is opt-in behind { requireWellFormed: true }.

Residual limitation

The default serialization path still emits the ill-formed DocType name verbatim; protection applies only when requireWellFormed: true is passed. No creation-time validation is added for the DocType name: 0.9.x already validates at createDocumentType, and the 0.8.x/unscoped creation gap is left unfixed — it cannot be closed without a breaking change.

1 / 3
Source: GitHub
First published (updated )
Severity
8.7
XSS
AV:N/AC:L/AT:N/PR:N/UI:N/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

Summary

Document.createElement() in @xmldom/xmldom accepts arbitrary strings as the tagName parameter with zero validation. The serializer emits the tag name verbatim into XML/HTML output. Critically, the requireWellFormed: true serializer option — the recommended mitigation from CVE-2026-41672, CVE-2026-41674, and CVE-2026-34601 — did NOT catch this, making it a bypass of the existing security controls.

An attacker who controls the element name string can inject arbitrary attributes (including event handlers) into the serialized output, leading to XSS when the output is consumed by a browser or downstream parser.

Details

Document.createElement() accepts any string as tagName and stores it directly on the element node without validation. When the document is later serialized via XMLSerializer.serializeToString(), the serializer emits the tagName verbatim into the output.

The XML specification requires element names to conform to the Name production. The existing createAttributeNS() and createElementNS() methods validate qualified names against an anchored name/QName pattern, but createElement() bypasses this entirely, and the requireWellFormed: true serializer path performed no element-name validation — rendering it ineffective against this vector.

Root Cause

1. createElement() stores the raw tagName string without any validation. 2. The serializer's requireWellFormed code path did not validate element names against the XML Name/QName production. 3. The serializer emits tagName directly into angle brackets: <${tagName}...>.

Proof of Concept

js const { DOMImplementation, XMLSerializer } = require('@xmldom/xmldom');

const impl = new DOMImplementation(); const serializer = new XMLSerializer(); const doc = impl.createDocument(null, 'root', null);

// Inject an element whose "name" contains attributes with an XSS payload const el = doc.createElement('img src=x onerror="alert(1)"'); doc.documentElement.appendChild(el);

const output = serializer.serializeToString(doc, { requireWellFormed: true }); console.log(output); // <root><img src=x onerror="alert(1)"/></root> // // A browser parsing this HTML will execute alert(1). // requireWellFormed: true did NOT prevent the injection.

Impact

Applications that use @xmldom/xmldom to construct DOM trees and serialize them to XML/HTML are vulnerable to injection attacks if any part of an element name originates from user input. This includes:

- Cross-Site Scripting (XSS): Injecting event handler attributes (onerror, onclick, etc.) into HTML output consumed by browsers. - XML injection: Breaking XML document structure by injecting closing tags, new elements, or processing instructions through the element name. - Security control bypass: Applications that adopted requireWellFormed: true as a mitigation for CVE-2026-41672 / 41674 / 34601 remained vulnerable through this vector.

@xmldom/xmldom can also be used inside browsers, where it mirrors the DOM API. Unlike the browser's createElement(), which rejects an invalid name with InvalidCharacterError, xmldom accepts it — developers may assume the same safety and skip validation.

Fix Applied

⚠ Opt-in required. Protection is not automatic. Existing serialization calls remain vulnerable unless { requireWellFormed: true } is explicitly passed. Applications that serialize untrusted DOM content should audit all serializeToString() call sites and add it.

When { requireWellFormed: true } is passed, the serializer now validates each element's serialized qualified name against the XML QName production and throws InvalidStateError before emitting the start tag. This also covers the namespace-prefix sub-vector: an invalid prefix surfaces either in the element qualified name (PREFIX:local) or in a synthesized xmlns:PREFIX declaration, and both are QName-checked.

Fixed under requireWellFormed: true in @xmldom/xmldom 0.9.11 and 0.8.14. Default serialization is unchanged.

PoC — fixed path

js const { DOMImplementation, XMLSerializer } = require('@xmldom/xmldom');

const doc = new DOMImplementation().createDocument(null, 'root', null); doc.documentElement.appendChild(doc.createElement('img src=x onerror="alert(1)"'));

// Default (unchanged): verbatim — injection present console.log(new XMLSerializer().serializeToString(doc)); // <root><img src=x onerror="alert(1)"/></root>

// Opt-in guard: throws InvalidStateError before serializing try { new XMLSerializer().serializeToString(doc, { requireWellFormed: true }); } catch (e) { console.log(e.name, e.message); // InvalidStateError: The element name "img src=x onerror="alert(1)"" is not a valid XML QName }

Why the default stays verbatim

The W3C DOM Parsing and Serialization spec defines a require well-formed flag whose default value is false. With the flag unset, the serializer emits element names verbatim, matching the XMLSerializer behavior of Chrome, Firefox, and Safari. Unconditionally throwing would be a behavioral breaking change with no spec justification; the opt-in requireWellFormed: true flag lets applications that require injection safety enable strict mode without breaking existing code.

Residual limitation

createElement(tagName) does not validate tagName at creation time. Enforcing an InvalidCharacterError for invalid names unconditionally at creation time is a breaking change and is deferred to the next breaking release. When the default serialization path is used (without requireWellFormed: true), invalid element names are still emitted verbatim; applications that do not pass requireWellFormed: true remain exposed.

Creation-time validation is tracked in a public issue on the next breaking-release milestone (filed at publication — issue link to be added), targeting the next breaking release.

1 / 3
Source: GitHub
First published (updated )
Severity
8.7
XSS
CVSS:4.0/AV:N/AC:L/AT:N/PR:N/UI:N/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

Summary

Element.setAttribute() in @xmldom/xmldom bypasses attribute name validation by calling the private createAttribute(name) method, which performs no validation. The public createAttribute() method correctly validates names against an anchored QName pattern, but setAttribute() never uses it. The serializer escapes attribute values but trusts attribute names, allowing an attacker to inject additional attributes (including event handlers) into serialized output. The requireWellFormed: true option did not catch this.

Details

Element.setAttribute(name, value) creates attribute nodes by calling the private createAttribute(name) method, which performs no validation on the name parameter. In contrast, the public Document.createAttribute(name) method validates the name against the QName production before creating the attribute node.

The result is a two-tier validation system where the most commonly used API (setAttribute) takes the unvalidated path:

- doc.createAttribute("bad name") — throws INVALIDCHARACTERERR (correct). - el.setAttribute("bad name", "value") — succeeds silently (vulnerable).

The serializer emits attribute names verbatim into the output. Because attribute values ARE escaped (quotes, ampersands, etc.), the injection must occur through the name. An attacker can terminate the current attribute and inject new ones by including quote and space characters in the attribute name.

Root Cause

1. setAttribute() calls createAttribute() (private, no validation) instead of createAttribute() (public, validates against QName). 2. The serializer trusts attribute names and emits them unescaped. 3. The serializer's requireWellFormed code path did not validate attribute names during serialization.

Proof of Concept

js const { DOMImplementation, XMLSerializer } = require('@xmldom/xmldom');

const impl = new DOMImplementation(); const serializer = new XMLSerializer(); const doc = impl.createDocument(null, 'root', null);

// The attribute name contains a closing quote, a space, and a new attribute doc.documentElement.setAttribute('class="safe" onclick', 'alert(1)');

const output = serializer.serializeToString(doc, { requireWellFormed: true }); console.log(output); // <root class="safe" onclick="alert(1)"/> // // The single setAttribute() call produced TWO attributes: // 1. class="safe" // 2. onclick="alert(1)" // // requireWellFormed: true did NOT prevent the injection.

Demonstrating the validation gap

js // Public createAttribute correctly rejects invalid names: try { doc.createAttribute('class="safe" onclick'); } catch (e) { console.log('createAttribute rejects:', e.message); }

// But setAttribute (which uses createAttribute) accepts the same input: doc.documentElement.setAttribute('class="safe" onclick', 'alert(1)'); // No error thrown

Impact

Applications that use setAttribute() with any user-controlled portion of the attribute name are vulnerable to attribute injection attacks. This includes:

- Cross-Site Scripting (XSS): Injecting event handler attributes into HTML output consumed by browsers. - Security attribute override: Overriding security-relevant attributes such as integrity, nonce, sandbox, or Content-Security-Policy meta attributes. - Validation bypass: The public createAttribute() API validates while setAttribute() does not, creating an inconsistent security boundary that developers cannot rely on. - requireWellFormed bypass: Applications that adopted requireWellFormed: true as a mitigation for prior CVEs remained vulnerable.

@xmldom/xmldom can also be used inside browsers, where it mirrors the DOM API. Unlike the browser's setAttribute(), which rejects an invalid attribute name with InvalidCharacterError, xmldom accepts it — developers may assume the same safety and skip validation.

Fix Applied

⚠ Opt-in required. Protection is not automatic. Existing serialization calls remain vulnerable unless { requireWellFormed: true } is explicitly passed. Applications that serialize untrusted DOM content should audit all serializeToString() call sites and add it.

When { requireWellFormed: true } is passed, the serializer now validates each serialized attribute's qualified name against the XML QName production and throws InvalidStateError before emitting it. This covers ordinary attribute names and synthesized xmlns:PREFIX namespace declarations (the namespace-prefix sub-vector).

Fixed under requireWellFormed: true in @xmldom/xmldom 0.9.11 and 0.8.14. Default serialization is unchanged.

PoC — fixed path

js const { DOMImplementation, XMLSerializer } = require('@xmldom/xmldom');

const doc = new DOMImplementation().createDocument(null, 'root', null); doc.documentElement.setAttribute('class="safe" onclick', 'alert(1)');

// Default (unchanged): verbatim — injection present console.log(new XMLSerializer().serializeToString(doc)); // <root class="safe" onclick="alert(1)"/>

// Opt-in guard: throws InvalidStateError before serializing try { new XMLSerializer().serializeToString(doc, { requireWellFormed: true }); } catch (e) { console.log(e.name, e.message); // InvalidStateError: The attribute name "class="safe" onclick" is not a valid XML QName }

Why the default stays verbatim

The W3C DOM Parsing and Serialization spec defines a require well-formed flag whose default value is false. With the flag unset, the serializer emits attribute names verbatim, matching the XMLSerializer behavior of Chrome, Firefox, and Safari. Unconditionally throwing would be a behavioral breaking change with no spec justification; the opt-in requireWellFormed: true flag lets applications that require injection safety enable strict mode without breaking existing code.

Residual limitation

setAttribute(name, value) does not validate name at creation time (unlike the public createAttribute(), which already does). Making setAttribute() reject invalid names unconditionally is a breaking change and is deferred to the next breaking release. When the default serialization path is used (without requireWellFormed: true), attribute names set via setAttribute() are still emitted verbatim; applications that do not pass requireWellFormed: true remain exposed.

Creation-time validation is tracked in a public issue on the next breaking-release milestone (filed at publication — issue link to be added), targeting the next breaking release.

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

xmldom is a pure JavaScript W3C standard-based (XML DOM Level 2 Core) DOMParser and XMLSerializer module. In @xmldom/xmldom prior to versions 0.9.10 and 0.8.13 and xmldom version 0.6.0 and prior, the package allows attacker-controlled processing instruction data to be serialized into XML without validating or neutralizing the PI-closing sequence ?>. As a result, an attacker can terminate the processing instruction early and inject arbitrary XML nodes into the serialized output. This issue has been patched in versions @xmldom/xmldom versions 0.9.10 and 0.8.13.

First published (updated )
Severity
7

xmldom is a pure JavaScript W3C standard-based (XML DOM Level 2 Core) DOMParser and XMLSerializer module. In @xmldom/xmldom prior to versions 0.9.10 and 0.8.13 and xmldom version 0.6.0 and prior, the package allows attacker-controlled comment content to be serialized into XML without validating or neutralizing comment-breaking sequences. As a result, an attacker can terminate the comment early and inject arbitrary XML nodes into the serialized output. This issue has been patched in versions @xmldom/xmldom versions 0.9.10 and 0.8.13.

First published (updated )
Severity
7

xmldom is a pure JavaScript W3C standard-based (XML DOM Level 2 Core) DOMParser and XMLSerializer module. In @xmldom/xmldom prior to versions 0.9.10 and 0.8.13 and xmldom version 0.6.0 and prior, seven recursive traversals in lib/dom.js operate without a depth limit. A sufficiently deeply nested DOM tree causes a RangeError: Maximum call stack size exceeded, crashing the application. This issue has been patched in versions @xmldom/xmldom versions 0.9.10 and 0.8.13.

First published (updated )
Severity
7

xmldom is a pure JavaScript W3C standard-based (XML DOM Level 2 Core) DOMParser and XMLSerializer module. In @xmldom/xmldom prior to versions 0.9.10 and 0.8.13 and xmldom version 0.6.0 and prior, the package serializes DocumentType node fields (internalSubset, publicId, systemId) verbatim without any escaping or validation. When these fields are set programmatically to attacker-controlled strings, XMLSerializer.serializeToString can produce output where the DOCTYPE declaration is terminated early and arbitrary markup appears outside it. This issue has been patched in versions @xmldom/xmldom versions 0.9.10 and 0.8.13.

First published (updated )
Severity
7

xmldom is a pure JavaScript W3C standard-based (XML DOM Level 2 Core) DOMParser and XMLSerializer module. In xmldom versions 0.6.0 and prior and @xmldom/xmldom prior to versions 0.8.12 and 0.9.9, xmldom/xmldom allows attacker-controlled strings containing the CDATA terminator ]]> to be inserted into a CDATASection node. During serialization, XMLSerializer emitted the CDATA content verbatim without rejecting or safely splitting the terminator. As a result, data intended to remain text-only became active XML markup in the serialized output, enabling XML structure injection and downstream business-logic manipulation. This issue has been patched in xmldom version 0.6.0 and @xmldom/xmldom versions 0.8.12 and 0.9.9.

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