0% found this document useful (0 votes)
19 views25 pages

Attack Directory Traversal

The document discusses directory traversal attacks, including how they work, their risks, and methods to prevent them. It explores techniques attackers use to exploit vulnerabilities and access unauthorized files, and provides best practices for input validation and limiting file access to strengthen defenses against these attacks.

Uploaded by

Gino Valdes
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
19 views25 pages

Attack Directory Traversal

The document discusses directory traversal attacks, including how they work, their risks, and methods to prevent them. It explores techniques attackers use to exploit vulnerabilities and access unauthorized files, and provides best practices for input validation and limiting file access to strengthen defenses against these attacks.

Uploaded by

Gino Valdes
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 25

Directory Traversal

Talha Eroglu, Ilgaz Senyuz, Okan Yildiz

July 16, 2023

Abstract

In this article, we explore the path traversal attacks, also known as


directory traversal attacks, and the potential harm they can cause to
a system. We begin with an introduction to path traversal, explaining
what it is and how attackers can exploit it to gain unauthorized access
to files and directories. We then dive into the different techniques that
can be used to exploit path traversal, including manipulating file paths
and using encoding techniques. To prevent these attacks, we discuss
several best practices, such as input validation and path normaliza-
tion. Finally, we provide examples of more secure code and discuss
how developers can implement these practices to strengthen their ap-
plication’s defenses against path traversal attacks. Whether you’re a
developer, a security professional, or just interested in learning more
about cyber-security, this article provides valuable insights into one of
the most common types of web application vulnerabilities.

1
Contents
1 Introduction to Directory Traversal 3

2 Possible Risks of Directory Traversal Vulnerabilities 4


2.1 Unauthorized Access to Sensitive Data . . . . . . . . . 5
2.2 Server and Application Compromise . . . . . . . . . . . 5
2.3 Privilege Escalation . . . . . . . . . . . . . . . . . . . . 5
2.4 Server and Application Compromise . . . . . . . . . . . 6

3 How to Exploit Directory Traversal Vulnerabilities 7

4 Preventing Directory Traversal Attacks 14


4.1 General Methods . . . . . . . . . . . . . . . . . . . . . 14
4.1.1 Input Validation . . . . . . . . . . . . . . . . . 15
4.1.2 Canonicalization . . . . . . . . . . . . . . . . . 16
4.1.3 Limit File System Access . . . . . . . . . . . . . 17
4.1.4 Use a Chroot Jail or Virtual Environment . . . 17
4.1.5 Avoid Exposing File System Structure . . . . . 18
4.1.6 Utilize Safeguards in Web Server Configuration 18
4.1.7 Keep Software Updated . . . . . . . . . . . . . 19
4.2 Attempt to Mitigate Exploited Vulnerabilities . . . . . 21

5 References 25

2
1 Introduction to Directory Traversal
Directory Traversal, also known as file path traversal, is a serious
web security vulnerability that enables attackers to read files on a
server that is running a web application. This can include sensitive
files such as application code and data, as well as credentials for back-
end systems and operating system files. In some cases, attackers may
also be able to modify files on the server, which can lead to a complete
takeover of the system.

Directory Traversal attacks typically occur when attackers manipu-


late input parameters in order to access files and directories outside
of the intended directory. By inserting special characters like ”../” or
”..”, attackers can navigate up the directory tree and access files that
should not be publicly accessible.

3
Figure 1: Directory Traversal

For example, consider a web application that allows users to upload


files. If the application does not properly validate user input, an at-
tacker can manipulate the file name to include special characters that
allow them to navigate outside of the upload directory. From there,
they may be able to access other files on the server, such as configura-
tion files or user databases, which can lead to a complete compromise
of the system.

2 Possible Risks of Directory Traversal


Vulnerabilities
Directory traversal vulnerabilities can pose significant risks to organi-
zations in various ways, including:

4
2.1 Unauthorized Access to Sensitive Data
One of the most significant risks associated with directory traver-
sal attacks is the unauthorized access to sensitive data. This can
include personal information, financial records, or proprietary intel-
lectual property. By exploiting directory traversal vulnerabilities, at-
tackers can gain access to files and directories that are not meant to be
publicly accessible, potentially leading to data breaches and significant
legal and financial consequences for the affected organization.

