← All reports

[5] ReadableStream.tee() type confusion via poisoned Array iterator

MediumWebCore Streams bindingsTypeConfusion

Overriding Array's iterator let page script pick what WebCore wrapped as a stream.

ff40757

Medium on what the patch establishes: page script can make WebCore wrap arbitrary objects as internal stream records. A memory-corruption ceiling needs either a consumer that misreads the forged record or unchecked release-mode indexing, and neither is pinned down for this path.

Much of WebKit's Streams API is written as privileged JavaScript builtins that page script can neither inspect nor forge, with C++ glue calling those builtins and wrapping what they return. InternalReadableStream, the C++ handle over a builtin-created stream record, is built from whatever the tee builtin returns as a two-element array, and that record carries private-name slots (@readableStreamController, @state) that only builtins can create. The glue assumes a private builtin's return value arrives exactly as the builtin produced it.

The angle: a page that overrides Array.prototype[Symbol.iterator] before calling tee() gets to decide which objects, and how many, WebCore wraps as internal readable streams.

convert<IDLSequence> is using Array.prototype[Symbol.iterator], which the page script can override. Instead of using convert<IDLSequence> in InternalReadableStream::tee, we directly look at indexed properties, so it cannot be intercepted. For good measure, we validate that both objects are internal readable streams. We also apply the same approach for createInternalTransformStream, via the new helper getInternalBuiltinResultObjects.

This changes behavior for LayoutTests/streams/transform-stream-poisoned-iterator-crash.html: the subtests no longer crash as Array.prototype[Symbol.iterator] is not used. The test is copied to sar3/streams/ with the new behavior.

Source/WebCore/bindings/js/InternalReadableStream.cpp

+static bool isInternalReadableStream(JSDOMGlobalObject& globalObject, JSC::JSObject& object)
+{
+ auto& vm = globalObject.vm();
+ return !!object.getDirect(vm, builtinNames(vm).readableStreamControllerPrivateName());
+}
...
- auto resultsConversionResult = convert<IDLSequence<IDLObject>>(*globalObject, result);
- if (resultsConversionResult.hasException(scope)) [[unlikely]]
- return Exception { ExceptionCode::ExistingExceptionError };
+ // convert<IDLSequence> is using Array.prototype[Symbol.iterator], which the page script can override.
+ auto resultArray = getInternalBuiltinResultObjects<2>(*globalObject, result);
+ RETURN_IF_EXCEPTION(scope, Exception { ExceptionCode::ExistingExceptionError });
+ if (!resultArray) [[unlikely]]
+ return Exception { ExceptionCode::TypeError, "Internal ReadableStream tee returned an unexpected value"_s };
 
- auto results = resultsConversionResult.releaseReturnValue();
- ASSERT(results.size() == 2);
+ auto results = *resultArray;
+ if (!results[0] || !results[1] || !isInternalReadableStream(*globalObject, *results[0].get()) || !isInternalReadableStream(*globalObject, *results[1].get())) [[unlikely]]
+ return Exception { ExceptionCode::TypeError, "Internal ReadableStream tee returned branches of unexpected types"_s };
 
return std::make_pair(InternalReadableStream::fromObject(jsDOMGlobalObject, *results[0].get()), InternalReadableStream::fromObject(jsDOMGlobalObject, *results[1].get()));

Source/WebCore/bindings/js/JSDOMBindingFacade.h

