Reputation:
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 echo
ing 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?
Upvotes: 7
Views: 2188
Reputation: 338128
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.
Upvotes: 8