← All reports

[6] JSC Wasm Memory grow UAF on concurrently-read MemoryHandle

MediumJSC WebAssembly memoryRace

Growing a WebAssembly.Memory could free its handle under a JIT or GC thread.

6548b1f

Medium. script로 도달 가능한 실제 cross-thread UAF입니다. 다만 attacker는 compiler thread나 GC thread와의 race에서 이겨야 합니다. 또한 그 thread가 읽기 전에 해제된 handle을 재점유해야 하며, regression test도 확률적으로 동작한다고 명시되어 있습니다.

JavaScriptCore의 WebAssembly linear memory는 여러 thread가 함께 다루는 공유 상태입니다. script thread가 memory를 grow하는 동안 background compiler thread와 garbage collector thread가 동시에 이를 들여다봅니다. WebAssembly.Memory의 실체인 엔진 객체 Wasm::Memory는 BufferMemoryHandle을 통해 자신의 allocation에 접근합니다. 이 handle은 base pointer, size, mode를 담는 thread-safe refcounted 레코드입니다. 이때 동시에 읽는 쪽은 한 가지 전제에 의존합니다. live memory에서 도달 가능한 handle은 그 memory가 살아 있는 동안 계속 같은 유효 객체여야 한다는 전제입니다.

관전 포인트: JSC가 bounds-checking WebAssembly.Memory를 compile하거나 marking하는 도중에 script가 해당 memory를 grow할 수 있습니다. 이 경우 background thread가 막 읽으려던 BufferMemoryHandle이 그 직전에 해제될 수 있습니다.

MemoryHandle에는 두 가지 mode의 조합으로 정해지는 네 가지 구성이 있습니다. 하나는 non-shared/shared이고, 다른 하나는 bounds-checking/signaling입니다. 그중 non-shared bounds-checking 구성에서는 Wasm Memory를 grow할 때 기존 MemoryHandle을 더 큰 allocation을 나타내는 새 handle로 바꿔 끼웠습니다. 문제는 MemoryHandle이 JIT thread와 GC thread에서도 접근된다는 점입니다. 나머지 세 mode에서는 Wasm Memory에 연결된 handle을 교체하지 않습니다.

이 patch는 같은 MemoryHandle instance를 새 allocation으로 in-place 갱신합니다. 그 결과 해당 mode도 나머지 세 mode와 동일하게 동작하게 되고, race를 피할 수 있습니다.

Tests: JSTests/stress/wasm-memory-grow-races-ftl-call-wasm-mode-read.js, JSTests/stress/wasm-memory-grow-races-gc-marking-size-read.js (marked slow).

Source/JavaScriptCore/wasm/WasmMemory.cpp

memcpySpan(unsafeMakeSpan(static_cast<uint8_t*>(newMemory), desiredSize), m_handle->mutableSpan());
- Ref newHandle = adoptRef(*new BufferMemoryHandle(newMemory, desiredSize, desiredSize, initial(), maximum(), sharingMode(), MemoryMode::BoundsChecking));
- m_handle->transferAnchors(newHandle.get());
- m_handle = WTF::move(newHandle);
+ m_handle->replaceAllocatedMemory(newMemory, desiredSize);
...

Source/JavaScriptCore/wasm/WasmMemory.h

- Ref<BufferMemoryHandle> m_handle;
+ const Ref<BufferMemoryHandle> m_handle;
...

Source/JavaScriptCore/runtime/BufferMemoryHandle.cpp

+void BufferMemoryHandle::replaceAllocatedMemory(void* newMemory, size_t newSize)
+{
+ RELEASE_ASSERT(m_sharingMode == MemorySharingMode::Default);
+ RELEASE_ASSERT(m_mode == MemoryMode::BoundsChecking);
+ ...
+ m_memory = CagedMemory(newMemory);
+ m_mappedCapacity = newSize;
+ updateSize(newSize);
+
+ BufferMemoryManager::singleton().freePhysicalBytes(oldSize);
+ freeVirtualPagesUnlessNullBasePointer(oldMemory, oldSize);
+}
...
-void BufferMemoryHandle::transferAnchors(BufferMemoryHandle& newHandle)
-{
- RELEASE_ASSERT(sharingMode() == MemorySharingMode::Default);
- std::scoped_lock locker(m_lock, newHandle.m_lock);
- newHandle.m_anchors = std::exchange(m_anchors, { });
-}

Memory::grow에서 handle 자체를 다시 끼우던 방식이 handle의 backing allocation만 in-place로 바꾸는 방식으로 변경되었습니다. 또한 handle의 identity가 compile time에 고정되었습니다. 더 이상 새 handle을 따라갈 필요가 없어진 ArrayBuffer refresh 경로도 단순화되었습니다.

