SharedArrayBuffers: refcount leak during serialization leads to potential use-after-free
A reference count leak in the handling of SharedArrayBuffers during structured cloning allows an attacker to overflow the reference count and cause a use-after-free. This could potentially lead to memory corruption and code execution.
Originally disclosed on Mozilla
- Fixed in 8 days
- Paid in 9 days
- Disclosed after 8 days
Created attachment 8853652
Proof-of-concept code to trigger the bug
Summary
-------
A refcount leak is present in the handling of SharedArrayBuffers during structured cloning. It can be abused to trigger a refcount overflow and subsequent use-after-free of a SharedArrayBuffer.
SharedArrayBuffers are not yet enabled in the release version of Firefox (v52). However, the current beta (v53) has them enabled.
Detailed description
--------------------
SharedArrayBuffers make use of a custom reference counting mechanism:
class SharedArrayRawBuffer
{
private:
mozilla::Atomic<uint32_t, mozilla::ReleaseAcquire> refcount_;
// ...
They can also be transferred to a web worker, in which case this refcount will be incremented by one. The following code is responsible for handling SharedArrayBuffers that are transferred during structured cloning:
bool
JSStructuredCloneWriter::writeSharedArrayBuffer(HandleObject obj)
{
if (!cloneDataPolicy.isSharedArrayBufferAllowed()) {
JS_ReportErrorNumberASCII(context(), GetErrorMessage, nullptr, JSMSG_SC_NOT_CLONABLE,
"SharedArrayBuffer");
return false;
}
Rooted<SharedArrayBufferObject*> sharedArrayBuffer(context(), &CheckedUnwrap(obj)->as<SharedArrayBufferObject>());
SharedArrayRawBuffer* rawbuf = sharedArrayBuffer->rawBufferObject();
// Avoids a race condition where the parent thread frees the buffer
// before the child has accepted the transferable.
rawbuf->addReference(); // [[ 1 ]]
intptr_t p = reinterpret_cast<intptr_t>(rawbuf);
return out.writePair(SCTAG_SHARED_ARRAY_BUFFER_OBJECT, static_cast<uint32_t>(sizeof(p))) &&
out.writeBytes(&p, sizeof(p));
}
At [[ 1 ]] the refcount of the SharedArrayBuffer is (artificially) increased to keep it alive during the transfer. It will later be decremented again during JSStructuredCloneReader::readSharedArrayBuffer. However, if the structured clone algorithm fails after the refcount has been increased, it is never decreased again, leading to a refcount leak. This in turn directly leads to a refcount overflow after 0x100000000 increments.
The structured clone algorithm checks for duplicates during serialization, thus `serialize([ab, ab]);` will only increment the refcount once. However, since different SharedArrayBufferObjects can point to the same SharedArrayRawBuffer instance, it is still possible to increment the refcount multiple times per invocation (which is much faster than incrementing once per invocation).
The attached POC implements this: first it creates 0x100000 copies of a SharedArrayBufferObject, then triggers the refcount leak to overflow the refcount. In a JavaScript shell on my 2015 MacBook Pro this takes about 35 minutes. It may be faster with more copies.
The POC makes use of some functions that are only available in the js shell: serialize(), unserialze(), and gc(). In the browser, serialize() and unserialize() can be replaced with window.postMessage(), while garbage collection can be triggered through other means (e.g. https://github.com/saelo/foxpwn/blob/master/code.js#L297).
Here is the output of executing poc.js:
> time ./obj-ff-release/dist/bin/js poc.js
1/4095 - 0.02%
2/4095 - 0.05%
3/4095 - 0.07%
4/4095 - 0.10%
5/4095 - 0.12%
...
4091/4095 - 99.90%
4092/4095 - 99.93%
4093/4095 - 99.95%
4094/4095 - 99.98%
4095/4095 - 100.00%
[2] 22920 segmentation fault ./obj-ff-release/dist/bin/js poc.js
./obj-ff-release/dist/bin/js poc.js 2057.79s user 71.22s system 99% cpu 35:37.80 total
The backtrace at the time of the crash (at engine shut down in this case):
* thread #1, queue = 'com.apple.main-thread', stop reason = EXC_BAD_ACCESS (code=1, address=0x103a00fe8)
* frame #0: 0x000000010054f080 js`js::SharedArrayRawBuffer::dropReference() [inlined] std::__1::__atomic_base<unsigned int, true>::fetch_sub(__op=1, __m=memory_order_acq_rel) at atomic:936 [opt]
frame #1: 0x000000010054f07b js`js::SharedArrayRawBuffer::dropReference() [inlined] mozilla::detail::IntrinsicAddSub<unsigned int, (mozilla::MemoryOrdering)1>::sub(aVal=1) at Atomics.h:259 [opt]
frame #2: 0x000000010054f07b js`js::SharedArrayRawBuffer::dropReference() [inlined] mozilla::detail::IntrinsicIncDec<unsigned int, (mozilla::MemoryOrdering)1>::dec(std::__1::atomic<unsigned int>&) at Atomics.h:291 [opt]
frame #3: 0x000000010054f07b js`js::SharedArrayRawBuffer::dropReference() [inlined] mozilla::detail::AtomicBaseIncDec<unsigned int, (mozilla::MemoryOrdering)1>::operator--() at Atomics.h:610 [opt]
frame #4: 0x000000010054f07b js`js::SharedArrayRawBuffer::dropReference(this=0x0000000103a00fe8) at SharedArrayObject.cpp:179 [opt]
frame #5: 0x000000010054f4aa js`js::SharedArrayBufferObject::Finalize(fop=<unavailable>, obj=0x00000001025821c0) at SharedArrayObject.cpp:310 [opt]
frame #6: 0x00000001004145e9 js`unsigned long js::gc::Arena::finalize<JSObject>(js::FreeOp*, js::gc::AllocKind, unsigned long) [inlined] js::Class::doFinalize(this=<unavailable>, fop=<unavailable>) const at Class.h:881 [opt]
frame #7: 0x00000001004145df js`unsigned long js::gc::Arena::finalize<JSObject>(js::FreeOp*, js::gc::AllocKind, unsigned long) [inlined] JSObject::finalize(js::FreeOp*) at jsobjinlines.h:87 [opt]
frame #8: 0x00000001004145b8 js`unsigned long js::gc::Arena::finalize<JSObject>(this=<unavailable>, fop=<unavailable>, thingKind=<unavailable>, thingSize=<unavailable>) at jsgc.cpp:465 [opt]
frame #9: 0x00000001004142d2 js`bool FinalizeTypedArenas<JSObject>(fop=<unavailable>, src=0x00007fff5fbfdb38, dest=0x00007fff5fbfdb60, thingKind=<unavailable>, budget=0x00007fff5fbfdb40, keepArenas=<unavailable>) at jsgc.cpp:523 [opt]
frame #10: 0x00000001003f647d js`FinalizeArenas(fop=<unavailable>, src=0x00007fff5fbfdb38, dest=0x00007fff5fbfdb60, thingKind=<unavailable>, budget=0x00007fff5fbfdb40, keepArenas=KEEP_ARENAS) at jsgc.cpp:557 [opt]
frame #11: 0x00000001003f627d js`js::gc::ArenaLists::backgroundFinalize(fop=<unavailable>, listHead=<unavailable>, empty=0x00007fff5fbfeba0) at jsgc.cpp:2780 [opt]
frame #12: 0x00000001003f94e5 js`js::gc::GCRuntime::sweepBackgroundThings(this=<unavailable>, zones=<unavailable>, freeBlocks=<unavailable>) at jsgc.cpp:3178 [opt]
frame #13: 0x000000010040179e js`js::gc::GCRuntime::endSweepingZoneGroup(this=0x0000000102373460) at jsgc.cpp:5258 [opt]
frame #14: 0x00000001004026ee js`js::gc::GCRuntime::sweepPhase(this=<unavailable>, sliceBudget=<unavailable>, lock=<unavailable>) at jsgc.cpp:5471 [opt]
frame #15: 0x000000010040496b js`js::gc::GCRuntime::incrementalCollectSlice(this=<unavailable>, budget=<unavailable>, reason=<unavailable>, lock=<unavailable>) at jsgc.cpp:6066 [opt]
frame #16: 0x0000000100405561 js`js::gc::GCRuntime::gcCycle(this=0x0000000102373460, nonincrementalByAPI=<unavailable>, budget=0x00007fff5fbfeee0, reason=DESTROY_RUNTIME) at jsgc.cpp:6351 [opt]
frame #17: 0x00000001004064f8 js`js::gc::GCRuntime::collect(this=0x0000000102373460, nonincrementalByAPI=<unavailable>, budget=<unavailable>, reason=DESTROY_RUNTIME) at jsgc.cpp:6500 [opt]
frame #18: 0x0000000100406881 js`js::gc::GCRuntime::gc(this=<unavailable>, gckind=<unavailable>, reason=<unavailable>) at jsgc.cpp:6566 [opt]
frame #19: 0x0000000100538457 js`JSRuntime::destroyRuntime(this=0x0000000102373000) at Runtime.cpp:308 [opt]
frame #20: 0x00000001003b85c4 js`js::DestroyContext(cx=0x0000000102341000) at jscntxt.cpp:226 [opt]
frame #21: 0x0000000100007f57 js`main(argc=<unavailable>, argv=<unavailable>, envp=<unavailable>) at js.cpp:8471 [opt]
frame #22: 0x0000000100001954 js`start + 52
Not written yet. The AI write-up for this report has not been written yet. The Original tab links to the source.
How it worked
Root cause
The reference count is incremented before serialization but not decremented if serialization fails, leading to a leak and eventual overflow.
Impact
A use-after-free could potentially lead to arbitrary code execution, though the proof-of-concept only demonstrates a crash.
What the attacker needed
Firefox 53 beta with SharedArrayBuffers enabled; Ability to run JavaScript in the browser; Many iterations to overflow the refcount
How it was found
- Create many SharedArrayBufferObjects that all point to the same underlying buffer.
- Trigger the structured clone algorithm to fail after incrementing the refcount, causing a leak.
- Repeat until the refcount overflows.
- Cause garbage collection to free the buffer while still referenced, leading to a crash.
Explained by bugbounty.wiki with AI from the original and checked against quotes from it; it can still be wrong. Read the original before relying on a detail.
Not written yet. The AI write-up for this report has not been written yet. The Original tab links to the source.
SharedArrayBuffers are a way for JavaScript to share memory between threads. The browser keeps track of how many references exist to a buffer using a counter. A bug caused the counter to be increased but not decreased when an error occurred during copying, so after many attempts the counter wrapped around to zero, making the browser think the buffer was no longer used and freeing it while still in use. This is called a use-after-free and can crash the browser or potentially let an attacker run code.
What is Memory corruption?
Native code reads or writes memory it should not: overflows, use-after-free, type confusion. The core of browser, kernel and parser bugs.