← All reports

[2] BroadcastChannel IPC-encodes a SerializedScriptValue a worker is deserializing

HighWebKit BroadcastChannelRace

A page's BroadcastChannel post races its own worker for one structured-clone payload.

5a14691

Rated High — renderer script controls both sides of a main-thread/worker race over one structured-clone payload, and one interleaving is a genuine UAF read whose bytes are copied into an outgoing IPC message. Turning that into a useful leak still needs heap reclaim inside the race window.

Structured-clone messaging in WebKit's renderer process relies on a single-consumer rule: a serialized message is either sent to another process or unpacked into JavaScript objects, never both at once. Each BroadcastChannel post (the same-origin pub/sub API between tabs and workers) goes through WebBroadcastChannelRegistry, the per-process registry that fans the message out to local channels and to the Networking process. The payload is a SerializedScriptValue — WebKit's structured-clone byte stream plus out-of-band storage such as WebCodecs chunk data — and unpacking it is meant to happen exactly once, by one consumer.

The angle: a page with one worker can race its own BroadcastChannel post so the main thread's IPC encoder walks video-chunk storage the worker has already moved out or freed, giving a renderer crash at the floor and a UAF read into an IPC payload in the worst interleaving.

Per the commit message (rdar://185760741), WebBroadcastChannelRegistry::postMessage() handed the same SerializedScriptValue to postMessageLocally() and to the IPC encoder for the NetworkProcess. When the last local recipient lives on a worker, its deserialization runs concurrently with the main thread's encode, and both failure shapes fault eight bytes into WebCodecsEncodedVideoChunkStorage::m_data. The fix sends to the NetworkProcess first, relying on Connection::sendWithAsyncReply() encoding synchronously before it returns. WebKitLegacy's registry had a simpler form of the same problem and now gives each recipient its own copy.

Source/WebKit/WebProcess/WebCoreSupport/WebBroadcastChannelRegistry.cpp

auto blobURLs = message->blobURLs().map([](auto& blobURL) {
return URL { blobURL };
});
- postMessageLocally(origin, name, source, message.copyRef(), callbackAggregator.copyRef());
+ // Send IPC first. postMessageLocally() consumes the SerializedScriptValue in the message, possibly on a different thread, so sending IPC afterward would be unsafe.
if (auto clientOrigin = toClientOrigin(origin))
- protect(broadcastChannelNetworkProcessConnection())->sendWithAsyncReply(Messages::NetworkBroadcastChannelRegistry::PostMessage { *clientOrigin, name, WebCore::MessageWithMessagePorts { WTF::move(message), { } }, WTF::move(blobURLs) }, [callbackAggregator] { }, 0);
+ protect(broadcastChannelNetworkProcessConnection())->sendWithAsyncReply(Messages::NetworkBroadcastChannelRegistry::PostMessage { *clientOrigin, name, WebCore::MessageWithMessagePorts { message.copyRef(), { } }, WTF::move(blobURLs) }, [callbackAggregator] { }, 0);
+
+ postMessageLocally(origin, name, source, WTF::move(message), WTF::move(callbackAggregator));
}
...

Source/WebKitLegacy/WebCoreSupport/WebBroadcastChannelRegistry.cpp

+ if (channelsForNameIterator == channelsForOriginIterator->value.end())
+ return;
+
+ size_t numberOfMessagesNeeded = 0;
+ for (auto& channelIdentifier : channelsForNameIterator->value) {
+ if (channelIdentifier != source)
+ ++numberOfMessagesNeeded;
+ }
+
for (auto& channelIdentifier : channelsForNameIterator->value) {
if (channelIdentifier == source)
continue;
- WebCore::BroadcastChannel::dispatchMessageTo(channelIdentifier, message.copyRef(), [callbackAggregator] { });
+ // SerializedScriptValue::deserialize() is destructive, so each recipient needs its own copy.
+ auto messageToDispatch = numberOfMessagesNeeded-- > 1 ? message->clone() : WTF::move(message);
+ WebCore::BroadcastChannel::dispatchMessageTo(channelIdentifier, WTF::move(messageToDispatch), [callbackAggregator] { });
}
...

LayoutTests/http/tests/broadcastchannel/postmessage-encodedvideochunks-to-worker.html

+ for (let i = 0; i < CHUNK_COUNT; ++i)
+ chunks.push(new EncodedVideoChunk({ type: "key", timestamp: i, data: new Uint8Array(CHUNK_SIZE) }));
+ const channel = new BroadcastChannel("postmessage-encodedvideochunks-to-worker");
+ channel.postMessage({ chunks });

In WebKit's registry, postMessage() previously called postMessageLocally(..., message.copyRef(), ...) and then moved message into MessageWithMessagePorts for sendWithAsyncReply(). The order is now reversed: the IPC send takes message.copyRef(), and postMessageLocally() runs afterward with WTF::move(message) and WTF::move(callbackAggregator), with a comment explaining why. postMessageLocally() itself is unchanged and still clones for every local recipient except the last, which gets the original.

