1

I'm pretty sure that you all are aware of this vulnerability, but i wonder how to patch this? I have seen this code in a tutorial that it is the way to patch this but still user can access all the files of the current directory:

<?php
$page = $_GET['page'];
if(@strstr($page,'../')){
    die('LFI Attempt Detected');
}
include($page);
?>

Please suggest a good way to patch this vulnerability.

SilverlightFox
  • 33,408
  • 6
  • 67
  • 178
Rehan Manzoor
  • 23
  • 1
  • 3

2 Answers2

4

The presented mitigation is absolutely insufficient. It’s not just possible to include any file from the current directory but also from any directory depending on the file system (i. e., \.. still works on Windows) or by using an absolute path (e. g., /… on Unix-like systems, or \… on Windows) as well via different protocols/wrappers (e. g., http://…, file://…, ftp://…, etc.), allowing the execution of arbitrary PHP code.

If you don’t want this, you should validate the parameter value. For example, if you only want to allow certain values, use an array and check whether the given value is in it:

$validValues = array();
if (!in_array($page, $validValues, true)) {
    die("invalid 'page' value");
}

If you want to allow any file within a certain directory, you could check whether the resulting absolute path is still pointing to a file within that directory using the technique described in Preventing Directory Traversal in PHP but allowing paths.

Gumbo
  • 2,003
  • 1
  • 13
  • 17
0

Restrict the input. You could do that using an array of file names that could be included or just use that single name and restrict to it. patch code looks like this (i didn't test it yet)

 $allowed_includes = array('config', 'index','register'); //list of files that are allowed to be included if //

(in_array($_GET['file'], $allowed_includes)) { //if the user supplied file exist in array
include_once($_GET['file']. '.php'); //include the name and add .php extension , include the file. }