← All reports

[5] WebGPU encode-time clear tracking trusted by never-submitted command buffers

MediumWebGPU Metal backendUninitializedMemory

WebGPU let a command buffer that never ran vouch that a texture was already zeroed.

0a45668

Medium. 실제로 실행되지 않는 작업만으로 script가 "이 texture는 이미 0으로 초기화되었다"는 상태를 위조할 수 있습니다. 그 결과 할당 직후 상태의 GPU 메모리를 항상 동일하게 읽어낼 수 있습니다. 그럼에도 Medium으로 유지하는 이유는 leak이 read-only이기 때문입니다. 또한 유출 데이터의 민감도는 Metal allocator가 메모리를 어떻게 재사용하는지에 달려 있는데, 이번 commit에서는 그 부분이 확정되지 않습니다.

웹에 노출되는 GPU API는 새로 만든 texture를 읽으면 전부 0으로 보인다고 보장합니다. 구현체는 보통 이 보장을 lazy하게 지키는데, 특정 영역을 처음 읽기 직전에야 clear를 수행합니다. WebKit의 WebGPU backend에서 Texture는 GPU process 쪽에서 Metal texture를 감싸는 wrapper입니다. 각 Texture에는 slice 단위 flag가 있어, 어떤 (mip level, array slice) 쌍이 이미 초기화되었는지를 기록합니다. 이때 zero-fill blit을 encode하는 helper인 clearTextureIfNeeded는 flag가 설정된 slice를 건너뜁니다. 한편 WebGPU는 encoder에 명령을 기록하는 단계와 queue에 제출하는 단계를 분리합니다. 따라서 이 flag를 신뢰하려면, flag를 설정한 작업이 실제로 실행된다는 전제가 성립해야 합니다.

관전 포인트: 페이지가 전체 영역을 덮는 copy를 기록만 하고 제출하지 않으면, 해당 slice는 cleared 상태로 남습니다. 이후 mappable buffer를 통해 texture의 할당 직후 GPU 메모리를 다시 읽어낼 수 있습니다.

Commit message(rdar://187343075)에 따르면, 제출되지 않은 render pass를 encode하는 과정에서 zero-initialization 추적 로직의 결함이 드러났습니다. 수정 사항은 작업이 제출되기 전까지는 texture가 clear되었다고 가정하지 않도록 변경되었습니다.

Source/WebGPU/WebGPU/CommandEncoder.mm

@@ -1257,7 +1259,7 @@
if (Queue::writeWillCompletelyClear(textureDimension, widthForMetal, logicalSize.width, heightForMetal, logicalSize.height, depthForMetal, logicalSize.depthOrArrayLayers))
 
- destinationTexture->setPreviouslyCleared(destination.mipLevel, destinationSlice);
+ destinationTexture->setProvisionallyCleared(destination.mipLevel, destinationSlice, *this);
else
clearTextureIfNeeded(destination, destinationSlice);
...
if (!blitCommandEncoder || texture.previouslyCleared(mipLevel, slice))
return;
...
 
- texture.setPreviouslyCleared(mipLevel, slice);
+ if (owningCommandEncoder)
+ texture.setProvisionallyCleared(mipLevel, slice, *owningCommandEncoder);
+ else
+ texture.setPreviouslyCleared(mipLevel, slice);
...
clearTracking();
+ m_device->getQueue()->discardProvisionalTextureClears(m_uniqueId);
m_device->removeCommandEncoder(m_uniqueId);

Source/WebGPU/WebGPU/CommandBuffer.mm

if (RefPtr commandEncoder = m_commandEncoder) {
auto& commandEncoderRef = *commandEncoder;
+ m_device->getQueue()->resolveProvisionalTextureClears(commandEncoderRef.uniqueId());
for (auto& function : m_preCommitHandlers)
result = function(*this, commandEncoderRef) && result;
 
- }
+ } else
+ m_device->getQueue()->resolveProvisionalTextureClears();

LayoutTests/fast/webgpu/texture-lazy-clear-forged-by-unsubmitted-encoder.html

+ // copy는 finish되었지만 제출되지 않으므로, 기록된 명령은 하나도 실행되지 않으며 read에서는 여전히
+ // lazy zero clear 결과가 보여야 합니다.
+ let forged = newTexture();
+ recordFullCopy(forged).finish();
+ window.forgedRead = await read(forged);
...
+ shouldBeEqualToString('forgedRead', '0');

