[2] Style flush UAF via fonts.ready re-entrancy during shadow-root iteration
Style recalc assumed no page script runs mid-walk. One prototype getter disagrees.
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.
Fix UAF due to mutation of m_inDocumentShadowRoots during iteration
Style::Scope::flushPendingDescendantUpdates()walksDocument::m_inDocumentShadowRoots(aWeakListHashSet) with a live iterator while callingflushPendingUpdate()on each descendant shadow scope. Flushing a shadow scope re-registers@font-facerules, which can drop the active count to zero and settledocument.fonts.ready, running an author getter. That getter can remove the iterated shadow root's host, freeing theListHashSetNodethe suspended iterator points at, and the loop then reads the freed node'sm_next.Fixed in two layers: (1) defer
document.fonts.readyresolution to a queued task instead of resolving synchronously while walkingm_inDocumentShadowRoots; (2) hold aScriptDisallowedScope::InMainThreadacross each loop that walksm_inDocumentShadowRootsand 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
Source/WebCore/css/FontFaceSet.cpp
LayoutTests/platform/glib/damage/crash-shadow-root-style-flush-font-promise.html
Patch Details
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.
Background
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.
Analysis
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.
Audit directions
- Live iterator over a node-based or weak container held across a callout that can reach script. The invariant is that no callout made while iterating may mutate the container being iterated. Narrow: grep WebCore for range-for loops over
Documentmembers of typeWeakListHashSet,WeakHashSet,ListHashSetandHashSetwhose body calls into style, layout, font, media or event code; the listedinDocumentShadowRoots()loops are now guarded, so confirm no other range-for over it makes a per-root callout, then check the document's other registries of the same container types. Match tell: afor (auto& x : container)orfor (Ref x : container)whose body has noScriptDisallowedScope, no snapshot (copyToVector) and noEventQueueScope. Wider: the same class arises withHashMapiteration across a callout that can trigger a rehash, withVectoriteration across append, and with intrusive lists; match tell: the container is reachable from a function the loop body transitively calls. Widest: this is the general iterator-invalidation-under-re-entrancy class. Java addedConcurrentModificationExceptionfor it, Chromium'sbase::ObserverListdefends against it explicitly, andstd::listerase-during-traversal is the C++ form; in any codebase, ask whether every loop body is proven unable to reach code that mutates the iterated container. - Promise resolution with an author-visible object as a hidden synchronous script entry point. Native code must not resolve a promise with an object whose
thenan author can define while it holds invariants script could break. Narrow: grepDOMPromiseProxy,DOMPromiseProxyWithResolveCallbackandDeferredPromise::resolvecall sites that pass*thisor another wrapper object outside a queued task; start with the remaining synchronous resolve in theFontFaceSetconstructor, then the readiness and finished promises in the animation, view-transition and media subsystems. Match tell: a resolve reachable from style, layout or loader callbacks without aqueueTask*wrapper. Wider: the same entry point exists wherever native code converts or settles values against author-mutable prototypes, such as dictionary conversion getters and iterator-protocol lookups. Widest: Blink'sScriptPromiseResolverand Gecko'sPromise::MaybeResolveface the identical thenable-lookup hazard; match tell: a native-side resolve whose argument's prototype chain is author-writable. - Font-loading state transitions fired synchronously from inside style resolution. A style or layout pass must never synchronously notify a client that can surface the event to script. Narrow: trace every client notification that
CSSFontFaceSetandCSSFontFaceemit (FontFaceSet::startedLoading/completedLoading, per-face load status,faceFinished-style callbacks) and check whether each settles promises or dispatches events synchronously. Match tell: settlement or dispatch code not wrapped inqueueTask*. Wider: the same shape applies to other client interfaces reachable during a style flush, including media-query listeners, image-load observers and custom-property registration. Widest: Gecko'snsContentUtils::AddScriptRunnerand Blink'sScriptForbiddenScopeenforce the same discipline, where rendering passes queue script-visible effects instead of running them; in any engine, audit whether the client callbacks a rendering pass fires bypass that queue.