CVE-2026-6722 CRITICAL 9.8 난이도Difficulty 고급Advanced

역직렬화기의 중복 키 처리에서 발생하는 Use-After-FreeUse-after-free in a deserializer's duplicate-key handling

공식 참조Official references: NVDCVE.org

CVE-2026-6722는 PHP (SOAP extension)의 Use-After-Free(CWE-416) 취약점으로, CVSS 9.8(CRITICAL)입니다. 영향 버전: 8.2.0 ≤ v < 8.2.31, 8.3.0 ≤ v < 8.3.31, 8.4.0 ≤ v < 8.4.21, 8.5.0 ≤ v < 8.5.6. 수정 버전: 8.2.31, 8.3.31, 8.4.21, 8.5.6.CVE-2026-6722 is an Use-After-Free (CWE-416) vulnerability in PHP (SOAP extension), rated CVSS 9.8 (CRITICAL). Affected: 8.2.0 ≤ v < 8.2.31, 8.3.0 ≤ v < 8.3.31, 8.4.0 ≤ v < 8.4.21, 8.5.0 ≤ v < 8.5.6. Fixed in: 8.2.31, 8.3.31, 8.4.21, 8.5.6.

제품Product PHP (SOAP extension)
영향 버전Affected 8.2.0 ≤ v < 8.2.31, 8.3.0 ≤ v < 8.3.31, 8.4.0 ≤ v < 8.4.21, 8.5.0 ≤ v < 8.5.6
수정 버전Fixed in 8.2.31, 8.3.31, 8.4.21, 8.5.6
심각도Severity CVSS 9.8 CRITICAL
취약점 유형Weakness CWE-416 Use-After-Free
공격 조건Attack conditions 원격 (네트워크) · 인증 불필요 · 사용자 상호작용 불필요Remote (network) · No authentication · No user interaction
SAMPLE 렌더링 시연용 샘플 — 본문의 기술 세부(코드·diff·흐름)는 사이트 기능을 보여주기 위한 예시이며 실제 어드바이저리와 다를 수 있습니다. 사실관계는 반드시 공식 참조로 확인하세요.Rendering sample — technical details (code, diff, flow) are illustrative and may differ from the actual advisory. Always verify against the official references.

1. TL;DR

신뢰할 수 없는 직렬화 데이터를 복원할 때, 같은 키가 두 번 나오면 첫 번째 값이 즉시 해제된다. 그런데 역직렬화기는 “앞에서 만든 값을 다시 가리키는” 백레퍼런스를 위해 그 값의 포인터를 따로 보관하고 있었다. 공격자는 해제된 슬롯을 자신이 고른 바이트로 다시 채운 뒤 백레퍼런스로 접근해, 가짜 객체를 진짜 객체처럼 다루게 만들 수 있다. 인증 없이 네트워크 입력만으로 닿는 경우 원격 코드 실행까지 가능하다(CVSS 9.8). 영향받는 버전과 수정 버전은 공식 어드바이저리를 따르고, 즉시 업데이트하라.

2. Flaw 분류

항목값
1차 CWECWE-416 Use-After-Free
연관 CWECWE-502 신뢰할 수 없는 데이터 역직렬화 · CWE-843 타입 혼동(결과)
공격 벡터네트워크 / 인증 불필요 / 사용자 상호작용 없음
영향기밀성·무결성·가용성 모두 High → 원격 코드 실행
전제애플리케이션이 외부 입력을 네이티브 역직렬화 함수에 넘긴다

이 글은 메모리 안전성 결함(UAF) 이 역직렬화라는 입력 경로를 통해 노출된 경우다. 같은 클래스의 다른 글과 비교하면 “수명(lifetime) 추적이 두 갈래로 나뉜다”는 공통 패턴이 보인다.

3. 근본 원인

역직렬화기는 키-값 쌍을 하나씩 읽어 해시 테이블에 넣는다. 동시에, 입력이 “N번째로 만든 값과 같은 것”이라고 가리킬 수 있도록 백레퍼런스 테이블 에 각 값의 포인터를 기록한다. 문제는 두 자료구조가 값의 수명을 서로 다르게 가정했다는 점이다.

