[JSC] Cached `String#replace` width-confusion fix
String#replace checked every replacement was 8-bit, then called your function again.
Component: JSC | 61b3aec
Source/JavaScriptCore/runtime/StringPrototypeInlines.h
JSTests/stress/string-replace-cached-replacement-changes-width.js
replaceAllWithCacheUsingRegExpSearchThreeArguments는 str.replace(globalRegExp, fn) 호출을 처리하는 JSC의 fast path입니다. 먼저 match마다 replacer를 호출하고, 반환된 결과를 JSString* 형태로 vector에 보관합니다. 이때 모든 replacement가 8-bit인지 여부도 함께 추적합니다. 이후 all-8-bit 또는 16-bit 경우에 맞는 크기로 output buffer를 한 번 할당하고, 각 조각을 그 안에 복사합니다. 한편 JSString은 내부적으로 StringImpl을 감싸고 있는데, 이 문자열을 property key로 사용하면 atomize가 수행됩니다. 즉 StringImpl이 기존의 canonical atom으로 교체되며, 이 atom은 내용은 같지만 width가 다를 수 있습니다. 패치 이전의 복사 loop는 저장된 각 replacement를 StringView::getCharacters8()로 읽었습니다. 패치 이후에는 두 width를 모두 처리하는 getCharacters()를 사용하도록 변경되었습니다. 함께 추가된 stress test는 /x/g와 /(x)/g 두 패턴에 대해 양방향 width 변화를 모두 다룹니다.
call #1: replacer returns R (8-bit) ─► "all 8-bit" recorded
call #2: table[R] = 2 ─► R atomized: StringImpl swapped
for existing 16-bit atom
copy loop (8-bit buffer):
Before: getCharacters8(buf) 16-bit data copied as Latin-1
After: getCharacters(buf) width-aware copy
Significance
8-bit 검사가 끝난 뒤에도 replacer callback이 이미 수집된 replacement의 width를 바꿀 수 있었고, 그 결과 복사 loop가 16-bit 문자 데이터를 Latin-1로 처리했습니다. JSC runtime에서 발생하는 width confusion에 해당합니다. 일반 JS 코드만으로 도달 가능하며, 발생 시점은 attacker가 제어하는 callback으로 조절할 수 있습니다.
Audit directions
User callback을 사이에 둔 전형적인 check-then-use 버그입니다. 좁은 범위에서는, 패치 이후에도 buffer 할당과 복사가 width 측면에서 일치하는지 확인할 필요가 있습니다. 또한 atomization이 내용을 보존한다는 점을 고려할 때, getCharacters() 내부의 narrowing이 안전한지도 점검해야 합니다.
범위를 넓히면 sibling 경로가 더 유망한 대상입니다. 먼저 callback을 거치는 동안 JSString*을 캐시하는 다른 replace/replaceAll/split/join fast path가 후보입니다. User code 호출 이후에 남아 있는 getCharacters8() / span<Latin1Character> 사용처도 살펴볼 필요가 있습니다. Two-argument 변형과 non-RegExp cached 변형 역시 같은 관점에서 확인해야 합니다.
JSC 내부에서 가장 넓게 보면, 살아 있는 JSString 아래에서 StringImpl을 교체하는 다른 경로들이 대상이 됩니다. Property-key atomization, rope resolution, string-to-identifier 변환이 여기에 해당합니다. 이런 경로가 미리 계산된 length나 width를 stale 상태로 만들 수 있는지 점검해야 합니다.
판별 신호는 다음과 같습니다. JS를 호출하는 loop 안에서 width나 length flag를 계산하고, loop가 끝난 뒤 문자열을 다시 읽지 않은 채 그 값을 사용하는 패턴입니다.