[1] CSSSegmentedFontFace::fontRanges() UAF via reentrant FontFace promise rehash
A font promise lets any page pick the exact moment a renderer cache dies
High. Dangling reference가 해제된 hash table의 bucket array를 가리키고, 이 array가 해제되는 시점은 author script가 정확히 고를 수 있습니다. 등급이 더 올라가지 않는 이유는 reclaim 단계 하나뿐입니다. 해제된 slot에 같은 크기의 allocation이 먼저 들어와야만 outer frame의 write가 제어 가능해지기 때문입니다.
WebKit CSS 엔진의 font matching은 계산 결과를 memoize합니다. 특정 family, size, style 조합에서 어떤 font가 어떤 code point를 담당하는지 한 번 계산하면, 그 목록을 cache에 저장해 둡니다. 덕분에 text measurement 때마다 같은 계산을 반복하지 않습니다. 이 cache는 CSSSegmentedFontFace의 m_cache에 있습니다. CSSSegmentedFontFace는 하나의 font family를 @font-face source의 순서 있는 목록으로 표현하는 객체입니다. 한편 m_cache는 WTF HashMap으로, entry를 단일 bucket array 안에 inline으로 저장합니다. Entry를 채우는 과정에서는 family의 source를 순회하며 각 source를 로드할 수 있습니다. 다만 이 순회 도중 다른 경로가 m_cache에 insert하는 상황은 전제되어 있지 않습니다.
관전 포인트: native frame이 reference를 통해 CSSSegmentedFontFace cache의 bucket array에 아직 write하고 있는 도중, 임의의 page script가 그 array를 해제할 수 있습니다. 결과적으로 해제 시점을 attacker가 조절하는 renderer use-after-free가 됩니다.
fontRanges()는 m_cache에 빈 FontRanges를 먼저 insert한 뒤, m_fontFaces를 순회하는 동안 bucket array 내부를 가리키는 reference를 유지했습니다. 루프 안에서는 CSSFontAccessor::font()가 호출됩니다. local() source라면 이 함수가 load를 synchronous하게 완료하고 FontFace의 loaded promise를 resolve하므로, 이 시점에 author script가 실행됩니다. 해당 script는 같은 객체의 fontRanges()에 재진입합니다. FontDescriptionKey에는 computedSize가 포함되어 있어, 호출마다 새로운 key가 insert됩니다. 이런 호출이 충분히 쌓이면 table이 rehash되고, outer 호출이 아직 가리키고 있는 array가 해제됩니다. 수정 방식은 FontRanges를 local 변수에 구성한 뒤, 루프가 끝난 다음 한 번만 insert하는 것입니다. ManualSlotAssignment::slotManualAssignmentDidChange와 AXIsolatedTree::updateChildren도 같은 패턴을 사용합니다. 두 함수 모두 하위 호출 코드가 insert할 수 있는 HashMap에 대해, 내부 reference 대신 local copy를 사용합니다.
Source/WebCore/css/CSSSegmentedFontFace.cpp
LayoutTests/sar3/fast/text/font-face/css-segmented-font-face-reentrancy-crash.html
Patch Details
fontRanges()가 더 이상 placeholder를 먼저 insert하지 않도록 변경되었습니다. 먼저 key를 한 번만 구성하고 m_cache.find(key)로 조회합니다. Hit이면 cached value의 copy를 반환합니다. Miss인 경우에는 FontRanges ranges를 stack local로 구성하도록 수정되었습니다. m_fontFaces를 순회하는 루프 자체는 그대로입니다. Face마다 CSSFontAccessor를 생성하고, 필요하면 font(ExternalResourceDownloadPolicy::Forbid)를 호출한 뒤 appendFont를 호출합니다. 이후 shrinkToFit()이 끝나면 완성된 값이 m_cache.add(WTF::move(key), ranges)로 정확히 한 번 insert됩니다. 재진입 위험은 주석으로 명시되었습니다. 새로 추가된 LayoutTest는 FontFace.prototype에 then getter를 설치합니다. 그리고 같은 family에 대해 서로 다른 40개의 pixel size로 font resolution에 재진입합니다.
같은 table에 재진입해 insert할 수 있는 호출을 거치는 동안 growable hash table storage에 대한 reference를 유지하고, 재진입 중의 rehash로 그 storage가 해제되는 패턴.
Background
WTF HashMap.
Key와 value를 하나의 bucket array에 inline으로 저장하는 open-addressing hash table입니다. Insertion으로 load factor가 threshold를 넘으면, table은 새 array를 할당하고 기존 array를 해제합니다. HashMap::add()는 AddResult를 반환하는데, 그 iterator->value는 이 array 내부를 가리키는 reference입니다.
Font 조회 구조.
CSSSegmentedFontFace는 하나의 family를 CSSFontFace entry의 sequence로 표현합니다. 각 entry는 @font-face rule이나 FontFace API에서 만들어집니다. fontRanges()는 FontDescription을 받아 FontRanges로 변환합니다. FontRanges는 (code-point range, FontAccessor) entry의 순서 있는 목록입니다. Shaping과 measurement 단계는 이 목록으로 code point마다 사용할 font를 고릅니다. 결과는 m_cache에 memoize되며, key는 FontDescriptionKey(size, weight, style 등의 속성)와 FontPaletteValues의 조합입니다.
CSSFontAccessor와 local() source.
CSSFontAccessor는 refcounted lazy handle입니다. 첫 font() 호출 시 자신의 CSSFontFace에 실제 Font를 요청하고, 그 결과를 cache합니다. 한편 local() source는 URL 대신 시스템에 설치된 font를 지정합니다. 따라서 network fetch가 개입하지 않으며, load가 synchronous하게 완료될 수 있습니다.
FontFace.loaded와 thenable 조회.
FontFace.loaded는 FontFace 객체 자체로 resolve되는 promise입니다. ECMAScript promise semantics에서는 promise를 객체로 resolve할 때 그 객체의 then property를 synchronous하게 읽습니다. 그래서 then getter는 이후의 microtask가 아니라 resolution 시점에 바로 실행됩니다.
Analysis
이번 버그는 JavaScript 재진입을 통해 도달하는, WTF HashMap bucket storage의 use-after-free입니다.
outer fontRanges() author script (then getter)
────────────────── ───────────────────────────
m_cache.add(key, {})
ranges = &bucket[k] ────┐
loop: accessor->font() │
local() load completes│
resolve(face.loaded) ─┼──► Get(face, "then")
│ measureText at 11px..50px
│ fontRanges() x40 -> m_cache.add(newKey)
│ rehash: old bucket array freed
│ ◄───┘
appendFont(ranges, ...) ┘ <- write into freed array
shrinkToFit / return copy <- read from freed array
왼쪽 열에서 ranges는 루프가 시작되기 전에 bucket array 안의 slot에 바인딩됩니다. 패치에 포함된 주석에 따르면, local() source에 대한 CSSFontAccessor::font()는 load를 synchronous하게 마치고 client에게 통지합니다. 이 과정에서 FontFace.loaded가 resolve될 수 있으며, regression test가 정확히 이 경로를 실행합니다. 이때 resolution은 Get(face, "then")을 수행합니다. 그 결과 outer frame이 루프 중간에 머문 상태에서 제어가 오른쪽 열로 넘어갑니다.
FontDescriptionKey에는 computed size가 포함됩니다. 그래서 서로 다른 pixel size로 호출되는 40번의 measureText는 매번 cache miss를 일으키고 새 key를 insert하게 됩니다. Insertion이 쌓여 load-factor threshold를 넘으면 table이 rehash되고, ranges가 가리키던 array가 해제됩니다. 이후 제어가 돌아오면 appendFont(ranges, ...)가 stale slot에 대해 ranges.appendRange(...)를 호출합니다. 이어서 shrinkToFit()이 같은 slot을 다시 변경합니다. 마지막으로 return ranges는 해제된 메모리를 바탕으로 결과를 copy-construct합니다.
주변 소스에는 두 번째 무효화 경로도 존재합니다. CSSSegmentedFontFace::fontLoaded()가 m_cache.clear()를 호출하기 때문입니다. fontLoaded()가 루프 안에서 synchronous하게 실행될 수 있다면, 이 경로 역시 ranges 아래의 table을 해제하게 됩니다. CSSFontFace.cpp의 client 통지는 iterateClients를 거칩니다. 다만 이 통지가 해당 루프 안에서 fontLoaded()까지 도달하는지는 확인되지 않았습니다.
Regression test는 네 단계로 버그를 유발합니다.
new FontFace('MyTestFam', 'local(Helvetica)')를 생성하고face.loaded에 접근한 뒤, face를document.fonts에 추가합니다.FontFace.prototype에thengetter를 정의합니다. 이후로는FontFace로 promise를 resolve할 때마다 이 getter가 synchronous하게 실행됩니다.OffscreenCanvas에서10px MyTestFam으로measureText('a')를 호출합니다. 이 호출이fontRanges()로 진입하고,local()source를 로드하면서loaded를 resolve합니다.- Getter 안에서는 11px부터 50px까지 40개의 size를 순회합니다. 각 호출은 같은 family 객체의
fontRanges()에 재진입해 새 key를 insert합니다. 결국 outer frame이 재개되기 전에 rehash가 강제됩니다.
타이밍은 항상 동일하게 재현됩니다. then getter가 dangling reference가 살아 있는 window 안에서 정확히 실행되고, size를 달리하면 원하는 시점에 rehash를 일으킬 수 있기 때문입니다. 직접적인 영향은 해제된 bucket array 안의 FontRanges slot 하나에 대한 UAF read와 write입니다. 먼저 write는 appendRange와 shrinkToFit이 stale Vector의 buffer pointer와 size field를 변경할 때 발생합니다. Ref<FontAccessor> entry를 저장하는 과정에서도 write가 일어납니다. 반면 read는 return ranges의 copy-out에서 발생합니다. 이때 Vector를 복사하면서, 그 안에서 발견되는 모든 FontAccessor pointer에 ref를 수행합니다.
확장 여부는 rehash 이후 outer frame이 재개되기 전까지, 해제된 array를 무엇이 다시 차지하느냐에 달려 있습니다. Getter의 script window가 바로 이 간극에 놓여 있으므로, 원론적으로 attacker는 그 사이에 allocation을 수행할 수 있습니다. 같은 크기이면서 attacker가 내용에 영향을 줄 수 있는 allocation이 해당 slot을 차지했다고 가정할 수 있습니다. 이 경우 outer frame의 연산은 attacker가 구성한 Vector metadata 위에서 동작하게 됩니다. 그러면 stale write가 controlled-pointer write나 fake refcounted object 접근으로 이어질 가능성이 있습니다. Exploit에 필요한 invariant는 HashMap table에 대한 allocator segregation이 이런 reclaim을 허용하는지 여부입니다. Reclaim이 없다면, 관찰되는 영향은 crash이거나 해제된 allocator 메모리의 조용한 손상에 그칠 것으로 보입니다. 이 경로는 document layout과 OffscreenCanvas measurement 양쪽 모두 WebContent process 안에서 실행됩니다. 단독으로는 sandbox를 넘지 않습니다.
이 vulnerability는 renderer process의 memory safety를 약화시킵니다. WebCore는 container 내부 reference를 쥔 native frame 도중에, 그 container를 변경할 수 있는 author script가 끼어들지 않는다고 전제합니다. 그런데 font loading 중의 promise resolution이 m_cache에 대해 이 전제를 깨뜨렸습니다. 결과적으로 page는 script가 고른 시점에 renderer가 해제된 heap allocation을 읽고 쓰도록 만들 수 있었습니다.
Insight. 쉽게 눈에 띄지 않는 교훈은 재진입 vector 쪽에 있습니다. CSSFontFace.cpp의 iterateClients는 client 통지를 ScriptDisallowedScope로 감쌉니다. 이 scope 안에서 script가 실행되면 debug build에서 assert가 발생합니다. 따라서 then getter에 도달하는 promise resolution은, 같은 load 완료 흐름 중 이 scope 밖의 별도 단계에 있을 가능성이 높습니다. Script-disallowed guard는 자신이 감싼 영역만 보호합니다. 바로 옆에 guard되지 않은 단계가 있으면 thenable 조회를 통해 synchronous script가 다시 들어오는데, wrapper 객체로 DOMPromise를 resolve하는 단계가 그 예입니다. 한편 correctness 측면의 side effect도 남아 있습니다. fontLoaded()는 m_cache를 비우지만, fix 이후의 fontRanges()도 루프가 끝나면 local에서 구성한 결과를 insert합니다. 그래서 재진입한 fontLoaded()가 실행되면 stale하지만 memory-safe한 entry가 남을 수 있습니다.
Audit directions
- 같은 table에 insert할 수 있는 호출을 넘어 유지되는 growable hash table 내부 reference. 지켜져야 할 invariant는
AddResult.iterator->value나ensure()reference가 소유 container에 도달할 수 있는 callee보다 오래 살아남지 않는 것입니다. Narrow: WebCorecss/,platform/graphics/의 font 코드(FontCache,CSSFontSelector,FontCascadeFonts),style/에서addResult.iterator->value와auto& x = map.add(/.ensure(를 검색합니다. 그 뒤에 loader, client, 또는 promise를 resolve하는 코드로의 호출이 이어지는지 확인합니다. Wider: 같은 형태는append를 넘어 유지되는Vectorelement reference에서도 나타납니다. Insertion을 넘어 유지되는ListHashSetiterator, body가 같은 map에 도달하는HashMap::ensurelambda도 마찬가지입니다. Widest:absl::flat_hash_map, LLVMDenseMap, Chromium의base::flat_map처럼 insertion 시 reference 안정성을 보장하지 않는 모든 map이 대상입니다. Java의HashMap.computeIfAbsent가 재귀적 수정 시ConcurrentModificationException을 던지는 것도 바로 이 이유 때문입니다. Code review에서는add/ensure로 바인딩한 local reference의 마지막 사용 전에 out-of-line 호출이 끼어 있다면 한 번 더 살펴볼 필요가 있습니다. - Platform object로 promise를 resolve하는 지점은 synchronous script 진입점. Thenable
then조회는 event dispatch를 막아둔 코드 안에서도 script를 실행합니다. 즉 객체로 promise를 resolve하는 것은 script를 호출하는 것과 같습니다. Narrow: layout, style, font, media 코드에서 wrapper 객체로DOMPromise나DOMPromiseProxyWithResolveCallback을 resolve하는 WebCore 호출 지점을 점검합니다.FontFace의loaded,FontFaceSet의ready/loadingdone부터 시작하는 것이 좋습니다. 그리고 그 아래 native frame이 raw reference나 iterator를 쥐고 있는지 확인합니다. Match tell: 다른 곳에서ScriptDisallowedScope아래에 놓이거나, cached container reference 아래에 놓인 코드에서 도달 가능한 resolve 호출. Wider: script에 노출된 객체에Get을 수행하는 모든 spec algorithm에 같은 synchronous getter 진입점이 존재합니다. Dictionary conversion,toJSON,Symbol.toPrimitive, iterator protocol 등이 해당합니다. Widest: 동작 도중 native 코드에서 promise를 resolve하는 모든 JS embedder(Blink, Gecko, Node.js native addon)가 대상입니다. Resolution을 재진입 경계로 취급하는지 확인할 필요가 있습니다. - Fill 계산 도중 invalidator가 실행될 수 있는 memoization cache. 무효화 경로(
fontLoaded()→m_cache.clear())가 fill 경로와 대칭적인지 확인합니다. Narrow:CSSSegmentedFontFace,CSSFontSelector,FontCascadeFonts에서 load 완료 client가 비우는 동시에, load를 유발하는 코드가 채우는 cache를 찾습니다. 이때 어떤 fill 경로도 table storage를 쥐고 있지 않은지 검증해야 합니다. 재진입한 clear 이후 fill 뒤의add가 stale data를 되살리지 않는지도 함께 확인합니다. Match tell: body가 같은 객체의clear()에 도달할 수 있는 루프 뒤에 오는add. Wider: 보통은 generation counter나 epoch check가 guard 역할을 합니다. Style resolution과 image decoding에서 이런 guard가 없는 cache를 찾아볼 필요가 있습니다. Widest: React memo cache나 build system의 incremental cache처럼, memoizing cache 전반에서 나타나는 invalidate-during-compute race에 해당합니다. Match tell: compute 시작 시점과 insert 시점 사이에 epoch 비교가 없는 경우.