← All reports

[3] drawIndexedIndirect clamp verdict survives an index-buffer rewrite

HighWebGPU Metal backendOOB

WebGPU proved a draw safe once, then kept trusting the proof after the indices changed.

411a4c9

Severity는 High이며, 항상 동일하게 재현됩니다. "clamp를 건너뛰어도 안전하다"는 판정이 캐시되어 있었는데, 정작 그 판정의 근거가 된 buffer의 변경은 반영하지 않았습니다. 그 결과 script가 고른 index가 GPU에서 bound buffer 범위를 넘어선 vertex fetch로 이어집니다. 최대 영향은 read-only GPU memory 노출입니다. 실제 영향은 driver의 robustness 동작과 vertex buffer 주변에 어떤 데이터가 위치하는지에 따라 달라집니다.

Metal의 indexed draw는 index * stride 위치에서 per-vertex data를 bounds check 없이 fetch합니다. 그래서 WebGPU 구현체는 GPU가 실행되기 전에 index 값을 직접 검증해야 합니다. 한편 drawIndexedIndirect는 count와 offset이 CPU 호출 인자가 아니라 GPU 측 args buffer에 들어 있는 draw입니다. 이 경우 WebKit은 clamp pass를 실행해 index buffer를 스캔합니다. 범위를 벗어난 index가 하나라도 있으면 draw count를 0으로 만듭니다. 다만 이 pass에는 GPU 시간이 들기 때문에 판정 결과를 캐시합니다. 이때 전제는 판정이 읽은 입력 중 하나라도 바뀌면 캐시가 무효화되어야 한다는 것입니다.

관전 포인트: 페이지는 먼저 범위 안의 index로 draw를 한 번 검증받을 수 있습니다. 이후 index buffer만 다시 기록하면, 다음에 동일한 draw를 호출할 때 clamp가 생략됩니다. 결과적으로 script가 고른 index가 GPU의 vertex fetch를 범위 밖으로 끌고 갑니다.

