[4] XMLDocumentParser UAF read: libxml2 attribute spans read after a microtask checkpoint frees them
A spec-mandated microtask turns plain XHTML into a heap disclosure candidate
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, andxmlStopParser()->xmlHaltParser()->xmlFreeParserInputBuffer()frees it synchronously.XMLDocumentParser::startElementNs()drains the microtask queue viaperformMicrotaskCheckpoint()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. aMutationObservercallback that removes the iframe holding the XML document.handleNamespaceAttributes()andhandleElementAttributes()then read the freed buffer throughtoAtomString(). 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
LayoutTests/fast/parser/resources/xml-parser-stopped-during-start-element-microtask-frame.xhtml
Patch Details
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.
Background
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.
Analysis
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:
- The XHTML frame defines
x-crash, so every<x-crash>start tag takes thewillConstructCustomElementbranch and drains microtasks insidestartElementNs(). - A
MutationObserveron the document element fires for children the parser already inserted, and its callback removes the hosting iframe from the parent document. - Long
data-vvalues enlarge the freed region thattoAtomString()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.
Audit directions
- Borrowed spans from a library callback outliving a script-running step inside the same callback. Narrow: audit every other SAX handler in
XMLDocumentParserLibxml2.cpp(characters,cdataBlock,processingInstruction,comment,entityDecl,internalSubset) for any call that can reach script before thexmlChar*arguments are fully copied. Match tell: aconst xmlChar*orstd::span<const xmlChar>parameter read afterperformMicrotaskCheckpoint,parserAppendChild,appendData, or any element-construction call. Wider: wherever WebKit wraps a C library that hands out borrowed buffers during callbacks, such as libxslt extension callbacks orTextResourceDecoder/ICU converters calling back into WebCore; look for a library-owned pointer stored in a local and used after a DOM mutation. Widest: any codebase embedding a SAX or streaming parser (expat, libxml2, Xerces, yajl) whose callbacks can re-enter user code. The audit question is whether anything the callback received is still read after user code had a chance to stop or free the parser. - Missing re-validation of parser state after script runs mid-step. Once script has run, the parser may already be torn down, so the remaining tree-building must be re-gated. Narrow: grep
XMLDocumentParser*.cppandHTMLConstructionSite/HTMLDocumentParserforperformMicrotaskCheckpointand custom-element construction call sites, and confirm each is followed by a stopped or detached check before touchingm_currentNodeor creating nodes.updateLeafTextNode()already shows the correct shape with its post-appendDataisStopped()re-check. Wider: the same re-gating is needed after synchronous event dispatch,ScriptElementexecution, and style flushes inside the HTML tree builder. Widest: any incremental parser or interpreter that calls user hooks mid-production (Gecko and Blink HTML parsers, template engines with user filters). In code review, any line after a hook call that dereferences the parser's own state without anisStopped()/isDetached()check is the tell. - Cancel paths that synchronously free resources an in-flight callback still borrows. Trace which frame-teardown paths reach
stopParsing()synchronously from inside a microtask, and inventory what each parser'sstopParsing()frees immediately versus defers. Narrow: compareXMLDocumentParser::stopParsing()(which callsxmlStopParser) withHTMLDocumentParser::stopParsing()and theScriptableDocumentParserbase; a hit is any synchronous free of tokenizer or input state that a caller higher on the stack may still be reading. Wider:MediaSource/SourceBufferparsers, WebVTTTextTrackparsers, andFontFacedecoders that document detach can stop. Widest: libuv/asio handle close during callbacks and Rust/C++ async cancellation. The robust mitigation is deferring the free until the outermost callback frame unwinds.