flawopen.com/path-traversal/Python

● CWE-918 · 高
セキュリティ研究 · FlawOpen

脆弱性の解説:Path Traversal in Python

How os.path.join silently discards the root directory when input starts with a slash, and how to use pathlib.Path.resolve() and is_relative_to().

💡 わかりやすい解説 (ELI5)

ホテルの客室カードリーダーが2階の部屋のみを開けるよう制限されている場面を例えに考えてみてください。もし宿泊客がドアのキーパッドに「../../master-safe」と入力すると、不備のある鍵が廊下を抜け出して支配人の金庫を直接解錠してしまいます。

主要な概念と専門用語

Web Application Security
主要概念 (Web Application Security):Core architecture component affected by CWE-918.
CWE-918
主要概念 (CWE-918):Standard Common Weakness Enumeration classification for path-traversal-python.
Defense-in-Depth
主要概念 (Defense-in-Depth):Multi-layered engineering verification and runtime boundary isolation.

ステップ・バイ・ステップの攻撃フロー

Step 1

ファイルパス入力の受信

エンドポイントがHTTPリクエストパラメータからユーザー指定のファイル名やパスを受け取ります。

Step 2

ディレクトリトラバーサル記号の挿入

攻撃者が '../' や '..%2f' などの相対パス記号や絶対パス指定を挿入します。

Step 3

ベースディレクトリ境界の突破

バックエンドが正規化パスの検証を行わずに文字列を連結し、公開フォルダ外へのアクセスを許容します。

Step 4

機密ファイルの漏洩または上書き

OSが /etc/passwd や設定ファイルなどの重要ファイルを読み取り、攻撃者へ返却します。

ソースコード比較:脆弱 vs 堅牢化

✕ 脆弱な実装
# VULNERABLE: os.path.join discards BASE_DIR if filename starts with '/'
import os
from flask import Flask, request, abort, send_file

app = Flask(__name__)
BASE_DIR = '/var/app/public/user_uploads'

@app.route('/download')
def download_file():
    filename = request.args.get('file')
    # If filename is "/etc/passwd", os.path.join returns "/etc/passwd"!
    # If filename is "../../etc/passwd", it traverses outside BASE_DIR
    target_path = os.path.join(BASE_DIR, filename)
    
    if not os.path.exists(target_path):
        abort(404)
    return send_file(target_path)
✓ 堅牢化されたセキュアパッチ
# HARDENED: Resolve canonical path and enforce strict boundary containment
from pathlib import Path
from flask import Flask, request, abort, send_file

app = Flask(__name__)
BASE_DIR = Path('/var/app/public/user_uploads').resolve()

@app.route('/download')
def download_file():
    filename = request.args.get('file', '')
    # 1. Strip leading slashes and resolve relative components
    clean_name = filename.lstrip('/\\')
    target_path = (BASE_DIR / clean_name).resolve()
    
    # 2. Strict containment check: target MUST be inside BASE_DIR
    if not target_path.is_relative_to(BASE_DIR) or not target_path.is_file():
        abort(403)
        
    return send_file(target_path)

エンジニアリング&システム堅牢化チェックリスト

References