How Directory Traversal Attacks Put Your Data at Risk

calender

What is a Directory traversal ?

A directory traversal, also called path traversal, is a type of attack where a hacker tricks a website or system into showing files that should be hidden or protected. Normally, these files might contain important or sensitive information that the hacker isn’t supposed to see. Imagine you have a locked drawer, but someone finds a way to open it without a key—that’s similar to what happens in a directory traversal attack. The hacker “travels” through the system’s folders (like traveling through a maze) to reach these hidden files. This can lead to serious security issues, especially if the exposed files contain personal or confidential data.

How Directory Traversal Works ?

1. Understanding File Paths

Web applications typically serve files like images, documents, or scripts from a designated directory on the server. For example, a website might store images in a folder like /var/www/html/images/ on a Linux server, or C:inetpubwwwrootimages on a Windows server.

Files and directories are accessed using file paths, which describe the location of the file in the directory structure. There are two main types of file paths:

  • Absolute Path: This is the full path to a file from the root directory (e.g., /var/www/html/images/photo.jpg or C:inetpubwwwrootimagesphoto.jpg).
  • Relative Path: This refers to the location of a file relative to the current directory. For example, images/photo.jpg refers to a file in the images folder inside the current directory.
2. How Web Applications Handle File Requests

In many web applications, users request files through URLs. For example:

  • A user requests an image like this: www.example.com/view?file=photo.jpg.
  • The server processes this request and looks for the file photo.jpg in a specific folder, such as /var/www/html/images/.
  • The server then sends the file back to the user, and the image is displayed.
3. Manipulating the File Path

A directory traversal vulnerability arises when the server does not properly validate or sanitize the input provided by the user. An attacker can exploit this by entering a malicious file path that tricks the server into navigating to a different directory. Attackers use special sequences like ../ (called “dot-dot-slash”) to move up in the directory structure. For example, if an attacker sends this URL: www.example.com/view?file=../../etc/passwd

Here’s what happens:

  • ../../ tells the server to go up two levels in the directory structure. Instead of looking for a file in /var/www/html/images/, the server will go to /etc/ (a system directory) and try to access the file passwd, which contains information about user accounts on Linux systems.
4. Attackers’ Techniques

Attackers can use various tricks to exploit directory traversal vulnerabilities. Some common techniques include:

  • Dot-dot-slash (../): This is the basic traversal technique where the attacker tries to go up in the directory structure by adding multiple ../ in the URL.
  • URL Encoding: Sometimes, servers might block ../, but attackers can bypass this by encoding the characters. For example:
  • Null Byte Injection: In older or poorly coded systems, attackers could append a null byte (%00), which terminates the file path early.

Common Exploits

1. Using ../ Sequences:

What It Is: The ../ sequence is a way to tell the system to move up one directory level. Multiple ../ sequences can be used to keep moving up the directory structure.

Example: Suppose a website lets you view files by specifying a file name in the URL: http://example.com/view?file=report.txt. An attacker could try changing the URL to http://example.com/view?file=../../../../etc/passwd.

Result: The ../../../../ part moves the file path up four directory levels, potentially allowing access to a sensitive file like /etc/passwd on Unix systems, which contains user account information.

2. Accessing Configuration Files:

What It Is: Attackers use path traversal to access configuration files that contain sensitive information, such as database credentials or encryption keys.

Example: By manipulating the file path in the URL, an attacker might access a configuration file like config.php, which could contain sensitive information about how the website is set up.

Result: Access to such files could allow the attacker to gain deeper access to the system, manipulate the website’s behavior, or steal sensitive data.

3. Viewing Source Code:

What It Is: Some web applications store their source code in files on the server. If an attacker can access these files, they might be able to find vulnerabilities or learn how the application works.

Example: An attacker might modify the file path to something like http://example.com/view?file=../../../../var/www/html/index.php.

Result: If successful, this could reveal the source code of the website’s main page, potentially exposing more vulnerabilities.

4. Viewing Source Code:

What It Is: Some web applications store their source code in files on the server. If an attacker can access these files, they might be able to find vulnerabilities or learn how the application works.

Example: Using a path traversal, an attacker might target the password file with http://example.com/view?file=../../../Windows/System32/config/SAM on a Windows server.

