← All reports

[2] Follow-up: ShareableBitmap context retains a pattern reference into another backend's ImageBuffer

MediumWebKit GPU ProcessRace

739ed31

Medium 등급입니다. 유발하려면 이미 장악된 web-content process가 필요합니다. 그 결과 얻을 수 있는 것은 platform drawing context에 대한 cross-thread race입니다. 다만 이 window에서 실제 memory corruption으로 가는 경로는 platform graphics 코드를 거칩니다. 해당 코드의 동작은 이 글에서 다루지 않습니다. 이번 commit의 hunk 자체는 test의 import 경로만 수정합니다.

Drawing state는 다른 drawing surface에 대한 strong reference를 가질 수 있습니다. 그래서 surface의 소유자를 옮길 때는 surface 자체만 볼 수 없습니다. 그 surface가 가리키는 모든 대상까지 함께 따져봐야 합니다. WebKit GPU process에서 fill brush는 Pattern일 수 있습니다. Pattern은 이미지를 반복해서 채우는 fill이며, 원본을 SourceImage에 보관합니다. SourceImage는 decode된 이미지, resource identifier, 다른 drawable surface에 대한 strong reference 중 하나를 담는 variant입니다. 한편 RemoteRenderingBackend는 client별 drawing service로, 각자 전용 work-queue thread에서 동작합니다. 각 backend는 자신이 넘기는 surface가 self-contained 상태라고 가정합니다. 즉 자신의 thread만 접근할 수 있는 resource로 되돌아가는 live reference가 남아 있지 않아야 합니다.

관전 포인트: 장악된 web-content process는 fill brush를 숨겨진 strong reference로 활용할 수 있습니다. 이 경우 다른 backend로 넘겨진 surface가 원래 backend의 live drawing target에 두 번째 thread에서 계속 접근하게 됩니다.

Follow-up: SerializedImageBuffer still leaks cross-RemoteRenderingBackend data through GraphicsContext for unaccelerated buffers

Unreviewed follow-up fix to apply RC_REMOVE_SEC_ACCEL_3 macro.

LayoutTests/ipc/set-fill-pattern-image-buffer-cross-backend-race-unaccelerated.html

- CoreIPC = (await import('./coreipc.js')).CoreIPC;
+ CoreIPC = (await import('../../ipc/coreipc.js')).CoreIPC;

아래는 이 test가 검증하는 보안 관련 코드를 WebKit tree의 패치 이후 상태 그대로 옮긴 것입니다. 변경 표시는 붙이지 않았습니다.

Source/WebKit/GPUProcess/graphics/RemoteRenderingBackend.cpp

Ref imageBuffer = RemoteImageBuffer::sinkIntoImageBuffer(remoteImageBuffer.releaseNonNull());
MESSAGE_CHECK(imageBuffer->hasOneRef(), "ImageBuffer in use");
// context를 해제해 context를 통한 cross-RemoteRenderingBackend state 유출을 방지합니다.
imageBuffer->releaseGraphicsContext();
// ... (DisplayList item 관련 FIXME와 'A backend that cannot release its context...' 주석은 생략)
MESSAGE_CHECK(!imageBuffer->hasGraphicsContext() || imageBuffer->renderingMode() == RenderingMode::DisplayList, "ImageBuffer cannot release its GraphicsContext");
bool success = m_sharedResourceCache->addSerializedImageBuffer(serializedIdentifier, WTF::move(imageBuffer));

Source/WebKit/WebProcess/GPU/graphics/ImageBufferShareableBitmapBackend.cpp

GraphicsContext& ImageBufferShareableBitmapBackend::context()
{
if (!m_context) {
auto context = m_bitmap->createGraphicsContext();
RELEASE_ASSERT(context);
adoptGraphicsContext(WTF::move(context));
}
return *m_context;
}
void ImageBufferShareableBitmapBackend::releaseGraphicsContext()
{
m_context = nullptr;
}

이 commit의 유일한 hunk는 regression test를 직접 수정합니다. coreipc.js의 import 경로가 ./coreipc.js에서 ../../ipc/coreipc.js로 변경되었습니다.

