Every single request is passed to PHP, for security reasons and because I don’t want to expose static files to unauthorized people.
I am concerned about the possibility of someone inject some malicious code through the $_SERVER["REQUEST_URI"] variable. I tried to remove sub-folders references but I still don’t know if it’s safe.
Nginx
rewrite ^ /index.php last;
index.php
<?php
$uri = $_SERVER["REQUEST_URI"];
$uri = strlen ($uri) > 1 ? substr ($uri, 1) : "index.html";
$uri = preg_replace ("/\/?\.\./", "", $uri, -1); // Remove sub-folders
if (file_exists (getcwd () . "/" . $uri)) {
$extension = substr ($uri, strrpos ($uri, "."));
switch ($extension) {
case ".css": $mime = "text/css"; break;
case ".js": $mime = "application/javascript"; break;
default:
$info = finfo_open (FILEINFO_MIME_TYPE);
$mime = finfo_file ($info, $uri);
finfo_close ($info);
break;
}
if ($mime === false)
header ("Content-Type: text/html; charset=utf-8"); // Default
else
header ("Content-type: " . $mime);
require ($uri);
}
else {
// Error, blah blah blah
}
?>
Yes, you are concerned about LFI (Local File Inclusion) attacks. It’s possible.
Currently when you are checking for . / and \ chars in URI, that would prevent Directory Traversal attack. It’s fairly good.
As you guessed, if you include files like this:
index.php?file=something.php
and in index.php
include $_GET[‘file’];
Attacker could read every file in your server, like this:
index.php?file=../../../../../../../../../../etc/passwd
So you have to take measures.
Here is a very good writing from Imperva on how to prevent LFI and RFI (Remote File Inclusion) attacks:
https://www.imperva.com/lg/lgw.asp?pid=463
without registration requirement:
http://www.slideshare.net/Imperva/how-to-prevent-rfi-and-lfi-attacks
Also Here:
http://25yearsofprogramming.com/blog/2011/20110124.htm