7

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
  • 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, 2015 at 3:18

2 Answers 2

10

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.

3
  • 5
    +1 Don't roll your own security when the solution is already in the standard library. Mar 6, 2015 at 1:54
  • I wonder how they implemented that function on windows. Mar 6, 2015 at 11:13
  • +1 for actually answering the question ('I can't presently think of a good reason why removing all ".." strings doesn't work')
    – AndreKR
    Jul 3, 2019 at 19:04
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.

3
  • 1
    "This will not be caught by str_replace and will still resolve into a malicious path." -> I'm quite sure both statements are wrong.
    – AndreKR
    Jul 3, 2019 at 19:03
  • @AndreKR I'm referring to a scenario like this one: "The Unicode encoding for the URL above will produce the same result as the first URL (Path Traversal Attack). However, if the application has an input security filter mechanism, it could refuse any request containing “../” sequence, thus blocking the attack. However, if this mechanism doesn’t consider character encoding, the attacker can bypass and access protected resource." owasp.org/index.php/Unicode_Encoding I hope that clarifies the point I was making. They phrased it better than me.
    – jsaigle
    Jul 4, 2019 at 20:11
  • 1
    That is still saying the same thing: That allegedly it's possible to encode .. in a way that is not 2E 2E but will still be interpreted as "parent directory" by the filesystem. And I don't think that is true.
    – AndreKR
    Jul 5, 2019 at 6:50

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .