← All reports

[2] Style flush UAF via fonts.ready re-entrancy during shadow-root iteration

HighWebCore Style / Font LoadingUAF

Style recalc assumed no page script runs mid-walk. One prototype getter disagrees.

86074ba

Style engine의 iterator가 가리키고 있는 list node를 prototype getter 하나로 해제할 수 있습니다. 필요한 것은 DOM, CSS @font-face, Font Loading API뿐이며, 이 점이 High로 분류된 이유입니다. Crash 이상으로 확장하려면 크기와 형태가 고정된 작은 node를 재점유해야 합니다. 다만 그 window가 attacker 자신의 getter 안에 놓여 있다는 점은 눈여겨볼 만합니다.

WebKit renderer의 style 재계산은 tree별 style 상태를 순회합니다. 이때 순회 도중에는 페이지 script가 실행되지 않는다는 전제가 깔려 있습니다. Document는 연결된 shadow root들을 WeakListHashSet에 보관합니다. 삽입 순서를 유지하는 set으로, 각 원소는 별도로 heap에 할당된 list node 안에 들어 있습니다. 한편 각 shadow root는 자신의 stylesheet와 resolver 상태를 담는 Style::Scope를 갖습니다. 문제는 순회의 매 iteration이 document.fonts를 갱신하는 코드까지 호출한다는 점입니다. document.fonts는 FontFaceSet이며, font 로딩이 끝나면 ready promise가 settle됩니다. 그런데도 순회가 안전하려면, loop가 끝나기 전까지 registry가 변경되지 않아야 합니다.

관전 포인트: FontFaceSet에 then getter를 정의한 페이지는 style flush 도중에 script를 실행할 수 있습니다. 그 script에서 shadow root를 분리하면, engine의 iterator는 이미 해제된 list node 위를 순회하게 됩니다.

Style::Scope::flushPendingDescendantUpdates()는 live iterator로 Document::m_inDocumentShadowRoots(WeakListHashSet)를 순회하면서, 하위 shadow scope마다 flushPendingUpdate()를 호출합니다. Shadow scope를 flush하면 @font-face rule이 다시 등록됩니다. 이 과정에서 active count가 0이 되면 document.fonts.ready가 settle되고, author getter가 실행될 수 있습니다. 해당 getter는 순회 중인 shadow root의 host를 제거할 수 있습니다. 그러면 중단된 iterator가 가리키던 ListHashSetNode가 해제되고, loop는 이어서 해제된 node의 m_next를 읽게 됩니다.

수정은 두 계층으로 이루어졌습니다. (1) m_inDocumentShadowRoots를 순회하는 도중 동기적으로 resolve하지 않고, document.fonts.ready resolve를 queue된 task로 미룹니다. (2) m_inDocumentShadowRoots를 순회하며 하위 scope를 호출하는 모든 loop에 ScriptDisallowedScope::InMainThread를 둡니다. 이런 loop는 모두 root마다 style system을 호출하고, 그 호출이 font 등록까지 도달할 수 있기 때문에 guard를 빠짐없이 적용했습니다.

Test: LayoutTests/platform/glib/damage/crash-shadow-root-style-flush-font-promise.html

Source/WebCore/style/StyleScope.cpp

void Scope::flushPendingDescendantUpdates()
{
ASSERT(m_hasDescendantWithPendingUpdate);
ASSERT(!m_shadowRoot);
+ ScriptDisallowedScope::InMainThread scriptDisallowedScope;
for (auto& descendantShadowRoot : m_document->inDocumentShadowRoots()) {
const_cast<ShadowRoot&>(descendantShadowRoot).styleScope().flushPendingUpdate();
}
...

Source/WebCore/css/FontFaceSet.cpp

void FontFaceSet::completedLoading()
{
 
- if (m_isDocumentLoaded && !m_readyPromise->isFulfilled())
 
- m_readyPromise->resolve(*this);
+ queueTaskKeepingObjectAlive(*this, TaskSource::FontLoading, [](auto& set) {
+ if (set.m_isDocumentLoaded && !set.m_readyPromise->isFulfilled())
+ set.m_readyPromise->resolve(set);
+ });
}
...

LayoutTests/platform/glib/damage/crash-shadow-root-style-flush-font-promise.html

+ document.fonts.ready;
+ const prependedStyle = document.createElement("style");
+ shadowRoot.prepend(prependedStyle);
+ Object.defineProperty(FontFaceSet.prototype, "then", {
+ configurable: true,
+ get() {
+ delete FontFaceSet.prototype.then;
+ host.remove(); // 순회 중인 Document::m_inDocumentShadowRoots node를 해제합니다.
+ return undefined;
+ }
+ });
+ document.styleSheets.length; // Scope::flushPendingDescendantUpdates()에 도달합니다.

이번 변경으로 document.fonts.ready의 settle 시점이 queue된 font-loading task로 옮겨졌습니다. 또한 document의 shadow-root registry를 순회하며 root마다 외부 호출을 수행하는 loop 앞에 script 실행 금지 guard가 추가되었습니다. 대상 loop는 아래에 정리되어 있습니다.

먼저 FontFaceSet.cpp의 completedLoading()은 더 이상 m_readyPromise를 그 자리에서 resolve하지 않습니다. m_isDocumentLoaded && !isFulfilled() 검사와 resolve(set) 호출은 queueTaskKeepingObjectAlive(*this, TaskSource::FontLoading, ...) lambda 안으로 이동했습니다. 그래서 settle과 그에 따른 then 조회는 이후의 event-loop task에서 발생합니다. 한편 startedLoading()의 loading event도 TaskSource::DOMManipulation에서 TaskSource::FontLoading으로 변경되었습니다. 결과적으로 두 notification이 같은 task source를 사용하게 됩니다.

ScriptDisallowedScope::InMainThread는 Document::inDocumentShadowRoots()를 range-for로 순회하며 root마다 외부 호출을 수행하는 loop 바로 앞에 배치되었습니다. 대상은 다음과 같습니다. - Style::Scope::flushPendingDescendantUpdates()(crash 지점), didChangeViewportSize(), invalidateMatchedDeclarationsCache() - Style::DocumentScope::releaseMemory(), collectResolverScopes(), didChangeStyleSheetEnvironment(), didChangeExtensionStyleSheets() - root마다 resolver를 강제로 생성하는 Style::TreeResolver::Scope::Scope(Document&, Update&) constructor - LocalDOMWindow::ensureCustomElementRegistry() - Internals::dumpStyleResolvers()

새 test의 expected output에는 FontFaceSet.prototype.then getter calls: 0이 기록되어 있습니다.

Re-entrancy 상황의 iterator invalidation: node 기반 container의 live iterator를 유지한 채 author script에 도달할 수 있는 외부 호출을 수행하고, 그 script가 container를 변경해 iterator의 node를 해제하는 패턴.

이 코드가 있는 위치. WebCore의 style system은 document와 그 안의 각 shadow tree에 대해 CSS를 resolve합니다. 이 과정은 모두 WebContent(renderer) process에서 실행됩니다.

ListHashSet과 WeakListHashSet. ListHashSet은 WTF가 제공하는 삽입 순서 유지 hash set입니다. 각 원소는 별도로 heap에 할당된 ListHashSetNode에 들어 있고, 이 node는 m_prev/m_next link를 갖습니다. Iterator는 node pointer를 감싼 얇은 wrapper에 불과하며, 원소를 제거하면 해당 node도 해제됩니다. WeakListHashSet<T>는 ListHashSet<WeakPtr<T>>를 감싸는 타입입니다. 이 iterator는 내부 iterator를 m_position에 저장하고 ++m_position으로 전진하는데, 이때 현재 node의 m_next를 따라갑니다.

Shadow-root registry. Document::inDocumentShadowRoots()는 현재 연결된 shadow root의 집합입니다. Root는 연결될 때 추가되고, 분리될 때 제거됩니다.

Style::Scope와 Style::DocumentScope. Style::Scope는 하나의 tree에 대한 active stylesheet, resolver, pending update를 보관합니다. Document 수준의 scope는 shadow root별 scope들을 조율하는 역할을 합니다. 이때 flushPendingDescendantUpdates()가 각 scope에 대기 중인 stylesheet 변경을 적용하도록 요청합니다. Script에서는 document.styleSheets 같은 API를 통해 이 함수에 도달할 수 있습니다. 또한 shadow scope의 sheet를 적용하는 과정에서 @font-face rule이 document의 font selector에 등록됩니다.

FontFaceSet(document.fonts). Font face와 그 로딩 상태를 추적합니다. startedLoading()과 completedLoading()은 내부의 CSSFontFaceSet이 보내는 notification입니다. 로딩 중인 face 집합이 비어 있지 않게 되거나 다시 비게 될 때 각각 호출됩니다. ready promise는 document 로딩이 끝난 뒤 font 로딩이 완료되면 settle되며, FontFaceSet 객체 자신으로 resolve됩니다.

Thenable assimilation. 객체로 promise를 resolve하면 그 객체의 then property가 동기적으로 조회됩니다. 따라서 객체나 prototype에 정의된 accessor가 resolve 시점에 곧바로 실행됩니다.

ScriptDisallowedScope::InMainThread. Author script가 실행되면 안 되는 구간을 표시하는 RAII counter입니다. Header 주석에 따르면, release build에서는 script 실행 검사에 들어 있는 release assertion에 의존합니다. 그래서 이 구간 안에서 script를 실행하려 하면 re-entrancy 대신 의도된 crash가 발생합니다.

Script re-entrancy 상황에서 iterator invalidation이 발생하고, 그 결과 container node에 대한 use-after-free로 이어집니다.

 flushPendingDescendantUpdates()            FontFaceSet.prototype.then getter
 -------------------------------            ---------------------------------
 it = inDocumentShadowRoots().begin()
 root->styleScope().flushPendingUpdate()
   Reset path: re-register @font-face
   old CSSFontFace removed, count -> 0
   completedLoading()
   m_readyPromise->resolve(*this)
   Get(FontFaceSet, "then") ----------->   host.remove()
                                             root disconnected
                                             ListHashSetNode freed
                                  <-----   return undefined
 ++m_position  -> reads freed node's m_next

왼쪽 loop는 snapshot 없이 live linked list를 그대로 순회합니다. 게다가 매 iteration마다 범위가 제한되지 않은 외부 호출을 수행합니다. Regression test의 header 주석에 따르면, pending update가 Reset 경로를 타는 shadow scope를 flush하면 @font-face를 포함한 모든 sheet가 다시 처리됩니다. 이렇게 rule이 재등록되면 기존 CSSFontFace가 제거됩니다. 그것이 유일하게 로딩 중인 face였다면 active count가 0이 되고, completedLoading()이 실행됩니다.

패치 이전에는 여기서 m_readyPromise->resolve(*this)가 그 자리에서 호출되었습니다. 그러면 thenable assimilation으로 인해 style flush 깊숙한 곳에서 author getter가 실행됩니다. Getter가 host를 제거하면 shadow root가 분리되고 registry에서 빠집니다. 이때 m_position이 가리키던 node가 해제됩니다. 결국 외부 호출이 반환된 뒤 ++m_position이 해제된 메모리에서 m_next를 읽게 됩니다.

일부 loop는 이미 for (Ref shadowRoot : ...) 형태를 쓰고 있었습니다. 이 방식은 ShadowRoot를 살아 있게 유지하지만, list node에는 아무런 보호도 제공하지 않습니다. 즉 원소를 보호한다고 해서 iterator까지 보호되는 것은 아닙니다.

Regression test는 의도적으로 정교하게 구성되어 있습니다. 먼저 document.fonts.ready에 접근해 promise를 생성합니다. 이어서 <style>을 shadow root에 append가 아니라 prepend하여 Reset 경로를 강제합니다. Getter는 한 번만 실행되도록 자기 자신을 삭제하고, host를 제거한 뒤 undefined를 반환합니다. 마지막으로 document.styleSheets.length가 flush를 유발해 flushPendingDescendantUpdates()에 도달합니다.

취약한 경로는 일반 web content에서 도달 가능합니다. 필요한 것은 DOM, CSS @font-face, Font Loading API, 그리고 prototype accessor뿐입니다. 해제되는 객체는 크기와 형태가 고정된 작은 ListHashSetNode로, WeakPtr<ShadowRoot> 하나와 link pointer 두 개를 담고 있습니다. 또한 getter 자체가 host.remove()와 iterator 전진 사이에서 임의의 JS를 실행합니다. 따라서 같은 callback 안에서 재점유를 시도할 수 있습니다.

해당 slot이 제어된 데이터로 재점유된다고 가정할 수 있습니다. 이 경우 위조된 m_next가 iterator를 attacker가 고른 가짜 node로 유도하게 됩니다. 이어서 get()이 그 node의 WeakPtr impl을 역참조해 ShadowRoot*를 얻고, loop body가 그 위에서 style-scope 호출을 수행하게 됩니다. 이 시나리오가 성립하면 primitive는 fake object나 type confusion 계열로 격상될 가능성이 있으며, control-flow 장악 후보도 생깁니다.

관건은 allocator가 이 node 타입에 적용하는 격리가 이런 재점유를 허용하는지입니다. 재점유가 불가능하다면 관찰되는 동작은 crash에 그칩니다. 또한 해제가 일어나려면 분리 시 node가 실제로 제거되어야 합니다. Null WeakPtr를 남겨 두고 나중에 정리하는 방식이라면 해제가 발생하지 않습니다. Test 주석은 실제로 node가 제거된다고 명시하고 있습니다.

이 vulnerability는 renderer의 memory safety를 약화시킵니다. Style engine은 document의 shadow-root registry를 순회하는 동안 author script가 실행되지 않는다고 가정합니다. 그런데 패치 이전에는 web content가 순회 도중 getter를 실행해 이 가정을 깰 수 있었습니다. 그 결과 WebContent process 안에서 ListHashSetNode에 대한 use-after-free가 발생합니다. 이를 제어된 내용으로 재점유하면 renderer 수준의 memory corruption primitive로 이어질 가능성이 있습니다. 다만 renderer 밖으로 나아가려면 별도의 sandbox escape가 여전히 필요합니다.

Insight: 두 계층의 수정은 서로 다른 역할을 합니다. 먼저 resolve를 task로 미룬 변경은 이미 알려진 script 진입 경로를 제거합니다. 반면 ScriptDisallowedScope는 이 외부 호출들을 거치는 미발견 경로가 있더라도, 이를 UAF 대신 release-assert crash로 바꿉니다. 즉 완화책이지 원천 차단은 아닙니다. 이 안전망이 얼마나 완전한지는 JSC의 thenable 조회가 검사가 걸린 script 진입 지점을 통과하는지에 달려 있습니다.