views:

402

answers:

4

Greetings, I'm hoping to make my tiny program secure so that potential malicious users cannot view sensitive files on the server.

 $path = "/home/gsmcms/public_html/central/app/webroot/{$_GET['file']}";


 if(file_exists($path)) {
  echo file_get_contents($path);
 } else {
  header('HTTP/1.1 404 Not Found');
 }

Off the top of my head I know that input such as '../../../../../../etc/passwd' would be trouble, but wondering what other malcious inputs I should expect and how to prevent them.

+3  A: 

Use basename rather than trying to anticipate all the insecure paths a user could provide.

philfreo
this may work in some situations, however I'm expecting input to include directories as well, ex: '/js/jquery/jquery.js'
SeanDowney
+5  A: 

realpath() will let you convert any path that may contain relative information into an absolute path...you can then ensure that path is under a certain subdirectory that you want to allow downloads from.

Bert Lamb
This was my final solution:$baseDir = "/home/gsmcms/public_html/central/app/webroot/";$path = realpath($baseDir . $_GET['file']);// if baseDir isn't at the front 0==strpos, most likely hacking attemptif(strpos($path, $baseDir)) { die('Invalid Path');} elseif(file_exists($path)) { echo file_get_contents($path);} else { header('HTTP/1.1 404 Not Found'); echo "The requested file could not be found";}
SeanDowney
+3  A: 

If you can, use a whitelist like an array of allowed files and check the input against that: if the file asked by the user isn't present in that list, deny the request.

kemp
This would be the best idea, but probably more work than I want to do :)
SeanDowney
Unless you want to leak the source of all your files under your webroot, you probably do want to do this.
Cheekysoft
+1  A: 

There is an additional and significant security risk here. This script will inject the source of a file into the output stream without any server-side processing. This means that all your source code of any accessible files will be leaked to the internet.

Cheekysoft
good point, I'll add a whitelist of allowed extensions such as: js, css, jpg, gif...
SeanDowney