2.2 Server and Application Compromise


Attackers may use directory traversal techniques to access configu-
ration files, source code, or other sensitive data that could be leveraged
to identify additional vulnerabilities within a web application or server.
This can lead to further exploitation, potentially resulting in a com-
plete compromise of the application or server environment. In such
cases, attackers may gain control over an organization’s digital infras-
tructure and execute additional attacks, such as installing malware or
conducting a distributed denial-of-service (DDoS) attack.

2.3 Privilege Escalation


Directory traversal attacks can also lead to privilege escalation, wherein
an attacker with limited access to a system is able to gain elevated priv-
ileges. This can occur when an attacker leverages a directory traversal
vulnerability to access files that grant them additional permissions or
provide information that can be used to exploit other vulnerabilities
in the system. With elevated privileges, an attacker may be able to

5
execute arbitrary code, manipulate data, or perform other malicious
actions that would otherwise be restricted.

2.4 Server and Application Compromise


In certain cases, attackers may not only gain unauthorized access
to sensitive files but also modify, delete, or tamper with them. This
can have severe consequences, particularly if the affected files are crit-
ical to the functioning of a web application or system. For example,
an attacker could modify a configuration file to introduce additional
vulnerabilities, alter a web page to display false information, or delete
critical files to cause system instability.

6
3 How to Exploit Directory Traversal Vul-
nerabilities
To better understand web application exploitation, we will be using
a lab environment that has already been set up. This lab includes
several PHP-based web applications, and you can access the relevant
environment through the references section. As shown in the figure
below, there is currently a PHP-based web application running on
port 8091 within the lab environment.

Figure 2: Lab environment

7
Our initial inspection of the webpage reveals that clicking on images
produces a URL in the format “loadimage.php?file name=image.png”.

Figure 3: Inspection of the page

8
We then open Burpsuite and enable interception in the Proxy tab.
Next, we click on an image, and as shown in the figure below, Burp
intercepts the corresponding request. From here, we proceed to inject
our payloads into the “file name” parameter in the GET request.

In order to send several payloads without intercepting everytime, we


send the captured intercept to repeater by right-clicking on the request
and selecting ’Send to Repeater’ option. This will allow us to see the
request and response together and take action accordingly.

Figure 4: Intercepted GET Request

9
When attempting to navigate to the root directory, we commonly
employ the ”../” notation, which allows us to move up one directory
level. The exact number of directories we need to climb is not always
known, hence the advantage of the ”../” notation, which lets us ascend
one directory at a time until we reach the root directory.

It’s crucial to remember that no matter how many ”../” notations we


add, we can’t go beyond the root directory. Therefore, adding extra
”../” notations as a safety measure will not harm or interfere with our
target payload, since these would be ignored once we have reached the
root level.

Our purpose of reaching the root directory is because this is typi-


cally where we can find the /etc/passwd file. In our context, we use
this as a common technique to test for directory traversal vulnerabil-
ities. Please note that our objective is not to gain access to this file
specifically, but to use it as an illustration of our vulnerability testing
approach.

After sending request with our crafted payload, we’ve successfully ac-
cessed /etc/passwd as you can see.

10
Figure 5: Succesful Exploitation

11
Moving forward, we will explore another web application in our lab.
It appears quite similar to the previous one and is also developed with
PHP. However, it seems to handle file requests differently.

Figure 6: Second Web Page

We carry out steps similar to the previous section by enabling inter-


ception in Burp and clicking on a random image. We then forward the
intercepted request to the repeater by right-clicking on it, as illustrated
in the image below.

12
Figure 7: Intercepted Request

We attempt to exploit the system using the previous payload, but


as shown in the image below, we receive a ’Hack detected’ response.
This suggests that the application is performing some form of input
validation in the background to prevent unauthorized access.

Figure 8: Failed exploitation attempt

13
Upon closer inspection of the application, we notice that it iden-
tifies any file name containing ’..’ and subsequently returns a ’Hack
detected’ message. While we could consider using URL encoding as a
standard approach, there is another crucial method we should explore
first. Up until now, we have attempted to read /etc/passwd using rel-
ative paths. It is now a good time to try absolute path as input.