이번 변경으로 Texture와 Queue에 provisional 단계의 clear-tracking 상태가 추가되었습니다. 먼저 encode 시점에 기록되던 모든 "cleared" 표시가 이 provisional 단계로 옮겨졌습니다. 이후 submit 시점과 모든 abandonment 경로에서 해당 상태를 정리하도록 구현되었습니다.

새로 추가된 상태는 다음과 같습니다. Texture에는 m_provisionalClears가 추가되었습니다. 이 필드는 provisionalClearKey(mipLevel, slice)를 key로 하는 HashCountedSet<uint64_t>이며, 영구 상태인 m_clearedToZero와 분리되어 있습니다. 함께 setProvisionallyCleared, promoteProvisionalClear, dropProvisionalClear, discardProvisionalClear, 그리고 private 함수 durablyCleared도 추가되었습니다. 이제 previouslyCleared(mip, slice)는 slice가 영구적으로 clear된 경우뿐 아니라, 미해결 provisional claim이 하나라도 있는 경우에도 true를 반환합니다. 덕분에 하나의 encoder 안에서는 중복 clear 제거가 그대로 동작합니다. 한편 Queue에는 { ThreadSafeWeakPtr<Texture>, mipLevel, slice, commandEncoderId } 형태의 vector인 m_provisionalTextureClears가 추가되었습니다. 이 vector는 addProvisionalTextureClear, removeProvisionalTextureClears, discardProvisionalTextureClears, resolveProvisionalTextureClears로 관리됩니다.

호출 지점도 변경되었습니다. CommandEncoder.mm, CommandEncoder.swift, RenderPassEncoder.mm에서 encode 시점에 표시하던 모든 지점이 이제 setProvisionallyCleared(..., encoder)를 호출합니다. 대상은 render pass attachment, resolve target, depth/stencil clear입니다. writeWillCompletelyClear를 사용하는 두 개의 full-coverage fast path도 포함되는데, 변수명으로 보면 copyBufferToTexture와 copyTextureToTexture의 destination에 해당합니다. RenderPassEncoder.mm의 attachment 표시도 마찬가지입니다. 또한 static 함수 clearTextureIfNeeded에 owningCommandEncoder 인자가 추가되었습니다. 이 값이 non-null이면 provisional claim이 기록됩니다. 반대로 null인 경우(queue 쪽 호출자)에는 기존처럼 영구 표시인 setPreviouslyCleared가 유지됩니다.

정리(reconciliation) 과정은 다음과 같습니다. CommandBuffer::preCommitHandler는 resolveProvisionalTextureClears(encoderId)를 호출해, commit되는 encoder의 claim을 영구 상태로 승격합니다. 다른 encoder의 미해결 claim에 대해서는 texture 쪽 flag를 내리고 entry를 다시 queue에 넣습니다. 이때 해당 slice가 다른 경로로 clear되지 않았다면, queue 자체의 blit encoder에 zero-clear를 encode합니다. PresentationContextIOSurface는 compute pass를 직접 commit하기 전에 resolve를 수행합니다. Claim이 폐기되는 경로는 ~CommandEncoder, discardCommandBuffer, CommandBuffer::makeInvalid입니다. m_lastErrorString을 설정하는 encoder invalidation 경로에서도 폐기되며, 이 경로는 CommandEncoder::makeInvalid일 가능성이 있습니다. 또한 Queue.mm의 teardown 경로(Queue::makeInvalid일 가능성이 있습니다)는 std::exchange로 provisional 목록 전체를 비우고, 살아 있는 각 texture의 claim을 직접 내립니다. 마지막으로 queue 쪽 writeTexture는 clear 필요 여부를 판단하기 전에 destination slice에 대해 discardProvisionalClear를 호출합니다.

작업의 효과를 commit 시점이 아니라 enqueue 시점에 완료된 것으로 기록하는 패턴. 버려진 작업이 남긴 상태를 이후의 fast path가 신뢰해, 필수 초기화를 건너뛰게 됨.

Encoding과 submission의 분리. GPUCommandEncoder는 copyBufferToTexture, beginRenderPass 등의 명령을 command buffer에 기록하고, finish()가 이를 GPUCommandBuffer로 확정합니다. device.queue.submit([...])로 commit되기 전까지 GPU에서는 아무것도 실행되지 않습니다. 또한 finish된 buffer는 나중에 제출될 수도, 끝내 제출되지 않을 수도 있습니다. 같은 buffer를 두 번 넣는 경우처럼 validation에서 거부될 수도 있습니다.

