I am implementing a simple directory listing script in PHP.
I want to ensure that the passed path is safe before opening directory handles and echoing the results willy-nilly.
$f = $_GET["f"];
if(! $f) {
$f = "/";
}
// make sure $f is safe
$farr = explode("/",$f);
$unsafe = false;
foreach($farr as $farre) {
// protect against directory traversal
if(strpos($farre,"..") != false) {
$unsafe = true;
break;
}
if(end($farr) != $farre) {
// make sure no dots are present (except after the last slash in the file path)
if(strpos($farre,".") != false) {
$unsafe = true;
break;
}
}
}
Is this enough to make sure a path sent by the user is safe, or are there other things I should do to protected against attack?
From stackoverflow
-
It may be that
realpath()is helpful to you.realpath()expands all symbolic links and resolves references to'/./','/../'and extra'/'characters in the input path, and returns the canonicalized absolute pathname.However, this function assumes that the path in question actually exists. It will not perform canonization for a non-existing path. In this case FALSE is returned.
Charlie Somerville : So I perform realpath() on the passed path, and check if it is underneath my 'safe' directory?Tomalak : Exactly. Since you get a no-nonsense path back (or FALSE), you can do a simple substring compare as the check.Charlie Somerville : Sounds good to me. Thanks!
0 comments:
Post a Comment