test가 검증하는 fix는 현재 tree에서 다음 상태입니다. 먼저 ImageBufferBackend에는 기본값이 true인 hasGraphicsContext()가 선언되어 있습니다. 함께 달린 주석은 context를 파괴할 수 없는 backend가 "must not be handed to a different owner"라고 명시합니다. 그 옆에는 기본 구현이 no-op인 releaseGraphicsContext()가 있습니다. ImageBufferShareableBitmapBackend는 releaseGraphicsContext()를 m_context = nullptr로, hasGraphicsContext()를 !!m_context로 override합니다. 이 backend의 context()는 필요한 시점에 adoptGraphicsContext()를 통해 context를 다시 생성합니다. RemoteRenderingBackend::moveToSerializedBuffer()는 hasOneRef() 검사 이후 context를 해제합니다. 이어서 addSerializedImageBuffer 호출 전에 MESSAGE_CHECK(!hasGraphicsContext() || DisplayList)를 적용합니다. 결과적으로 context를 유지하는 backend는 fail closed로 처리됩니다. state를 다른 backend에 넘기는 대신, 메시지를 보낸 WebContent process가 종료됩니다.

내부 state를 정리하지 않는 container의 ownership 이전. 이전 소유자의 thread 전용 resource에 대한 strong reference가 새 소유자의 thread에서 도달 가능한 상태로 남는 패턴.

GPU process의 work queue. WebKit GPU process는 WebContent process를 대신해 drawing을 수행합니다. 각 RemoteRenderingBackend는 여러 RemoteImageBuffer를 소유합니다. drawing command는 stream IPC를 통해 backend 전용 StreamConnectionWorkQueue로 들어오는데, 이는 해당 connection만을 위한 serial thread입니다.

ImageBuffer backend. ImageBuffer는 storage와 drawing context를 ImageBufferBackend로부터 받습니다. Accelerated backend는 IOSurface 기반 CGContext를 사용합니다. 반면 unaccelerated backend는 ShareableBitmap(ImageBufferShareableBitmapBackend)을 사용하고, DisplayList backend는 command를 기록합니다.

GraphicsContext, Pattern, SourceImage. GraphicsContext는 fill brush, stroke brush 같은 변경 가능한 drawing state를 갖습니다. fill brush는 Pattern일 수 있으며, Pattern은 SourceImage를 보관합니다. SourceImage는 Ref<NativeImage>, Ref<ImageBuffer>, 아직 resolve되지 않은 RenderingResourceIdentifier 중 하나를 담는 variant입니다. 따라서 pattern fill이 다른 ImageBuffer에 대한 strong reference를 가질 수 있습니다.

ThreadSafeRefCounted. ImageBuffer는 ThreadSafeRefCountedAndCanMakeThreadSafeWeakPtr입니다. refcount가 atomic하게 갱신되므로, 어떤 thread에서든 reference를 획득하고 해제할 수 있습니다. 다만 atomic refcounting이 관장하는 범위는 객체의 lifetime뿐입니다. 객체 내부에 대한 접근까지 동기화하지는 않습니다.

backend 간 buffer 이동. MoveToSerializedBuffer는 한 backend에서 buffer를 꺼내 process 전역 shared resource cache에 serialized identifier로 등록합니다. 이후 MoveToImageBuffer를 통해 다른 backend가 이를 adopt할 수 있습니다. 이때 adopt하는 backend는 다른 thread에서 동작할 수도 있습니다.

MESSAGE_CHECK와 IPC testing API. MESSAGE_CHECK는 메시지를 invalid로 표시하고, GPU process가 문제의 WebContent process 종료를 요청하도록 합니다. IPCTestingAPIEnabled는 layout test에 raw IPC 전송 기능을 노출합니다. 이를 통해 장악된 WebContent process가 보낼 수 있는 메시지를 모델링합니다.

ownership 이전 이후에도 reference chain 하나가 살아남았습니다. 이 버그는 그 chain이 만들어낸 cross-thread race입니다.

  Backend A thread                       Backend B thread
  ----------------                       ----------------
  tile (accelerated ImageBuffer) <--Ref--+
    IOSurface CGContext                  |   carrier (unaccelerated, adopted)
                                         |     GraphicsContext (never dropped)
                                         |       fill brush: Pattern
                                         +------   SourceImage = Ref<ImageBuffer>
  FillRect / ClearRect on tile               FillRect on carrier
        +------> same platform context <------+     (no synchronization)

다이어그램은 오른쪽부터 읽으면 됩니다. carrier는 GraphicsContext가 그대로 남은 상태로 backend B에 도착합니다. 이동 과정에서 context가 사라졌는지 확인하지 않았기 때문입니다. test 주석에 따르면 unaccelerated backend는 "used to ignore releaseGraphicsContext()" 상태였습니다. [1]의 diff에서도 이 부분이 명시적인 do-nothing override로 드러납니다. 살아남은 context 안의 fill brush는 Pattern이며, 그 SourceImage는 A의 tile을 가리키는 Ref<ImageBuffer>를 보관합니다.

