Path Traversal via User-Controlled File Path
Description
User input passed to open() may allow path traversal attacks. This can expose or overwrite arbitrary files on the server. Validate file paths and ensure they remain within a trusted directory.
Examples
Insecure Code
python
open(user_input, 'r')Secure Code
python
import os
def safe_open_file(filename, base_path):
abs_path = os.path.abspath(filename)
if not abs_path.startswith(base_path):
raise ValueError("Invalid path")
return open(abs_path, 'r')Remediation
Validate file paths using a trusted directory and ensure they do not allow traversal outside of it.
Rule Details
| Field | Value |
|---|---|
| ID | CODE-0252 |
| Category | Injection |
| Severity | CRITICAL |
| CWE | CWE-22 |
| Confidence | HIGH |
| Impact | HIGH |
| Likelihood | MEDIUM |
| Exploitability | EASY |
| Tags | path traversal, file inclusion |
| OWASP | A01:2021-Broken Access Control |