Web › Module 5 › Lesson 3
Path Traversal & File Upload
Stop ../ directory escapes and unsafe uploads from becoming remote code execution
Visual · web_developer
Path traversal walks the filesystem with ../ sequences. Unsafe file uploads store attacker-controlled content where the server might execute it.
Opening
Two paths to the same bad day
Path traversal: GET /download?file=report.pdf becomes file=../../../etc/passwd and the server serves secrets. Unsafe upload: POST avatar.php.jpg that the web server executes as PHP because it lives under /uploads/ with script execution enabled. Both are classic web bugs that defense checklists still catch in pentests.
1. Path Traversal Basics
Apps that read files based on user input must map names to an allowed directory and reject traversal sequences. Attack inputs: ../, ..\\, URL-encoded %2e%2e%2f, double encoding, and Unicode normalization tricks.
2. Safe File Handling Pattern
Resolve path inside an allowed base directoryimport os BASE = "/var/app/safe_downloads" def safe_path(user_file): name = os.path.basename(user_file) # strip directories full = os.path.realpath(os.path.join(BASE, name)) if not full.startswith(BASE): raise PermissionError("traversal blocked") return full
import os
BASE = "/var/app/safe_downloads"
def safe_path(user_file):
name = os.path.basename(user_file) # strip directories
full = os.path.realpath(os.path.join(BASE, name))
if not full.startswith(BASE):
raise PermissionError("traversal blocked")
return full3. File Upload Defenses
Store outside web root
Serve via controlled download endpoint, not direct URL to /uploads/.
Validate type and content
Check magic bytes, not just extension; block executables.
Randomize names
UUID filenames—users never pick shell.php.
Disable script execution
Upload directory must not run PHP, JSP, or CGI.
Scan uploads in a sandbox
For high-risk apps, antivirus or CDR (content disarm) on uploads adds another layer—but never rely on it instead of blocking executable content.
Knowledge Check
Path traversal tries to:
Multiple choice
Knowledge Check
True or False: Storing uploads outside the web root reduces direct execution risk.
True or False
Knowledge Check
os.path.basename() helps by:
Multiple choice