Memory::grow의 non-shared BoundsChecking 경로는 원래 새 BufferMemoryHandle을 생성했습니다. 이어서 transferAnchors로 instance anchor를 옮긴 뒤 m_handle을 재할당했습니다. 이제는 대신 BufferMemoryHandle::replaceAllocatedMemory(newMemory, desiredSize)를 호출합니다. 이 함수는 먼저 Default/BoundsChecking mode인지 RELEASE_ASSERT로 확인합니다. 그다음 m_memory, m_mappedCapacity, atomic m_size(updateSize 경유)를 새 값으로 기록합니다. 마지막으로 freePhysicalBytes(oldSize)로 기존 physical byte 집계를 반환하고, 기존 virtual page를 해제합니다. transferAnchors는 삭제되었고, Wasm::Memory::m_handle은 const Ref<BufferMemoryHandle>로 변경되었습니다.

부수적인 변경도 함께 들어갔습니다. ~BufferMemoryHandle에 있던 null base pointer 특례 처리는 static helper freeVirtualPagesUnlessNullBasePointer로 분리되었습니다. ArrayBufferContents::refreshAfterWasmMemoryGrow와 ArrayBuffer::refreshAfterWasmMemoryGrow에서는 Wasm::Memory* parameter가 제거되었습니다. buffer의 handle이 이제 memory의 handle과 같은 객체이기 때문입니다. 이에 맞춰 호출 지점인 JSWebAssemblyMemory::growSuccessCallback도 수정되었고, wasm/WasmMemory.h에 대한 SaferCPP expectation 한 줄은 제거되었습니다. 새로 추가된 slow stress test 두 개는 mem.grow(1)을 서로 다른 동작과 경합시킵니다. 하나는 CallWasm으로 strength reduction된 caller의 FTL tier-up이고, 다른 하나는 live memory 256개에 대한 --collectContinuously=1 marking입니다.

다른 thread가 자체 reference 없이 owner를 거쳐 역참조하는 공유 refcounted 멤버를 한 thread에서 재할당하는 패턴. pointer load와 field read 사이에 마지막 reference가 해제될 수 있습니다.

WebAssembly.Memory와 handle. JSC에서 WebAssembly.Memory의 실체는 Wasm::Memory이며, 이 객체가 BufferMemoryHandle을 보유합니다. handle은 ThreadSafeRefCounted이고 하나의 allocation을 기술합니다. 구성 요소는 base pointer m_memory, atomic m_size, m_mappedCapacity, initial/maximum page 수입니다. 여기에 MemorySharingMode(Default 또는 Shared)와 MemoryMode(BoundsChecking 또는 Signaling)가 더해집니다.

Signaling과 BoundsChecking. Signaling mode는 guard page를 포함한 넓은 virtual 영역을 미리 예약해 둡니다. 이후 Wasm의 out-of-bounds 접근은 hardware fault로 잡아냅니다. 반면 BoundsChecking mode는 현재 size를 기준으로 명시적인 bounds check를 생성합니다. BoundsChecking은 fast-memory 예약을 쓸 수 없을 때 사용됩니다. 비활성화된 경우(--useWasmFastMemory=0), 플랫폼에서 지원하지 않는 경우, 한도(BufferMemoryManager::m_maxFastMemoryCount)가 소진된 경우가 여기에 해당합니다.

Memory::grow. grow는 memory를 확장한 뒤 grow-success callback을 호출합니다. JSWebAssemblyMemory::growSuccessCallback은 이 callback에서 연관된 ArrayBuffer를 detach하거나 refresh합니다.

ThreadSafeRefCounted와 Ref. 객체는 atomic refcount가 0이 되는 시점에 파괴됩니다. 다른 객체의 Ref 멤버를 거쳐 얻은 raw pointer나 reference는 그 자체로 count에 포함되지 않습니다.

동시 compilation. DFG/FTL compilation은 background worklist thread에서 JS mutator와 동시에 실행됩니다. 이때 해당 thread는 graph가 참조하는 runtime 객체를 읽을 수 있습니다. DFG strength reduction 과정에서는 constant-folding된 WebAssemblyFunction 호출이 CallWasm node로 바뀔 수 있습니다. FTL은 이 node를 JS-to-Wasm 직접 호출로 lowering합니다. commit message에 따르면 이 lowering 단계에서 callee memory의 mode를 읽습니다.

동시 marking. JSC의 GC는 marking을 concurrent하게, 그리고 parallel하게 수행할 수 있습니다. marking thread는 live cell에 대해 visitChildren을 실행합니다. 이 과정에서 mutator가 계속 동작하는 동안 native 쪽 상태를 읽을 수도 있습니다.

이번 문제는 BufferMemoryHandle 객체에 대한 cross-thread use-after-free입니다. mutator가 refcounted 멤버를 재할당하는 동작과, helper thread가 reference를 잡지 않은 채 이를 읽는 동작 사이의 data race에서 비롯됩니다.

  Mutator (JS)                          FTL plan / GC marker
  ------------                          --------------------
                                        h = memory.m_handle.ptr()  (no ref)
  mem.grow(1)
    BoundsChecking + Default path
    newHandle = new BufferMemoryHandle
    m_handle = move(newHandle)
      old handle refcount -> 0
      ~BufferMemoryHandle: free pages
      free(handle)
                                        h->m_mode / h->m_size  <- UAF read