Commit message(rdar://182324564)에 따르면, stale cache로 인해 drawIndexedIndirect가 GPU core에서 OOB read를 수행하게 됩니다.

LayoutTests/fast/webgpu/regression/draw-indexed-indirect-stale-clamp-after-index-write.html

+ // 24 bytes / arrayStride 8 => minVertexCount 3이므로, 3 이상의 index 값은 out of bounds입니다.
+ let vertexData = new Float32Array([-1, -3, -1, 1, 3, 1]);
+ let vertexBuffer = device.createBuffer({ size: vertexData.byteLength, usage: GPUBufferUsage.VERTEX | GPUBufferUsage.COPY_DST });
...
+ let indexBuffer = device.createBuffer({ size: 8, usage: GPUBufferUsage.INDEX | GPUBufferUsage.COPY_DST });
+ device.queue.writeBuffer(indexBuffer, 0, new Uint16Array([0, 1, 2, 0])); // 8 bytes: uint16 index buffer는 4 bytes보다 커야 합니다
...
+ // 한 번만 기록하고 다시는 기록하지 않습니다: 다시 기록하면 args buffer 자체의 캐시가 무효화되어 이 설정이 무력화됩니다.
+ let argsBuffer = device.createBuffer({ size: 20, usage: GPUBufferUsage.INDIRECT | GPUBufferUsage.COPY_DST });
+ device.queue.writeBuffer(argsBuffer, 0, new Uint32Array([3, 1, 0, 0, 0]));
...
+ pass.setIndexBuffer(indexBuffer, 'uint16');
+ pass.drawIndexedIndirect(argsBuffer, 0);
...
+ // Frame 0: index 0,1,2가 모두 minVertexCount 미만이므로 clamp pass가 실행되어 통과하고,
+ // indirectIndexedBufferRecomputed()가 argsBuffer에 판정을 캐시합니다.
+ let frame0 = await drawAndReadback();
+
+ // index buffer만 minVertexCount 이상의 값으로 다시 기록합니다. index buffer의 generation은 증가하지만,
+ // 판정이 저장된 argsBuffer에는 아무 변화가 없습니다.
+ device.queue.writeBuffer(indexBuffer, 0, new Uint16Array([3, 4, 5, 0]));
+
+ // Frame 1: pipeline, buffer, offset이 모두 동일합니다 - 기존 predicate가 비교하던 항목은 하나도 바뀌지 않았습니다.
+ // 그래도 clamp pass는 다시 실행되어 minVertexCount 이상의 index를 찾고 indexCount를 0으로 만들어야 하며, 화면은 clear 상태로 남아야 합니다.
+ let frame1 = await drawAndReadback();
...
+ shouldBeEqualToString('frame0.join()', '0,255,0,255');
+ shouldBeEqualToString('frame1.join()', '255,0,0,255');

Production 코드의 hunk는 이번 글에 포함하지 않았습니다. 대신 위 regression test에 결함의 형태가 드러납니다. Test 설명에는 관련 함수로 indirectIndexedBufferRequiresRecomputation()과 indirectIndexedBufferRecomputed()가 명시되어 있습니다.

먼저 test는 세 가지를 준비합니다. vertex 3개짜리 buffer(minVertexCount 3), 0,1,2,0을 담은 index buffer, 그리고 indexCount 3으로 한 번만 기록된 args buffer입니다. Frame 0에서 draw를 수행하면 통과 판정이 args buffer에 캐시됩니다. 이어서 index buffer만 3,4,5,0으로 다시 기록하고, 나머지 파라미터는 그대로 둔 채 다시 draw합니다. 이때 frame 1에서 기대하는 결과는 green(draw 실행)이 아니라 red clear입니다. Clamp가 다시 실행되어 indexCount를 0으로 만들었다는 의미입니다.

이번 fix로 캐시된 판정이 index buffer 내용 변경을 반영하도록 수정되었습니다. Buffer.h에는 buffer별 m_indexContentsGeneration이 선언되어 있고, indexBufferContentsModified(...)가 호출될 때 증가합니다. 이 값이 새로운 invalidation key로 쓰였을 가능성이 존재합니다. 다만 정확한 동작 방식은 여기서 확정되지 않습니다.

한 객체에 캐시되어 있지만 실제로는 다른 객체의 mutable 내용에서 도출되고, 그 내용이 invalidation key에서 빠져 있는 memoized validation 판정.

Indexed draw. drawIndexed/drawIndexedIndirect는 index buffer에서 uint16 또는 uint32 index 목록을 읽습니다. 각 index는 어떤 vertex의 attribute를 fetch할지 지정합니다. Fetch 위치는 vertex-step-mode인 각 vertex buffer 안에서 index * arrayStride로 계산됩니다.

Indirect draw. drawIndexedIndirect(argsBuffer, offset)는 indexCount, instanceCount, firstIndex, baseVertex, firstInstance를 GPU buffer에서 읽습니다. 이 buffer는 MTLDrawIndexedPrimitivesIndirectArguments layout을 따릅니다. 따라서 encode 시점의 CPU는 이 값들을 알 수 없습니다.

minVertexCount와 robust access. minVertexCount는 bound된 vertex-step-mode buffer들이 제공할 수 있는 vertex 수 중 가장 작은 값입니다. 각 buffer 크기를 arrayStride로 나눈 값을 기준으로 합니다. 이 값 이상의 index는 존재하지 않는 vertex를 가리킵니다. WebGPU는 범위를 벗어난 접근이 bound resource 바깥을 절대 읽지 않도록 요구합니다. 그러나 Metal의 indexed fetch는 이를 보장하지 않습니다. 그래서 WebKit backend가 직접 검증을 수행하며, indirect indexed draw에서는 clamp pass가 그 역할을 담당합니다.

Validation 캐싱. Buffer는 특정 draw 구성이 이미 안전하다고 입증되었음을 기록하는 캐시를 유지합니다. 덕분에 이후 동일한 draw는 validation을 건너뛸 수 있습니다. Indirect-indexed 판정은 indirectIndexedBufferRecomputed / indirectIndexedBufferRequiresRecomputation이 관리합니다. 한편 Buffer.h는 write마다 증가하는 index content generation(m_indexContentsGeneration)도 추적합니다. 여기에 더해 지금까지 기록된 index 값의 monotone upper bound(m_indexValueUpperBoundUint / m_indexValueUpperBoundUshort)도 유지합니다.

Cache key가 불완전해서 validation 캐시가 stale 상태로 남는 버그입니다. 그 결과로 GPU에서 out-of-bounds read가 발생합니다.

  Before:                                After:
  frame 0: clamp pass, 0,1,2 < 3         frame 0: clamp pass, verdict cached
    verdict cached on argsBuffer
  writeBuffer(indexBuffer, 3,4,5)        writeBuffer(indexBuffer, 3,4,5)
    argsBuffer untouched                   index-content change observed
  frame 1: predicate compares            frame 1: verdict invalid
    offset, minVertexCount, ... ==          └─► clamp pass re-runs
    └─► clamp skipped                            └─► indexCount = 0
         └─► fetch vertex[3..5]  OOB                  └─► red clear, no draw

판정은 두 buffer에 의존하는 함수입니다. 그런데 왼쪽 열의 predicate는 args buffer 쪽 항목만 비교했습니다. Test 설명에 따르면 비교 대상은 indirectOffset, minVertexCount, minInstanceCount, indexType, indexBufferOffsetInBytes, drawType입니다. writeBuffer 단계에서는 index buffer의 generation만 증가하고 args buffer는 그대로 남습니다. 그래서 frame 1의 비교도 여전히 일치하고, 새 index 값은 한 번도 bounds check를 거치지 않습니다. Test 설명은 "no high-water-mark trick is needed"라고 강조합니다. 즉 monotone upper-bound 추적과 무관하게, args buffer의 판정은 애초에 index buffer write를 전혀 관찰하지 못했다는 의미입니다.

Test는 fetch된 attribute 값에 의존하지 않고 결과를 관찰할 수 있도록 구성되어 있습니다. 이를 위해 @builtin(vertex_index)를 사용하고, frame마다 pixel 하나를 readback합니다. 이를 통해 stale 판정이 남아 있으면 draw가 "skip the clamp, draw green, and fetch vertex attributes past the end of the 3-vertex buffer"하게 된다는 점이 드러납니다. 도달 조건도 단순합니다. 변경되지 않은 args buffer를 공유하는 평범한 drawIndexedIndirect 호출 두 번과, 그 사이에 끼워 넣은 index buffer writeBuffer 하나면 충분합니다. Clamp 생략 역시 항상 동일하게 재현됩니다.

얻을 수 있는 primitive는 vertex buffer base 기준의 GPU 측 out-of-bounds read입니다. Offset은 script가 고른 index에 arrayStride를 곱한 값이며, 최대 범위는 uint16에서 65535 * arrayStride, uint32에서 2^32 * arrayStride입니다. 생략된 pass가 보호하는 대상은 index 기반 vertex fetch뿐이므로, read-only primitive에 해당합니다.

다만 실제 out-of-bounds memory read로 이어지는지는 하나의 가정에 기대고 있습니다. Metal driver나 hardware가 자체 robustness로 fetch를 0으로 만들거나 clamp하지 않는다는 가정입니다. 여기에 fetch된 값이 readable render target으로 흘러가는 경우를 생각할 수 있습니다. WebGPU API에서는 이런 구성이 어렵지 않습니다. 인접 메모리에 다른 context의 데이터까지 있다면, attribute format과 draw count로 범위가 제한되는 GPU memory 노출로 이어질 가능성이 있습니다. 한편 encoding은 GPU process에서 이루어지지만 실제 접근은 shader core에서 실행됩니다. 따라서 이 버그 단독으로는 code execution이나 sandbox escape로 이어지지 않습니다.

WebGPU의 security model은 web content가 발행한 어떤 draw도 shader core가 bound buffer 바깥을 읽게 만들 수 없다고 가정합니다. WebKit은 이 가정을 clamp pass로 강제합니다. 그런데 fix 이전에는 script가 고른 index가 vertex buffer 끝을 넘어선 vertex fetch로 이어졌습니다. 결과적으로 이 vulnerability는 WebGPU의 robustness 경계를 약화시킵니다. 이 read가 다른 GPU allocation에 닿고, 그 값이 copyTextureToBuffer나 mapAsync로 읽을 수 있는 출력으로 흘러간다고 가정할 수 있습니다. 이 경우 web content에서 도달 가능한 GPU memory information disclosure로 이어질 가능성이 있습니다. Cross-origin 데이터까지 닿을 수 있는지는 GPU memory layout에 달려 있습니다.

Insight: Buffer.h에는 이미 두 종류의 index content 추적이 존재합니다. 하나는 write마다 바뀌는 generation이고, 다른 하나는 monotone high-water mark입니다. Generation은 모든 write에서 변하므로, 정확한 내용에 의존하는 캐시된 증명이라면 이 값을 invalidation key로 쓰는 것이 올바릅니다. 반면 upper bound는 최댓값에만 의존하는 증명에서만 안전합니다. 이 파일에서 monotone bound를 key로 쓰는 캐시가 있다면 같은 수준의 점검이 필요합니다. 내용을 읽은 buffer와 다른 buffer에 저장된 캐시도 마찬가지입니다. 이번 주 appendix에는 같은 캐시 계열의 sibling 세 건(cb21dfb, fb81a00, 45270f2)이 함께 실려 있습니다.