← All reports

[4] XMLDocumentParser UAF read: libxml2 attribute spans read after a microtask checkpoint frees them

HighWebCore XML parserUAF

A spec-mandated microtask turns plain XHTML into a heap disclosure candidate

f4d7b99

High. Plain XHTML markup plus a mutation observer reaches it from any page, and the read copies freed heap bytes into an attribute string whose length the attacker chooses. It stays a read: no write into the freed region exists on this path.

WebKit parses XML and XHTML by driving libxml2 in streaming SAX mode, where the library calls back into WebKit for each tag and hands over pointers into its own input buffer rather than copies. XMLDocumentParser::startElementNs(), WebKit's handler for each opening tag, receives attribute values as (start, end) pointer pairs that stay valid only while libxml2's parser context keeps its input alive. When the tag names a registered custom element, the HTML spec also requires the parser to drain the microtask queue first, and the invariant is that nothing libxml2 lent the callback is read after script has had a chance to run.

The angle: a page that loads an XHTML document in a frame can make startElementNs() copy freed libxml2 heap memory into an attribute string of attacker-chosen length. That is a renderer crash at minimum, and a heap disclosure if the attribute stays script-reachable.

libxml2's SAX2 startElementNs() hands WebKit the element's namespace and attribute arrays as raw (const xmlChar*) spans that point directly into the parser context's input buffer. libxml2 owns that buffer, and xmlStopParser() -> xmlHaltParser() -> xmlFreeParserInputBuffer() frees it synchronously. XMLDocumentParser::startElementNs() drains the microtask queue via performMicrotaskCheckpoint() before reading those spans, on the path taken when the element being started matches a registered custom element. Any microtask can stop or detach this parser, e.g. a MutationObserver callback that removes the iframe holding the XML document. handleNamespaceAttributes() and handleElementAttributes() then read the freed buffer through toAtomString(). Fix this by copying every libxml2-owned span into WebKit-owned storage before the microtask checkpoint runs. Also bail out after the checkpoint if it stopped the parser.

Source/WebCore/xml/parser/XMLDocumentParserLibxml2.cpp

willConstructCustomElement = protect(window->customElementRegistry())->findInterface(qName);
}
 
+ // Copy every span libxml2 owns into WebKit-owned storage here, before any code that can
+ // run script such as performMicrotaskCheckpoint().
+ Vector<Attribute> prefixedAttributes;
+ bool shouldUseNullCustomElementRegistry = false;
+ bool handledAttributes = handleNamespaceAttributes(prefixedAttributes, namespaces, shouldUseNullCustomElementRegistry);
+ bool success = handledAttributes ? handleElementAttributes(prefixedAttributes, libxmlAttributes, numAttributes, shouldUseNullCustomElementRegistry) : false;
+
std::optional<ThrowOnDynamicMarkupInsertionCountIncrementer> markupInsertionCountIncrementer;
std::optional<CustomElementReactionStack> customElementReactionStack;
 
if (willConstructCustomElement) [[unlikely]] {
markupInsertionCountIncrementer.emplace(*document);
protect(document->eventLoop())->performMicrotaskCheckpoint(document->vm());
+ // Draining the microtask queue may have stopped or detached this parser, in which case we
+ // must not keep building the tree.
+ if (isStopped())
+ return;
customElementReactionStack.emplace(document->globalObject());
}
 
- Vector<Attribute> prefixedAttributes;
- bool shouldUseNullCustomElementRegistry = false;
- bool handledAttributes = handleNamespaceAttributes(prefixedAttributes, namespaces, shouldUseNullCustomElementRegistry);
- bool success = handledAttributes ? handleElementAttributes(prefixedAttributes, libxmlAttributes, numAttributes, shouldUseNullCustomElementRegistry) : false;
-

LayoutTests/fast/parser/resources/xml-parser-stopped-during-start-element-microtask-frame.xhtml

+customElements.define("x-crash", class extends HTMLElement { });
+new MutationObserver(function () {
+ var frame = parent.document.getElementById("frame");
+ if (frame)
+ frame.remove();
+}).observe(document.documentElement, { childList: true, subtree: true });
...
+<x-crash data-v="AAAA...AAAA"></x-crash>

The calls to handleNamespaceAttributes() and handleElementAttributes() move from after the custom-element block to before it. These calls convert libxml2-owned spans into AtomStrings inside a Vector<Attribute>, so every span is now copied before performMicrotaskCheckpoint() can run script. Inside the willConstructCustomElement branch, an if (isStopped()) return; now follows the checkpoint, so a parser stopped during the drain no longer goes on to create the element, look up the registry, or append to the tree. A new LayoutTest loads an XHTML iframe that registers x-crash, installs a MutationObserver that removes its hosting iframe, and contains a run of <x-crash> elements with very long data-v values.

Borrowed pointers into a callee-owned buffer held across a re-entrancy point that can synchronously trigger the owner's teardown.