Zero-initialization과 lazy clearing. WebGPU spec은 새 texture가 모든 texel이 0인 것처럼 동작하도록 요구합니다. WebKit의 Metal backend는 초기화된 (mipLevel, slice) 쌍을 Texture::m_clearedToZero에 기록합니다. 초기화되지 않은 slice를 읽을 수 있는 연산이 실행되기 전에는 CommandEncoder::clearTextureIfNeeded가 previouslyCleared(mip, slice)를 확인합니다. 결과가 false이면 0으로 채운 임시 buffer로부터 blit을 encode합니다.

중복 clear 생략. slice 전체를 덮어쓰는 연산은 clear를 생략하고 바로 초기화 완료로 표시할 수 있습니다. 전체 extent를 덮는 copy(Queue::writeWillCompletelyClear로 확인)나 loadOp: clear를 사용하는 render pass가 여기에 해당합니다.

Queue 쪽 staging과 pre-commit hook. Queue는 queue.writeTexture 같은 queue 쪽 write를 위해 자체 staging command buffer와 blit encoder를 보유합니다. 한편 CommandBuffer::preCommitHandler는 제출된 buffer가 MTLCommandQueue에 commit되기 직전에 실행됩니다.

Weak reference. ThreadSafeWeakPtr<T>는 WTF의 weak reference로, 대상 객체가 파괴되면 null을 반환합니다. 덕분에 queue는 texture의 lifetime을 늘리지 않고도 이를 참조할 수 있습니다.

Resource 상태 추적의 logic error이며, 그 결과로 uninitialized memory read가 발생합니다.

  Before:
  encoder A: full copy into slice  ─► setPreviouslyCleared   [durable]
  A finished / dropped / rejected  ─► recorded copy never runs
  encoder B: copyTextureToBuffer   ─► clearTextureIfNeeded: flag set, skip
  submit(B)                        ─► reads as-allocated memory   LEAK

  After:
  encoder A: full copy             ─► setProvisionallyCleared(slice, A)
  A dropped/invalid                ─► discardProvisionalTextureClears(A)
  A merely unsubmitted             ─► claim still pending
  submit(B): preCommitHandler      ─► resolve(B): drop A's claim,
                                      queue blit encodes zero-clear
  B reads                          ─► zeros

"Before" 부분에는 빠져 있던 invariant가 드러납니다. slice를 초기화된 것으로 기록하려면, 그 slice를 초기화하는 작업의 실행이 보장되어야 합니다. 그런데 encoder는 encode 시점에 영구 flag를 설정했습니다. 반면 실제로 texel을 기록하는 명령은 해당 encoder의 MTLCommandBuffer 안에만 있었고, queue.submit으로 commit되어야만 실행되었습니다. 문제는 encoder가 버려졌을 때 flag를 되돌리는 경로가 없었다는 점입니다. 그래서 이후 실제로 제출된 read가 clearTextureIfNeeded에서 previouslyCleared == true를 보고, zero-fill을 encode하기 전에 반환했습니다. 테스트는 세 가지 abandonment 경로를 다룹니다. submit 없이 finish()만 호출하는 경우, finish하지 않은 encoder를 버리는 경우, 같은 buffer가 두 번 포함되어 submit이 거부되는 경우입니다.

위조된 flag는 queue 쪽 write도 오도했습니다. 위조된 slice의 일부만 덮는 queue.writeTexture는 clear를 건너뛰었고, 덮이지 않은 영역은 초기화되지 않은 채 남았습니다. 테스트의 partlyWrittenAfterForge 케이스가 이 상황을 다루며, 복원된 clear가 write보다 먼저 실행되는지도 함께 확인합니다.

"After" 부분에서는 제출되지 않은 encoder가 일종의 "갚아야 할 빚"을 지게 됩니다. 테스트는 이 빚이 잘못 처리되는 상황을 방지합니다. 먼저 writtenAfterForge는 전체를 덮는 writeTexture가 slice를 스스로 초기화하는 경우입니다. 이때 밀려 있던 clear가 그 위에 덮이면 안 되는데, queue write 경로의 discardProvisionalClear가 이를 막습니다. 다음으로 beforeDeferredCopyRead / afterDeferredCopyRead는 read보다 먼저 finish되었지만 나중에 제출된 copy를 다룹니다. 이 copy는 read에 보이면 안 되며, 동시에 read에 필요했던 zero-clear 이후에도 결과가 유지되어야 합니다.

