[3] OffscreenCanvas measureText() FontMetrics UAF via worker font-cache pruning
A Worker's measureText() hands back numbers read from a freed Font.
Medium. The stale read lands in values returned straight to script through TextMetrics, so this is an info-leak channel rather than a crash-only bug. There is no write through the stale reference, and any useful bits have to survive a float conversion.
Text measurement in WebKit's font stack resolves a font description into concrete font objects through a per-thread cache that periodically evicts entries nobody else references. A FontCascade, the description of the font for a run of text, points at a refcounted set of realized fonts, and the primary Font (one concrete font instance) carries the FontMetrics (ascent, descent, line gap) that measureText() reports. Anything borrowed from a cache entry stays valid only while something other than the cache still holds that entry.
The angle: a Worker calling OffscreenCanvas.measureText() can force a font load mid-measurement that prunes the cache, then receive fields read from the freed primary Font back as TextMetrics numbers.
Fix FontMetrics reference UAF
CanvasRenderingContext2DBase::measureTextInternal()holds a reference to the primary font'sFontMetricsacross afontProxy->width()call; howeverwidth()can mutate theFontCache, and thus free theFontMetricsobject. Move the metrics retrieval down past text measurement so that it cannot be invalidated before it is used.Test: sar3/fast/canvas/offscreen-canvas2d-measuretext-font-metrics-uaf.html
Source/WebCore/html/canvas/CanvasRenderingContext2DBase.cpp
LayoutTests/sar3/fast/canvas/offscreen-canvas2d-measuretext-font-metrics-uaf.html
Patch Details
One function changes. Before the patch, measureTextInternal() bound auto& font = *fontProxy; and auto& fontMetrics = font.metricsOfPrimaryFont(); up front, then called font.width(textRun, &glyphOverflow). The patch drops both early bindings, calls fontProxy->width() and fontProxy->fontCascade() directly, and binds fontMetrics only after width() and emHeightAscentAndDescent() have run, with a comment giving the reason. No check or guard is added; the fix is a reorder that shrinks the reference's lifetime so it no longer spans the call that can free its owner. The new test runs measureText() on an OffscreenCanvas in a Worker, with two pending FontFaces backed by a 1.1 MB data: URL and 3500 dummy contexts with unique font families.
A raw reference into a refcounted, cache-owned object held across a call that can synchronously invalidate and prune the owning cache.
Background
Where this lives.
Canvas exposes measureText() to script; WebCore's platform font stack turns font families into realized Font objects through a per-thread cache. OffscreenCanvas gives Workers a 2D context, so measurement then runs on the worker thread against that worker's own font selector and per-thread caches.
The ownership chain.
FontCascade refers to a refcounted FontCascadeFonts, which lazily realizes fallback ranges (Vector<UniqueRef<FontRanges>>) and caches the primary font and glyph pages. A FontRanges is an ordered list of Ranges, each covering part of Unicode (for example from an @font-face unicode-range) and holding a Ref<FontAccessor> that produces the actual Font, possibly triggering a download. Font is RefCounted and carries its metrics, which FontCascade::metricsOfPrimaryFont() returns by reference.
FontCascadeCache.
A per-thread cache mapping a key to a shared FontCascadeFonts. The key combines the font description and family names, plus the font selector's id and version when the selector is not simple for that description. Each insertion bumps a prune counter, and pruneUnreferencedEntries() periodically evicts entries whose FontCascadeFonts hasOneRef(), meaning only the cache still holds them.
CSSFontSelector and download policy.
CSSFontSelector resolves @font-face/FontFace families for a document or worker and carries a version that changes when faces are added or finish loading. ExternalResourceDownloadPolicy tells FontRanges::Range::font() whether it may start or pump a pending web-font load when a glyph is requested.
Analysis
This is a use-after-free read: a borrowed const FontMetrics& survives a call that can prune the cache owning the Font it points into.
measureTextInternal() (worker thread)
-------------------------------------
fontMetrics = &primaryFont.metrics <- borrow into Font
width()
glyph walk, policy = Allow
pending @font-face loads synchronously
selector version bumps -> FontCascade re-keyed
new cache entry -> pruneCounter hits interval
pruneUnreferencedEntries():
old FontCascadeFonts (cache-only) destroyed
FontRanges destroyed -> primary Font freed
read fontMetrics -> TextMetrics fields <- UAF read
In the diagram, the borrow happens before width(), and everything indented under width() can free its target. Per the test comment, the worker's glyph walk uses ExternalResourceDownloadPolicy::Allow, so a pending @font-face is loaded synchronously inside the call, and a data: URL of 1 MB or more skips CSSFontFaceSource::opportunisticallyStartFontDataURLLoading(), so the face is still pending at that point. Load completion dispatches selector invalidation, which re-keys the canvas's FontCascade. The cache side is visible in FontCascadeCache.cpp: makeFontCascadeCacheKey() includes the selector's uniqueId and version() only when hasComplexFontSelector is true. A worker selector with faces added via self.fonts.add() meets that condition here, so each version bump makes the re-keyed cascade miss and insert a new entry; for simple-selector descriptions the key does not change and this step does not happen. retrieveOrAddCachedFonts() increments a static pruneCounter per insertion and calls pruneUnreferencedEntries() every 1000th insertion (50 on iOS). Once the canvas's cascade has moved to a new FontCascadeFonts, the old one is cache-only, gets pruned, and its FontRanges are destroyed. The test comment states the primary Font dies with it; that last-reference step rests on the test and on the fix itself, since other holders (FontCache, CSSFontFaceSource, a retained FontAccessor) are not ruled out by the source.
The test is tuned to make this deterministic:
- 3500 dummy
OffscreenCanvascontexts with unique families push the shared prune counter close to and past the 1000-entry interval. - Two
FontFaces use a 1.1 MBdata:URL so neither is pre-warmed and both are still pending at the glyph walk. - Cherokee characters (
\u13A0\u13A2\u13A4) forceCodePath::Simple. measureText()triggers the synchronous load, the re-key, the insert that crosses the interval, and the prune, all insidewidth(); the freedFont's metrics then reach script.
That precision (a size chosen to bypass a specific pre-warm, a context count sized against the prune interval) reads as source-guided trigger construction rather than blind fuzzing.
Exploitability: reachable from ordinary web content via OffscreenCanvas in a Worker. The immediate effect is a read of the freed Font's metrics, returned to script as TextMetrics values, which is a direct info-leak channel. Because the prune counter is process-global, insertions on other threads could shift the timing; the test compensates by over-provisioning. Escalation depends on reclaim control. Font is declared with WTF_DEPRECATED_MAKE_FAST_ALLOCATED_WITH_HEAP_IDENTIFIER(Font, Font) rather than TZone type segregation. If, as is generally the case in WTF, that macro only yields a distinct heap in heap-breakdown or debug configurations and otherwise falls back to ordinary fastMalloc, a freed Font slot could be reclaimed by any same-size-class object, not only other Fonts. The open question is which reclaiming objects could place controlled or pointer-derived bits at the FontMetrics offset, and whether any copied value keeps those bits through its float conversion. The ceiling is a small, fixed-size read; there is no write.
This vulnerability weakens memory safety in the WebContent process. Script in a Worker could make the engine read fields of a freed Font and hand them back through TextMetrics, breaking the rule that freed renderer heap memory is never observable from web content. The plausible gain is an information leak of whatever later occupies the slot, useful against ASLR or heap-layout secrecy as one stage of a larger chain; on its own it yields no write primitive and no sandbox escape.
Insight: FontCascadeFonts.h already warns that realized ranges "are held by reference across calls that can realize further fallbacks, so they are stored indirectly, and must never move." That protects against vector reallocation inside one FontCascadeFonts, not against the whole object being pruned when a nested load re-keys the cascade. Two details turn a rare race into a near-deterministic trigger: worker-side synchronous loading turns a measurement getter into a re-entrancy point, and pruneCounter is a function-local static without thread_local, so one counter is shared by every thread even though the cache itself is per-thread. Script can flood insertions toward the interval, which makes the prune point attacker-steerable but not fully attacker-controlled.
Audit directions
- Borrowed reference into a cache-owned object held across a call that can mutate the cache. Nothing borrowed from a cache entry may outlive a call that can insert into, re-key, or prune that cache. Narrow: grep
CanvasRenderingContext2DBase.cppand otherFontCascadeconsumers forauto& ... = ...metricsOfPrimaryFont()orprimaryFont()bindings followed bywidth(,glyphDataForCharacter(,drawText(orcodePath(, starting with thefillText/strokeTextpaths and canvas text helpers that run off the main thread. Match tell: aconst Font&,const FontMetrics&orconst FontRanges&local declared before aFontCascademeasurement or draw call and read after it. Wider: the same shape appears with any borrowedconst T&into aFontCascadeFonts-owned structure (glyph pages,MixedFontGlyphPageentries,TextMeasurementCacheresults) held acrossrealizeFallbackRangesAt()or a font load; match tell: a borrowed result from one cache accessor that survives a second accessor capable of inserting into the same or a sibling cache. Widest: classic reference invalidation across container mutation, like holding astd::vectorelement acrosspush_backor iterating a Python dict while a callee mutates it, and exactly what Rust's borrow checker rejects; match tell in any codebase: can the callee reach the container that owns what I'm borrowing? - Lazy-loading getters that become re-entrancy points on some threads only. Here,
ExternalResourceDownloadPolicy::Allowon workers lets a glyph lookup complete a font load and dispatch selector invalidation mid-call. Narrow: enumerate callers ofFontRanges::Range::font()andFontRanges::glyphDataForCharacter()that passAllow, and trace whatCSSFontSelector::fontModified()andFontFaceSetcompletion can run synchronously from there. Match tell: a getter whose main-thread path is pure but whose worker path calls a loader-completion callback. Wider: inspect other WebCore paths that fork on main thread versus worker, such asOffscreenCanvasimage decoding and font loading inFontFaceSet.load(), and check whether worker-only synchronous completion invalidates state main-thread code assumed stable. Widest: any lazy-on-access system, such as Hibernate or SQLAlchemy lazy relationships that flush or refresh session state on attribute access, has the same hazard; match tell: a property access that can trigger I/O completion handlers which mutate the object graph the caller holds into. - Count-driven global cache eviction as an attacker-steerable timing primitive.
FontCascadeCache::retrieveOrAddCachedFonts()uses a process-global function-localstaticpruneCounterand a fixed interval (1000, or 50 on iOS), which script can drive to placepruneUnreferencedEntries()inside a chosen window with high probability. Narrow: audit every call site that can insert intoFontCascadeCacheon behalf of a nested invalidation, including them_entries.remove(m_entries.random())overflow path, and check whether any caller holds a borrowed reference into an entry at that moment. Wider: review other WebCore caches with count- or size-triggered pruning, such asFontCacheinactive-font purging and glyph-page or shaped-text caches; match tell: a static or process-global counter advanced by script-creatable objects, gating an eviction that drops the last ref. Widest: deterministic eviction triggers (GC thresholds, LRU caps, generation counters) make lifetime bugs reliably triggerable in any engine; when auditing a UAF candidate, check whether an attacker can drive the eviction counter and whether sharing it across threads adds or removes noise.