What is Relative Path Traversal?
Relative Path Traversal (CWE-23) is a type of vulnerability that occurs when external input is used to construct a pathname within a restricted directory, but does not properly neutralize sequences such as “..” which can resolve to an outside location.
As defined by the MITRE Corporation under CWE-23, and classified by the OWASP Foundation under Injection…
Quick Summary
Relative Path Traversal (CWE-23) is a vulnerability that arises when external input is used to construct a pathname within a restricted directory. This can lead to attackers creating or modifying files outside of their intended locations, reading unexpected files, or causing denial-of-service conditions.
This article covers the definition, examples, and prevention techniques for Relative Path Traversal.
Relative Path Traversal Overview
What
Relative Path Traversal (CWE-23) is a vulnerability that occurs when external input is used to construct a pathname within a restricted directory. This can lead to attackers creating or modifying files outside of their intended locations, reading unexpected files, or causing denial-of-service conditions.
Why it matters
If exploited, attackers may be able to create or overwrite critical files that are used to execute code, modify files and directories, read unexpected files, and cause denial-of-service conditions. This vulnerability impacts the confidentiality, integrity, availability, and execution of applications.
Where it occurs
Relative Path Traversal can occur in any application that uses external input to construct a pathname within a restricted directory.
Who is affected
Any user or system administrator who relies on an application with Relative Path Traversal vulnerabilities could be affected by this issue. This includes developers, security teams, and end-users of the application.
How Relative Path Traversal Works
Root Cause
Relative Path Traversal occurs when external input is used to construct a pathname within a restricted directory. The vulnerability arises because sequences such as “..” can resolve to an outside location, allowing attackers to create or modify files outside their intended locations.
Attack Flow
- An attacker provides malicious input that includes sequences such as “..”.
- The application uses this input to construct a pathname within the restricted directory.
- The sequence of “..” resolves to an outside location, allowing the attacker to access files or directories outside the intended scope.
Vulnerable Code
# Example vulnerable Python code using relative paths
import os
def read_file(path):
with open(os.path.join('/restricted_dir', path), 'r') as file:
return file.read()
read_file('../outside_dir/file.txt')
Secure Code
# Example secure Python code using absolute paths and input validation
import os
def read_file(path):
restricted_path = os.path.abspath('/restricted_dir/' + path)
if not os.access(restricted_path, os.R_OK):
raise ValueError("File is not readable.")
with open(restricted_path, 'r') as file:
return file.read()
Business Impact of Relative Path Traversal
- Integrity: The attacker may be able to modify critical files that are used for security mechanisms.
- Confidentiality: The attacker may be able to read unexpected files and expose sensitive data.
- Availability: The attacker may be able to overwrite or delete critical files, causing the application to fail.
Relative Path Traversal Attack Scenario
- An attacker discovers a vulnerable application that uses relative paths within restricted directories.
- The attacker provides malicious input containing sequences such as “..” to construct a pathname outside of the intended directory.
- The application executes the code using this input and allows the sequence “..” to resolve, resulting in unauthorized access to files or directories outside the intended scope.
How to Detect Relative Path Traversal
Manual Testing
Manually test your application for Relative Path Traversal vulnerabilities by providing malicious input that includes sequences such as “..” within restricted directory paths. Look for errors related to file operations and unexpected behavior.
Automated Scanners (SAST / DAST)
Use automated SAST or DAST scanners like SonarQube, Fortify, or OWASP ZAP to detect Relative Path Traversal vulnerabilities in your application code. These tools can identify patterns that suggest the use of relative paths within restricted directories.
PenScan Detection
PenScan’s scanner engines, including ZAP, Nuclei, Wapiti, Nikto, SSLyze, Dalfox, and Nmap, can detect Relative Path Traversal vulnerabilities by analyzing your application code. These tools are designed to identify potential security issues in real-time.
How to Fix Relative Path Traversal
Input Validation
Assume all input is malicious and use an “accept known good” input validation strategy. This involves using a list of acceptable inputs that strictly conform to specifications, rejecting any input that does not strictly conform, or transforming it into something that does.
Canonicalization
Inputs should be decoded and canonicalized to the application’s current internal representation before being validated. Use built-in path canonicalization functions like realpath() in C, getCanonicalPath() in Java, GetFullPath() in ASP.NET, realpath() or abs_path() in Perl, or realpath() in PHP.
Firewalls
Use an application firewall that can detect attacks against this weakness. It can be beneficial in cases where the code cannot be fixed (because it is controlled by a third party), as an emergency prevention measure while more comprehensive software assurance measures are applied, or to provide defense in depth [REF-1481].
Framework-Specific Fixes for Relative Path Traversal
Java
// Example secure Java code using absolute paths and input validation
import java.nio.file.*;
public class SecureFileReader {
public static void readFile(String path) throws IOException {
File file = new File("/restricted_dir/" + path);
if (!file.exists() || !Files.isReadable(file.toPath())) {
throw new FileNotFoundException("File not found or not readable.");
}
Path restrictedPath = Paths.get("/restricted_dir/" + path);
Files.readAllLines(restrictedPath);
}
}
Node.js
// Example secure Node.js code using absolute paths and input validation
const fs = require('fs');
const path = require('path');
function readFile(path) {
const restrictedPath = path.resolve('/restricted_dir', path);
if (!fs.existsSync(restrictedPath) || !fs.accessSync(restrictedPath, fs.R_OK)) {
throw new Error("File not found or not readable.");
}
return fs.promises.readFile(restrictedPath, 'utf-8');
}
try {
const content = await readFile(path);
console.log(content);
} catch (err) {
console.error(err.message);
}
Python/Django
# Example secure Django view using absolute paths and input validation
from django.http import HttpResponse
def read_file(request, path):
restricted_path = os.path.abspath('/restricted_dir/' + path)
if not os.access(restricted_path, os.R_OK):
return HttpResponse("File is not readable.", status=403)
with open(restricted_path, 'r') as file:
content = file.read()
return HttpResponse(content)
PHP
// Example secure PHP code using absolute paths and input validation
<?php
function read_file($path) {
$restrictedPath = realpath('/restricted_dir/' . $path);
if (!file_exists($restrictedPath) || !is_readable($restrictedPath)) {
throw new Exception("File not found or not readable.");
}
return file_get_contents($restrictedPath);
}
?>
How to Ask AI to Check Your Code for Relative Path Traversal
You can ask AI to review your code by pasting it into a prompt like ‘Review the following [language] code block for potential CWE-23 Relative Path Traversal vulnerabilities and rewrite it using [primary fix technique]: [paste code here].’
Relative Path Traversal Best Practices Checklist
- Assume all input is malicious.
- Use an “accept known good” input validation strategy, i.e., use a list of acceptable inputs that strictly conform to specifications.
- Reject any input that does not strictly conform to specifications or transform it into something that does.
- Always validate inputs thoroughly.
- Decompose and canonicalize the input before validating it.
- Use built-in path canonicalization functions like
realpath()in C,getCanonicalPath()in Java, etc.
Relative Path Traversal FAQ
How can I detect Relative Path Traversal vulnerabilities?
You can detect Relative Path Traversal vulnerabilities through manual testing, automated scanning tools like SAST/DAST, or using PenScan’s scanner engines such as ZAP, Nuclei, Wapiti, Nikto, SSLyze, Dalfox, and Nmap.
How do I fix Relative Path Traversal?
You can fix Relative Path Traversal by input validation, canonicalizing paths, and using firewalls to detect attacks. For example, assume all input is malicious, use an allowlist of acceptable inputs, decode and canonicalize the input before validating it.
How do I ask AI to check for Relative Path Traversal vulnerabilities?
You can ask AI to review your code by pasting it into a prompt like ‘Review the following [language] code block for potential CWE-23 Relative Path Traversal vulnerabilities and rewrite it using [primary fix technique]: [paste code here].’
Vulnerabilities Related to Relative Path Traversal
| CWE | Name |
|---|---|
| CWE-184 | Insecure Direct Object Reference (IDOR) |
| CWE-601 | Improper Restriction of Exports (CWE-601) |
References
- MITRE CWE - 23
- OWASP Top 10: Injection
- CAPEC: CAPEC-139, CAPEC-76