tags:

views:

36

answers:

2

I have a project which requires using user input to include files into a PHP script. The user input could be any relative URL (EX:/folder1/folder2/file.jpg, /folder1/folder2/)

Would the following be a fool-proof regexp to check if the input is sane:

if(preg_match('/^(\/[-_a-zA-Z0-9]+)+\/?$/D', $_GET['loc']))
{
   //Location is good!
}

Obviously im looking to avoid any local file inclusion attacks. Before I get white-list suggestions instead of including the file like the above, I have 1000s of files, so a switch statement or if/else wont work.

+2  A: 

You can put all the files to be included in a single directory say /x/y/data and then do a check like the following:

$filename = realpath("/x/y/data/$_POST[location]");

// Make sure that $filename is under /usr/local/data    
if ('/x/y/data/' =  = substr($filename, 0, 10)) {

// safe..include the file.

} else {    

// not safe..reject.   

}
codaddict
A: 

I'd build a whitelist of all the allowable files and only allow files on matches with that. If this is not practical for some reason, then I'd reluctantly attempt some sort of regex (But path separators are diff depending on platform, so good luck). Be sure to lock this thing down with the php directive open_basedir. This will at least minimize the damage in case something happens.

Eric Butera