← All reports

[1] Canvas 2D FontProxy use-after-free via thenable re-entrancy in measureText()

HighWebCore Canvas 2DUAF

measureText() keeps running on a font object your promise getter just freed.

673f4df

High. Ordinary page script frees the heap buffer underneath a font call that is still executing on it, through both <canvas> and OffscreenCanvas. Getting past a crash depends on reclaiming that buffer before the resumed font code reads pointer-typed members.

Canvas text rendering keeps a save/restore stack of drawing states, and each state carries the font used to measure and draw text. That font lives in a FontProxy, an internal wrapper around the resolved FontCascade (the font plus its fallback chain) that is notified when web fonts finish loading. Text APIs assume the font object they are calling into stays at a fixed address for the whole call.

The angle: any page that can call measureText() can, from inside a promise getter, grow the canvas state stack and free the heap buffer holding the font object that measurement is still running on.

CanvasRenderingContext2DBase::fontProxy() returns a raw pointer to the FontProxy of the current state. If the state stack is changed between the call and the use of that pointer, the pointer can refer to a freed FontProxy, because pushing a state can reallocate the stack's buffer. 320073@main tried to fix this by auditing every fontProxy() call site and fetching a fresh pointer each time. There is still a way to invalidate the pointer while it is in use. FontProxy::metricsOfPrimaryFont() can trigger font loading, and a loaded font can resolve a JS promise. That promise can call save() on the context. If enough states are saved, the stack reallocates and the FontProxy running metricsOfPrimaryFont() is freed. When the promise returns, metricsOfPrimaryFont() continues on freed memory.

The only fix is to make FontProxy ref-counted so it can be kept alive during operations. Callers of fontProxy() now protect it before use. A saved State would otherwise share the same FontProxy through its Ref<>, so State gets a custom clone that value-clones the proxy. Each saved state keeps its own copy, as before. Copy-on-write is left as future work.

Source/WebCore/html/canvas/CanvasRenderingContext2DBase.h

