説明
tarアーカイブは信頼できる親の下に作った新規の非公開ディレクトリへ展開してください。パスやリンクを制限しない設定では、展開先の外にあるファイルが上書きされるおそれがあります。
想定される影響
サービスアカウントが書き込めるファイルは破損する可能性があります。ほかのプロセスが変更されたファイルを使うと、サービス停止、情報漏えい、権限昇格につながるおそれがあります。
対処方法
- 展開フィルターがあるPythonでは
extractall(..., filter="data")を指定し、展開先の外を指すパスやリンク、特殊ファイル、過剰な権限を制限します。Python 3.14以降の既定値はdataです。フィルターを省略すると実行環境の設定が使われます。 - フィルターがない場合は通常ファイルとディレクトリだけを許可し、シンボリックリンクとハードリンクを拒否します。各パスが展開先に収まることを確認してから新規ファイルを作ります。
- 実際の展開バイト数、項目数、処理時間は別途制限してください。
例
変更前
python
# ランタイムの既定フィルターによるtar展開
import tarfile
def unsafe_extract(tar_file_path, extract_path):
with tarfile.open(tar_file_path) as tar:
tar.extractall(path=extract_path)
変更後
python
# 展開先を制限するtar展開
import tarfile
import os
import shutil
from pathlib import Path
def safe_extract(tar_file_path, extract_path):
destination = Path(extract_path)
# 既存ファイルやリンクのない専用ディレクトリーにのみ展開
destination.mkdir(mode=0o700, exist_ok=False)
destination = destination.resolve()
with tarfile.open(tar_file_path) as tar:
if hasattr(tarfile, "data_filter"):
# 展開フィルターに対応するランタイムの制限付きデータ展開
tar.extractall(path=destination, filter="data")
return
# 古いランタイム用: リンクと特殊ファイルを拒否し、ディレクトリー境界を確認
for member in tar.getmembers():
if member.issym() or member.islnk():
raise ValueError("Tar links are not allowed")
if not (member.isfile() or member.isdir()):
raise ValueError("Unsupported tar entry type")
target = (destination / member.name).resolve()
try:
target.relative_to(destination)
except ValueError as error:
raise ValueError("Tar entry escapes extraction directory") from error
if member.isdir():
target.mkdir(parents=True, exist_ok=True, mode=0o700)
continue
target.parent.mkdir(parents=True, exist_ok=True, mode=0o700)
source = tar.extractfile(member)
if source is None:
raise ValueError("Tar entry has no file data")
fd = os.open(target, os.O_WRONLY | os.O_CREAT | os.O_EXCL, 0o600)
with source, os.fdopen(fd, "wb") as output:
shutil.copyfileobj(source, output)
この関数は tarfile.data_filter の有無で展開方法を選びます。古い環境向けの処理では各パスの実体を確認し、os.O_EXCL で既存ファイルの上書きを防ぎます。