← All reports

[2] Style flush UAF via fonts.ready re-entrancy during shadow-root iteration

HighWebCore Style / Font LoadingUAF

Style recalc assumed no page script runs mid-walk. One prototype getter disagrees.

86074ba

A prototype getter frees the list node a style-engine iterator is standing on, using only DOM, CSS @font-face and the Font Loading API, which is why this is High. Escalating past a crash means reclaiming a small fixed-shape node, but the window to do so sits inside the attacker's own getter.

Style recalculation in WebKit's renderer walks per-tree style state on the assumption that no page script runs in the middle of the walk. The document keeps its connected shadow roots in a WeakListHashSet, an insertion-ordered set whose elements each live in their own heap-allocated list node, and each shadow root has a Style::Scope holding its own stylesheet and resolver state. The walk is safe only if that registry is not modified before the loop finishes, even though each iteration calls into code that updates document.fonts, the FontFaceSet whose ready promise settles once font loading completes.

The angle: a page that defines a then getter on FontFaceSet can run script in the middle of a style flush, disconnect a shadow root, and leave the engine's iterator walking a freed list node.

Style::Scope::flushPendingDescendantUpdates() walks Document::m_inDocumentShadowRoots (a WeakListHashSet) with a live iterator while calling flushPendingUpdate() on each descendant shadow scope. Flushing a shadow scope re-registers @font-face rules, which can drop the active count to zero and settle document.fonts.ready, running an author getter. That getter can remove the iterated shadow root's host, freeing the ListHashSetNode the suspended iterator points at, and the loop then reads the freed node's m_next.

Fixed in two layers: (1) defer document.fonts.ready resolution to a queued task instead of resolving synchronously while walking m_inDocumentShadowRoots; (2) hold a ScriptDisallowedScope::InMainThread across each loop that walks m_inDocumentShadowRoots and calls into a descendant scope. The guard goes on every such loop, since each makes a per-root callout into the style system that can reach font registration.

Test: LayoutTests/platform/glib/damage/crash-shadow-root-style-flush-font-promise.html

Source/WebCore/style/StyleScope.cpp