beforeDeferredCopyRead == "0"이라는 기대값이 성립하려면, queue의 catch-up clear가 commit되는 buffer의 read보다 먼저 실행되어야 합니다. 이 순서는 Queue::finalizeBlitCommandEncoder가 staging buffer를 사용자 MTLCommandBuffer보다 먼저 commit한다는 점에 의존합니다. 다만 테스트는 이 조건을 검증할 뿐, 이번 변경이 직접 보장하는 사항은 아닙니다. 마찬가지로 이중 submit이 거부되는 케이스가 discard 경로에 도달한다는 점도 테스트의 기대 결과로 드러날 뿐입니다. Queue::submit의 validation 코드에서 직접 확인되지는 않습니다.

표준 WebGPU API만으로 안정적으로 exploit할 수 있습니다. 테스트 설명에 따르면, 이후 제출된 copyTextureToBuffer가 "flag를 신뢰해 lazy zero clear를 건너뛰었습니다". 각 위조 케이스는 전부 0인 read 결과를 기대값으로 둡니다. Clear가 생략되면 texture의 할당 직후 내용이 그대로 반환됩니다. Metal/IOGPU allocation이 할당 시 0으로 채워지지 않는다면, 그 내용은 이전 데이터입니다. 애초에 lazy-clear 설계가 존재하는 이유가 바로 이 전제입니다.

Primitive는 texture slice 단위로 동작합니다. device 최대 크기와 array layer 수까지 확장할 수 있고, 크기와 format은 attacker가 고를 수 있으며, 반복도 자유롭습니다. 다만 내용 자체는 제어할 수 없습니다. Write나 control-flow primitive는 아닙니다. pointer 또는 ASLR leak으로 쓰일 가능성도 고려할 수 있지만, 이는 픽셀이 아닌 GPU process 데이터가 같은 backing page를 공유한다는 조건이 성립해야 합니다. 제공된 context로는 이 조건이 확인되지 않습니다.

남은 확장 쟁점은 두 가지입니다. 하나는 texture allocation이 WebGPU device, origin, process 사이에서 공유되는 pool에서 오는지입니다. 다른 하나는 크기나 format 선택으로 재사용을 유도할 수 있는지입니다. 추적 로직은 GPU process에 있으며, 유출된 바이트는 buffer mapping을 통해 WebContent로 전달됩니다. Code execution이나 sandbox 제어 경계 침범은 수반되지 않습니다. 그러나 attacker context 바깥의 잔류 메모리가 노출된다면, 이는 data-isolation 경계를 넘는 셈입니다.

이 vulnerability는 메모리 격리 경계인 WebGPU resource zero-initialization 보장을 약화시킵니다. WebGPU는 web content가 새 texture를 뒷받침하는 GPU 메모리의 이전 내용을 절대 관찰할 수 없다고 가정합니다. 패치 이전에는 script가 실제 write 없이 "이미 clear됨" 상태를 위조할 수 있었습니다. 이후 mapAsync로 texture를 다시 읽으면, Metal allocation에 남아 있던 내용이 그대로 반환되었습니다. Allocator가 다른 페이지, origin, process의 렌더링 내용을 담았던 메모리를 재사용했다면, cross-origin 또는 cross-process 픽셀 데이터가 노출될 가능성이 있습니다.

Insight: 전형적인 optimistic-commit 결함입니다. 이번 fix에서 흥미로운 부분은 encoder 간 케이스입니다. encoder가 서로 교차하는 상황에서는 commit 시점에 정확히 승격하는 것만으로는 부족합니다. 그래서 queue는 아직 대기 중인 다른 encoder가 claim한 slice에 대해 catch-up clear를 내보내야 합니다. PresentationContextIOSurface hunk는 앞으로 MTLCommandQueue에 직접 commit하는 모든 코드가 지켜야 할 hook을 드러냅니다. preCommitHandler를 우회하는 경로가 생기면 같은 버그가 조용히 재발하기 때문입니다. 아래 [6]은 같은 주에 인접한 순서 실수로 동일한 보장이 깨진 사례입니다.