As shown in the figure below, we filled in the file name field with
’/etc/passwd’ and successfully read the file.

Figure 9: Successful exploitation

4 Preventing Directory Traversal Attacks

4.1 General Methods


Directory Traversal Attacks are a type of vulnerability in web applica-
tions that can allow attackers to access sensitive files and directories

14
on a web server. To prevent these types of attacks, developers should
follow best practices when designing and implementing their web appli-
cations. It is recommended that application functionality is designed
in a way that avoids passing user-controllable data to filesystem op-
erations. One approach is to reference known files using an index
number instead of their name and to save user-supplied file content
using application-generated filenames. However, in situations where
passing user-controllable data to a filesystem operation is unavoidable,
it is crucial to follow all the steps below:

4.1.1 Input Validation

Thorough input validation is essential for preventing path traversal at-


tacks. Validate user-provided inputs by checking for any illegal char-
acters or sequences. Use a whitelist approach, permitting only allowed
characters, and avoid blacklisting, as attackers can often find ways to
bypass it. Regular expressions can be employed to perform this vali-
dation effectively. For instance, you can use a regex pattern like

^[a-zA-Z0-9_\-]+$

to only allow alphanumeric characters, underscores, and hyphens in


the input.

Key points:

• Whitelist approach

• Check for illegal characters or sequences

• Use regular expressions for validation

15
4.1.2 Canonicalization

Canonicalization, also known as path normalization, is the process of


converting file paths into a standard representation. This process helps
eliminate redundant or potentially harmful elements, such as ”../” or
”./”. It’s crucial to perform canonicalization after input validation, as
attackers may use different path representations to bypass the valida-
tion checks.

One effective method to prevent path traversal attacks is to compare


the canonical path (realpath) of the requested file with the raw path. If
they differ, this indicates the presence of potentially harmful elements
in the raw path. This can serve as an alert for a possible path traversal
attack.

Most programming languages provide libraries or built-in functions to


perform canonicalization, such as realpath() in PHP, os.path.normpath()
in Python or java.nio.file.Paths.get() in Java. These functions convert
the file path to its canonical form, making it easier to perform the
comparison mentioned above.

Key points:
• Convert file paths to standard representation

• Remove redundant or harmful elements

• Compare the canonical path with the raw path for potential dis-
crepancies

• Use built-in functions or libraries for canonicalization

16
4.1.3 Limit File System Access

To limit an application’s file system access, first identify the neces-


sary files and directories the application needs to access. Then, set
appropriate file system permissions and employ the principle of least
privilege. This ensures that the application has the minimum level of
access required to function correctly. In the case of a successful path
traversal attack, this practice can help limit the potential impact.

Key points:

• Restrict access to necessary files and directories

• Set appropriate file system permissions

• Apply the principle of least privilege

4.1.4 Use a Chroot Jail or Virtual Environment

A chroot jail is a method of isolating an application’s file system within


a specific directory. By changing the root directory for the application,
it cannot access files or directories outside the designated area. This
confinement helps limit the potential damage from a successful path
traversal attack. On Unix-like systems, the chroot command can be
used to set up a chroot jail. Alternatively, you can use virtual envi-
ronments, such as Docker containers or virtual machines, to achieve a
similar level of isolation.

Key points:

• Confine application within a specific directory

17
• Use chroot command, Docker containers, or virtual machines

• Limit the impact of a successful path traversal attack

4.1.5 Avoid Exposing File System Structure

Prevent attackers from gaining valuable information about your appli-


cation’s file system structure by using generic error messages. Avoid
providing detailed error messages that may reveal sensitive informa-
tion, such as file paths or directory structures. This practice can reduce
the risk of an attacker exploiting exposed information for a path traver-
sal attack.

Key points:
• Use generic error messages

• Avoid revealing sensitive information

• Reduce risk of information exploitation

4.1.6 Utilize Safeguards in Web Server Configuration

Web server configurations can help mitigate path traversal attacks by


implementing various security measures. These include:

• Define rules that restrict access to sensitive files or directories.


For example, in Apache, you can use the .htaccess file to limit
access to specific resources.

• P revent unauthorized users from viewing the contents of your


directories. In Apache, you can add the following configuration
to your .htaccess file: Options -Indexes.

