Skip to content
All posts

How to Fix Path Manipulation: Understanding and Mitigating Your Code

Introduction

In this article, we'll look at two types of path manipulation vulnerabilities: the traditional form of path manipulation, or directory traversal as it’s often called, which occurs when input parameters are improperly handled, and a specialized variation known as zip entry overwrite, also known as “ZipSlip”. Both types present noteworthy security risks, and understanding their mechanisms is useful for preventing potential exploitation.

Before we dive in, let’s see some real-world examples of breaches affected by this super-common vulnerability.

Real-world Occurrences of Path Manipulation

GitLab Path Traversal Vulnerability (CVE-2023-2825)

In 2023, GitLab disclosed a path traversal vulnerability (CVE-2023-2825) that highlighted the dangers of improper file path validation during uploads. This vulnerability allowed attackers to leverage directory traversal techniques to read arbitrary files on the server, exposing sensitive data.

Key details of the vulnerability:

1) Attackers could upload specially crafted file paths containing sequences like ../../ to access directories outside the intended scope.

2) Sensitive files, such as GitLab configuration files and SSH private keys, were accessible to attackers, posing risks of data leakage and further exploitation.

3) The vulnerability affected GitLab Community and Enterprise Editions across multiple versions, requiring organizations to patch immediately to prevent potential breaches.

Fortinet Path Traversal Vulnerability (CVE-2018-13379)

In 2018, a path traversal vulnerability (CVE-2018-13379) was discovered in Fortinet's FortiOS SSL VPN web portal. This vulnerability allowed unauthenticated attackers to access system files by sending crafted HTTP resource requests, leading to unauthorized disclosure of sensitive information.

Key details of the vulnerability:

1) Attackers could exploit the vulnerability to download system files, including sensitive information such as password files and VPN session data.

2) The attack did not require prior authentication, making it easier for attackers to exploit the vulnerability remotely.

3) The vulnerability affected multiple versions of FortiOS, necessitating prompt updates to mitigate potential risks.

What Are Path Manipulation via Input Parameters Vulnerabilities?

Path manipulation via input parameters occurs when an application processes user-supplied input to construct file paths without properly validating or sanitizing the input. 

Attackers can exploit this by injecting malicious path sequences, such as ../, into input parameters, enabling unauthorized access to files or directories outside the intended scope. 

For instance, consider a web application that allows users to view files, where the name of the file is provided in an input parameter. Assume that the files are stored in a dedicated directory on the server’s file system, let’s say /opt/myapp/user-files/. An attacker might send a request with a crafted parameter, like ../../../etc/passwd, to “go up” in the directory tree and gain access to unauthorized sensitive system files. 

This vulnerability often arises due to insufficient input validation, making it a common and severe threat in web and file-based applications.

What Are Zip Entry Overwrite Vulnerabilities?

Zip entry overwrite vulnerabilities occur when applications extract files from zip archives without adequately validating filenames. Malicious archives can contain crafted entries that overwrite existing files within the extraction directory. When combined with directory traversal sequences, these vulnerabilities escalate, allowing files to be written outside the intended directories.

For example, consider a zip archive containing the following entries:

  • config.json (intended to overwrite legitimate configuration files)
  • ../../../../etc/passwd (used for directory traversal)

Without proper validation, such entries can exploit an archive extraction vulnerability to overwrite system files or leak sensitive data.

Risks associated with zip entry overwrite generally include:

1) Arbitrary file overwrite - This occurs when an attacker uses a crafted zip file to overwrite files within the application's extraction directory. For example, an attacker could replace configuration files or logs with malicious versions, causing the application to behave unpredictably or compromise its security.

2) Remote code execution - By overwriting executable files or scripts within the application's directory, an attacker can introduce and execute malicious code. If the application runs the compromised file, the attacker may gain control of the system, potentially accessing sensitive data or further infiltrating the network.

3) Data loss or corruption - Legitimate files, such as configuration files or user-generated data, can be replaced or corrupted. This can lead to application downtime, loss of important user data, or require costly recovery and remediation efforts to restore normal functionality.

Common Causes: How Does This Issue Usually Occur

Path manipulation vulnerabilities typically stem from several key issues:

1) Improper Input Validation Security: Failing to sanitize user-supplied file paths.
2) Inadequate Path Checks: Not verifying canonical paths of extracted files.
3) Outdated Libraries: Using insecure or outdated zip-handling libraries.
4) Low-Level APIs: Directly handling archives without secure abstractions.

Mitigation

Prevention Techniques

To mitigate risks from path manipulation and zip entry overwrite vulnerabilities, developers should use the following practices:

  1. Validate Input Paths: Strictly validate all user-supplied paths and filenames against a whitelist.
  2. Use Secure APIs: Utilize high-level archive-handling APIs designed to prevent directory traversal attacks.
  3. Canonical Path Checks: Ensure extracted files remain within designated directories using canonical path comparisons.
  4. Implement Secure Coding Practices: Regularly review and update code to align with best practices for security.

Mobb's Approach to Patching

Mobb recommends a multi-layered strategy to effectively address path manipulation and zip entry overwrite vulnerabilities. 

The first step is to ensure that user-supplied paths are strictly confined to a predefined directory structure through validation or sanitization. This measure prevents unauthorized access to sensitive directories. The second step involves using libraries or APIs that are designed for secure zip handling.

Fix Example #1: Parameter-based Path Manipulation (Java)

Here's an example of how to conduct secure file extraction in Java (for typical path manipulation):


    

import java.nio.file.Path;
import java.nio.file.Paths;

public class SecureFileExtractor {
    private static final String EXTRACTION_DIR = "/safe/extraction/path/";

    public void extractFile(String fileName) {
        Path filePath = Paths.get(EXTRACTION_DIR, fileName).normalize();
        if (!filePath.startsWith(EXTRACTION_DIR)) {
            throw new SecurityException("Invalid file path");
        }
        // Proceed with safe extraction
    }
}

 

Fix Example #2: Zip Entry Overwrite (JavaScript)

Here’s an example of how to use the adm-zip library safely by performing proper path checks:


    

const AdmZip = require('adm-zip');
const path = require('path');

function extractZip(zipPath, extractPath) {
    const zip = new AdmZip(zipPath);
    const zipEntries = zip.getEntries();

    zipEntries.forEach((entry) => {
        const entryPath = path.join(extractPath, entry.entryName);
        const normalizedPath = path.normalize(entryPath);

        if (!normalizedPath.startsWith(extractPath)) {
            throw new Error(`Malicious entry detected: ${entry.entryName}`);
        }

        // Extract the entry regardless of whether it's a file or directory
        zip.extractEntryTo(entry, extractPath, false, true);
    });
}

 

Mitigation Strategies

To mitigate the risks of path manipulation and zip entry overwrite vulnerabilities, consider the following approaches:

  1. Regular Audits and Penetration Tests: Periodic security assessments can help identify vulnerabilities before attackers exploit them.
  2. Write Restrictions During Extraction: Ensure that file writes during archive extraction are restricted to designated directories.
  3. Utilize a Code Vulnerability Remediation Tool: Tools like Mobb can automate the detection and remediation of these vulnerabilities, providing an additional layer of security.

Conclusion

Preventing vulnerabilities like directory traversal and zip entry overwrites requires both proactive and automated approaches. Tools like Mobb enable developers to identify and remediate these issues efficiently, ensuring secure code is shipped faster and with fewer risks. 

Organizations can secure their applications and defend against contemporary threats by utilizing automated remediation and focusing on secure coding practices.

By addressing directory traversal, zip entry overwrite, and input validation security issues with these strategies, developers can reduce the risk of remote code execution and data compromise.

Take Your Next Steps With Mobb.ai

Mobb provides an advanced automated solution to detect and resolve path manipulation and archive extraction vulnerabilities in your applications. By integrating Mobb.ai into your development workflow, you can:

  1. Identify risks like directory traversal and arbitrary file overwrite in real-time.
  2. Leverage automation to patch vulnerabilities efficiently.
  3. Enhance your security posture with industry-leading secure coding practices.

With Mobb.ai, you can start shipping secure code more quickly and protect your apps from today’s threats.

Daniel Kelley
Daniel Kelley is a reformed black hat computer hacker who collaborates with our team to research the latest threats and methodology being used by cybercriminals.