/* 개념을 보여주기 위해 단순화한 의사 코드 — 실제 소스와 다르다 */
static int decode_pair(table_t *ht, decode_ctx_t *ctx, reader_t *r)
{
    key_t    key = decode_key(r);
    value_t *val = decode_value(ctx, r);   /* 새 값 생성, backref 테이블에도 등록됨 */
    value_t *old = table_find(ht, key);

    if (old) {                             /* 중복 키! */
        table_update(ht, key, val);
        value_release(old);                /* refcount 1 → 0, 즉시 free */
    } else {
        table_insert(ht, key, val);
    }
    return 0;
}
  • 해시 테이블 관점: old 는 더 이상 테이블에 없으니 해제해도 된다.
  • 백레퍼런스 테이블 관점: old 는 여전히 “k번째로 만든 값”이며, 참조 카운트를 올리지 않은 채(borrowed) 포인터만 들고 있다.

즉 소유권을 가진 쪽(해시 테이블)이 객체를 놓아 버렸는데, 빌려 쓴 쪽(백레퍼런스)은 그 사실을 모른다. 이것이 UAF의 전형적인 모양이다: “해제하는 경로”와 “참조를 보관하는 경로”가 서로 다른 장부를 쓴다.

4. 익스플로잇 흐름(개념)

  1. 트리거 — 중복키로 해제
  2. 힙 재점유 — 문자열 할당
  3. dangling 포인터 역참조
  4. RCE
개념 흐름도 — 실행 가능한 페이로드가 아닙니다
  1. 트리거 — 같은 키를 두 번 넣으면 첫 번째 값이 해제된다. 백레퍼런스 테이블에는 그 주소가 그대로 남는다.
  2. 힙 재점유 — 할당자는 방금 해제된 크기와 같은 크기의 요청에 그 슬롯을 우선 재사용한다. 공격자가 바로 다음 원소로 “같은 크기의 문자열”을 두면, 그 문자열의 바이트가 해제된 값 구조체의 자리를 차지한다.
  3. dangling 포인터 역참조 — 입력이 백레퍼런스로 k번째 값을 가리키면, 엔진은 문자열 바이트를 값 구조체로 해석한다. 타입 태그·포인터 필드를 공격자가 정한 셈이므로 타입 혼동 상태가 된다.
  4. RCE — 가짜 객체에 대해 소멸자나 메서드 호출이 일어나는 순간, 엔진은 공격자가 고른 주소의 함수 테이블을 따라간다. 실제로 이 단계까지 가려면 ASLR을 우회하기 위한 주소 누출 등 추가 프리미티브가 필요하며, 이 글은 그 세부를 다루지 않는다.

학습 포인트: UAF 자체는 “잘못된 읽기”일 뿐이다. 코드 실행으로 바뀌는 지점은 해제된 슬롯을 공격자 데이터로 재점유할 수 있는가, 그리고 그 데이터가 함수 포인터로 해석되는가 두 가지다.

5. 트리거 조건

  • 애플리케이션이 외부에서 온 직렬화 문자열(쿠키, 폼 필드, 캐시, 메시지 큐 등)을 네이티브 역직렬화 함수에 그대로 넘긴다.
  • 입력 안에 같은 키가 두 번 등장하고, 그 뒤에 덮어쓴 값을 가리키는 백레퍼런스 가 온다.
  • 영향받는 버전의 런타임을 사용한다(정확한 버전 범위는 References의 공식 어드바이저리 참조).
  • 인증이 필요 없는 엔드포인트에서 위 입력을 받으면 CVSS 9.8(AV:N/AC:L/PR:N/UI:N)이 된다.

반대로 외부 입력을 네이티브 역직렬화에 넘기지 않는 애플리케이션은, 런타임이 취약 버전이라도 이 경로로는 도달할 수 없다. 그렇다고 업데이트를 미뤄도 된다는 뜻은 아니다.

6. 패치 분석

