7

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?

anonymous coward
  • 11,122
  • 11
  • 60
  • 79

1 Answers1

9

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.

Tomalak
  • 306,836
  • 62
  • 485
  • 598