Back
+30 XP
Concept

Safe Path Traversal Checker

Users supplying relative file paths like ../../etc/passwd can escape storage boundaries. Standard os.path.join fails to block directory traversal. Validating that os.path.commonpath([base_dir, resolved_path]) equals base_dir strictly confines file access within allowed directory trees.

python
import os

base = os.path.abspath(base_dir)
target = os.path.abspath(os.path.join(base, user_path))
if os.path.commonpath([base, target]) != base:
    raise PermissionError("Path traversal blocked!")

# Safe Path Traversal Checker When an application serves user downloads via `send_file(os.path.join("/var/data/uploads", filename))`, an attacker doesn't request `report.pdf`. They request `../../../../etc/shadow`. 🛑🔓 In Python, `os.path.abspath(os.path.join("/var/data/uploads", "../../../../etc/shadow"))` happily returns `"/etc/shadow"`. If your code checks `if filename.startswith("/")`, it misses `../` relative traversals entirely. The gold standard in Python 3.5+ is `os.path.commonpath([base_dir, resolved_path])`. If the common ancestor between the base directory and the target path does not exactly equal the base directory, the user is attempting to escape the sandbox. ```python import os base = os.path.abspath("/var/uploads") target = os.path.abspath(os.path.join(base, user_input)) if os.path.commonpath([base, target]) != base: raise PermissionError("Sandbox escape detected!") ``` ## Pop Quiz Why does `os.path.join('/base/path', '../../etc/passwd')` resolve to `'/etc/passwd'`? - [ ] The `..` operator traverses to parent directories; abspath normalizes out intermediate directory components. - [ ] The Linux kernel automatically maps root directories to `/etc/passwd`. - [ ] Because Python filesystems require backslashes to distinguish directory boundaries. - [ ] To prevent relative symlinks from generating filesystem deadlock locks. ## Real-World Challenge Implement `safe_resolve_path(base_dir: str, user_path: str) -> str`. - Canonicalize `base_dir` and the combined `target` path. - Enforce that `os.path.commonpath([base, target]) == base`. - If the resolved path points outside `base_dir`, raise `PermissionError`. <details> <summary>Solution</summary> ```python import os def safe_resolve_path(base_dir: str, user_path: str) -> str: base = os.path.abspath(base_dir) target = os.path.abspath(os.path.join(base, user_path)) try: common = os.path.commonpath([base, target]) except ValueError: # Happens on Windows if paths reside on different drive letters raise PermissionError("Path traversal across distinct drives blocked") if common != base: raise PermissionError(f"Access denied: path '{user_path}' escapes sandbox '{base_dir}'") return target # Verification sandbox = "/var/app/storage" # 1. Valid paths within sandbox p1 = safe_resolve_path(sandbox, "docs/report.pdf") assert p1 == "/var/app/storage/docs/report.pdf" p2 = safe_resolve_path(sandbox, "./nested/../image.png") assert p2 == "/var/app/storage/image.png" # 2. Path traversal attack attack_caught = False try: safe_resolve_path(sandbox, "../../../etc/passwd") except PermissionError: attack_caught = True assert attack_caught is True ``` </details>