← All reports

[5] Editor/WebPageMac UAF: key-command and IME text borrowed by `const&` across event dispatch

HighWebCore EditingUAF

7947a74

Bug class와 도달 범위를 기준으로 High로 평가합니다. 가변 크기 allocation에서 발생하는 renderer heap UAF이며, 모든 editable element의 event handler로 흐름을 유도할 수 있습니다. 다만 시작하려면 실제 키보드 또는 IME 입력이 필요할 가능성이 높습니다. 확장 경로에 대한 질문도 아직 남아 있습니다. script로 도달 가능한 어떤 동작이 실제로 storage를 해제하는지는 확인되지 않았습니다.

브라우저의 native editing 코드는 데이터를 빌려온 view 형태로 다른 루틴에 전달하는 경우가 많습니다. 문제는 그 루틴이 DOM event를 발생시킨다는 점입니다. event가 발생할 때마다, 제어가 돌아오기 전에 page JavaScript가 동기적으로 실행됩니다. macOS에서는 AppKit이 각 keystroke를 KeypressCommand 목록으로 변환합니다. 각 항목은 insertText: 같은 editing selector 하나와 해당 text로 구성됩니다. 이 목록은 refcounted DOM KeyboardEvent의 by-value Vector 멤버인 m_keypressCommands에 저장됩니다. commit message에 따르면, 이 명령들을 실행하는 WebContent 측 루프인 WebPage::executeKeypressCommandsInternal은 해당 vector를 const&로 받습니다. IME composition을 확정하거나 취소하는 Editor::setComposition도 caller가 소유한 heap storage에서 text를 const&로 받습니다. 이 storage는 KeypressCommand의 text일 가능성이 높습니다. 결과적으로 두 함수 모두, 실행되는 동안 빌려온 데이터가 유효하게 유지된다고 가정합니다.

관전 포인트: page의 event handler가 m_keypressCommands storage를 해제할 수 있는 경우를 가정할 수 있습니다. 이때 executeKeypressCommandsInternal은 아직 같은 storage를 순회하는 중입니다. 이 경우 editable element에 평범하게 타이핑하는 것만으로 renderer use-after-free로 이어질 가능성이 있습니다. 대상은 command 목록 길이에 따라 크기가 달라지는 heap buffer입니다.

use-after-free of m_keypressCommands in Editor::setComposition. Copy both text in setComposition and commands in executeKeypressCommandsInternal onto the stack; these point to heap memory when invoked from their respective call sites, but the logic in both of these methods can fire events and trigger JavaScript (and thus, have the potential to corrupt the heap).

Source/WebKit/WebProcess/WebPage/mac/WebPageMac.mm

