Preventing Directory Traversal in PHP but allowing paths

Asked
Active3 hr before
Viewed126 times

10 Answers

directory
90%

ircmaxell's answer wasn't fully correct. I've seen that solution in several snippets but it has a bug which is related to the output of realpath(). The realpath() function removes the trailing directory separator, so imagine two contiguous directories such as:,First check for traversal attempts using a custom implementation of a realpath() like function, which however works for arbitrary paths, not just existing files. There's a good starting point here. Extend it with urldecode() and whatever else you think may worth checking.,Finally so the path now points to an existing location, therefore you can now do the proper check using the methods suggested above utilising realpath(). If at this point it turns out a traversal has happened, you are still safe more or less, as long as you make sure to prevent any attempts writing into the target path. Also right now you can delete the target file/dir and say it was a traversal attempt.,This line alone if (strpos(urldecode($fileName), '..') !== false) should be enough to prevent traversal, however, there are many different ways hackers can traverse directories so its better to make sure the user starts with the real base path.

Well, one option would be to compare the real paths:

$basepath = '/foo/bar/baz/';
$realBase = realpath($basepath);

$userpath = $basepath.$_GET['path'];
$realUserPath = realpath($userpath);

if ($realUserPath === false || strpos($realUserPath, $realBase) !== 0) {
   //Directory Traversal!
} else {
   //Good path!
}
load more v
88%

Directory traversal, also called path traversal, is a vulnerability that allows attackers to break out of a web server’s root directory and access other locations in the server's file system. Let’s see what makes directory traversal attacks possible and what you can do to prevent them.,Directory traversal, also called path traversal, is a vulnerability that allows attackers to break out of a web server's root directory and access other locations in the server's file system. Let's see what makes directory traversal attacks possible and what you can do to prevent them.,Path traversal attacks rely on two vulnerable elements: the web application code and the web server configuration. By taking care to avoid vulnerabilities in both areas, you can mitigate the majority of such attacks.,This value would be appended to the path, causing the web server to execute the following include() call to climb into the /etc directory and load the password file:

To take a simple example, let’s say we have a “Show File” button that opens the following URL when clicked:

https: //www.example.com/show_file.php?file=report.txt
load more v
72%

See the OWASP Testing Guide article on how to test for path traversal vulnerabilities.,Relative Path Traversal,The following examples show how the application deals with the resources in use.,All but the most simple web applications have to include local resources, such as images, themes, other scripts, and so on. Every time a resource or file is included by the application, there is a risk that an attacker may be able to include a file or remote resource you didn’t authorize.

Root directory: “/ “ 
Directory separator: “/ “
load more v
65%

Learn about Laravel path traversal attacks, where they can happen on Laravel-based websites, and how to prevent them.,Code that reads and writes files from any directory might suffer from path traversal attacks if any part of the file name is user-generated. ,I've shown an example with Laravel's download() function and used Laravel's storage_path() helper in the previous sections. However, that doesn't mean the problem occurs only in this scenario. ,Congratulations, you just downloaded the file with the environment variables, containing possibly all your precious credentials!

Route::get('/download/PrivateDocument', function() {
   return response() - > download(storage_path('app/PrivateDocument.pdf'));
});
load more v
75%

Path traversal, also known as directory traversal, is a web security risk that allows the attacker to read unrecognized files on the application server. This may include application code and data, credentials of reverse programs, and sensitive system files.,In an earlier example you saw how an attacker can reach our confidential files. To prevent this attack, you need to check for path traversal vulnerabilities. Here’s how:,To prevent path traversal, you need to take care of two things: your web server, and its configuration.  Both are related to each other, you just need to execute the right steps to avoid this vulnerability.,To prevent this, you must first check for path traversal vulnerabilities.

 

https://your-app.com/user-info.php?file=../../etc/passwd

https: //your-app.com/user-info.php?file=../../etc/passwd
load more v
40%

I have a base path /whatever/foo/,and $_GET['path'] should be relative to it.,However how do I accomplish this (reading the directory), without allowing directory traversal?,I assume you mean without allowing users to traverse the directory yes?

eg.

/\.\.|\.\./
load more v
22%

Path traversal attacks rely on two vulnerable elements: the web application code and the web server configuration. By taking care to avoid vulnerabilities in both areas, you can mitigate the majority of such attacks.,Vulnerability Remediation,If the application simply takes the value of the file parameter from the URL and passes it to a system call, it would traverse the relative path ../../etc/passwd  and ask the system to load the password file. ,To test for path traversal attack, the attacker could try to access the system file /etc/passwd by visiting the URL:

Path traversal attacks rely on two vulnerable elements: the web application code and the web server configuration. By taking care to avoid vulnerabilities in both areas, you can mitigate the majority of such attacks.

Vulnerable web applications use unvalidated user inputs in file names and paths and it is strongly recommended that file paths should not be accepted by user input. If you do need to take file names or paths from user inputs, ensure they are properly sanitized by whitelisting permitted names and/or characters. Blacklisting characters to filter out ../ and similar strings.On the web server side, ensure you are using up-to-date web server software.

.. /
60%

Website Security Scanner,Get the latest content on web security in your inbox each week.,PHP Security Best Practices,Read more about directory traversal.

In the following example, the script passes an unvalidated/unsanitized HTTP request value directly to the include() PHP function. This means that the script will try to include whatever path/filename is passed as a parameter:

$file = $_GET['file'];
include($file);
load more v
48%

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., +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 '19 at 19:04 , Are there any gaps in the range of gravitational wave frequencies we can detect? ,realpath() is generally a better solution for this situation.

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.

..

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.

..

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.

% 2 E % 2 E

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.

str_replace
load more v
23%

Giving appropriate permissions to directories and files. A PHP file typically runs as www-data user on Linux. We should not allow this user to access system files. But this doesn’t prevent this user from accessing web-application specific config files.,Process URI requests that do not result in a file request, e.g., executing a hook into user code, before continuing below.,A path traversal attack allows attackers to access directories that they should not be accessing, like config files or any other files/directories that may contains server’s data not intended for public.,A typical example of vulnerable application in PHP code is:

 http: //www.mywebsite.com.

Using the same ../ technique, an attacker can escape out of the directory containing the PDFs and access anything they want on the system.

http: //www.mywebsite.com/?template= ../../../../../../../../../etc/passwd
load more v

Other "directory-undefined" queries related to "Preventing Directory Traversal in PHP but allowing paths"