void Scope::flushPendingDescendantUpdates()
{
ASSERT(m_hasDescendantWithPendingUpdate);
ASSERT(!m_shadowRoot);
+ ScriptDisallowedScope::InMainThread scriptDisallowedScope;
for (auto& descendantShadowRoot : m_document->inDocumentShadowRoots()) {
const_cast<ShadowRoot&>(descendantShadowRoot).styleScope().flushPendingUpdate();
}
...

Source/WebCore/css/FontFaceSet.cpp

void FontFaceSet::completedLoading()
{
- if (m_isDocumentLoaded && !m_readyPromise->isFulfilled())
- m_readyPromise->resolve(*this);
+ queueTaskKeepingObjectAlive(*this, TaskSource::FontLoading, [](auto& set) {
+ if (set.m_isDocumentLoaded && !set.m_readyPromise->isFulfilled())
+ set.m_readyPromise->resolve(set);
+ });
}
...

LayoutTests/platform/glib/damage/crash-shadow-root-style-flush-font-promise.html

+ document.fonts.ready;
+ const prependedStyle = document.createElement("style");
+ shadowRoot.prepend(prependedStyle);
+ Object.defineProperty(FontFaceSet.prototype, "then", {
+ configurable: true,
+ get() {
+ delete FontFaceSet.prototype.then;
+ host.remove(); // Frees the iterated Document::m_inDocumentShadowRoots node.
+ return undefined;
+ }
+ });
+ document.styleSheets.length; // Reaches Scope::flushPendingDescendantUpdates().

The change moves settlement of document.fonts.ready into a queued font-loading task, and puts a script-disallowed guard in front of the per-root-callout loops over the document's shadow-root registry listed below.

In FontFaceSet.cpp, completedLoading() no longer resolves m_readyPromise inline. The m_isDocumentLoaded && !isFulfilled() check and the resolve(set) call now run inside a queueTaskKeepingObjectAlive(*this, TaskSource::FontLoading, ...) lambda, so settlement and the then lookup it triggers happen in a later event-loop task. startedLoading() moves its loading event from TaskSource::DOMManipulation to TaskSource::FontLoading, so both notifications share one task source.

A ScriptDisallowedScope::InMainThread is placed directly before each range-for over Document::inDocumentShadowRoots() that calls out per root: Style::Scope::flushPendingDescendantUpdates() (the crashing site), didChangeViewportSize() and invalidateMatchedDeclarationsCache(); Style::DocumentScope::releaseMemory(), collectResolverScopes(), didChangeStyleSheetEnvironment() and didChangeExtensionStyleSheets(); the Style::TreeResolver::Scope::Scope(Document&, Update&) constructor, which forces resolver creation per root; LocalDOMWindow::ensureCustomElementRegistry(); and Internals::dumpStyleResolvers(). The new test's expected output records FontFaceSet.prototype.then getter calls: 0.

Iterator invalidation under re-entrancy: a live iterator over a node-based container held across a callout that can reach author script, which mutates the container and frees the iterator's node.

Where this lives. WebCore's style system resolves CSS for the document and for each shadow tree inside it. All of it runs in the WebContent (renderer) process.

ListHashSet and WeakListHashSet. ListHashSet is WTF's insertion-ordered hash set. Each element lives in a separately heap-allocated ListHashSetNode with m_prev/m_next links, iterators are thin wrappers around a node pointer, and removing an element frees its node. WeakListHashSet<T> wraps a ListHashSet<WeakPtr<T>>; its iterator stores the underlying iterator as m_position and advances with ++m_position, which follows the current node's m_next.

The shadow-root registry. Document::inDocumentShadowRoots() is the set of currently connected shadow roots. Roots are added when connected and removed when disconnected.

Style::Scope and Style::DocumentScope. A Style::Scope holds one tree's active stylesheets, resolver, and pending updates. The document-level scope coordinates the per-shadow-root scopes, and flushPendingDescendantUpdates() asks each one to apply pending stylesheet changes; script reaches it through APIs such as document.styleSheets. Applying a shadow scope's sheets also registers any @font-face rules with the document's font selector.

FontFaceSet (document.fonts). It tracks font faces and their load status. startedLoading() and completedLoading() are notifications from the backing CSSFontFaceSet when the set of loading faces becomes non-empty or empty. The ready promise settles once loading completes after the document has loaded, and it resolves with the FontFaceSet object itself.

Thenable assimilation. Resolving a promise with an object synchronously reads that object's then property, so any accessor on the object or its prototype runs at the moment of resolution.

ScriptDisallowedScope::InMainThread. An RAII counter marking a region where author script must not run. Per its header comment, release builds rely on release assertions in the script-execution check, so an attempt to run script inside the region becomes a deliberate crash rather than re-entrancy.

This is a use-after-free of a container node caused by iterator invalidation under script re-entrancy.

 flushPendingDescendantUpdates()            FontFaceSet.prototype.then getter
 -------------------------------            ---------------------------------
 it = inDocumentShadowRoots().begin()
 root->styleScope().flushPendingUpdate()
   Reset path: re-register @font-face
   old CSSFontFace removed, count -> 0
   completedLoading()
   m_readyPromise->resolve(*this)
   Get(FontFaceSet, "then") ----------->   host.remove()
                                             root disconnected
                                             ListHashSetNode freed
                                  <-----   return undefined
 ++m_position  -> reads freed node's m_next

The loop on the left walks the live linked list with no snapshot, and each iteration makes an unbounded callout. As the regression test's header comment describes, flushing a shadow scope whose pending update takes the Reset path re-processes all its sheets, including @font-face. Re-registering those rules removes the previous CSSFontFace; if it was the only loading face, the active count drops to zero and completedLoading() runs. Before the fix, that called m_readyPromise->resolve(*this) inline, and thenable assimilation ran the author getter deep inside the style flush. The getter removes the host, which disconnects the shadow root and drops it from the registry, freeing the node under m_position. When the callout returns, ++m_position reads m_next from freed memory.

Several of these loops already used for (Ref shadowRoot : ...), which keeps the ShadowRoot alive but does nothing for the list node. Protecting the element does not protect the iterator.

The regression test is built deliberately. It touches document.fonts.ready so the promise exists, then prepends rather than appends a <style> to the shadow root to force the Reset path. The getter deletes itself so it fires once, removes the host, and returns undefined. document.styleSheets.length then drives the flush that reaches flushPendingDescendantUpdates().

The vulnerable path is reachable from ordinary web content using only DOM, CSS @font-face, the Font Loading API and a prototype accessor. The freed object is a small, fixed-shape ListHashSetNode holding a WeakPtr<ShadowRoot> and two link pointers, and the getter itself runs arbitrary JS between host.remove() and the iterator advance, so a reclaim attempt can happen in the same callback. If the slot were reclaimed with controlled data, the forged m_next would steer the iterator to an attacker-chosen pseudo-node; get() would dereference that node's WeakPtr impl to obtain a ShadowRoot*, and the loop body would make a style-scope call on it. That would raise the primitive toward a fake-object or type-confusion class with a control-flow candidate. Whether the allocator's isolation for this node type permits such a reclaim is the gating question; without reclaim, the observed effect is a crash. The free also depends on disconnection physically removing the node rather than leaving a null WeakPtr for lazy cleanup, which the test comment asserts.

This vulnerability weakens renderer memory safety. The style engine assumes no author script runs while it walks the document's shadow-root registry, and before the fix web content could break that by running a getter mid-walk. The result is a use-after-free of a ListHashSetNode inside the WebContent process; reclaiming it with controlled contents could yield a renderer-plane memory-corruption primitive, and anything beyond the renderer would still need a separate sandbox escape.

Insight: The two layers of the fix do different jobs. Deferring the resolve to a task removes the known path to script. ScriptDisallowedScope turns any undiscovered path through these callouts into a release-assert crash instead of a UAF, which mitigates but does not prevent; whether the JSC thenable lookup passes through a checked script-entry point is the condition that decides how complete that net is.