Php directory traversal issue
Hi We have some php code using the file_get_contents () function and I understand this is vulnerable to directcoty redirect attacks. Given the following code:
$mydata=$_GET['thefile'];
$data = file_get_contents ('/var/html'.$file);
echo $data
How can I do some simple filtering on the input so that I can block the possibility that someone might be dragging and dropping directories while playing with my input?
/ MR
source to share
You want basename :
$mydata = basename(realpath($_GET['thefile']));
Added to (minor changes) your example:
$file=$_GET['thefile'];
$mypath='/var/www/';
$location= basename(realpath($mypath.$file));
$data = file_get_contents($location);
echo $data;
Note ... while this does some level of error checking, it does not do error handling. I'll leave it up to you.
source to share
If $_GET['thefile']
you won't be using folders like "images / fileX.jpg" you can use basename ()
$filename = basename($_GET['thefile']);
readfile('/var/html/'.$filename);
When '../../passwords.txt' is given as $_GET['thefile']
, it will be converted basename
to 'passwords.txt'.
Adding realpath()
inside the base name does not add any security.
If your script must support subdirectories, use realpath () to determine if it is in the '/ var / html' directory.
$baseDir = realpath('/var/html/'); // (mayby /var/html is a symlink)
$baseDirLength = strlen($baseDir);
$filepath = realpath('/var/html/'.$_GET['thefile']);
if (substr($filepath, 0, $baseDirLength) == $baseDir) {
// Even when all the '../' in the thefile are resolved
// the path is within the $baseDir
} else {
// invalid $_GET['thefile']
}
source to share