how to serve a file only out of one directory and down

Discussions of secure PHP coding. Security in software is important, so don't be afraid to ask. And when answering: be anal. Nitpick. No security vulnerability is too small.

Moderator: General Moderators

Post Reply
yehosef
Forum Newbie
Posts: 2
Joined: Tue Jul 25, 2006 8:17 am

how to serve a file only out of one directory and down

Post by yehosef »

I need to pass a filename to a script and I need that script to then do a readfile() on the file (for a Content-disposition download). I want people to only be able to access a certain subdirectory (eg "downloads") and below. There are different subdirectories beneath this so $filename includes a path:

download/goodThings/great.txt
download/betterThings/super.txt

What should I do keep people out of my ../secretThings directory?

I had tried

Code: Select all

if (ereg('\.\.', $filename))
    die('bad filename'); //die, do not process
But I don't know if that's enough.

Thank you,
User avatar
feyd
Neighborhood Spidermoddy
Posts: 31559
Joined: Mon Mar 29, 2004 3:24 pm
Location: Bothell, Washington, USA

Post by feyd »

User avatar
Jenk
DevNet Master
Posts: 3587
Joined: Mon Sep 19, 2005 6:24 am
Location: London

Post by Jenk »

Code: Select all

//this is a 'psuedo root' - the base dir.
$ROOT_PATH = realpath('/path/to/root/');

//path to the requested file.
$path = realpath('path/to/some/file');

if ((preg_match('/^' . preg_quote($ROOT_PATH, '/') . '.*/i', $path)) && (is_file($path)) {
    readfile($path);
} else {
        die('Path to file is above root/base dir, or does not exist.');
}
yehosef
Forum Newbie
Posts: 2
Joined: Tue Jul 25, 2006 8:17 am

what about passing as PATH_INFO?

Post by yehosef »

If I pass the path like this

/dl.php/goodstuff/file.txt

and use the $_SERVER['PATH_INFO']

would that be ok? I tried testing it and if you put in ../../ it seems to translate it to a path in the browser.

Thanks
Post Reply