수정의 핵심은 “덮어쓴 값의 수명을 백레퍼런스의 수명과 맞추는 것”이다. 즉시 해제하지 않고 역직렬화 컨텍스트가 끝날 때 한꺼번에 해제 하도록 미룬다.

+3−1c
@@ static int decode_pair(table_t *ht, decode_ctx_t *ctx, reader_t *r)
    value_t *old = table_find(ht, key);

    if (old) {                             /* 중복 키! */
        table_update(ht, key, val);
        value_release(old);                /* refcount 1 → 0, 즉시 free */
        /* backref 테이블이 old 를 빌려 쓰고 있을 수 있다.
         * 컨텍스트 종료(decode_ctx_destroy) 시점까지 해제를 미룬다. */
        decode_ctx_defer_release(ctx, old);
    } else {
        table_insert(ht, key, val);
    }
  • 삭제된 한 줄(value_release(old))이 바로 UAF의 시작점이었다.
  • 추가된 줄은 해제를 없애지 않고 시점만 옮긴다 → 메모리 누수 없이, 백레퍼런스가 살아 있는 동안 슬롯이 재사용되지 않는다.
  • 2단계(힙 재점유)가 불가능해지므로 이후 흐름 전체가 끊긴다. “패치 한 줄이 왜 RCE를 막는가”에 대한 답이 여기 있다.

대안적인 수정으로는 백레퍼런스 테이블이 참조 카운트를 직접 올리는 방법(빌림 → 소유)도 있다. 어느 쪽이든 원칙은 같다: 참조를 보관하는 모든 곳이 수명 장부에 참여해야 한다.

7. 탐지·완화

즉시 조치

  • 공식 어드바이저리의 수정 버전으로 런타임을 업데이트한다(배포판 패키지 포함).
  • 외부 입력을 네이티브 역직렬화 함수에 넘기는 코드를 찾아 JSON 등 데이터 전용 포맷 으로 바꾼다. 이것은 이 CVE와 무관하게 CWE-502 계열 전반을 막는다.

탐지

  • 웹 워커 프로세스의 비정상 종료(segfault) 로그가 갑자기 늘었는지 확인한다. UAF 익스플로잇 시도는 실패할 때 크래시를 남기는 경우가 많다.
  • 직렬화 데이터를 받는 엔드포인트에서 같은 키가 반복되는 비정상 입력을 로깅한다. 단, 시그니처 기반 차단은 우회가 쉬우므로 보조 수단으로만 쓴다.

격리된 실습(로컬 Docker 랩)

  • 인터넷과 분리된 컨테이너에 취약 버전을 AddressSanitizer(ASan) 빌드로 띄우고, 중복 키 입력을 넣었을 때 출력되는 heap-use-after-free 리포트를 읽어 본다. “어디서 free 되었고(freed by), 어디서 다시 쓰였는가(READ of size … )“의 두 스택이 3장의 두 장부와 정확히 대응한다.
  • 같은 입력을 패치된 버전에 넣으면 리포트가 사라지는 것을 확인한다. 이것이 패치 검증의 기본 형태다.

8. References

1. TL;DR

When restoring untrusted serialized data, a key that appears twice causes the first value to be freed immediately. But the deserializer had separately stored a pointer to that value for back-references (“same as the value decoded earlier”). An attacker can refill the freed slot with bytes of their choice and then reach it through a back-reference, making the engine treat a fake object as a real one. Reachable from unauthenticated network input, this can lead to remote code execution (CVSS 9.8). Follow the official advisory for affected/fixed versions and update now.

2. Flaw classification

FieldValue
Primary CWECWE-416 Use-After-Free
Related CWECWE-502 Deserialization of Untrusted Data · CWE-843 Type Confusion (consequence)
Attack vectorNetwork / no auth / no user interaction
ImpactC/I/A High → remote code execution
PreconditionThe application passes external input to the native deserializer

This is a memory-safety flaw (UAF) exposed through a deserialization input path. Compared with other posts in the class, the common shape is “lifetime tracking split into two ledgers”.

3. Root cause

