SlideShare a Scribd company logo
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.
• Prevent 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

More Related Content

PPTX
Css and its types
Mansi Mahadik
 
PPTX
Directory Traversal & File Inclusion Attacks
Raghav Bisht
 
PPTX
Secure Coding 101 - OWASP University of Ottawa Workshop
Paul Ionescu
 
PDF
Defcon 27 - Writing custom backdoor payloads with C#
Mauricio Velazco
 
PPTX
malware
Deepak Chawla
 
PDF
An Introduction to CSS
Vidya Ananthanarayanan
 
ODP
Squid Proxy Server
13bcs0012
 
PDF
Web Application Security and Awareness
Abdul Rahman Sherzad
 
Css and its types
Mansi Mahadik
 
Directory Traversal & File Inclusion Attacks
Raghav Bisht
 
Secure Coding 101 - OWASP University of Ottawa Workshop
Paul Ionescu
 
Defcon 27 - Writing custom backdoor payloads with C#
Mauricio Velazco
 
malware
Deepak Chawla
 
An Introduction to CSS
Vidya Ananthanarayanan
 
Squid Proxy Server
13bcs0012
 
Web Application Security and Awareness
Abdul Rahman Sherzad
 

What's hot (20)

PPTX
File inclusion
AaftabKhan14
 
PPTX
Introduction to path traversal attack
Prashant Hegde
 
PPTX
Validation Controls in asp.net
Deep Patel
 
PPTX
Viruses ppt
Kartik Kalpande Patil
 
PDF
The-Hacker-Playbook-Practical-Guide-To-Penetration-Testing-2014.pdf
prasunkagrawal
 
PPTX
Ethical Hacking Certifications | Certified Ethical Hacker | Ethical Hacking |...
Simplilearn
 
ODP
OWASP Secure Coding
bilcorry
 
PPT
Computer hacking
shreyas dani
 
PPTX
Basics of Denial of Service Attacks
Hansa Nidushan
 
PDF
Java Journal & Pyresso: A Python-Based Framework for Debugging Java
CrowdStrike
 
PPTX
Archtecture of world wide web
techlovers3
 
DOCX
Problem solving UNIT - 4 [C PROGRAMMING] (BCA I SEM)
Mansi Tyagi
 
PPTX
Click jacking
Ronan Dunne, CEH, SSCP
 
PPTX
Ch 04 asp.net application
Madhuri Kavade
 
PDF
CSS selectors
Héla Ben Khalfallah
 
PPTX
Cookies in servlets.ppt
Swetha S
 
PPTX
Forms in html5
hrisi87
 
PPTX
Port forwarding
Ronak Mehta
 
PDF
Operators in PHP
Vineet Kumar Saini
 
File inclusion
AaftabKhan14
 
Introduction to path traversal attack
Prashant Hegde
 
Validation Controls in asp.net
Deep Patel
 
The-Hacker-Playbook-Practical-Guide-To-Penetration-Testing-2014.pdf
prasunkagrawal
 
Ethical Hacking Certifications | Certified Ethical Hacker | Ethical Hacking |...
Simplilearn
 
OWASP Secure Coding
bilcorry
 
Computer hacking
shreyas dani
 
Basics of Denial of Service Attacks
Hansa Nidushan
 
Java Journal & Pyresso: A Python-Based Framework for Debugging Java
CrowdStrike
 
Archtecture of world wide web
techlovers3
 
Problem solving UNIT - 4 [C PROGRAMMING] (BCA I SEM)
Mansi Tyagi
 
Click jacking
Ronan Dunne, CEH, SSCP
 
Ch 04 asp.net application
Madhuri Kavade
 
CSS selectors
Héla Ben Khalfallah
 
Cookies in servlets.ppt
Swetha S
 
Forms in html5
hrisi87
 
Port forwarding
Ronak Mehta
 
Operators in PHP
Vineet Kumar Saini
 
Ad

Similar to Directory_Traversel.pdf (20)

PPTX
Directory traversal
penetration Tester
 
PDF
SOHOpelessly Broken
The Security of Things Forum
 
PDF
CNIT 129S: 10: Attacking Back-End Components
Sam Bowne
 
PDF
Session9-File Upload Security
zakieh alizadeh
 
PPTX
The Hacking Game - Think Like a Hacker Meetup 12072023.pptx
lior mazor
 
PDF
Remote file path traversal attacks for fun and profit
Dharmalingam Ganesan
 
PPT
Bsides-Philly-2016-Finding-A-Companys-BreakPoint
Zack Meyers
 
