View previous topic :: View next topic |
Author |
Message |
TRUSTAbyss -
Joined: 29 Oct 2003 Posts: 3752 Location: USA, GA
|
Posted: Sat Jul 14, 2007 5:41 pm Post subject: Free PHP Function: pathOK() |
|
|
Hello Everyone,
I was looking for a way to prevent a "URL Directory Traversal" attack from the relative path dot syntax. I found a function in PHP that expands all symbolic links and resolves references to '/./', '/../' and extra '/' characters in the input path and return the canonicalized absolute pathname. This function allowed me to be able to detect when a user requests a file outside of their allowed directory. The function I'm about to show you is great for protecting your files from this type of URL attack. It also allows you to use the ../ syntax in a URL to serve your files safely.
This function will be used in FileLimit. An example is below.
Code: | <?php
/**
* pathOK() Function
* Created by: Joshua H. (TRUSTAbyss)
*
* This function returns a boolean value.
* Usage: pathOK("DocumentRoot", "VirtualPath");
*/
function pathOK($droot, $vpath)
{
$droot = str_replace("\\", "/", realpath($droot));
$fpath = str_replace("\\", "/", realpath($droot.'/'.$vpath));
if (preg_match("/^".preg_quote($droot, '/')."/", $fpath))
{
return TRUE;
}
else
{
return FALSE;
}
}
$droot = $_SERVER['DOCUMENT_ROOT'];
$vpath = $_GET['path'];
if (pathOK($droot, $vpath))
{
echo "The path is OK. ";
}
else
{
header("HTTP/1.1 404 Not Found");
echo "<b>404 Not Found</b>";
}
?> |
Note: If the path/file does not exist or is outside of your Document Root, it will return FALSE. This means that the path is not OK.
http://localhost/function.php?path=/ (The path is OK)
http://localhost/function.php?path=/.. (The path isn't OK)
Hope you guys find this PHP function useful.
Kind regards, Josh
Last edited by TRUSTAbyss on Mon Aug 04, 2008 8:44 pm; edited 3 times in total |
|
Back to top |
|
|
aprelium -
Joined: 22 Mar 2002 Posts: 6800
|
Posted: Sun Jul 15, 2007 11:28 pm Post subject: Re: Free PHP Function: pathOK() |
|
|
TRUSTAbyss,
A minor suggestion: it's more secure to use realpath() to canonize $droot too (in case it contains a non canonical path). So we suggest that you replace the first line of the function with:
Code: | $droot = str_replace("\\", "/", realpath($droot)); |
_________________ Support Team
Aprelium - http://www.aprelium.com |
|
Back to top |
|
|
TRUSTAbyss -
Joined: 29 Oct 2003 Posts: 3752 Location: USA, GA
|
Posted: Sun Jul 15, 2007 11:29 pm Post subject: |
|
|
I just replaced it. Thanks for the suggestion. |
|
Back to top |
|
|
TRUSTAbyss -
Joined: 29 Oct 2003 Posts: 3752 Location: USA, GA
|
Posted: Mon Aug 04, 2008 7:45 pm Post subject: |
|
|
The code above has been updated to support PHP 6 in the future. I basically replaced the eregi() function with preg_match(). |
|
Back to top |
|
|
|