Result: If they gain access to the SAM file (which stores hashed passwords), they could potentially crack these hashes and gain unauthorized access to user accounts.

5. Log File Access:

What It Is: Attackers might access log files to gather sensitive information, such as error logs that contain stack traces or even user data.

Example: The URL might be altered to http://example.com/view?file=../../../../var/log/apache2/error.log.

Result: Accessing the error log could provide the attacker with detailed error messages that might contain clues about other vulnerabilities or reveal sensitive data.

6. Extracting Password Files:

What It Is: In some systems, password files are stored in specific locations. An attacker might try to access these files to obtain user credentials.

Example: Using a path traversal, an attacker might target the password file with http://example.com/get.php?file=../../../../etc/passwd on a linux server.

Result: If an attacker gains access to the /etc/shadow file on a Linux system (which stores hashed passwords), they could potentially crack these hashes and gain unauthorized access to user accounts.

Detection and Mitigation

1. Input Validation:
  • Thorough Checking: Input validation involves checking every piece of data that users enter into your application, whether it’s a file name, a URL parameter, or a form field. This process ensures that the input follows the expected format and doesn’t include any harmful patterns like ../ that could be used for path traversal.
  • Sanitization: Sanitizing inputs means cleaning them up by removing or neutralizing anything that could be dangerous. For instance, if a user tries to include ../ in a file path, your application should remove these characters or reject the input altogether.
  • Whitelisting: Instead of just looking for bad input, you can use whitelisting to only allow certain characters or patterns that are known to be safe. For example, if you know that file names should only contain letters and numbers, you can block anything else.

How It Protects: Proper input validation and sanitization prevent attackers from sneaking harmful commands into your system, keeping unauthorized files out of reach.

2. Use of Safe APIs:
  • Safe File Handling: Many programming languages and frameworks offer APIs (Application Programming Interfaces) that are specifically designed to handle file paths securely. These APIs don’t allow direct user input to manipulate file paths, which helps prevent path traversal.
  • Path Normalization: Safe APIs often include path normalization features, which automatically clean up file paths, removing dangerous elements like ../. This ensures that the path stays within the intended directory.
  • Why It Matters: By using these built-in tools, you reduce the risk of making mistakes in your code that could expose your system to path traversal attacks. It’s like using a pre-built lock instead of trying to make your own—it’s more reliable and secure.
3.  Set Proper File Permissions
  • Least Privilege: Ensure that the web server and application have only the necessary permissions for file and directory access. Avoid giving write or execute permissions unnecessarily.
  • Disable Directory Listings: If directory browsing is enabled, disable it to prevent attackers from gaining insight into the file structure of your server.
4. Limit User-Supplied File Names
  • File Extensions and MIME Type Validation: Allow only files with specific extensions or validate their MIME types to prevent unauthorized file access.
  • Store Files in Restricted Directories: Place user-uploaded or generated files in specific directories that are separate from the rest of your system.
5. Error Handling
  • Avoid Exposing Full File Paths: Don’t expose sensitive server paths in error messages, as this can give attackers valuable information about the server structure.
6. Regular Security Audits
  • Penetration Testing: Regularly test your web applications for path traversal vulnerabilities using automated tools or manual penetration testing.
  • Security Patches: Keep your server, application framework, and libraries up to date with the latest security patches.
Example

Vulnerable PHP code

This is an example of insecure code where user input is directly used to construct a file path without proper validation.

<?php

// Vulnerable PHP code

if (isset($_GET[‘file’])) {

$file = $_GET[‘file’];  // Get the file name from the URL

// Construct the file path using user input

$filePath = “uploads/” . $file;

// Serve the file if it exists

if (file_exists($filePath)) {

header(‘Content-Type: ‘ . mime_content_type($filePath));

readfile($filePath);

} else {

echo “File not found!”;

}

} else {

echo “No file specified!”;

}

?>

Why Is This Vulnerable?

  • The input parameter $_GET[‘file’] is used directly, allowing an attacker to traverse directories by using ../ in the file name (e.g., ../../etc/passwd).
  • This allows access to sensitive files outside the intended directory, creating a directory traversal vulnerability.

Secure Version

Here’s how to fix the vulnerability by sanitizing the file path and ensuring the file remains within the intended directory.