여기서 Ref라는 점은 test의 기대 동작에서 추론한 것입니다. test는 이후 tile을 이동하려 하면 hasOneRef() 검사가 "ImageBuffer in use"로 실패할 것으로 기대합니다. 이런 결과는 무언가가 tile에 대한 strong reference를 여전히 보유하고 있을 때만 나옵니다. 같은 기대 동작은 또 다른 사실도 드러냅니다. race와 무관하게, 숨겨진 reference만으로도 A의 ownership invariant가 깨진다는 점입니다.

B가 FillRect를 실행하면, pattern을 resolve하는 과정에서 A의 tile을 읽습니다. test 주석에 따르면 "supplies the IOSurface CGContext that resolving the pattern would race against" 역할을 하는 것은 accelerated tile뿐입니다. 같은 시점에 왼쪽 열에서는 A의 thread가 tile 자체의 context로 drawing을 수행합니다. ImageBuffer는 thread-safe refcounted이므로 tile 객체 자체는 살아 있습니다. 즉 ImageBuffer use-after-free는 아닙니다. 위험 요소는 tile의 platform drawing context와 backing store에 대한 동기화되지 않은 접근입니다.

fix는 serialized buffer가 context에 묶인 reference를 갖지 않는다는 invariant를 복원했습니다. 이제 ShareableBitmap backend는 실제로 m_context를 해제합니다. 또한 이동 시 hasGraphicsContext()가 여전히 true인 backend는 거부되며, DisplayList buffer만 예외로 남습니다.

이런 구조로 볼 때 [1]과 같은 발견 경로를 추정할 수 있습니다. 먼저 기존 release 메커니즘을 따르지 않는 ImageBufferBackend subclass를 나열합니다. 그다음 IPC testing API harness로 그 틈을 공략합니다. 이 harness는 RemoteRenderingBackend 세 개를 사용해 work-queue thread 세 개를 확보합니다.

이 버그는 장악된 WebContent process에서 일반적인 rendering IPC만으로 도달 가능합니다. 여러 backend에 걸쳐 MoveToSerializedBuffer/MoveToImageBuffer와 SetFillPatternImageBuffer를 호출하면 됩니다. regression test는 IPC testing API로 이를 재현합니다.

race를 memory corruption으로 확장하려면 추가 조건이 필요합니다. adopt한 backend의 FillRect와 소유 backend의 drawing이 thread-safe하지 않은 platform graphics state 안에서 interleave되어야 합니다. 그 대상은 IOSurface CGContext이며, interleave 결과 해당 state가 불일치 상태로 남아야 합니다. 이 interleaving으로 platform context 내부가 손상될 수 있다면, 형태가 불분명한 GPU-process memory-corruption primitive로 이어질 가능성이 있습니다. 그렇지 않다면 rendering 불일치나 crash 수준에 머무를 것입니다.

남은 점검 과제는 하나입니다. 동시 사용이 단순히 잘못된 rendering을 넘어 memory corruption을 일으키는 window가 해당 platform state에 존재하는지 여부입니다. 무기화에 성공한다면 WebContent에서 GPU process로 넘어가는 확장 단계가 될 수 있습니다. 다만 그 자체로 완전한 sandbox escape에 해당하지는 않습니다.

이 vulnerability는 GPU process 내부의 memory-safety isolation을 약화시킵니다. rendering 모델은 두 가지를 전제합니다. 첫째, 각 backend의 resource는 해당 backend의 work-queue thread에서만 접근됩니다. 둘째, serialized buffer는 self-contained 상태로 인계됩니다. unaccelerated buffer에서는 context에 묶인 pattern reference가 이 두 전제를 모두 깨뜨렸습니다. 그래서 WebContent process를 장악한 attacker가 두 thread에서 같은 platform context나 backing store에 동기화되지 않은 drawing을 동시에 유발할 수 있었습니다. 이 race가 platform graphics state를 손상시킨다면, WebContent sandbox를 벗어나는 과정에서 GPU-process memory corruption 발판으로 이어질 가능성이 있습니다.

Takeaway. 이동의 배타성은 이동된 객체 뒤의 reference graph가 허락하는 만큼만 성립합니다. root에서 hasOneRef()를 확인해도, 그 drawing state가 무엇을 쥐고 있는지는 알 수 없습니다. FIXME에 적힌 DisplayList 예외 역시 정확히 이 유형의 문제가 남아 있음을 문서로 인정한 셈입니다.