← All reports

[1] WGSL `__ArrayLength` slots assigned in declaration order swap buffer bounds

HighWebGPU WGSL compilerOOB

Two WebGPU layouts looked identical. They disagreed on which buffer was which size.

a2572ee

High. 한 storage buffer의 bound를 인접한 다른 buffer의 length word에서 가져왔습니다. 그 결과 script가 16바이트 allocation 너머로 향하는 write의 index와 값을 모두 지정할 수 있었습니다. 영향 범위는 GPU-visible memory 안에 머뭅니다. CPU 측 compromise로 확장하려면 별도의 isolation 실패가 필요하며, 이번 변경만으로는 그런 실패가 입증되지 않습니다.

Shader compiler와 host 측 resource layout 코드는 암묵적인 binary layout에 대해 정확히 같은 이해를 공유해야 합니다. 어느 slot에 buffer 크기가 들어 있는지를 두고 양쪽이 어긋나면, bounds check는 엉뚱한 buffer를 기준으로 수행됩니다. WebKit의 WGSL compiler는 WebGPU shading language를 Metal로 변환하는 translator입니다. 이 compiler는 각 bind group을 argument buffer로 묶습니다. Argument buffer는 pointer와 metadata를 숫자 index에 배치한 struct입니다. 또한 runtime-sized array마다 숨겨진 __<name>_ArrayLength word가 추가됩니다. 이 word에는 buffer별 크기가 담기며, arrayLength()와 runtime array의 bounds 처리가 이 값에 의존합니다. 이때 전제는 script에서 동일해 보이는 두 bind-group layout이라면 숨겨진 word도 같은 위치에 놓인다는 점입니다.

관전 포인트: WebGPU를 사용하는 페이지는 작은 storage buffer의 bound가 더 큰 sibling buffer의 length로 잡히도록 만들 수 있습니다. 이 상태에서 GPU process의 GPU-visible memory 안에서 해당 buffer 너머로 read/write를 수행할 수 있습니다. Index와 값은 모두 script가 지정합니다.

Commit message는 간결합니다. 충돌을 피하기 위해 buffer length를 id 기준으로 정렬한다는 내용뿐입니다(rdar://185201177, webkit.org/b/323234). Regression test는 Metal shader validation을 켠 상태로 실행됩니다.

Source/WebGPU/WGSL/GlobalVariableRewriter.cpp

std::optional<Error> RewriteGlobalVariables::collectGlobals()
{
- Vector<std::tuple<AST::Variable*, unsigned>> bufferLengths;
+ Vector<std::tuple<AST::Variable*, unsigned, unsigned>> bufferLengths;
...
packResource(*globalVar);
 
- bufferLengths.append({ globalVar, resource->group });
+ bufferLengths.append({ globalVar, resource->group, resource->binding });
}
}
 
for (auto& [_, vector] : m_groupBindingMap)
std::ranges::sort(vector, { }, &std::pair<unsigned, String>::first);
 
