| name | path-traversal-anti-pattern |
| description | Security anti-pattern for path traversal vulnerabilities (CWE-22). Use when generating or reviewing code that handles file paths, reads or writes files based on user input, or serves static content. Detects joining user input to paths without proper sanitization or validation. |
Path Traversal Anti-Pattern
Severity: High
Summary
Attackers read or write files outside intended directories by manipulating user input in file paths. Using sequences like ../ without validation allows navigation up directory trees to access /etc/passwd, source code, or credentials.
The Anti-Pattern
The anti-pattern is concatenating user input into file paths without validating for directory traversal characters.
BAD Code Example
from flask import request
import os
BASE_DIR = "/var/www/uploads/"
@app.route("/files/view")
def view_file():
filename = request.args.get("filename")
file_path = os.path.join(BASE_DIR, filename)
try:
with open(file_path, 'r') as f:
return f.read()
except FileNotFoundError:
return "File not found.", 404
GOOD Code Example
from flask import request
import os
BASE_DIR = "/var/www/uploads/"
@app.route("/files/view/secure")
def view_file_secure():
filename = request.args.get("filename")
if ".." in filename or filename.startswith("/"):
return "Invalid filename.", 400
file_path = os.path.join(BASE_DIR, filename)
real_path = os.path.realpath(file_path)
real_base_dir = os.path.realpath(BASE_DIR)
if not real_path.startswith(real_base_dir + os.sep):
return "Access denied: Path is outside of the allowed directory.", 403
try:
with open(real_path, 'r') as f:
return f.read()
except FileNotFoundError:
return "File not found.", 404
Detection
- Trace user input: Follow any user-controlled input (from request parameters, body, headers, etc.) that is used in a file operation.
- Look for path concatenation: Search for functions that join or concatenate strings to form file paths (e.g.,
os.path.join, + on strings).
- Check for missing validation: Verify that before being used, the input is checked for path traversal sequences (
../, ..\). A simple search-and-replace for ../ is not sufficient due to potential bypasses like ....//.
- Ensure path canonicalization: The most important check is to see if the application resolves the final path to its absolute, canonical form and then verifies that it is still within the intended base directory.
Prevention
Related Security Patterns & Anti-Patterns
References