# Improper Limitation of a Pathname to a Restricted Directory ('Path Traversal') (CWE-22) The product uses external input to construct a pathname that is intended to identify a file or directory that is located underneath a restricted parent directory, but the product does not properly neutralize special elements within the pathname that can cause the pathname to resolve to a location that is outside of the restricted directory. **Stack:** Python - Prevalence: 高 频繁被利用 - Impact: 关键 1 条严重级别为关键的规则 - Prevention: 已记录 6 个修复示例 **OWASP:** Broken Access Control (A01:2021-Broken Access Control) - #1 ## Description Many file operations are intended to take place within a restricted directory. By using special elements such as '..' and '/' separators, attackers can escape outside of the restricted location to access files or directories that are elsewhere on the system. ## Prevention 基于 2 条 Shoulder 检测规则的 Path Traversal 预防策略。 ### Python Use os.path.basename() or pathlib to restrict file access to intended directories Validate extracted file paths stay within the target directory before writing ## Warning Signs - [HIGH] untrusted user input being used in file system operations without proper validation - [HIGH] unsafe extraction of ZIP/TAR archives without path validation ## Consequences - 读取文件或目录 - 修改文件或目录 - 执行未授权代码 ## Mitigations - 使用经过审查的库或框架,以防止此弱点出现 - 使用严格符合规范的可接受输入的允许列表 - 对于文件名,使用限制字符集的严格允许列表 ## Detection - Total rules: 6 - Critical: 1 - Languages: go, javascript, typescript, python ## Rules by Language ### Python (2 rules) - **Path Traversal / Directory Traversal** [HIGH]: Detects untrusted user input being used in file system operations without proper validation. - Remediation: Use os.path.basename() to extract the filename only. ```python import os safe_filename = os.path.basename(user_filename) ``` Learn more: https://shoulder.dev/learn/python/cwe-22/path-traversal - **Zip Slip / Archive Path Traversal** [HIGH]: Detects unsafe extraction of ZIP/TAR archives without path validation. Malicious archives can contain filenames with "../" to write files outside the intended directory (path traversal). Always validate extracted paths. - Remediation: Validate that extracted paths stay within the target directory before writing. ```python import zipfile import os def safe_extract(zip_path, extract_to): with zipfile.ZipFile(zip_path, 'r') as zf: for member in zf.namelist(): target = os.path.normpath(os.path.join(extract_to, member)) if not target.startswith(os.path.abspath(extract_to)): raise ValueError(f"Path traversal: {member}") zf.extract(member, extract_to) ``` Learn more: https://shoulder.dev/learn/python/cwe-22/zip-slip