PHP protected root

My friend found a problem in my script, it gives access to root files.

This url provides the passwd file:

http://site.com/attachment.php?file=../../../../../../etc/passwd 

How to avoid this security hole?

+6
security php root
source share
4 answers

There are several different solutions. If there can only be a file name, basename () will be used.

However, if this may be the way, a more complex solution is required.

 //assume current directory, but can be set anything. Absolute path of course $basedir = dirname(__FILE__); //assume our files are below document root. //Otherwise use it root dir instead of DOCUMENT_ROOT $filename = realpath($_SERVER['DOCUMENT_ROOT'].$_GET['file']); if (substr($filename,0,strlen($basedir)) !== $basedir) { header ("HTTP/1.0 403 Forbidden"); exit; } 

there is also a useful PHP configuration option open_basedir

+4
source share

Do not upload files using the URL String .... Define unique identifiers to indicate the file, not the path.

You may have seen downloads such as http://www.mysite.com/download.php?id=23423 that they do, use this identifier to extract the file name and path from db, and then load it.

+14
source share

You can use realpath() and dirname() to check URLs against $_SERVER['DOCUMENT_ROOT'] (or any other directory is "safe" to load).

If the result of realpath() indicates outside the safe directory, you can reject the download request.

There is also an open_basedir security directive (and runtime from 5.3).

+3
source share

I assume that you have a directory in which all attachments are stored.

Just check if the file is in your directory.

  // http://www.php.net/manual/en/function.basename.php // http://cz.php.net/manual/en/function.file-exists.php if (file_exists($attachments_path . "/" . basename($_GET['file'])) { // do work } 

Starx has posted a solution that seems great. However, this can be done without a database. If someone uploads a file, you can save the file as md5($filename).$extension and use a script.

+1
source share

All Articles