+template<unsigned expectedLength>
+std::optional<std::array<JSC::Strong<JSC::JSObject>, expectedLength>> getInternalBuiltinResultObjects(JSC::JSGlobalObject& globalObject, JSC::JSValue value)
+{
+ auto* array = arrayFromValue(value, expectedLength);
+ if (!array) [[unlikely]]
+ return { };
...
+ for (unsigned index = 0; index < expectedLength; ++index) {
+ auto element = objectFromArrayAt(globalObject, vm, scope, *array, index);
+ if (!element) [[unlikely]]
+ return { };
...

The change adds a non-observable unpacking helper to the bindings facade, moves both builtin-result call sites onto it, and adds a private-slot brand check on the tee path.

The helper, getInternalBuiltinResultObjects<N>() in JSDOMBindingFacade.h, works in three steps: arrayFromValue() requires a real JSArray (JSC::isJSArray) whose length() equals exactly N; objectFromArrayAt() reads each element with JSArray::getDirectIndex() and requires it to be an object; the elements come back as std::array<JSC::Strong<JSC::JSObject>, N> inside std::optional, with any mismatch yielding std::nullopt.

In InternalReadableStream::tee(), the conversion through convert<IDLSequence<IDLObject>> is replaced by the helper, and the release-inert ASSERT(results.size() == 2) becomes real validation: a TypeError if the result is not a two-element array, and a TypeError if either branch fails the new static isInternalReadableStream(), which checks for the readableStreamControllerPrivateName slot via getDirect. InternalReadableStream::fromObject() gains an ASSERT(isInternalReadableStream(...)). In createInternalTransformStream(), the != 3 size check moves into the helper and the existing dynamicDowncast<JSReadableStream>/dynamicDowncast<JSWritableStream> checks stay. The old transform-stream-poisoned-iterator-crash test now logs when the poisoned next() runs and treats "did not throw" as PASS; its expectation still records the "truncated iterator" subcase as FAIL with "Internal TransformStream creation returned an unexpected result".

Privileged code unpacking a trusted internal result through a user-overridable language protocol, letting page script substitute values that native code trusts without a brand check.

Streams as builtins. WHATWG Streams in WebKit are largely implemented as JS builtins such as ReadableStreamInternals.js. Builtins are privileged JS functions that can read and write private-name slots (@readableStreamController, @state, ...) that page script can neither see nor forge. C++ classes like InternalReadableStream and InternalWritableStream hold the record a builtin returns in a DOMGuarded<JSC::JSObject> and call further builtins on it through invokeReadableStreamFunction().

tee(). ReadableStream.prototype.tee() splits one stream into two branch streams; the builtin returns the branches as a two-element array.

The WebIDL sequence converter. convert<IDLSequence<T>> has a fast path for plain arrays whose iteration is unobservable (isIteratorProtocolFastAndNonObservable). Otherwise it runs the full ECMAScript iterator protocol: look up [Symbol.iterator] and call next() until done.

Array.prototype[Symbol.iterator]. An ordinary writable property, so any page script can replace it. Replacing it invalidates JSC's iterator-protocol watchpoint, and the generic path is taken for every array.

getDirectIndex() and getDirect(). JSObject::getDirectIndex() reads an object's own indexed storage without consulting prototypes or iterators. getDirect() with a private name reads an own slot that only builtins can create, which makes its presence an unforgeable brand.

This is a type confusion: a page-supplied object is accepted where an internal readable-stream record is expected, and in release builds a missing length check compounds it.

  tee builtin returns:   [ branch0, branch1 ]     (real internal records)
                               |
  Before: convert<IDLSequence>  -> Array.prototype[Symbol.iterator]  (page JS)
                               |
  page iterator yields:  [ {plain object}, ... ]  (any count, any identity)
                               |
  results[0], results[1]  (only ASSERT on size; no brand check)
                               |
  InternalReadableStream::fromObject(obj)  -> DOMGuarded<JSObject>
      expected: @readableStreamController, @state, @reader slots
      actual:   page object, cannot carry private-name slots

Reading the diagram top to bottom: the builtin produced real branches, but WebCore unpacked them with the public WebIDL converter. The patch's own comment states that converter uses Array.prototype[Symbol.iterator]; JSDOMConvertSequences.h shows the fallback to forEachInIterable() when the fast-path check fails for the numeric specialization, and the patch comment is the basis for the IDLObject path behaving the same way. Once the iterator is overridden, page JS decides both the element count and the identity of each element.

The two call sites diverged afterward. createInternalTransformStream() already checked size() != 3 and downcast each result to JSReadableStream/JSWritableStream, which matches the pre-fix expectation that every poisoned case threw TypeError. tee() had only ASSERT(results.size() == 2), which compiles out in release, and no type check, so it passed results[0] and results[1] straight to fromObject(). The poisoned next() also runs page JS in the middle of tee(), possibly after the builtin has already acted on the source stream.

Exploitability: any page script can override the iterator before calling ReadableStream.prototype.tee() or constructing a TransformStream. For tee(), the pre-fix state is that unvalidated objects, in an unchecked count, are wrapped as internal readable streams, provided page-level tee() reaches InternalReadableStream::tee(); ReadableStream.cpp also has a C++ tee path through StreamTeeUtilities, and which one a given stream takes is not established here. Two sinks are candidates. First, if the poisoned iterator yields fewer than two elements, results[1] indexes past the conversion Vector's size; if WTF Vector indexing is not release-bounds-checked on this path, that would be an out-of-bounds read of a Strong<JSObject> slot whose ceiling would be a fake-object candidate, and if it is release-checked, as recent WebKit hardening suggests, it ends as a controlled crash. Second, a consumer of the branch streams (the ReadableStream::create(Ref<InternalReadableStream>&&) path, or a builtin using @getByIdDirectPrivate results without re-checking) would have to treat missing private slots as a valid controller or reader. Absent such a consumer, the object-shape confusion would likely cap out at builtin assertion failures or a controlled crash. The regression test's comment asserts that the C++ side "dereferences attacker-controlled memory", but that comment describes the TransformStream path, which was already rejecting all three subcases.

The pattern looks like variant analysis: the existing transform-stream-poisoned-iterator-crash test had already applied the poisoned-iterator technique to createInternalTransformStream, and auditing sibling call sites that run convert<IDLSequence> on builtin results surfaces tee(), which lacked the transform path's checks.

This vulnerability weakens the boundary between page-controlled JavaScript and WebCore's privileged builtin plumbing. The streams bindings assume values returned from private builtins are trusted records that page script cannot forge or intercept, and before the fix that held only while Array.prototype[Symbol.iterator] was untouched. The plausible gain would range from a renderer crash up to renderer-process memory corruption, but anything beyond broken stream-internal invariants is a projection until a consumer on the tee() path is shown to turn a non-branded record into a memory-safety violation. The bug stays inside WebContent; crossing the sandbox would need a separate escape.

Insight: The builtin side is protected by private names, but the C++ side reused a public-facing converter that honours page-overridable protocols, so the trust the builtin established was lost on the way out. The fix applies two complementary defences: never run observable protocols on internal results, and brand-check outputs by private-slot presence. Two loose ends remain in the source. InternalWritableStream::fromObject() still wraps any JSObject without a brand assertion. And the updated expectation still shows the poisoned next() called twice and the "truncated iterator" subcase failing, even though C++ no longer consults the iterator, which suggests builtin-side code on the TransformStream creation path still iterates through the page-overridable protocol somewhere.