A directory traversal attack aims to access files and directories that are stored outside the intended folder. By manipulating files with "dot-dot-slash (../)" sequences and its variations, or by using absolute file paths, it may be possible to access arbitrary files and directories stored on the filesystem; including application source code, configuration, and other critical system files.
In this lesson, you will learn how directory traversal works and how to mitigate it in your application. You will first use a directory traversal attack to hack a vulnerable web server. We will then explain directory traversal by showing you the backend code of that vulnerable server. Finally, we will teach you how to prevent directory traversal from affecting your code.
Ready to learn? Buckle your seat belts, put on your hacker's hat, and let's get started!
Essentially, the attack is accomplished by adding characters such as ../
into a URL that serves content from a directory structure. The content is usually served from a base directory, such as /public
. An attacker can supply filenames that contain ../
or a URL encoded equivalent %2e%2e%2f
. These URLs allow the attacker to break out of the base directory and view files stored in other folders on the filesystem.
To illustrate this, let's jump into the code. Below you will find the a function, which constructs a filesystem path from the URL. All files and directories returned by the function are served statically by the web server.
We can use the “realpath” function to dereference the requested (relative) path, and return the absolute path of the file.
By defining a base path (or an array of allowable paths) in our program, we can compare them to the output of realpath and decide whether a request should be permitted or not. If the prefix paths do not match up, then our user could be attempting to access files they’re not supposed to!
Now include()
will only be called if a given file is prefixed with “/todoapp/public/images”, and otherwise does nothing.
To learn more about directory traversal, check out some other great content produced by Snyk:
Read our white paper on Zip Slip, a directory traversal vulnerability that results in remote code execution.
If the white paper got you worried, learn how to mitigate Zip Slip in your code-base with our cheat sheet.
Have a look at our YouTube video which further explains directory traversal and digs into a real-world example of directory traversal affecting a well-known open-source library.