August 22, 2010

PHP secure root

Question by James

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

This url gives passwd file:

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

How to escape this security hole?

Answer by Your Common Sense

There are several different solutions.
If there can be only a filename, a basename() solution would work.

However, if it can be path, a more complex solution is needed

//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's 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

Answer by Starx

Dont download the files using URL String…. Define unique IDs to denote a file, rather than paths.

You might have seen downloads like this http://www.mysite.com/download.php?id=23423 what they do, use this id, to take out the file name and path from the db and then download it.

Author: Nabin Nepal (Starx)

Hello, I am Nabin Nepal and you can call me Starx. This is my blog where write about my life and my involvements. I am a Software Developer, A Cyclist and a Realist. I hope you will find my blog interesting. Follow me on Google+

...

Please fill the form - I will response as fast as I can!