-bool WebPage::executeKeypressCommandsInternal(const Vector<WebCore::KeypressCommand>& commands, KeyboardEvent* event)
+bool WebPage::executeKeypressCommandsInternal(const Vector<WebCore::KeypressCommand>& passedCommands, KeyboardEvent* event)
{
RefPtr frame = event ? frameForEvent(event) : m_page->focusController().focusedOrMainFrame();
if (!frame)
return false;
ASSERT(frame->page() == corePage());
 
+ auto commands = passedCommands;
+
Ref editor = frame->editor();
bool eventWasHandled = false;
Borrow borrowedCommands = commands;

Source/WebCore/editing/Editor.cpp

-void Editor::setComposition(const String& text, SetCompositionMode mode)
+void Editor::setComposition(const String& passedText, SetCompositionMode mode)
{
ASSERT(mode == ConfirmComposition || mode == CancelComposition);
+
+ auto text = passedText;
+
Ref document = this->document();
SetCompositionScope setCompositionScope(document.copyRef());

두 파일에 각각 하나씩, 같은 형태의 변경이 적용되었습니다. 먼저 Editor::setComposition(const String&, SetCompositionMode)는 confirmComposition/cancelComposition이 사용하는 overload입니다. 이 함수의 parameter 이름이 passedText로 변경되었습니다. 그리고 SetCompositionScope를 생성하거나 composition 로직을 실행하기 전에, 이 값을 곧바로 auto text에 복사하도록 수정되었습니다. WebPage::executeKeypressCommandsInternal도 parameter 이름을 passedCommands로 바꾸었습니다. 이 값은 frame null-check 직후 local auto commands로 복사됩니다. 기존의 Borrow borrowedCommands = commands;와 실행 루프는 이제 이 local 복사본을 대상으로 동작합니다. 한편 guard나 control flow는 추가되지 않았습니다. 결과적으로 caller 소유 heap storage에 대한 두 개의 borrowed view가 owned stack 값으로 바뀌었습니다. 각 값은 underlying StringImpl과 Vector buffer에 대한 자체 reference를 보유합니다. 테스트 변경은 없습니다.

Script에 재진입해 container를 변경하거나 해제할 수 있는 호출 구간에서, 해당 mutable container storage를 가리키는 borrowed reference를 계속 유지하는 패턴.

이 코드가 있는 위치. WebKit의 UI process는 키 입력을 받아 AppKit으로 해석합니다. 이후 그 결과로 생성된 명령을 key event와 함께 WebContent process로 전달합니다. WebContent process는 page를 호스팅하며 sandbox 안에서 실행됩니다. 이곳에서는 WebEditorClient::handleKeyboardEvent와 didDispatchInputMethodKeydown이 KeyboardEvent를 WebPage::handleEditingKeyboardEvent로 전달합니다. commit message에 따르면, 이 함수가 event의 command vector를 executeKeypressCommandsInternal에 전달합니다. 실행 대상은 focused frame의 Editor입니다.

KeypressCommand와 KeyboardEvent. KeypressCommand는 AppKit editing selector 하나와 관련 text를 기록합니다. selector로는 insertText:나 이동·삭제 명령 등이 있습니다. Cocoa에서 KeyboardEvent는 이 명령들을 by-value 멤버 m_keypressCommands에 저장합니다. 그리고 mutable accessor인 Vector<KeypressCommand>& keypressCommands()를 통해 이 멤버를 외부에 노출합니다.

Editor::setComposition. ConfirmComposition 또는 CancelComposition으로 호출되면, 진행 중인 IME composition을 확정하거나 취소합니다. 이 과정에서 focused editable element로 composition, beforeinput/input, text 삽입 event가 dispatch됩니다.

WTF::String과 WTF::Vector. String은 refcounted StringImpl을 감싸는 smart-pointer wrapper입니다. String을 복사하면 새 reference를 획득합니다. 반면 const String&로 바인딩하면 reference를 획득하지 않고 caller의 객체를 alias합니다. Vector<T>는 heap element buffer를 소유합니다. 이 buffer는 clear(), 대입, capacity를 넘는 확장 시 해제되거나 재할당됩니다. const Vector& parameter는 caller의 vector 객체를 alias합니다.

Re-entrancy. Re-entrancy 지점은 native 코드가 DOM event를 dispatch하는 지점입니다. 이때 page JavaScript가 동기적으로 실행되며, 제어가 돌아오기 전에 C++에서 보이는 상태를 변경할 수 있습니다.

JavaScript re-entrancy를 거치는 동안 dangling const&를 통해 발생하는 use-after-free입니다.

  executeKeypressCommandsInternal(const Vector& commands)       page JS
  ───────────────────────────────────────────────────────       ───────
  commands ── alias ──► event->m_keypressCommands (heap buf)
  for each cmd in commands:
    editor runs cmd ── beforeinput/input/composition ──────►  handler
                                                               m_keypressCommands
                                                               cleared / grown?
                                                               buffer freed
                       ◄──────────────────────────────────────  returns
    next cmd = commands[i+1]   <- read from freed buffer

패치 이전에는 두 함수 모두, 다른 객체가 소유한 storage를 alias하는 const& parameter를 받았습니다. 그리고 두 함수 모두 이후 DOM event를 dispatch하는 로직을 실행했습니다. commit message는 alias된 storage가 m_keypressCommands라고 명시합니다. 또한 handleEditingKeyboardEvent가 event의 command vector를 executeKeypressCommandsInternal로 넘기는 중간 단계라고 설명합니다. 다이어그램에서 루프는 beforeinput/input/composition/textInput event를 발생시키는 editing command를 실행합니다. 이 구간에서 script로 도달 가능한 작업이 m_keypressCommands를 clear하거나, 재대입하거나, 확장하는 경우를 생각할 수 있습니다. 그러면 commands가 가리키는 buffer가 해제되거나 재할당됩니다. 결과적으로 루프의 다음 element 접근은 해제된 메모리를 읽게 됩니다.

Editor::setComposition은 한 단계 더 깊은 곳에서 같은 형태를 가집니다. commit message에 따르면, 호출 지점에서 text 인자는 heap memory를 가리킵니다. 같은 vector 안에 있는 KeypressCommand의 text 필드일 가능성이 높습니다. 이 함수는 text 사용을 마치기 전에 composition 및 input event를 발생시킵니다. 이 구간에서 backing storage가 해제되면, text는 해제된 buffer 안의 String slot을 가리키는 dangling reference가 됩니다. String만 재대입되는 경우라도, 그 StringImpl의 마지막 reference가 해제될 가능성이 있습니다. 이번 복사는 두 경우를 모두 차단합니다. Vector의 copy constructor는 각 KeypressCommand를 복사하고, String의 복사는 StringImpl에 대한 reference를 새로 획득합니다. 그래서 script가 원본에 무엇을 하든 local 값은 유지됩니다.

이 경로는 editable element의 event handler를 통해 web content에서 도달 가능합니다. 다만 시작하려면 실제 사용자의 키보드 또는 IME 입력이 필요할 가능성이 높습니다. script로 생성한 KeyboardEvent에는 AppKit KeypressCommand가 포함되지 않는 것으로 보이기 때문입니다. 이 명령들은 실제 keystroke를 UI process의 AppKit이 해석한 결과로 채워집니다. 한편 KeyboardEvent의 mutable accessor는 storage가 변경될 수 있다는 점을 나타냅니다. 하지만 script로 도달 가능한 어떤 동작이 실제로 이 변경을 수행하는지는 아직 열린 질문입니다. 그 변경이 단순 재대입에 그치는지, 실제 해제를 일으키는지도 마찬가지입니다. 이 답이 primitive의 강도를 결정합니다.

결과는 어떤 변경이 일어나는지에 따라 달라질 것으로 보입니다. 첫째는 해제된 Vector<KeypressCommand> backing buffer에 대한 stale read입니다. 크기는 command 수 × sizeof(KeypressCommand)로 결정됩니다. 둘째는 StringImpl의 마지막 reference가 해제된 dangling String입니다. 이 경우 크기는 문자열 길이에 따라 결정됩니다. 해제된 Vector buffer가 다른 데이터로 재점유되는 경우를 가정할 수 있습니다. 이때 buffer 안의 String slot은 StringImpl* pointer로 재해석됩니다. 그러면 stale read가 fake StringImpl 접근으로 이어질 가능성이 있습니다. 이는 info leak 또는 refcount-decrement write primitive의 후보가 될 수 있습니다. 다만 그 범위는 editing 경로가 text와 command 이름을 어떻게 사용하는지에 따라 제한됩니다. 재점유가 없다면 관찰되는 동작은 crash에 그칠 것으로 보입니다. 또한 executeKeypressCommandsInternal 경로는 macOS 전용이고, setComposition은 공유 WebCore 코드입니다. 두 경로 모두 단독으로는 WebContent sandbox를 넘지 못합니다.

이 vulnerability는 WebContent process의 memory safety를 약화합니다. native editing 코드는 전달받은 command 목록과 composition text가 호출 전체 동안 유효하다고 가정했습니다. 문제는 같은 코드가 dispatch하는 event handler 구간에서 이 가정을 보장하는 장치가 없었다는 점입니다. page가 해당 handler 안의 script를 유도해 backing storage를 해제할 수 있다면, renderer는 해제된 Vector/StringImpl 메모리를 사용하게 됩니다. 즉 renderer 영역의 memory corruption에 해당합니다. 그 상한은 해제된 slot을 제어된 데이터로 재점유할 수 있는지에 달려 있습니다.

Insight. 이번 fix는 lifetime guard가 아니라 방어적 복사입니다. 함수가 caller 소유 데이터를 빌려오면서 동시에 event를 dispatch할 때, WebKit이 사용하는 표준적인 해결 방식입니다. 눈여겨볼 부분은 executeKeypressCommandsInternal이 이미 vector를 Borrow로 감싸고 있었다는 점입니다. 다만 그 borrow는 함수가 소유하지 않은 reference에서 생성되었습니다. 일반적인 borrow-tracking helper처럼, Borrow가 자신의 handle을 통한 변경만 추적한다고 가정할 수 있습니다. 그렇다면 event의 소유자가 다른 alias를 통해 storage를 변경하는 상황은 감지하지 못합니다. 이 위험은 전파되기도 합니다. setComposition처럼 m_keypressCommands에서 파생된 const&를 받는 모든 callee가 같은 위험을 물려받습니다. 그런데 이런 함수 시그니처 어디에도 내부에서 event dispatch가 일어난다는 신호가 없습니다.