[6] JSC Wasm Memory grow UAF on concurrently-read MemoryHandle
Growing a WebAssembly.Memory could free its handle under a JIT or GC thread.
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이 그 직전에 해제될 수 있습니다.
[JSC] Update MemoryHandle in place when growing non-shared bounds-checking memory
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는 같은
MemoryHandleinstance를 새 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
Source/JavaScriptCore/wasm/WasmMemory.h
Source/JavaScriptCore/runtime/BufferMemoryHandle.cpp
Patch Details
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가 해제될 수 있습니다.
Background
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 쪽 상태를 읽을 수도 있습니다.
Analysis
이번 문제는 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가 그대로 유발 절차에 해당합니다.
- FTL test는
--useConcurrentJIT=true환경에서 Wasm export의 caller가 tier-up되는 동안mem.grow(1)을 반복 실행합니다. 그러면 DFG가 caller를CallWasm으로 strength reduction하고, FTL plan이 worklist thread에서 memory의 mode를 읽게 됩니다. - GC test는 live memory 256개를 유지한 채
--collectContinuously=1조건에서 grow를 반복합니다. 이 상태에서 marking thread는JSWebAssemblyMemorycell을 계속 방문하며 handle size를 읽습니다. - race가 의미를 가지려면 memory가 BoundsChecking mode여야 합니다. 다만 GC test는
--useWasmFastMemory=0을 전달하지 않습니다. 따라서 memory가 이 mode로 들어가는지는maxNumWasmFastMemories대비 fast-memory가 소진되는지에 달려 있습니다. - 두 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로 읽는 쪽이 여기에 해당합니다.
Audit directions
- owner가 재할당하는 refcounted 멤버를 다른 thread가 자체 ref 없이 owner를 거쳐 읽는 경우. GC cell이나 compiler가 볼 수 있는 runtime 객체에서 도달 가능한 객체라면 두 조건 중 하나를 만족해야 합니다. identity를 안정적으로 유지하거나, concurrent thread가 자신이 보유한 ref를 통해서만 읽어야 합니다. Narrow: DFG/FTL plan이나
visitChildren이 off-thread로 읽는 객체에서 non-constRef</RefPtr<멤버를 JSC 전체에서 검색합니다.Wasm::Instance,Wasm::Table,Wasm::CalleeGroup,JSWebAssemblyModule등이 대상이며, mutator에서 이 멤버를 재할당하는 지점이 있는지 확인합니다. Match: main thread에서의 멤버 대입과*Plan,Lower*,visitChildren/visitAdditionalChildren경로에서의 역참조가 함께 존재하는 경우입니다. 이때 ref도 잡지 않고 cell lock도 보유하지 않는다면 해당됩니다. Wider: 같은 형태는reset()으로 교체되는std::unique_ptr멤버에서도 나타납니다. concurrent reader가 있는 상태에서의Vector재할당, 교체 시 native 상태가 해제되는 pointee를 가진WriteBarrierslot도 마찬가지입니다. Widest: concurrent JIT 또는 GC thread를 가진 runtime이라면 모두 이 유형의 문제가 존재합니다. V8의 background TurboFan이 heap에 인접한 native handle을 읽는 경우, HotSpot의 concurrent compiler가Method/ConstantPoolmetadata를 읽는 경우가 예입니다. 이들 runtime은 명시적인 handle scope나 safepoint까지 해제를 미루는 방식을 사용합니다. 따라서 그런 메커니즘이 없는 codebase라면, 교체된 객체가 helper thread의 safepoint 도달 이전에 해제되는지 살펴볼 필요가 있습니다. - In-place 재할당으로 hazard가 handle에서 내부 pointer로 옮겨가는 경우.
replaceAllocatedMemory는 non-atomic인m_memory와m_mappedCapacity를 기록하고, 기존 page를 즉시 해제합니다. 따라서memory()를 off-thread로 읽거나 cache해 두는 쪽이 새로운 점검 대상이 됩니다. Narrow: JIT worklist thread, signal handler(isInGrowableOrFastMemory), GC에서 도달 가능한 호출 지점을 나열합니다. 대상은BufferMemoryHandle::memory(),Memory::basePointer(),mappedCapacity()입니다. 그다음freeVirtualPagesUnlessNullBasePointer가 실행되기 전에, 기존 base pointer를 보유한 모든 주체가 anchor나 grow-success callback을 통해 refresh되는지 확인합니다. Match:grow이전에 capture한 base pointer를 이후에도 사용하면서,Ref<BufferMemoryHandle>이 해당 byte를 살려 둔다고 가정하는 경우입니다. Wider:SharedArrayBufferContents, resizableArrayBufferview, typed array vector caching에서도 같은 형태가 나타납니다. Widest: buffer를 in-place로 교체하면서 기존 buffer를 즉시 해제하는 container라면 모두 해당합니다. Rust에서unsafealiasing 뒤에 있는realloc방식의 buffer,data()pointer가 남아 있는 상태에서의std::vector확장 등이 예입니다. - 구성 matrix에서 한 칸만 공유 invariant를 벗어나는 경우. 나머지
MemorySharingModexMemoryMode경로를 살펴, 네 구성 중 정확히 하나에서만 다르게 동작하는 연산이 있는지 점검합니다. Narrow:Memory::grow,growShared,tryCreate,createZeroSized,~BufferMemoryHandle의 switch arm을 확인합니다. identity, ownership, 해제 순서가 칸마다 다른지가 관심 대상입니다. Wider: 같은 matrix 점검을ArrayBufferContents(shared vs. non-shared, fixed vs. resizable)에도 적용합니다.MemoryMode에 따라 분기하는 Wasm tier codegen도 대상입니다. Match: 재할당, 해제, pointer 재할당 같은 side effect가 sibling arm에서는 발생하지 않는 switch arm입니다. Widest: 구성 matrix와 concurrent consumer를 함께 가진 시스템이라면 어디서든 어긋난 칸 하나가 숨어 있을 수 있습니다. mode별로 page를 교체하는 storage engine, size class별 release 경로를 가진 allocator 등이 예입니다.