The deserializer reads key/value pairs into a hash table. At the same time it records each value’s pointer in a back-reference table so the input can say “same as the N-th value”. The two structures assumed different lifetimes for the same value.

/* Simplified pseudo-code to illustrate the concept — not the real source */
static int decode_pair(table_t *ht, decode_ctx_t *ctx, reader_t *r)
{
    key_t    key = decode_key(r);
    value_t *val = decode_value(ctx, r);   /* new value, also registered as a backref */
    value_t *old = table_find(ht, key);

    if (old) {                             /* duplicate key! */
        table_update(ht, key, val);
        value_release(old);                /* refcount 1 -> 0, freed immediately */
    } else {
        table_insert(ht, key, val);
    }
    return 0;
}
  • From the hash table’s view: old is no longer in the table, so freeing it is fine.
  • From the back-reference table’s view: old is still “the k-th value”, held as a borrowed pointer without a refcount.

The owner let go of the object while the borrower never found out. That is the canonical UAF shape: the path that frees and the path that keeps a reference use different ledgers.

4. Exploit flow (conceptual)

  1. Trigger — free via duplicate key
  2. Heap reclaim — string allocation
  3. Dangling pointer deref
  4. RCE
Conceptual flow — not an executable payload
  1. Trigger — inserting the same key twice frees the first value; its address remains in the back-reference table.
  2. Heap reclaim — the allocator prefers to reuse a just-freed slot for a same-size request. A same-size string placed next lands in the freed value’s slot.
  3. Dangling dereference — a back-reference to the k-th value makes the engine interpret the string bytes as a value struct. The attacker chose the type tag and pointer fields: type confusion.
  4. RCE — once a destructor or method is invoked on the fake object, the engine follows a function table at an attacker-chosen address. In practice this needs extra primitives such as an address leak to defeat ASLR; this post does not cover them.

Takeaway: a UAF alone is just a bad read. It becomes code execution only if the freed slot can be reclaimed with attacker data and that data is interpreted as a function pointer.

5. Trigger conditions

  • The application passes externally sourced serialized strings (cookies, form fields, caches, message queues…) straight to the native deserializer.
  • The input contains the same key twice, followed by a back-reference to the overwritten value.
  • An affected runtime version is in use (see the official advisory in References).
  • When reachable from an unauthenticated endpoint, this is CVSS 9.8 (AV:N/AC:L/PR:N/UI:N).

Applications that never pass external input to native deserialization cannot be reached through this path even on a vulnerable runtime — which is not a reason to postpone the update.

6. Patch analysis

The fix aligns the overwritten value’s lifetime with the back-references: instead of freeing immediately, it defers the free until the deserialization context ends.

+3−1c
@@ static int decode_pair(table_t *ht, decode_ctx_t *ctx, reader_t *r)
    value_t *old = table_find(ht, key);

    if (old) {                             /* duplicate key! */
        table_update(ht, key, val);
        value_release(old);                /* refcount 1 -> 0, freed immediately */
        /* the backref table may still borrow old.
         * defer the free until decode_ctx_destroy(). */
        decode_ctx_defer_release(ctx, old);
    } else {
        table_insert(ht, key, val);
    }
  • The removed line (value_release(old)) was where the UAF began.
  • The added line does not remove the free, it moves it — no leak, and the slot cannot be reused while back-references are alive.
  • Step 2 (heap reclaim) becomes impossible, so the whole chain breaks. That is why one patched line stops the RCE.

An alternative fix is for the back-reference table to take its own refcount (borrow → own). Either way: everything that keeps a reference must participate in the lifetime ledger.

7. Detection & mitigation

Immediate actions

  • Update the runtime to the fixed version from the official advisory (including distro packages).
  • Find code that passes external input to native deserialization and switch to data-only formats such as JSON. This blocks the whole CWE-502 family, not just this CVE.

Detection

  • Watch for spikes in worker-process crashes (segfaults). Failed UAF exploitation attempts often leave crashes behind.
  • Log abnormal serialized input with repeated keys at endpoints that accept it. Signature blocking is easy to bypass; use it only as a supplement.