PPTX
Secure Code Warrior - Local file inclusion
Secure Code Warrior
 
PPTX
Uwvwwbwbwbwbwbwbwbnit-4 - web security.pptx
VikasTuwar1
 
PDF
Ch 10: Attacking Back-End Components
Sam Bowne
 
PDF
Ch 13: Attacking Other Users: Other Techniques (Part 1)
Sam Bowne
 
PDF
Study of Directory Traversal Attack and Tools Used for Attack
ijtsrd
 
PDF
Realities of Security in the Cloud - CSS ATX 2017
Alert Logic
 
PDF
pentesting
Bobzyn
 
PDF
Java secure development part 1
Rafel Ivgi
 
PDF
Penetration Testing is the Art of the Manipulation
JongWon Kim
 
PDF
Advanced Threats and Lateral Movement Detection
Greg Foss
 
PPTX
Pentesting Tips: Beyond Automated Testing
Andrew McNicol
 
PPTX
Secure programming with php
Mohmad Feroz
 
PPT
Beyond Automated Testing - RVAsec 2016
Andrew McNicol
 
Directory traversal
penetration Tester
 
SOHOpelessly Broken
The Security of Things Forum
 
CNIT 129S: 10: Attacking Back-End Components
Sam Bowne
 
Session9-File Upload Security
zakieh alizadeh
 
The Hacking Game - Think Like a Hacker Meetup 12072023.pptx
lior mazor
 
Remote file path traversal attacks for fun and profit
Dharmalingam Ganesan
 
Bsides-Philly-2016-Finding-A-Companys-BreakPoint
Zack Meyers
 
Secure Code Warrior - Local file inclusion
Secure Code Warrior
 
Uwvwwbwbwbwbwbwbwbnit-4 - web security.pptx
VikasTuwar1
 
Ch 10: Attacking Back-End Components
Sam Bowne
 
Ch 13: Attacking Other Users: Other Techniques (Part 1)
Sam Bowne
 
Study of Directory Traversal Attack and Tools Used for Attack
ijtsrd
 
Realities of Security in the Cloud - CSS ATX 2017
Alert Logic
 
pentesting
Bobzyn
 
Java secure development part 1
Rafel Ivgi
 
Penetration Testing is the Art of the Manipulation
JongWon Kim
 
Advanced Threats and Lateral Movement Detection
Greg Foss
 
Pentesting Tips: Beyond Automated Testing
Andrew McNicol
 
Secure programming with php
Mohmad Feroz
 
Beyond Automated Testing - RVAsec 2016
Andrew McNicol
 
Ad

More from Okan YILDIZ (14)

PDF
XSS.pdf
Okan YILDIZ
 
PDF
IDOR.pdf
Okan YILDIZ
 
PDF
Buffer Overflow - English.pdf
Okan YILDIZ
 
PDF
File Inclusion.pdf
Okan YILDIZ
 
PDF
Azure Security Check List - Final.pdf
Okan YILDIZ
 
PDF
IDOR.pdf
Okan YILDIZ
 
PDF
Phishing, Smishing and vishing_ How these cyber attacks work and how to preve...
Okan YILDIZ
 
PDF
XSS.pdf
Okan YILDIZ
 
PDF
command-injection-v3.pdf
Okan YILDIZ
 
PDF
VoIP (Voice over Internet Protocol).pdf
Okan YILDIZ
 
PDF
Buffer overflow
Okan YILDIZ
 
PDF
Some Kitapçık
Okan YILDIZ
 
PDF
Sosyal Mühendislik Saldırıları
Okan YILDIZ
 
PDF
DNS Güvenliği
Okan YILDIZ
 
XSS.pdf
Okan YILDIZ
 
IDOR.pdf
Okan YILDIZ
 
Buffer Overflow - English.pdf
Okan YILDIZ
 
File Inclusion.pdf
Okan YILDIZ
 
Azure Security Check List - Final.pdf
Okan YILDIZ
 
IDOR.pdf
Okan YILDIZ
 
Phishing, Smishing and vishing_ How these cyber attacks work and how to preve...
Okan YILDIZ
 
XSS.pdf
Okan YILDIZ
 
command-injection-v3.pdf
Okan YILDIZ
 
VoIP (Voice over Internet Protocol).pdf
Okan YILDIZ
 
Buffer overflow
Okan YILDIZ
 
Some Kitapçık
Okan YILDIZ
 
Sosyal Mühendislik Saldırıları
Okan YILDIZ
 
DNS Güvenliği
Okan YILDIZ
 

Recently uploaded (20)

PDF
67243-Cooling and Heating & Calculation.pdf
DHAKA POLYTECHNIC
 