- class FontProxy final : public FontSelectorClient {
+ class FontProxy final : public RefCounted<FontProxy>, public FontSelectorClient {
public:
- FontProxy() = default;
+ static Ref<FontProxy> create();
+ Ref<FontProxy> clone() const;
...
struct State final {
State();
+ State clone() const;
...
String unparsedFont;
- FontProxy font;
+ Ref<FontProxy> font;
...

Source/WebCore/html/canvas/CanvasRenderingContext2DBase.cpp

@@ realizeSavesLoop
- m_stateStack.append(state());
+ m_stateStack.append(state().clone());
@@ measureTextInternal
- auto* fontProxy = this->fontProxy();
+ RefPtr fontProxy = this->fontProxy();
if (!fontProxy->realized())
return metrics;
...
// Bind the primary font's metrics only after width() has run, since it can rebuild the font cache.
auto& fontMetrics = fontProxy->metricsOfPrimaryFont();

LayoutTests/fast/canvas/offscreen-canvas2d-measuretext-uaf.html

+ // After this, m_stateStack will store on the heap instead of the inline storage.
+ context.save();
+ context.lineWidth = 0.5;
+ context.font = '10px MyTestFam';
+ Object.defineProperty(FontFace.prototype, 'then', {
+ configurable: true,
+ get() {
+ ...
+ for (let i = 0; i < 18; i++) {
+ context.save();
+ context.lineWidth = 1 + i;
+ }
+ ...
+ }
+ });
+ context.measureText('a');

The change moves FontProxy out of each State into its own refcounted heap allocation, changes the save path to deep-clone that allocation so saved states stay independent, and pins the proxy with a strong reference at every caller that uses it across further font calls.

On the ownership side, FontProxy now derives from RefCounted<FontProxy> alongside FontSelectorClient and gains static Ref<FontProxy> create() and Ref<FontProxy> clone() const. Its default constructor, copy constructor and copy assignment become private. State::font changes from FontProxy to Ref<FontProxy>, and both CanvasRenderingContext2D::fontProxy() and OffscreenCanvasRenderingContext2D::fontProxy() now return state().font.ptr().

On the cloning side, State gets a custom clone() that copies the struct and then replaces the font with protect(this->font)->clone(). A FIXME notes copy-on-write as future work. State's copy constructor becomes private, move operations are explicitly defaulted, and realizeSavesLoop() appends state().clone() instead of a plain copy.

On the caller side, measureTextInternal, drawTextUnchecked, setLetterSpacing and setWordSpacing replace auto* fontProxy (or repeated fontProxy() calls) with RefPtr fontProxy. drawTextUnchecked also hoists one CheckedRef to the FontCascade. One-shot uses in canDrawText, the setFont*/setTextRendering/setLang setters, textOffset, setFontWithoutUpdatingStyle, OffscreenCanvasRenderingContext2D::setFont, and the State::canvasFont*()/fontString() getters are wrapped in protect(...). NODELETE is removed from all eight State const getters, including canvasLineCap, canvasLineJoin, canvasTextAlign and canvasTextBaseline, which do not touch the font; the commit gives no reason for those four. Four regression tests (canvas2d-measuretext-{uaf,null-deref} and their offscreen- twins) install a then getter on FontFace.prototype that calls save() and sets lineWidth during measureText().

Pointer into an element of a growable container held across a script re-entrancy point that can reallocate the container, including the implicit this of a method running on that element.

Canvas state stack. save() pushes a copy of the current drawing state (transform, styles, line width, font) and restore() pops it. WebKit defers the push: save() only increments m_unrealizedSaveCount, and the copies are materialized by realizeSaves()/realizeSavesLoop() the first time a state-mutating setter such as lineWidth runs.

Vector<State, 1> storage. m_stateStack is a WTF Vector with one inline slot inside the owning context, spilling to a heap buffer once it grows past that. When a WTF Vector outgrows its capacity, it allocates a larger buffer, moves every element across, destroys the old elements, and frees the old heap buffer.

FontProxy and the Font Loading API. FontProxy wraps the context's FontCascade and registers as a FontSelectorClient, so it hears when web fonts finish loading. measureText() asks it for widths and primary-font metrics. A FontFace added to document.fonts can be named in context.font, and its loaded promise resolves with the FontFace itself once loading completes.

Thenable assimilation. When a promise is resolved with an object, the engine synchronously performs Get(value, "then") to see whether the value is itself a thenable. Any getter defined for then on the object or its prototype runs at that moment, inside whatever native frame performed the resolution.

Ref, RefPtr and protect(). WebKit's reference-counting smart pointers. A Ref/RefPtr local keeps its target alive until the local leaves scope; protect(x) yields a temporary strong reference.

This is a use-after-free caused by a pointer into a reallocatable container surviving a script re-entrancy point.

 measureTextInternal()                   FontFace.prototype.then getter
 ---------------------                   ------------------------------
 fontProxy = &state().font
   (raw ptr into m_stateStack buffer)
 font call -> pending web font loads
           -> FontFace.loaded resolves
           -> Get(FontFace, "then") ---> save() x N; lineWidth = ...
                                           realizeSavesLoop()
                                           m_stateStack grows:
                                           move States, ~FontProxy,
                                           free old buffer
 font call resumes <-------------------- return
 this / fontProxy  ==> freed buffer

In the left column, measureTextInternal takes a raw fontProxy and makes several font calls through it: the width computation on its FontCascade, emHeightAscentAndDescent(protect(fontProxy->fontCascade())) (also reached through textOffset), and fontProxy->metricsOfPrimaryFont(). Per the test comment, measuring requests metrics, which forces the pending MyTestFam face to load, and completing the load resolves FontFace.loaded. The test comment is the basis for the resolution happening synchronously inside one of those font calls; which call hosts the re-entry is not pinned down by the source, but the test's wording about measureText fetching metrics "from a freed FontCascade" points to a FontCascade method's this, or the enclosing FontProxy, as the stale receiver.

Thenable assimilation fires the getter in the right column. save() only bumps the unrealized count; the lineWidth assignment then realizes the saves (the test comment "Set line width to ensure new states are created" implies this), so realizeSavesLoop() appends states until the vector exceeds capacity. The reallocation destroys every old State, running ~FontProxy, and frees the old buffer. When the getter returns, the font call in progress, and any later use of the raw local, resume on destroyed or freed memory.

The invariant that broke was never written down: the stack must not reallocate, and the current state must not be destroyed, while that pointer or the this of a method running on it is live. 320073@main enforced it at call sites by fetching fresh pointers. Call-site discipline cannot help when the invalidated pointer is the receiver of the very method that re-enters.

The two test variants differ in where the stale pointer lands:

  1. -uaf tests. One save() plus a lineWidth set moves the stack off the inline slot onto the heap (the test says so in a comment). The 18 saves inside the getter then grow that heap buffer, so the old buffer is freed and the stale pointer targets freed heap memory.
  2. -null-deref tests. No prior save, so the first growth moves the stack out of the inline slot. The inline storage is not freed, but the State and FontProxy there have been moved from and destroyed. The test naming and the inline capacity of Vector<State, 1> suggest the resumed call then reads moved-from or destructed members that are null; confirming this requires the ~FontProxy body and FontProxy's move semantics.

Exploitability is a web-reachable UAF from plain JavaScript on the main thread, and the regression tests show a reliable crash. The freed allocation is the whole state-stack buffer, and the number of save() calls steers its capacity, so its size class is plausibly attacker-influenced. If the freed buffer were reclaimed with controlled contents between the free and the resumed call, the stale reads could consume attacker-shaped pointer fields from the embedded FontCascade, which would make this a fake-object or control-flow candidate rather than just a crash. The candidates to establish are pointer-typed or virtually dispatched members read after the getter returns: the FontCascade's fonts reference and the FontSelectorClient vtable of FontProxy. The inline-storage variant likely tops out at a null dereference. Whether the same trigger is reachable from OffscreenCanvas inside a worker is not established; the four tests run on the main thread.

Before the fix, this vulnerability weakened memory safety in the WebContent renderer. The text pipeline assumed the font object behind fontProxy() stays alive while a method runs on it, and ordinary web script could break that from a promise-thenable getter, through both HTMLCanvasElement and OffscreenCanvas contexts. If the freed memory were reclaimed with attacker-shaped data, this could serve as a renderer-plane memory-corruption foothold. Escaping the WebContent sandbox would still require a separate bug.

Insight: The pre-patch code already knew about re-entrancy here. measureTextInternal carried the comment "Bind the primary font's metrics only after width() has run, since it can rebuild the font cache" (that reordering is fix [3] below), and CanvasRenderingContext2D::fontProxy() wraps realization in a ScriptDisallowedScope. Both are local, ordering-based mitigations, and the scope only covers realization, not the later font calls where script actually runs. The durable fix changes the ownership model: once the proxy is a refcounted heap object, a Vector reallocation moves Ref handles and never destroys the proxy in use.