다이어그램에서 오른쪽 열은 handle pointer를 load한 뒤 역참조합니다. 그 사이에 왼쪽 열이 Memory가 쥐고 있던 reference를 해제합니다. 이 구성에서 handle을 보유할 수 있는 다른 주체는 두 가지였습니다. 하나는 resizable ArrayBufferContents::m_memoryHandle인데, refreshAfterWasmMemoryGrow가 직접 이를 새 handle로 재할당했습니다. 다른 하나는 fixed-length buffer의 destructor task에 capture된 protectedHandle입니다.

한편 GC marking test는 .buffer를 전혀 건드리지 않습니다. 그래서 이 test에서는 기존 handle의 유일한 owner가 Memory였고, 재할당과 동시에 handle이 파괴되었습니다. 먼저 destructor가 Gigacage::freeVirtualPages로 기존 page를 해제했고, 이어서 handle 객체 자체가 deallocate되었습니다. commit message와 test 이름을 보면 읽는 쪽은 두 곳입니다. CallWasm을 lowering하면서 memory의 mode를 읽는 concurrent FTL compiler가 하나입니다. 다른 하나는 handle의 size를 읽는 GC marking thread입니다(예: extra-memory reporting).

수정 이후에는 handle의 identity가 고정되고, 내부 상태만 바뀝니다. m_mode와 m_sharingMode에 대한 읽기는 살아 있는 객체를 대상으로 하며, 두 field는 생성 이후 다시 기록되지 않습니다. 또한 m_size는 std::atomic입니다.

regression test가 그대로 유발 절차에 해당합니다.

  1. FTL test는 --useConcurrentJIT=true 환경에서 Wasm export의 caller가 tier-up되는 동안 mem.grow(1)을 반복 실행합니다. 그러면 DFG가 caller를 CallWasm으로 strength reduction하고, FTL plan이 worklist thread에서 memory의 mode를 읽게 됩니다.
  2. GC test는 live memory 256개를 유지한 채 --collectContinuously=1 조건에서 grow를 반복합니다. 이 상태에서 marking thread는 JSWebAssemblyMemory cell을 계속 방문하며 handle size를 읽습니다.
  3. race가 의미를 가지려면 memory가 BoundsChecking mode여야 합니다. 다만 GC test는 --useWasmFastMemory=0을 전달하지 않습니다. 따라서 memory가 이 mode로 들어가는지는 maxNumWasmFastMemories 대비 fast-memory가 소진되는지에 달려 있습니다.
  4. 두 test 모두 느리고 확률적이어서, ASan 실행을 여러 번 반복해야 결과가 나옵니다.

Exploitability의 전제 조건은 FTL plan 또는 GC marker와의 좁은 cross-thread race에서 이기는 것입니다. 실제로 확인된 결과는 해제된 BufferMemoryHandle의 m_mode/m_size를 읽는 동작까지입니다. 해제된 handle slot을 재점유했을 때 attacker가 무엇에 영향을 줄 수 있게 될지는 아직 열려 있습니다. FTL의 CallWasm lowering이 읽어 들인 mode를 어떻게 사용하는지에 달려 있으며, 이 부분이 확장 가능성을 판단할 때 남아 있는 미해결 지점입니다.

이 vulnerability는 JS mutator와 JSC의 concurrent helper thread가 맞닿는 경계에서 WebContent process 내부의 memory safety를 약화시킵니다. JSC는 compiler thread와 marking thread가 들여다보는 동안 live Wasm::Memory에서 도달 가능한 객체가 유효하게 유지된다고 가정합니다. 그러나 수정 이전에는 non-shared bounds-checking mode의 handle에 대해 이 가정이 성립하지 않았습니다. 확인된 결과는 해제된 BufferMemoryHandle에 대한 cross-thread read입니다.

Insight: m_handle이 const Ref로 바뀌면서, 나머지 세 구성이 이미 따르던 암묵적인 규칙이 compiler가 강제하는 규칙이 되었습니다. 동시에 이번 수정은 lifetime semantics도 바꿉니다. 이제 기존 page는 기존 handle의 destructor가 아니라 replaceAllocatedMemory 안에서 해제됩니다. 즉 Ref<BufferMemoryHandle>을 보유하더라도 더 이상 기존 backing이 유지되지 않습니다. 그래서 확인해야 할 속성은 cached base pointer를 보유한 모든 주체가 그 해제 이전에 detach되거나 refresh되는지입니다. fixed-length ArrayBuffer destructor task, anchor로 refresh되는 instance cache, m_memory를 off-thread로 읽는 쪽이 여기에 해당합니다.