PDF
Zero carbon Building Design Guidelines V4
BassemOsman1
 
PPTX
business incubation centre aaaaaaaaaaaaaa
hodeeesite4
 
PDF
settlement FOR FOUNDATION ENGINEERS.pdf
Endalkazene
 
PDF
Advanced LangChain & RAG: Building a Financial AI Assistant with Real-Time Data
Soufiane Sejjari
 
PPTX
FUNDAMENTALS OF ELECTRIC VEHICLES UNIT-1
MikkiliSuresh
 
PPTX
Tunnel Ventilation System in Kanpur Metro
220105053
 
PPTX
MSME 4.0 Template idea hackathon pdf to understand
alaudeenaarish
 
PDF
top-5-use-cases-for-splunk-security-analytics.pdf
yaghutialireza
 
PDF
Top 10 read articles In Managing Information Technology.pdf
IJMIT JOURNAL
 
PDF
dse_final_merit_2025_26 gtgfffffcjjjuuyy
rushabhjain127
 
PPTX
Chapter_Seven_Construction_Reliability_Elective_III_Msc CM
SubashKumarBhattarai
 
PPTX
Module2 Data Base Design- ER and NF.pptx
gomathisankariv2
 
PDF
flutter Launcher Icons, Splash Screens & Fonts
Ahmed Mohamed
 
PDF
Traditional Exams vs Continuous Assessment in Boarding Schools.pdf
The Asian School
 
PDF
67243-Cooling and Heating & Calculation.pdf
DHAKA POLYTECHNIC
 
PDF
Introduction to Ship Engine Room Systems.pdf
Mahmoud Moghtaderi
 
PDF
Unit I Part II.pdf : Security Fundamentals
Dr. Madhuri Jawale
 
DOCX
SAR - EEEfdfdsdasdsdasdasdasdasdasdasdasda.docx
Kanimozhi676285
 
PDF
Natural_Language_processing_Unit_I_notes.pdf
sanguleumeshit
 
67243-Cooling and Heating & Calculation.pdf
DHAKA POLYTECHNIC
 
Zero carbon Building Design Guidelines V4
BassemOsman1
 
business incubation centre aaaaaaaaaaaaaa
hodeeesite4
 
settlement FOR FOUNDATION ENGINEERS.pdf
Endalkazene
 
Advanced LangChain & RAG: Building a Financial AI Assistant with Real-Time Data
Soufiane Sejjari
 
FUNDAMENTALS OF ELECTRIC VEHICLES UNIT-1
MikkiliSuresh
 
Tunnel Ventilation System in Kanpur Metro
220105053
 
MSME 4.0 Template idea hackathon pdf to understand
alaudeenaarish
 
top-5-use-cases-for-splunk-security-analytics.pdf
yaghutialireza
 
Top 10 read articles In Managing Information Technology.pdf
IJMIT JOURNAL
 
dse_final_merit_2025_26 gtgfffffcjjjuuyy
rushabhjain127
 
Chapter_Seven_Construction_Reliability_Elective_III_Msc CM
SubashKumarBhattarai
 
Module2 Data Base Design- ER and NF.pptx
gomathisankariv2
 
flutter Launcher Icons, Splash Screens & Fonts
Ahmed Mohamed
 
Traditional Exams vs Continuous Assessment in Boarding Schools.pdf
The Asian School
 
67243-Cooling and Heating & Calculation.pdf
DHAKA POLYTECHNIC
 
Introduction to Ship Engine Room Systems.pdf
Mahmoud Moghtaderi
 
Unit I Part II.pdf : Security Fundamentals
Dr. Madhuri Jawale
 
SAR - EEEfdfdsdasdsdasdasdasdasdasdasdasda.docx
Kanimozhi676285
 
Natural_Language_processing_Unit_I_notes.pdf
sanguleumeshit
 

Directory_Traversel.pdf

  • 1. 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
  • 2. 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
  • 3. 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
  • 4. 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
  • 5. 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
  • 6. 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
  • 7. 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
  • 8. 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
  • 9. 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
  • 10. 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
  • 11. Figure 5: Succesful Exploitation 11
  • 12. 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
  • 13. 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
  • 14. 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
  • 15. 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
  • 16. 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
  • 17. 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
  • 18. • 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. • Prevent unauthorized users from viewing the contents of your directories. In Apache, you can add the following configuration to your .htaccess file: Options -Indexes. 18
  • 19. • 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
  • 20. 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
  • 21. 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
  • 22. 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
  • 23. 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
  • 24. 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
  • 25. 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