← All reports

[3] OffscreenCanvas measureText() FontMetrics UAF via worker font-cache pruning

MediumWebCore Canvas 2DUAF

A Worker's measureText() hands back numbers read from a freed Font.

01b45e6

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.

CanvasRenderingContext2DBase::measureTextInternal() holds a reference to the primary font's FontMetrics across a fontProxy->width() call; however width() can mutate the FontCache, and thus free the FontMetrics object. 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

if (!fontProxy->realized())
return metrics;
 
- auto& font = *fontProxy;
- auto& fontMetrics = font.metricsOfPrimaryFont();
-
GlyphOverflow glyphOverflow;
glyphOverflow.computeBounds = true;
- float fontWidth = font.width(textRun, &glyphOverflow);
+ float fontWidth = fontProxy->width(textRun, &glyphOverflow);
metrics->setWidth(fontWidth);
 
FloatPoint offset = textOffset(fontWidth, textRun.direction());
- auto [emHeightAscent, emHeightDescent] = emHeightAscentAndDescent(protect(font.fontCascade()));
+ auto [emHeightAscent, emHeightDescent] = emHeightAscentAndDescent(protect(fontProxy->fontCascade()));
+ // Bind the primary font's metrics only after width() has run, since it can rebuild the font cache.
+ auto& fontMetrics = fontProxy->metricsOfPrimaryFont();
...

LayoutTests/sar3/fast/canvas/offscreen-canvas2d-measuretext-font-metrics-uaf.html

+// measureTextInternal() binds `auto& fontMetrics = fontProxy->metricsOfPrimaryFont()` - a
+// reference into the primary Font - and then calls fontProxy->width(). On a worker, width()
+// walks glyphs with ExternalResourceDownloadPolicy::Allow, so a still-pending @font-face is
+// loaded synchronously inside the call. Its completion dispatches font selector invalidation,
+// which re-keys this canvas' FontCascade; the previous FontCascadeFonts becomes
+// cache-only and FontCascadeCache::pruneUnreferencedEntries() destroys it, taking the
+// primary Font with it.
...
+for (let i = 0; i < 3500; i++) {
+ const dummy = new OffscreenCanvas(1, 1).getContext('2d');
+ dummy.font = '10px "dummy' + i + '"';
...
+const pendingFontURL = 'url("data:font/ttf;base64,' + 'A'.repeat(1100000) + '")';
...
+ context.measureText('\\u13A0\\u13A2\\u13A4');

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.

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.

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:

  1. 3500 dummy OffscreenCanvas contexts with unique families push the shared prune counter close to and past the 1000-entry interval.
  2. Two FontFaces use a 1.1 MB data: URL so neither is pre-warmed and both are still pending at the glyph walk.
  3. Cherokee characters (\u13A0\u13A2\u13A4) force CodePath::Simple.
  4. measureText() triggers the synchronous load, the re-key, the insert that crosses the interval, and the prune, all inside width(); the freed Font'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.