Directory Traversal Attacks Explained: How to Detect and Stop Them

Harshal ShahHarshal Shah
4 min read

Directory Traversal, also known as Path Traversal, is a serious web vulnerability that allows attackers to gain unauthorized access to the server’s filesystem by manipulating input paths. By exploiting this vulnerability, an attacker can access files that are outside the intended directories, potentially leading to the exposure of sensitive system files, application code, or user data.

In this blog, I will explain what Directory Traversal attacks are, demonstrate how they work through a real-time example, and then focus on the detection and prevention techniques that can help protect your applications from this attack.

What is a Directory Traversal Attack?

A Directory Traversal attack occurs when a web application fails to validate user inputs correctly, allowing the user to manipulate file paths and access restricted files. Typically, attackers use sequences like ../ to traverse the directory structure, moving upwards in the folder hierarchy.

For instance:

http://example.com/index.php?page=../../etc/passwd

In this example, the attacker is trying to access the /etc/passwd file by navigating out of the web root folder, potentially exposing sensitive system information.

Real-Time Example: How Directory Traversal Works

Let’s look at a real-time example of a vulnerable web application where a user can access files through a URL parameter.

http://example.com/view.php?file=report.pdf

Here, the application retrieves the report.pdf file from the server's /files/ directory and displays it to the user. However, without proper input validation, an attacker could change the parameter to:

http://example.com/view.php?file=../../../etc/passwd

In this case, the ../../../ allows the attacker to move out of the /files/ directory, traverse the file system, and attempt to access the passwd file, which contains sensitive system information such as usernames and hashes of passwords on a Linux system.

Detection of Directory Traversal Attacks

1. Log Monitoring

One of the primary methods for detecting Directory Traversal attacks is by actively monitoring server logs. Suspicious patterns such as repeated usage of ../ or access attempts to sensitive files like /etc/passwd or C:\Windows\system.ini should raise red flags.

What to look for in logs:

  • Requests containing multiple ../ sequences.

  • Attempts to access sensitive system files (e.g., /etc/passwd, /etc/shadow).

  • Unusual error messages such as “file not found” indicating attempts to access out-of-bound directories.

For example, you might see this in your server logs:

[02/Oct/2024:10:22:56] "GET /view.php?file=../../../../etc/passwd HTTP/1.1" 200

This shows that an attacker successfully used Directory Traversal to attempt to read the passwd file.

2. Security Scanning Tools

Tools such as OWASP ZAP, Burp Suite, and Acunetix can help identify Directory Traversal vulnerabilities during security assessments. These tools will attempt to exploit file inclusion or path manipulation vulnerabilities and report them for remediation.

3. File Integrity Monitoring (FIM)

Using File Integrity Monitoring systems can alert administrators if sensitive system files are accessed or modified unexpectedly, helping to detect unauthorized access due to a Directory Traversal attack.

Prevention of Directory Traversal Attacks

1. Input Validation and Sanitization

To prevent Directory Traversal attacks, input provided by users must be properly sanitized and validated. Any input that could affect the file system should be strictly validated for dangerous patterns such as ../.

Best practices include:

  • Only allowing whitelisted characters for file paths (e.g., letters, numbers, underscores).

  • Blocking sequences such as ../ and ..\.

  • Using predefined paths or filename prefixes that the user cannot modify.

Here’s an example of simple input validation in PHP:

$filename = basename($_GET['file']); // Only allow the filename, remove any directory path
$file = '/var/www/uploads/' . $filename;

This code ensures that the user cannot traverse directories by limiting the input to just the filename.

2. Use Absolute Paths

Wherever possible, use absolute file paths to restrict file access to a specific directory. Avoid allowing users to directly control file paths.

For example:

$whitelisted_files = array('report.pdf', 'summary.pdf');
if (in_array($_GET['file'], $whitelisted_files)) {
    include('/var/www/reports/' . $_GET['file']);
}

Here, the file being requested must be from a predefined whitelist, blocking any attempt to traverse directories.

3. Limit File Permissions

Ensure that the web server’s file system is properly configured with strict permissions. Sensitive files should not be readable by the web application, and directories should have minimal access privileges.

4. Web Application Firewall (WAF)

Deploy a Web Application Firewall (WAF) to automatically detect and block requests that attempt Directory Traversal. WAFs can examine incoming requests for patterns like ../ and stop them before they reach the application.

5. Error Handling

Ensure proper error handling and never display detailed error messages or file paths to users. If a Directory Traversal attack is attempted and the application throws an error, it should be a generic message like “File not found,” without revealing the internal structure of your directories.

Conclusion

Directory Traversal attacks are simple but can be devastating if left unchecked. Detecting these attacks requires vigilance through log monitoring, security scanning, and file integrity checks. Prevention, on the other hand, relies on strong input validation, secure file path management, and robust access controls.

By implementing these detection and prevention mechanisms, you can protect your web applications from unauthorized file access, keeping your systems and data secure.

0
Subscribe to my newsletter

Read articles from Harshal Shah directly inside your inbox. Subscribe to the newsletter, and don't miss out.

Written by

Harshal Shah
Harshal Shah

Navigating the convergence of cybersecurity, DevOps, and cloud landscapes, I am a tech explorer on a mission. Armed with the prowess to secure digital frontiers, streamline operations through DevOps alchemy, and harness the power of the cloud, I thrive in the dynamic intersection of these domains. Join me on this journey of innovation and resilience as we sculpt a secure, efficient, and future-ready tech realm.