<?php

// Secure PHP code to prevent directory traversal

if (isset($_GET[‘file’])) {

// Sanitize the input to prevent directory traversal by removing any “..”

$file = basename($_GET[‘file’]); // Get the file name only, without any directory path

// Define the base directory to restrict file access

$baseDir =DIR . ‘/uploads/’;

// Construct the absolute path of the file

$filePath = realpath($baseDir . $file);

// Check if the file exists and is within the allowed directory

if ($filePath && strpos($filePath, realpath($baseDir)) === 0 && file_exists($filePath)) {

header(‘Content-Type: ‘ . mime_content_type($filePath));

readfile($filePath);

} else {

echo “File not found or access denied!”;

}

} else {

echo “No file specified!”;

}

?>

Mitigation Techniques:

  • basename($_GET[‘file’]): This strips any directory components from the file name, ensuring only the base file name is used. It prevents input like ../../etc/passwd from being processed.
  • realpath(): Converts the user input path to an absolute path and checks if the file resides within the uploads/ directory. It prevents attackers from accessing files outside the allowed directory.
  • Directory Check: We use strpos() to ensure that the absolute file path starts with the base directory (uploads/). This prevents traversing out of the directory.

Tools for Testing Path Traversal Vulnerabilities

Security Tools:

1. Burp Suite:

  • What It Is: Burp Suite is a comprehensive security testing tool for web applications. It provides features like intercepting proxy, scanner, and various testing utilities.
  • How It Helps: Burp Suite’s scanner can detect path traversal vulnerabilities by analyzing how your application handles file path inputs. It can automatically test for various payloads and identify potential vulnerabilities.
  • Additional Features: It includes tools for manual testing and can be customized with extensions to enhance its capabilities.

2. OWASP ZAP (Zed Attack Proxy):

  • What It Is: OWASP ZAP is an open-source web application security scanner designed to find vulnerabilities in web applications.
  • How It Helps: ZAP includes automated scanners and manual testing tools that can help identify path traversal vulnerabilities. It can crawl your application, analyze request and response patterns, and detect issues related to file path handling.
  • Additional Features: It offers various plugins and integrations, making it a flexible tool for security assessments.

3. Custom Scripts:

  • What They Are: Custom scripts are tailored tools or scripts written specifically for testing path traversal vulnerabilities in your application.
  • How They Help: These scripts can automate the process of sending crafted file path requests to your application, testing for common traversal patterns like ../ or ..%2f. They can be adapted to test different scenarios and payloads based on your application’s structure.
  • Additional Features: Custom scripts allow for targeted testing and can be integrated into your development pipeline for continuous security checks.

Automated Scanners:

1. Routine Scanners:

  • What They Are: Automated scanners are tools designed to perform regular security assessments on web applications. They can be configured to scan for various vulnerabilities, including path traversal.
  • How They Help: These scanners run scheduled checks and use predefined rules to identify potential vulnerabilities. They can quickly scan large applications and provide reports on detected issues, including path traversal vulnerabilities.
  • Examples: Tools like Nessus, Qualys, and Rapid7 are examples of automated scanners that include web application scanning features.

2. Vulnerability Assessment:

  • What It Is: Automated scanners assess the security of your application by identifying and reporting vulnerabilities. They help maintain a routine check on the security status of your application.
  • How It Helps: Automated vulnerability assessments can catch path traversal issues early, ensuring that they are addressed before they can be exploited. They offer a quick way to evaluate the security of your application and prioritize remediation efforts.
  • Additional Features: Many scanners provide detailed reports and remediation guidance, helping you fix vulnerabilities efficiently.

Conclusion

In conclusion, directory traversal (or path traversal) is a serious vulnerability that can allow attackers to access sensitive files on a server. By manipulating file paths, they can move outside of intended directories and view or steal confidential data, like passwords or system configurations. To protect against this, web applications must validate and sanitize user input, use secure APIs for file handling, restrict file permissions, and regularly update software with security patches. Testing tools like Burp Suite, OWASP ZAP, and automated scanners can help detect and fix these vulnerabilities before they’re exploited.

At IOSCAPE we are committed to improving web security and protecting critical data of our customers from cyber threats to ensure a safer digital environment.

Follow Us