3

Lets say I want to build a simple PHP script that let me access files inside a folder:

$path = $_GET['path']; $path = str_replace('..', '', $path); $path = "./static/" . $path; readfile($path);

Is the line 2 on this example enough to avoid people reading files outside the 'static' folder?

  • 1
    I believe .. is perfectly allowed to be part of a filename (so a..txt is OK). Your code breaks on legitimate filenames. – cpast Mar 6 '15 at 3:18
7

I can't presently think of a good reason why removing all ".." strings doesn't work, but the most appropriate way would be use the realpath() function and ensure the start of the string matches the intended full directory path.

  • 5
    +1 Don't roll your own security when the solution is already in the standard library. – James Mishra Mar 6 '15 at 1:54
  • I wonder how they implemented that function on windows. – CodesInChaos Mar 6 '15 at 11:13
4

It's very easy for attackers to encode the literal string .. in a number of ways. The easiest way is using URL encoding which encodes .. as %2E%2E. This will not be caught by str_replace and will still resolve into a malicious path. See the OWASP Path Traversal page for more examples.

realpath() is generally a better solution for this situation.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.