CWE-23: Relative Path Traversal

Learn about CWE-23 (Relative Path Traversal), its security impact, exploitation methods, and prevention guidelines.

What is Relative Path Traversal?

• Overview: Relative Path Traversal is a vulnerability where an application constructs a file path using external input without properly sanitizing it, allowing attackers to access files or directories outside the intended restricted directory.

• Exploitation Methods:

  • Attackers can exploit this vulnerability by crafting input that includes sequences like "../" to navigate the directory structure upwards and access unauthorized files.
  • Common attack patterns include inserting traversal sequences into file paths submitted through web forms, URLs, or API requests.

• Security Impact:

  • Direct consequences of successful exploitation include unauthorized access to sensitive files, such as configuration files, password files, or other confidential data.
  • Potential cascading effects include data leakage, privilege escalation, and further system compromise if sensitive information is accessed.
  • Business impact may involve data breaches, loss of customer trust, legal liabilities, and financial losses.

• Prevention Guidelines:

  • Specific code-level fixes include validating and sanitizing all user inputs used in file path construction, ensuring inputs are stripped of traversal sequences.
  • Security best practices involve using built-in functions or libraries that handle file paths securely and implementing strict access controls to sensitive directories.
  • Recommended tools and frameworks can include static code analysis tools to detect path traversal vulnerabilities and web application firewalls (WAFs) to block malicious path traversal attempts.
Corgea can automatically detect and fix Relative Path Traversal in your codebase. [Try Corgea free today](https://corgea.app).

Technical Details

Likelihood of Exploit: Not specified

Affected Languages: Not Language-Specific

Affected Technologies: Not specified

Vulnerable Code Example

import os

def read_file(filename):
    # Vulnerable to path traversal attacks
    # An attacker can manipulate the filename to access files outside the intended directory
    base_directory = '/var/www/data/'
    file_path = os.path.join(base_directory, filename)  # Construct the full file path
    try:
        with open(file_path, 'r') as file:  # Attempt to open the file
            return file.read()  # Return the file contents
    except FileNotFoundError:
        return "File not found."

# Example usage
# read_file('../../etc/passwd')  # This could potentially expose sensitive system files

How to fix Relative Path Traversal?

To fix the Relative Path Traversal vulnerability, we need to ensure that user input does not allow navigation outside the intended directory. This can be achieved by:

  1. Sanitizing Input: Remove or neutralize sequences like ../ that allow directory traversal.
  2. Path Normalization: Use functions to normalize the path to prevent directory traversal.
  3. Access Control: Implement strict access control policies to ensure sensitive files cannot be accessed.

In Python, the os.path module provides functionality to safely handle and normalize paths. By resolving the absolute path and ensuring it starts with the intended base directory, we can prevent path traversal.

Fixed Code Example

import os

def read_file_secure(filename):
    base_directory = '/var/www/data/'
    # Normalize the path to prevent path traversal
    file_path = os.path.normpath(os.path.join(base_directory, filename))
    
    # Ensure the file path is within the base directory
    if not file_path.startswith(os.path.abspath(base_directory) + os.sep):
        raise ValueError("Access to the path is denied")
    
    try:
        with open(file_path, 'r') as file:
            return file.read()  # Securely read the file
    except FileNotFoundError:
        return "File not found."

# Example usage
# read_file_secure('myfile.txt')  # This will safely open the file if it exists within the base directory

In the fixed example, os.path.normpath is used to normalize the path, eliminating any ../ sequences that could allow an attacker to traverse directories. We then check that the normalized path starts with the absolute path of base_directory, ensuring the file access remains within the intended directory. If the check fails, an exception is raised to prevent unauthorized access. This approach effectively mitigates the risk of path traversal attacks.

Corgea Logo

Find this vulnerability and fix it with Corgea

Scan your codebase for CWE-23: Relative Path Traversal and get remediation guidance

Start for free and no credit card needed.