+ // 충돌을 피하기 위해 buffer length를 id 기준으로 정렬
+ std::ranges::sort(bufferLengths, { }, [](const auto& bufferLength) {
+ return std::pair { std::get<1>(bufferLength), std::get<2>(bufferLength) };
+ });
+
if (!bufferLengths.isEmpty()) {
- for (const auto& [variable, group] : bufferLengths) {
+ for (const auto& [variable, group, webBinding] : bufferLengths) {
auto name = AST::Identifier::make(makeString("__"_s, variable->name(), "_ArrayLength"_s));
...

LayoutTests/fast/webgpu/regression/repro_185201177.html

+@group(0) @binding(0) var<storage, read_write> a0 : array<u32>;
+@group(0) @binding(1) var<storage, read_write> a1 : array<u32>;
+@group(1) @binding(1) var<storage, read_write> b1 : array<u32>;
+@group(1) @binding(0) var<storage, read_write> b0 : array<u32>;
...
+ b1[a1[0]] = a1[1];
...
+ // group 0의 layout으로 encode한 bind group을 group index 1에 설정합니다. 두 layout 모두
+ // 같은 pipeline이 자동 생성했으며 entry도 동일합니다 ...
+ const crossBindGroup = device.createBindGroup({
+ layout: pipeline.getBindGroupLayout(0),
+ entries: [
+ { binding: 0, resource: { buffer: large } },
+ { binding: 1, resource: { buffer: small } },

RewriteGlobalVariables::collectGlobals()에는 세 가지 변경이 적용되었습니다. 먼저 bufferLengths tuple이 (variable, group)에서 (variable, group, binding)으로 확장되었습니다. 이를 위해 resource->binding도 함께 기록하도록 수정되었습니다. 다음으로 bufferLengths를 std::pair { group, binding } 기준으로 정렬하는 std::ranges::sort가 새로 추가되었습니다. 위치는 기존 m_groupBindingMap의 group별 정렬 바로 뒤입니다. 마지막으로 runtime-sized buffer마다 __<name>_ArrayLength 변수를 하나씩 생성하는 emission loop가 변경되었습니다. 이 loop의 structured binding은 [variable, group, webBinding]으로 수정되었습니다.

결과적으로 숨겨진 length 변수는 이제 module-scope source 순서가 아니라 (group, @binding) 순서로 생성됩니다. Regression test는 group 1의 binding을 역순으로 선언합니다. 그리고 group 0용 bind group을 index 1에 binding합니다.

숨겨진 bounds metadata의 slot이 source 선언 순서대로 할당되었습니다. 그래서 visible entry가 같은 layout끼리도 어느 slot에 어느 buffer의 length가 있는지가 달라질 수 있습니다.

WGSL resource. WGSL resource는 @group(N) @binding(M)이 붙은 module-scope 변수입니다. Runtime-sized array(길이가 지정되지 않은 array<T>)는 buffer가 bind된 뒤에야 크기가 정해집니다. 이 크기는 arrayLength(&x)가 실행 시점에 반환합니다. WebKit compiler는 buffer마다 __<var>_ArrayLength라는 숨겨진 word를 생성합니다. 생성된 shader code는 크기가 필요할 때마다 이 값을 읽습니다.

Metal의 argument buffer. 각 WebGPU bind group은 Metal argument buffer로 변환됩니다. Argument buffer는 pointer, texture, sampler, 그리고 합성된 length word를 각각 숫자 index에 배치한 struct입니다. Host 측 BindGroup은 자신의 BindGroupLayout에 따라 이 index들에 값을 encode합니다. 이때 BindGroupLayout.mm의 BufferBindingType::ArrayLength entry가 length word에 대응하는 host 측 항목입니다.

Auto layout과 layout 재사용. layout: 'auto'를 사용하면 pipeline은 compiler reflection을 통해 shader에서 각 group의 BindGroupLayout을 도출합니다. 한편 WebGPU는 한 layout으로 생성한 bind group을 entry가 동등한 다른 layout에서도 사용할 수 있도록 허용합니다. 그래서 같은 layout 정의가 여러 group slot에 쓰일 수 있습니다.

collectGlobals. RewriteGlobalVariables::collectGlobals는 이 pass의 진입점입니다. Module의 선언을 순회하면서 각 resource의 group과 binding을 m_groupBindingMap에 기록합니다. 이어서 resource type을 pack하고, 합성 length 변수를 생성합니다. 이 과정은 pipeline 생성 시점에 GPU process에서 실행됩니다.

원인은 check 누락이 아닙니다. Slot 할당이 어긋나면서 GPU device memory에서 OOB read/write가 발생하는 문제입니다.

  Group 0 source order           Group 1 source order
  @binding(0) a0                 @binding(1) b1
  @binding(1) a1                 @binding(0) b0
  len slots: [a0, a1]            len slots: [b1, b0]

  crossBindGroup (group 0 layout) set at index 1:
    slot 0 = len(large, 1 MiB)  ──►  shader reads as len(b1)
    slot 1 = len(small, 16 B)   ──►  shader reads as len(b0)
  b1 is the 16-byte buffer, bounded by 1 MiB
    └─► b1[a1[0] = 0x800] = a1[1]   write lands past the allocation

패치 이전의 collectGlobals는 선언이 등장한 순서대로 bufferLengths에 append했고, 이후 정렬하지 않았습니다. 반면 m_groupBindingMap의 user-visible entry는 @binding 기준으로 정렬되어 있었습니다. 이 순서 의존성은 두 가지 정황에서 도출됩니다. 하나는 fix가 이 vector의 순서만 바꿨다는 점입니다. 다른 하나는 test가 slot이 "chosen by @binding, not by declaration order"라고 설명한다는 점입니다. 다만 vector 순서가 argument buffer의 member index로 바뀌는 정확한 emission 단계는 직접 입증되지 않았습니다. 이 연결 고리 하나만큼은 추론에 해당합니다.

각 auto layout은 자기 group의 선언 순서와는 내부적으로 일관될 것으로 보입니다. Test의 positive control(group 1을 getBindGroupLayout(1)로 bind한 경우)이 정상 동작하는 이유도 이것으로 설명될 수 있습니다. 즉 깨진 invariant는 그보다 좁습니다. Visible {binding, visibility, type} entry가 동일한 두 auto layout이라도, length word를 서로 다른 index에 배치할 가능성이 있습니다. 위 diagram에서 group 0은 binding 0의 length를 먼저 두고, group 1은 binding 1의 length를 먼저 둡니다. 그래서 group 0용 bind group이 index 1에서 허용되면, b1에는 1 MiB buffer의 element count가 전달됩니다.

유발 조건은 전부 web content에서 도달 가능합니다. 필요한 요소는 세 가지입니다. 한 group의 선언 순서를 뒤집은 WGSL module, layout: 'auto' pipeline, 그리고 한 group의 layout으로 만든 bind group을 다른 index에 재사용하는 구성입니다. Test는 binding 0에 1 MiB buffer를, binding 1에 16바이트 buffer를 배치합니다. 이 경우 a1[0]에서 읽은 index 0x800은 shader가 인식하는 bound 안에 들어갑니다. Test 주석에 따르면 store는 작은 allocation을 약 8192바이트 지난 위치에 기록됩니다.

같은 swap으로 read도 통과하며, arrayLength() 역시 다른 binding의 크기를 보고합니다. Host 측 compatibility check가 cross-group bind group을 허용했는지는 이 check가 숨겨진 argument buffer index까지 비교하는지에 달려 있습니다. Test는 거부를 안전한 결과로 취급합니다. 결국 write가 성립하려면 bind group이 허용된다는 조건이 전제되어야 합니다.

Primitive는 attacker가 고른 buffer의 base를 기준으로 GPU device memory에서 동작합니다. Index와 값은 attacker가 지정하며, 범위는 swap된 sibling buffer의 length로 제한됩니다. 남은 확장 경로의 쟁점은 작은 storage buffer 너머에 무엇이 놓이는가입니다. 다른 WebGPU device의 buffer나 texture일 수도 있고, 내부 staging buffer나 indirect-argument buffer일 수도 있습니다.

이들을 attacker가 크기를 정한 buffer 근처에 안정적으로 배치할 수 있다고 가정해 볼 수 있습니다. 이 경우 해당 객체에 대한 data corruption 또는 disclosure primitive로 이어질 가능성이 있습니다. 반면 CPU 측 GPU process state까지 도달하려면 Metal의 GPU address-space isolation과 unified-memory mapping이 관건이 됩니다. 제공된 context로는 이 부분이 확인되지 않습니다. Shader는 GPU process를 대신해 실행되며, 이 버그만으로는 CPU code execution이나 sandbox 밖으로 나가는 경로가 드러나지 않습니다.

이 vulnerability는 WebGPU의 memory-safety 경계를 약화시킵니다. WebKit은 이 경계를 shader compiler에서 강제합니다. WebGPU는 storage buffer에 대한 모든 shader 접근이 해당 buffer의 bound 범위 안에 머물도록 요구합니다. Runtime-sized array의 경우, binding별 __ArrayLength word가 이 제한을 구현하는 수단 중 하나입니다.

패치 이전에는 web content가 한 buffer의 접근 범위를 다른 buffer의 length로 제한되도록 조작할 수 있었습니다. 그 결과 attacker가 index와 값을 지정한 read/write를 작은 storage buffer 너머로 수행할 수 있었습니다. 이를 통해 GPU process가 소유한 다른 GPU 상주 resource를 손상시키거나 노출시킬 가능성이 있습니다.

Insight: Metal 위에서 WebGPU의 안전성은 compiler와 host 측 layout 코드가 암묵적인 ABI에 정확히 합의하는지에 달려 있습니다. 어느 index에 어느 pointer와 어느 length가 놓이는지가 바로 그 ABI입니다. 각 auto layout 자체는 일관되어 있었습니다. 문제는 겉보기에 동일한 layout이 기대되는 자리에 다른 layout의 encoding이 사용될 때에만 드러났습니다. Fix는 숨겨진 slot에 canonical한 (group, binding) 순서를 부여해 이 의존성을 제거했습니다. 일반 규칙으로 정리하면, binding별 숨겨진 metadata는 (group, binding)의 순수 함수이거나 layout-compatibility key의 일부여야 합니다.