← All reports

[6] WebGPU `Queue::writeTexture` marks slices cleared before the write is emitted

MediumWebGPU Metal backendUninitializedMemory

4d2ad87

전형적인 Medium 사례입니다. [5]와 같은 zero-init 보장이 이번에는 다른 형태의 순서 실수로 깨졌습니다. upload가 slice 전체를 덮을 것이라는 예측만으로 flag가 설정되었고, 이후 unaligned offset 때문에 upload 자체가 생략되었습니다. 영향의 상한은 stale texture slice 하나입니다. 다른 context로까지 영향이 미치는지는 IOSurface와 Metal pool의 재사용 방식에 달려 있습니다.

Lazy zero-initialization이 성립하려면 "이미 초기화됨" 상태 기록이 반드시 초기화 write 이후에 갱신되어야 합니다. 그보다 먼저 갱신되어서는 안 됩니다. WebKit의 WebGPU backend에서 Queue::writeTexture는 GPUQueue.writeTexture의 GPU process 측 구현으로, CPU의 byte를 texture로 upload하는 역할을 맡습니다. 이 함수는 writeWillCompletelyClear를 참조해 별도의 zero-fill을 생략할지 결정합니다. writeWillCompletelyClear는 upload가 slice 전체를 덮는지 판단하는 predicate입니다. 이때 zero-fill 여부를 결정하는 slice별 cleared flag는 실제로 write가 끝난 메모리만을 나타내야 합니다.

관전 포인트: writeTexture 파라미터를 제어할 수 있다면, upload는 생략된 채 slice만 초기화된 것으로 표시되게 만들 수 있습니다. 이후 해당 slice에 남아 있던 stale backing store byte를 mappable buffer로 복사해 올 수 있습니다.

commit message(rdar://187344513)에 따르면, setPreviouslyCleared 호출은 validation이 끝날 때까지 미뤄지도록 변경되었습니다. 그렇지 않으면 이전 allocation의 내용이 유출될 수 있기 때문입니다.

Source/WebGPU/WebGPU/Queue.mm

bool clearWasNeeded = false;
+ const bool writeCompletelyClearsSlice = writeWillCompletelyClear(textureDimension, widthForMetal, logicalSize.width, heightForMetal, logicalSize.height, depthForMetal, logicalSize.depthOrArrayLayers);
+ auto markSliceAsCleared = [&](NSUInteger destinationSlice) {
+ if (writeCompletelyClearsSlice)
+ texture->setPreviouslyCleared(destination.mipLevel, destinationSlice);
+ };
for (uint32_t layer = 0; layer < sliceCount; ++layer) {
...
- if (!texture->previouslyCleared(destination.mipLevel, destinationSlice)) {
- if (writeWillCompletelyClear(textureDimension, widthForMetal, logicalSize.width, heightForMetal, logicalSize.height, depthForMetal, logicalSize.depthOrArrayLayers))
- texture->setPreviouslyCleared(destination.mipLevel, destinationSlice);
- else {
- clearWasNeeded = true;
- clearTextureIfNeeded(destination, destinationSlice);
- }
+ if (!texture->previouslyCleared(destination.mipLevel, destinationSlice) && !writeCompletelyClearsSlice) {
+ clearWasNeeded = true;
+ clearTextureIfNeeded(destination, destinationSlice);
}
}
...
withBytes:byteCast<char>(data.subspan(sourceOffset).data())
bytesPerRow:bytesPerRow
bytesPerImage:0];
+ markSliceAsCleared(destinationSlice);
...
destinationOrigin:destinationOrigin
options:options];
+ markSliceAsCleared(destinationSlice);

Source/WebGPU/WebGPU/CommandEncoder.mm

