0
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

zipfile.extractallは本当に危険か:Windowsで../と絶対パスを実測する

0
Posted at

はじめに

ZIPの展開処理は、Zip Slip(../ によるディレクトリ脱出)が有名です。しかしPythonの zipfile.extractall() は、現在のバージョンでは危険なパスを無害化します。古い記事のまま「extractallは危険」と決めつけると、逆に必要な検証を落とします。

この記事では、Windows上のPython 3.11で ../・絶対パス・ドライブレター付きパスを実際に展開し、何がどこへ出るかを確認します。

環境

  • Windows 11(ビルド 10.0.26200)
  • Python 3.11.5

やったこと

1. 攻撃的なZIPを作る

import zipfile
from pathlib import Path

base = Path("C:/work/ziptest")
base.mkdir(parents=True, exist_ok=True)
zpath = base / "evil.zip"

with zipfile.ZipFile(zpath, "w") as z:
    z.writestr("../up.txt", "up")
    z.writestr("/abs.txt", "abs")
    z.writestr("C:/drive.txt", "drive")
    z.writestr("ok.txt", "ok")

2. extractallで展開する

out = base / "out"
out.mkdir()
with zipfile.ZipFile(zpath) as z:
    print(z.namelist())
    z.extractall(out)

結果:

['../up.txt', '/abs.txt', 'C:/drive.txt', 'ok.txt']

展開後のファイル:

out\abs.txt
out\drive.txt
out\ok.txt
out\up.txt

../up.txt は out\up.txt に、/abs.txt と C:/drive.txt も out の中に収まりました。out の外には出ていません。

3. 自分で検証する

extractall が無害化するからといって、すべてを任せてよいわけではありません。展開前に「展開後の絶対パスが宛先の内側か」を検証します。

import os
import zipfile
from pathlib import Path

def safe_extract(zpath: Path, dest: Path) -> None:
    dest = dest.resolve()
    with zipfile.ZipFile(zpath) as z:
        for member in z.infolist():
            target = (dest / member.filename).resolve()
            if not str(target).startswith(str(dest) + os.sep):
                raise ValueError(f"unsafe path: {member.filename}")
        z.extractall(dest)

実行結果:

ValueError: unsafe path: ../up.txt

../up.txt を展開前に拒否できました。

4. シンボリックリンクも確認する

ZIPはシンボリックリンクを格納できます。展開先の外を指すリンクがあると、後続の読み書きが外へ漏れます。ZipInfo.external_attr を見て、リンク属性のエントリを拒否するか、展開後に確認します。

with zipfile.ZipFile(zpath) as z:
    for info in z.infolist():
        mode = info.external_attr >> 16
        if mode & 0o120000 == 0o120000:
            print("symlink:", info.filename)

5. 展開サイズの上限も決める

圧縮爆弾(zip bomb)に備え、展開後の合計サイズとファイル数を制限します。

MAX_TOTAL = 500 * 1024 * 1024  # 500MB
MAX_FILES = 10_000

with zipfile.ZipFile(zpath) as z:
    infos = z.infolist()
    if len(infos) > MAX_FILES:
        raise ValueError("too many files")
    if sum(i.file_size for i in infos) > MAX_TOTAL:
        raise ValueError("too large")

ハマった点

「extractallは危険」はバージョン依存

古いPythonや他言語の実装では、../ がそのまま展開されることがありました。Python 3.11の実測では無害化されましたが、バージョンを確認せずに前提にしないでください。自前の検証を入れるのが安全です。

大文字小文字と区切り文字

Windowsはパスの大文字小文字を区別しません。startswith の比較は、os.path.normcase を通すか、Path.is_relative_to() を使うと安全です。

target = (dest / member.filename).resolve()
if not target.is_relative_to(dest):
    raise ValueError(member.filename)

展開先をユーザー入力から作らない

展開先のパスを外部入力から組み立てると、それ自体がパストラバーサルの入口になります。展開先はアプリが決めた固定ディレクトリにします。

まとめ

  • Python 3.11の extractall は ../・絶対パス・ドライブレターを展開先の内側へ無害化した。
  • ただしバージョン依存なので、展開前に is_relative_to() で検証する。
  • シンボリックリンク属性と、展開サイズ・ファイル数の上限も確認する。
  • 展開先は外部入力から組み立てない。
  • 「無害化される」と「検証不要」は別の話。
0
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?