In WebKitLegacy's registry, postMessage() gains a release-mode early return when channelsForNameIterator == end() (previously only an ASSERT), counts non-source recipients into numberOfMessagesNeeded, and gives each recipient message->clone() except the last, which receives WTF::move(message). A regression test posts 32 chunks of 2 MiB each to a worker over 20 iterations.

A shared reference to a destructively consumed object handed to two consumers on different threads, so one walks storage the other is moving out and releasing.

Process model and BroadcastChannel. BroadcastChannel lets same-origin (partitioned) browsing contexts and workers exchange messages by channel name. In the WebContent process, WebBroadcastChannelRegistry::postMessage() delivers each message to local channels via postMessageLocally() and BroadcastChannel::dispatchMessageTo(), and forwards it over IPC (Messages::NetworkBroadcastChannelRegistry::PostMessage) to the Networking process, which relays it to other WebContent processes. Opaque-origin channels are not forwarded: toClientOrigin() returns std::nullopt for them.

SerializedScriptValue. WebKit's structured-clone representation: a byte stream plus SerializedScriptValueInternals, which holds out-of-band objects such as array buffers, blob URLs and WebCodecs chunk storage. clone() produces an independent copy.

Destructive deserialization. Per the commit message, deserialize() rebuilds JS objects on the receiving thread's VM by moving members out of SerializedScriptValueInternals rather than copying them. Each instance is therefore meant to be deserialized once, by one consumer.

EncodedVideoChunk storage. WebCodecs EncodedVideoChunk objects are backed by a ref-counted WebCodecsEncodedVideoChunkStorage (whose byte member the commit message names m_data). A serialized value carries them as a vector of Ref<WebCodecsEncodedVideoChunkStorage>.

Ref and IPC encoding. Ref<T> is WebKit's non-null refcounted pointer; moving out of it leaves the source null, and the object dies with its last reference. IPC encoding serializes a message by walking its fields — for a SerializedScriptValue, that includes iterating the internals' storage vectors.

This is a cross-thread data race whose consequence is a null dereference or a use-after-free read.

  Main thread                          Worker thread
  ───────────                          ─────────────
  postMessageLocally(copyRef)
    last recipient gets original ───►  deserialize(original)
  sendWithAsyncReply(... message ...)    readWebCodecsEncodedVideoChunk()
    encoder walks serializedVideoChunks    moves Ref out of chunks[i]
    reads chunks[i]  ◄───────────────      (chunks[i] now null)
      └─► null base, fault at m_data     CloneDeserializer destroyed
    reads chunks[j]  ◄───────────────      storage for chunks[j] released
      └─► UAF read of freed storage

In the left column, postMessageLocally() returns after handing the original object to the worker's channel, and the main thread then encodes that same object. In the right column, the worker's CloneDeserializer is concurrently moving Ref elements out of serializedVideoChunks and, once destroyed, releasing them. Nothing synchronizes the two columns: the missing invariant is single ownership of a destructively consumed value. The fix moves the encode entirely above the hand-off arrow, so by the time any local recipient sees the value, the encoder has finished.

The WebKitLegacy variant gave the same object to every local recipient, so every recipient after the first deserialized a gutted value; with recipients on different threads, they would deserialize the same internals concurrently, the same race class in single-process form.

The regression test is a race amplifier: 32 chunks of 2 MiB keep the encoder walking the vector for a long time while the single worker recipient deserializes the original, repeated 20 times. Reachability needs only BroadcastChannel, a dedicated Worker and EncodedVideoChunk, and the attacker controls timing and window width through chunk count.

Two primitive shapes come out of the interleaving. A moved-from Ref gives a null-base dereference at the small m_data offset — a reliable controlled crash with no attacker data involved. Already-released storage gives a main-thread UAF read of a WebCodecsEncodedVideoChunkStorage and the buffer its stale m_data describes, with the output flowing into the IPC encoder buffer. If an attacker could reclaim the freed slot with controlled contents during the window, the encode could become an attacker-steered read whose output lands in a NetworkBroadcastChannelRegistry::PostMessage payload relayed to other same-origin channels. That depends on race granularity between deserializer teardown and the per-element walk, the storage object's allocator class, and whether the copied span reaches script in a receiving context. The worker side also reads internals the main thread is concurrently reading, so tearing in the deserializer cannot be ruled out, though the commit message describes faults only on the encoder side. The corrupted encode would face the Networking process's normal IPC decoding validation; this bug alone does not cross the sandbox.

This vulnerability weakens memory safety in the WebContent process. A SerializedScriptValue is supposed to be consumed by exactly one party — IPC-encoded or destructively deserialized, never both at once. Before the fix, web content could break that invariant and make the main thread dereference chunk storage the worker had moved out or freed; the floor is an attacker-triggered renderer crash, and with reclaim, the freed-storage case could expose renderer heap contents through the BroadcastChannel path.

Insight: SerializedScriptValue looks like an immutable shared value — it travels as Ref<SerializedScriptValue> and copyRef() is cheap — but semantically it is a move-only token, because deserialize() dismantles it. Both registries got this wrong in different ways, and the type system flagged neither. Note also that the WebKit fix is temporal rather than structural. Per the commit message it holds because sendWithAsyncReply encodes synchronously before returning, so it stays correct only while the IPC layer keeps that behavior.