18
• Rewrite URLs to prevent direct access to specific file types. In
Apache, you can use the mod rewrite module to create rewrite
rules.

For other web servers, such as Nginx or Microsoft IIS, similar con-
figurations can be applied to achieve comparable levels of protection.

Key points:

• Implement access control rules

• Disable directory listing

• Apply URL rewriting

4.1.7 Keep Software Updated

Regularly update your application, libraries, and server software to


ensure the latest security patches are applied. This helps to mitigate
known vulnerabilities that attackers might exploit for a path traversal
attack. Establish a routine for checking and applying updates and se-
curity patches, and stay informed about any security-related announce-
ments for the software you use.

Key points:

• Maintain up-to-date software

• Apply the latest security patches

• Establish a routine for updates and patches

19
By following these best practices, you can significantly reduce the
risk of a successful path traversal attack and protect your application
and its sensitive data. Remember, security is an ongoing process; stay
vigilant and continually assess your application’s security posture to
ensure the highest level of protection.

20
4.2 Attempt to Mitigate Exploited Vulnerabilities
Let’s begin with our first scenario. In the provided source code for the
file reading operation, you can see that no precautions have been taken
to prevent security vulnerabilities. As a result, we could easily access
sensitive files like /etc/passwd using relative paths with dot-dot-slash
(../) approach.

Figure 10: Scenario 1- Source Code

Four our case, We implemented a very basic sanitizeFilePath func-


tion. It provides a layer of protection by ensuring the requested file
is within the allowed directory which is under images folder, and san-
itizing the input to avoid malicious characters. It works by removing
directory information from the input, calculating a secure absolute
path, and verifying that the file is located in the intended directory.
While this method offers a more comprehensive level of security, it’s
important to note that it doesn’t provide absolute protection.

21
Figure 11: Scenario 2- sanitizeFilePath function added

After implementing these modifications, let’s attempt to access the


/etc/passwd file once again using the ../ method. As demonstrated
below, we can no longer retrieve the file with our initial basic exploit
attempt. The sanitizeFilePath function recognizes that the requested
file is not located within the ”images” folder and returns an invalid
path error.

Figure 12: Scenario 1- Initial Exploit Method Failed

22
As we proceed to the second scenario, let’s remember that we pre-
viously exploited it by accessing the /etc/passwd file using an absolute
path. Upon examining the source code, it becomes apparent that the
code only checks for the presence of the ”../” sequence in the file in-
put. The intention is to prevent path traversal attacks by stopping the
script execution with a ”Hack detected” message if it detects the ”..”
sequence.

Figure 13: Scenario 2- Source Code

However, this approach has some limitations in securing the code:

• The code solely checks for the ”..” sequence, but creative attack-
ers might use different encoding methods or techniques to bypass
this basic check.

• It doesn’t restrict access to a specific directory or a predefined


set of allowed files.

• The input file name is neither sanitized nor validated in any other
way.

Considering that we only need to display eight specific images, it’s


a great idea to implement a whitelist approach, which will allow access
to only these files. This method will enhance the security of the code,
ensuring that only the desired images are accessible. The following

23
example demonstrates how to modify the code using a whitelist that
contains the eight image files we want to allow:

Figure 14: Scenario 2- Whitelist Check Added

Now, let’s attempt to exploit this level using the same payload we
used in the how to exploit section. As you can see, the attacker’s
provided input is not on the whitelist, so our function detects the
discrepancy and returns an error. I would like to reiterate that these
precautions are quite basic, and in real-world scenarios, a multi-layered
security approach should be implemented for optimal protection.

24
Figure 15: Scenario 2- Initial Exploit Method Failed

5 References
• https://github.com/0136misa/path-traversal-vulnerabilities

• https://www.invicti.com/learn/directory-traversal-path-traversal/

• https://portswigger.net/web-security/file-path-traversal

• https://www.acunetix.com/websitesecurity/directory-traversal/

• https://www.synopsys.com/glossary/what-is-path-traversal.
html

• https://cheatsheetseries.owasp.org/cheatsheets/Input_Validation_
Cheat_Sheet.html

• https://owasp.org/www-community/attacks/Path_Traversal

• https://wiki.owasp.org/index.php/File_System#Path_traversal

25

You might also like