if (texture.usage().contains(WebGPU::TextureUsage::Transient))
return;
- texture.setPreviouslyCleared(mipLevel, slice);
auto logicalExtent = texture.logicalMiplevelSpecificTextureExtent(mipLevel);
if (!logicalExtent.width)
return;
...
if (slice >= mtlTexture.arrayLength)
return;
+ texture.setPreviouslyCleared(mipLevel, slice);
[blitCommandEncoder
copyFromBuffer:temporaryBuffer
...

LayoutTests/ipc/webgpu-write-texture-unaligned-offset-marks-slice-cleared.html

+ // dataLayout.offset = 2는 writeTexture에서 허용되는 값입니다 ... slice를 cleared로 기록한 뒤 write를 건너뛰면
+ // copyTextureToBuffer()가 lazy zero-clear를 생략하게 되어 poison이 노출됩니다.
+ writeTextureWithCopy(wholeTexture(texture), new Uint8Array(2 + IMAGE_SIZE).fill(WRITE), wholeImage(2), extent3D(SIZE, SIZE, 1));

Queue::writeTexture는 이제 writeCompletelyClearsSlice를 한 번만 계산합니다. 또한 이 값이 true일 때만 flag를 설정하는 markSliceAsCleared lambda가 추가되었습니다. 한편 slice별 사전 loop에서는 더 이상 flag를 설정하지 않고, lazy clearTextureIfNeeded가 필요한지만 판단합니다(!previouslyCleared && !writeCompletelyClearsSlice).

실제로 write를 발행하는 모든 지점 뒤에는 markSliceAsCleared(destinationSlice) 또는 markSliceAsCleared(0) 호출이 추가되었습니다. 1D, 2D, 3D에 대한 CPU 측 -replaceRegion:...withBytes: 호출과 blit encoder의 copyFromBuffer:... 호출이 여기에 해당합니다. 결과적으로 write를 실제로 수행한 code path만 slice를 cleared로 표시하게 되었습니다.

CommandEncoder::clearTextureIfNeeded에서도 setPreviouslyCleared의 위치가 변경되었습니다. 기존에는 함수 맨 앞, 즉 logicalExtent.width 검사를 비롯한 early return보다 앞에 있었습니다. 수정 후에는 zero-fill을 수행하는 copyFromBuffer:temporaryBuffer 직전으로 이동했습니다. CommandEncoder.swift의 Swift 구현에도 같은 변경이 적용되었습니다. 이와 함께 unaligned offset을 담은 조작된 RemoteQueue::WriteTextureWithCopy message를 전송하는 IPC layout test가 새로 추가되었고, GLib용 skip expectation도 함께 들어갔습니다.

보증 대상인 side effect가 일어나기 전에 "initialized" flag를 먼저 확정해, 이후 bail-out 시 한 번도 write되지 않은 메모리 위에 flag만 남는 패턴.

WebGPU의 lazy zero-initialization. WebGPU spec은 texture와 buffer가 처음 사용될 때 0으로 채워진 상태로 보이도록 요구합니다. 실제 GPU 메모리가 재사용된 것이더라도 마찬가지입니다. 그래서 구현체는 보통 allocation 시점에 바로 clear하지 않고, 실제로 필요해지는 시점까지 clear를 미룹니다.

previouslyCleared(mipLevel, slice). Metal backend가 subresource별로 유지하는 bit로, 특정 (mip level, array slice)에 정의된 내용이 들어 있는지를 기록합니다. 이 값이 false이면 CommandEncoder::clearTextureIfNeeded가 개입합니다. 해당 slice를 읽거나 부분적으로 write하기 전에, 0으로 채운 임시 buffer로부터 slice로 향하는 blit을 encode합니다.

writeWillCompletelyClear. upload가 slice의 logical extent 전체를 덮는지 판단합니다. 전체를 덮는다면 write 자체가 모든 texel을 초기화하므로 별도의 clear가 불필요해집니다.

Queue::writeTexture 경로. GPUQueue.writeTexture를 구현하며, 여러 encoding 경로를 갖고 있습니다. queue가 idle 상태일 때는 CPU 측 -[MTLTexture replaceRegion:...withBytes:] 경로를 사용합니다. 그 외의 경우에는 staging을 거친 blit encoder의 copyFromBuffer: 경로로 처리됩니다. 각 경로는 다시 texture dimension(1D, 2D, 3D)별로 나뉩니다.

Presentation context texture. GPUCanvasContext.getCurrentTexture()는 frame 사이에서 재활용되는 IOSurface 기반 texture를 반환합니다. regression test의 주석에 따르면, PresentationContextIOSurface::getCurrentTexture()는 texture를 획득할 때마다 cleared bit를 초기화합니다. 재활용된 내용이 다시 clear되도록 하기 위해서입니다. 즉 이전 frame의 pixel이 페이지로 그대로 전달되지 않도록 막는 WebGPU의 방어 장치에 해당합니다.

Process 모델. WebGPU 명령은 WebContent에서 IPC(RemoteQueue, RemoteCommandEncoder 등)를 통해 직렬화된 뒤 GPU process에서 실행됩니다.

상태를 추적하는 순서가 잘못되어, 초기화되지 않은 메모리가 노출되는 uninitialized memory disclosure입니다.

  Before:                                After:
  writeTexture(offset = 2)               writeTexture(offset = 2)
    pre-loop: full coverage?               pre-loop: full coverage?
      └─► setPreviouslyCleared(slice)        └─► no flag, no clear yet
    replaceRegion path                     replaceRegion path
      └─► unaligned offset: write skipped    └─► unaligned offset: write skipped
                                             └─► markSliceAsCleared not reached
  copyTextureToBuffer()                  copyTextureToBuffer()
    └─► flag set: skip zero-fill           └─► flag unset: zero-fill
         └─► stale bytes into buffer            └─► zeros into buffer

왼쪽 열에서 writeWillCompletelyClear는 "이 write가 slice 전체를 초기화할 것"이라는 판단의 대리 지표로 쓰였습니다. 이 예측만으로 flag가 확정되었고, lazy clear도 함께 생략되었습니다. 문제는 그 다음입니다. test 주석에 따르면, idle queue의 replaceRegion 경로가 dataLayout.offset 값 2에 대해 write를 건너뛰었습니다. offset 2는 writeTexture에서 허용되는 값이지만, texel block 크기의 배수는 아닙니다. commit message는 이를 bit가 설정된 시점에 validation이 아직 끝나지 않았던 문제로 설명합니다. 결과적으로 해당 slice는 이전 내용을 그대로 담은 채 initialized로 표시되었고, zero-fill은 한 번도 수행되지 않았습니다.

clearTextureIfNeeded의 C++ 구현과 Swift 구현에도 같은 형태의 문제가 있었습니다. bit가 !logicalExtent.width, slice >= mtlTexture.arrayLength 같은 early return보다 먼저 설정되었기 때문입니다. 그래서 중간에 bail-out된 clear도 slice를 cleared로 기록했습니다. 반면 오른쪽 열에서는 모든 상태 확정 지점이 실제 write를 발행하는 호출 바로 뒤로 옮겨졌습니다. 따라서 어떤 bail-out이 발생하더라도 flag는 변경되지 않습니다.

test는 재활용된 IOSurface 기반의 presentation context texture를 사용합니다. 해당 주석에 따르면 PresentationContextIOSurface::getCurrentTexture()는 획득할 때마다 previouslyCleared()를 false로 초기화합니다. stale content를 다시 clear하기 위한 장치인데, 이 버그는 정확히 그 초기화를 무력화했습니다. readback 경로는 copyTextureToBuffer입니다. test는 flag가 설정된 이후 이 경로가 zero-fill을 생략하는 상황을 재현하고, 앞서 write한 "poison"이 노출되지 않는지를 검증합니다.

결과적으로 attacker가 안정적으로 유발할 수 있는 uninitialized texture memory read가 성립합니다. 범위는 attacker 자신의 texture 중 mip/slice 하나로 한정된 info leak이며, 데이터는 mappable buffer를 통해 반환됩니다. write primitive는 없고, texture를 뒷받침하는 메모리를 attacker가 선택할 수도 없습니다.

regression test가 읽어 오는 byte는 같은 페이지가 앞서 write한 것뿐입니다. 경계를 넘는 leak이 성립하려면 추가 조건이 필요합니다. PresentationContextIOSurface 뒤의 IOSurface pool이나 일반 texture 뒤의 Metal heap이, 다른 context·origin·process가 마지막으로 소유했던 메모리를 페이지에 할당해야 합니다. 즉 pool의 재사용 범위가 영향의 상한을 결정합니다. 버그 자체는 GPU process에 있지만, 데이터는 WebContent 측 호출자에게 반환됩니다. sandbox를 넘지 않으며, GPU process에서 code execution으로 이어지지도 않습니다.

이 vulnerability는 WebGPU의 resource initialization 보장을 약화시키는데, 해당 보장은 메모리 기밀성 경계에 해당합니다. WebGPU는 어떤 resource도 이전 allocation이 남긴 내용을 노출해서는 안 된다고 요구합니다. 이 구현은 slice별 previouslyCleared bit로 그 요구 사항을 강제합니다. fix 이전에는 writeTexture 파라미터를 제어하는 attacker가 slice를 cleared로 표시된 채 write되지 않은 상태로 남길 수 있었습니다. 이후 copyTextureToBuffer로 다시 읽어 backing memory에 남아 있던 내용을 노출시키는 것이 가능했습니다. commit message에 따르면 그 내용은 이전 allocation의 데이터입니다.

Takeaway: "initialized" bit는 초기화를 실제로 수행한 호출 바로 뒤에 설정해야 합니다. 초기화를 예측한 predicate를 근거로 설정해서는 안 됩니다. 또한 같은 함수가 .mm과 .swift 양쪽에 존재한다면, 두 곳 모두에서 순서를 바로잡아야 합니다.