Prevent Path Traversal
Canonicalize and validate all filesystem paths constructed from user input — verifying they resolve within an intended base directory — to block directory traversal attacks that read or overwrite arbitrary server files.
Why This Is Best Practice
Adopted by: OWASP Top 10 2021 A01 (Broken Access Control) includes path traversal. CWE-22 is one of the most common CVE categories — 2,000+ CVEs listed in NVD. Apache HTTP Server (CVE-2021-41773), Pulse Secure (CVE-2019-11510), and Citrix (CVE-2019-19781) all had critical path traversal vulnerabilities. NIST NVD rates path traversal CVEs up to CVSS 10.0 (maximum criticality).
Impact: CVE-2021-41773 (Apache HTTP Server path traversal) allowed unauthenticated remote code execution via a crafted URL — patched in hours after public disclosure, but thousands of servers were exploited before patching. Pulse Secure CVE-2019-11510 enabled reading VPN credentials without authentication, affecting governments and enterprises globally. Path traversal on file upload enables webshell upload → full server compromise.
Why best: Stripping ../ sequences from user input is the legacy approach — it fails against encoded variants (%2e%2e%2f, %252e, ..%2f), null bytes, and OS-specific separators. Canonicalization via realpath() (or equivalent) resolves all encoding variants to an absolute path, and the prefix check (startswith(base_dir)) is applied to the canonical result.
Sources: OWASP Path Traversal Cheat Sheet; CVE-2021-41773 analysis; CWE-22; OWASP File Upload Cheat Sheet
Steps
Canonicalize paths and verify they stay within the base directory:
import os
BASE_DIR = '/var/app/uploads'
def safe_path(user_filename):
# Remove any path components from user input
filename = os.path.basename(user_filename)
# Construct the candidate path
candidate = os.path.join(BASE_DIR, filename)
# Canonicalize — resolves .., symlinks, encoded chars
canonical = os.path.realpath(candidate)
# Verify it's within the base directory
if not canonical.startswith(os.path.realpath(BASE_DIR) + os.sep):
raise SecurityError(f"Path traversal detected: {user_filename}")
return canonical
Reject filenames with path separators — strip or reject inputs containing /, \, .., null bytes, or non-printable characters:
import re
def sanitize_filename(name):
# Allow only alphanumeric, dash, underscore, dot
if not re.match(r'^[a-zA-Z0-9._-]+$', name):
raise ValueError("Invalid filename characters")
if name.startswith('.'):
raise ValueError("Hidden files not allowed")
if len(name) > 255:
raise ValueError("Filename too long")
return name
For file downloads, use indirect references — store files by UUID or hash, never expose real filenames to users:
import uuid
# On upload: store with UUID
file_id = str(uuid.uuid4())
stored_path = os.path.join(BASE_DIR, file_id)
shutil.copy(uploaded_file, stored_path)
db.store(file_id=file_id, original_name=filename, owner=user_id)
# On download: look up UUID, never use user input as path
@app.route('/download/<file_id>')
def download(file_id):
record = db.get(file_id=file_id, owner=current_user.id)
if not record:
abort(404)
return send_file(os.path.join(BASE_DIR, file_id),
download_name=record.original_name)
Validate file content type on upload — check MIME type from file magic bytes, not the Content-Type header or file extension:
import magic # python-magic library
ALLOWED_MIME_TYPES = {'image/jpeg', 'image/png', 'image/gif', 'application/pdf'}
def validate_file_type(file_bytes):
detected = magic.from_buffer(file_bytes[:2048], mime=True)
if detected not in ALLOWED_MIME_TYPES:
raise ValueError(f"File type not allowed: {detected}")
Store uploaded files outside the web root — files in the web root are directly accessible; files outside it must be explicitly served:
/var/app/
web/ ← web root, served by Nginx
index.html
uploads/ ← outside web root, not directly accessible
uuid1.jpg
Never store uploads in static/, public/, or any directory served by the web server.
Restrict file extensions for uploads — allowlist permitted extensions, reject all others:
ALLOWED_EXTENSIONS = {'.jpg', '.jpeg', '.png', '.gif', '.pdf'}
def allowed_extension(filename):
_, ext = os.path.splitext(filename.lower())
return ext in ALLOWED_EXTENSIONS
Defense-in-depth: rename files on storage (step 3's UUID approach eliminates extension attacks entirely).
Rules
- Always use
realpath() (or equivalent) for canonicalization — string manipulation of paths is insufficient.
- Check the canonical path starts with
base_dir + os.sep, not just base_dir — without os.sep, ../uploads_malicious would pass a startswith('/uploads') check.
- On Windows, path separators are both
\ and /, and drive-letter paths (C:\) must be handled — prefer UUID-based storage over path validation on Windows.
- Symlinks inside the base directory can point outside it —
realpath() resolves them; ensure the resolved target is also within bounds.
Common Mistakes
- Stripping
../ with regex — ....// after stripping ../ becomes ../; recursive stripping fails with %2e%2e/ encoding.
- Using
os.path.join without realpath check — os.path.join('/uploads', '../etc/passwd') resolves to /etc/passwd on Unix.
- Allowing
.php, .py, .sh extensions in uploads — if the file is served from the web root, it executes as server-side code.
- Trusting Content-Type header for file type validation — attackers set it to
image/jpeg while uploading a PHP webshell.
1---2name: prevent-path-traversal3description: Use when building file upload, file download, file serving, or any feature where user input influences a filesystem path — including filename parameters, directory parameters, or file include logic.4source: 'OWASP Path Traversal Cheat Sheet; OWASP File Upload Cheat Sheet (owasp.org/www-project-cheat-sheets); OWASP Top 10 2021 A01; CWE-22; CWE-434'5tags: [security, owasp, path-traversal, file-upload, directory-traversal, developer, input-validation]6metadata:7 source: https://skillmd.com/skills/jeffreytse/prevent-path-traversal8---910# Prevent Path Traversal1112Canonicalize and validate all filesystem paths constructed from user input — verifying they resolve within an intended base directory — to block directory traversal attacks that read or overwrite arbitrary server files.1314## Why This Is Best Practice1516**Adopted by:** OWASP Top 10 2021 A01 (Broken Access Control) includes path traversal. CWE-22 is one of the most common CVE categories — 2,000+ CVEs listed in NVD. Apache HTTP Server (CVE-2021-41773), Pulse Secure (CVE-2019-11510), and Citrix (CVE-2019-19781) all had critical path traversal vulnerabilities. NIST NVD rates path traversal CVEs up to CVSS 10.0 (maximum criticality).17**Impact:** CVE-2021-41773 (Apache HTTP Server path traversal) allowed unauthenticated remote code execution via a crafted URL — patched in hours after public disclosure, but thousands of servers were exploited before patching. Pulse Secure CVE-2019-11510 enabled reading VPN credentials without authentication, affecting governments and enterprises globally. Path traversal on file upload enables webshell upload → full server compromise.18**Why best:** Stripping `../` sequences from user input is the legacy approach — it fails against encoded variants (`%2e%2e%2f`, `%252e`, `..%2f`), null bytes, and OS-specific separators. Canonicalization via `realpath()` (or equivalent) resolves all encoding variants to an absolute path, and the prefix check (`startswith(base_dir)`) is applied to the canonical result.1920Sources: OWASP Path Traversal Cheat Sheet; CVE-2021-41773 analysis; CWE-22; OWASP File Upload Cheat Sheet2122## Steps23241. **Canonicalize paths and verify they stay within the base directory**:2526 ```python27 import os2829 BASE_DIR = '/var/app/uploads'3031 def safe_path(user_filename):32 # Remove any path components from user input33 filename = os.path.basename(user_filename)34 # Construct the candidate path35 candidate = os.path.join(BASE_DIR, filename)36 # Canonicalize — resolves .., symlinks, encoded chars37 canonical = os.path.realpath(candidate)38 # Verify it's within the base directory39 if not canonical.startswith(os.path.realpath(BASE_DIR) + os.sep):40 raise SecurityError(f"Path traversal detected: {user_filename}")41 return canonical42 ```43442. **Reject filenames with path separators** — strip or reject inputs containing `/`, `\`, `..`, null bytes, or non-printable characters:4546 ```python47 import re4849 def sanitize_filename(name):50 # Allow only alphanumeric, dash, underscore, dot51 if not re.match(r'^[a-zA-Z0-9._-]+$', name):52 raise ValueError("Invalid filename characters")53 if name.startswith('.'):54 raise ValueError("Hidden files not allowed")55 if len(name) > 255:56 raise ValueError("Filename too long")57 return name58 ```59603. **For file downloads, use indirect references** — store files by UUID or hash, never expose real filenames to users:6162 ```python63 import uuid6465 # On upload: store with UUID66 file_id = str(uuid.uuid4())67 stored_path = os.path.join(BASE_DIR, file_id)68 shutil.copy(uploaded_file, stored_path)69 db.store(file_id=file_id, original_name=filename, owner=user_id)7071 # On download: look up UUID, never use user input as path72 @app.route('/download/<file_id>')73 def download(file_id):74 record = db.get(file_id=file_id, owner=current_user.id)75 if not record:76 abort(404)77 return send_file(os.path.join(BASE_DIR, file_id),78 download_name=record.original_name)79 ```80814. **Validate file content type on upload** — check MIME type from file magic bytes, not the `Content-Type` header or file extension:8283 ```python84 import magic # python-magic library8586 ALLOWED_MIME_TYPES = {'image/jpeg', 'image/png', 'image/gif', 'application/pdf'}8788 def validate_file_type(file_bytes):89 detected = magic.from_buffer(file_bytes[:2048], mime=True)90 if detected not in ALLOWED_MIME_TYPES:91 raise ValueError(f"File type not allowed: {detected}")92 ```93945. **Store uploaded files outside the web root** — files in the web root are directly accessible; files outside it must be explicitly served:9596 ```97 /var/app/98 web/ ← web root, served by Nginx99 index.html100 uploads/ ← outside web root, not directly accessible101 uuid1.jpg102 ```103104 Never store uploads in `static/`, `public/`, or any directory served by the web server.1051066. **Restrict file extensions for uploads** — allowlist permitted extensions, reject all others:107108 ```python109 ALLOWED_EXTENSIONS = {'.jpg', '.jpeg', '.png', '.gif', '.pdf'}110111 def allowed_extension(filename):112 _, ext = os.path.splitext(filename.lower())113 return ext in ALLOWED_EXTENSIONS114 ```115116 Defense-in-depth: rename files on storage (step 3's UUID approach eliminates extension attacks entirely).117118## Rules119120- Always use `realpath()` (or equivalent) for canonicalization — string manipulation of paths is insufficient.121- Check the canonical path starts with `base_dir + os.sep`, not just `base_dir` — without `os.sep`, `../uploads_malicious` would pass a `startswith('/uploads')` check.122- On Windows, path separators are both `\` and `/`, and drive-letter paths (`C:\`) must be handled — prefer UUID-based storage over path validation on Windows.123- Symlinks inside the base directory can point outside it — `realpath()` resolves them; ensure the resolved target is also within bounds.124125## Common Mistakes126127- **Stripping `../` with regex** — `....//` after stripping `../` becomes `../`; recursive stripping fails with `%2e%2e/` encoding.128- **Using `os.path.join` without `realpath` check** — `os.path.join('/uploads', '../etc/passwd')` resolves to `/etc/passwd` on Unix.129- **Allowing `.php`, `.py`, `.sh` extensions in uploads** — if the file is served from the web root, it executes as server-side code.130- **Trusting Content-Type header for file type validation** — attackers set it to `image/jpeg` while uploading a PHP webshell.