Isolated lab (local Docker)

  • In an offline container, run an AddressSanitizer (ASan) build of an affected version and read the heap-use-after-free report produced by duplicate-key input. The two stacks — “freed by” and “READ of size …” — map exactly to the two ledgers in section 3.
  • Feed the same input to the patched version and confirm the report disappears. That is the basic shape of patch verification.

8. References

챌린지Challenge

격리 Docker 랩Isolated Docker lab

본인이 소유한 인터넷 분리 환경에서만 실습하세요. 채점은 브라우저 안에서만 이뤄지며(정답은 서버에 없습니다), 무기화된 익스플로잇 작성은 학습자 몫입니다.Run only in an isolated environment you own. Grading happens entirely in your browser (the answer is not stored on any server), and writing a weaponized exploit is left to you.

목표Objective

격리된 Docker 랩에서 중복 키 역직렬화로 UAF를 재현하고(ASan 리포트), 패치 전후를 비교한 뒤, 해제된 슬롯을 다시 채워 dangling 백레퍼런스가 가리키는 값을 복구해 플래그를 얻는다.In the isolated Docker lab, reproduce the duplicate-key UAF (ASan report), compare the patched vs vulnerable builds, then reclaim the freed slot so the dangling back-reference recovers the hidden value and reveals the flag.

단계별 과제Tasks

  1. labs/CVE-2026-6722 를 받아 인터넷과 분리된 컨테이너에서 두 빌드(vuln / patched)를 만든다.Get labs/CVE-2026-6722 and build both targets (vuln / patched) inside an internet-isolated container.
  2. ASan 빌드에 inputs/01-reproduce-uaf.txt 를 넣어 heap-use-after-free 리포트를 재현하고, 리포트의 freed-by 스택과 READ-of 스택이 3장의 해시테이블/백레퍼런스 두 장부에 각각 어떻게 대응하는지 적는다.Run inputs/01-reproduce-uaf.txt against the ASan build, reproduce the heap-use-after-free report, and note how its freed-by stack and READ-of stack map to the hash-table vs back-reference ledgers from section 3.
  3. 같은 입력을 patched 빌드에 넣어 리포트가 사라지는지 확인한다(해제 시점을 컨텍스트 종료로 미룬 효과).Feed the same input to the patched build and confirm the report is gone (the effect of deferring the free to context teardown).
  4. vuln(비-ASan) 빌드에서 해제된 슬롯을 당신이 고른 바이트로 다시 채우고, dangling 백레퍼런스로 그 값을 읽어 출력된 플래그를 제출한다.On the vuln (non-ASan) build, reclaim the freed slot with bytes you choose, read it back through the dangling back-reference, and submit the flag it prints.

힌트Hints

힌트Hint 1

중복 키는 첫 번째 값을 즉시 해제하지만, 백레퍼런스 테이블의 그 인덱스는 해제된 주소를 그대로 가리킨다. get <index> 가 바로 그 dangling 참조를 사용한다.The duplicate key frees the first value immediately, but that index in the back-reference table still points at the freed address. get <index> is what dereferences the dangling pointer.

힌트Hint 2

glibc tcache 는 같은 크기 블록을 LIFO 로 재사용한다. 해제 직후 같은 크기 할당은 바로 그 슬롯을 돌려받는다 — 랩의 raw 연산이 그 자리를 당신이 고른 바이트로 채우는 수단이다.glibc tcache reuses same-size blocks LIFO, so an allocation of the same size right after the free gets that exact slot back. The lab's raw op is how you place your chosen bytes there.

힌트Hint 3

값 구조체의 맨 앞 4바이트는 kind 태그다. 랩 소스(deserialize.c)에서 crafted 태그 상수를 찾아 재점유 바이트의 앞부분을 그 값에 맞춰라. 자세한 경로는 README 의 Flag 설명 참고.The first 4 bytes of the value struct are the kind tag. Find the crafted tag constant in the lab source (deserialize.c) and set the front of your reclaim bytes to it. See the README's Flag section for the full path.