SAX parsing. In SAX mode, libxml2 calls user-provided callbacks as it tokenizes instead of building its own tree. In SAX2's startElementNs, attribute values arrive as (value_start, value_end) pointer pairs into the parser context's input buffer, which libxml2 owns. xmlStopParser() halts an in-progress parse, after which libxml2 releases the context's input state.

WebKit's side of the parser. XMLDocumentParser owns the libxml2 context through RefPtr<XMLParserContext> m_context, a wrapper around an xmlParserCtxtPtr. PendingCallbacks is WebKit's queue for SAX events that arrive while the parser is paused, for example while waiting on a script, and queued events are deep-copied.

Microtask checkpoints and custom elements. A microtask checkpoint is the point where the event loop drains queued microtasks, including promise reactions and MutationObserver callbacks. The HTML spec requires the parser to perform one before synchronously constructing a custom element, so arbitrary script can run in the middle of a start-tag callback.

Mutation observers and frame removal. MutationObserver callbacks are delivered as microtasks, batched from DOM mutations such as the parser inserting earlier children. Removing an <iframe> from its parent disconnects its content frame, which stops all loaders and parsers for the document inside.

This is a use-after-free read of a heap buffer owned by a third-party library.

  startElementNs(<x-crash data-v=...>)       microtask drain
  ───────────────────────────────────         ───────────────
  spans -> libxml2 input buffer
  findInterface("x-crash") -> custom
  performMicrotaskCheckpoint() ──────────►  MutationObserver cb
                                              frame.remove()
                                               ... stopParsing()
                                               xmlStopParser()
                                               xmlFreeParserInputBuffer()
                               ◄──────────   (buffer freed)
  handleElementAttributes()
    toAtomString(spans)   <- read from freed buffer

Before the fix, the borrowed spans lived across the checkpoint shown in the middle of the diagram. Pending MutationObserver deliveries for nodes the same parser inserted earlier run during the drain, and the commit message traces the teardown they trigger: HTMLFrameOwnerElement::disconnectContentFrame() → FrameLoader::frameDetached() → stopAllLoaders() → DocumentLoader::stopLoading() → FrameLoader::stopLoading() → XMLDocumentParser::stopParsing() → xmlStopParser() → xmlHaltParser() → xmlFreeParserInputBuffer(). When control returns, the attribute handlers read the freed buffer through toAtomString(). The test comment ties the freed buffer to attribute value spans specifically. Namespace prefix and URI pointers in libxml2 SAX2 are typically dictionary-interned, so the UAF is firmly established for attribute values. A secondary defect: after the checkpoint, the function kept creating and inserting an element for a parser that libxml2 had already halted, which the new isStopped() return closes.

The regression test assembles the trigger from three pieces:

  1. The XHTML frame defines x-crash, so every <x-crash> start tag takes the willConstructCustomElement branch and drains microtasks inside startElementNs().
  2. A MutationObserver on the document element fires for children the parser already inserted, and its callback removes the hosting iframe from the parent document.
  3. Long data-v values enlarge the freed region that toAtomString() later reads.

Reachability needs nothing beyond ordinary web content. The reliable outcome is a renderer crash under ASan or poisoned allocators. Under realistic allocators, the outcome could instead be stale heap bytes copied into an attribute AtomString. The read is copy-only: toAtomString() copies bytes into a new string, and nothing writes into the freed region on this path. The ceiling is therefore a heap content disclosure if the copied attribute stays script-observable, and a crash otherwise. Two reachability questions decide escalation. Can script in the same drain reclaim the freed system-malloc slot with attacker-chosen or secret-bearing data before the read? Does the element built after the stop, with those attributes, remain reachable from script, for example through a document reference held by the parent? The size claim applies to the simple-literal case the test exercises; after entity expansion or attribute normalization, value pointers may point into separately allocated copies instead. The code runs in the WebContent process and needs a separate escape to cross the sandbox.

This vulnerability weakens memory safety in the WebContent process. The SAX contract assumes callback arguments stay valid for the whole callback, and script run mid-callback could free that storage while WebKit still intended to read it. Freed heap contents would be copied into attribute strings of attacker-chosen length. If those strings reach script-visible DOM, the bug serves as an out-of-bounds-in-time heap disclosure, for example to defeat ASLR in a renderer chain. At minimum it is a web-reachable renderer crash.

Insight. WebKit already knew the safe pattern. PendingCallbacks::appendStartElementNSCallback deep-copies every span with xmlStrdup/xmlStrndup precisely because the deferred path outlives the callback. The bug is an ordering regression on the immediate path: the spec-mandated checkpoint was inserted between receiving the borrowed spans and consuming them. Any spec change that adds a script-running step inside a parser callback silently turns a non-reentrant callback into a reentrant one. The MutationObserver + frame.remove() shape is a reusable trigger for reaching stopParsing() from inside the parser.