Path Traversal in APIs
What is Path Traversal?
APIs are particularly vulnerable to path traversal because they often handle file operations programmatically without the same protections browsers provide. Attackers can exploit this vulnerability in several ways:
Configuration File Exposure: Many APIs read configuration files based on environment or tenant parameters. An attacker could traverse to /etc/passwd, /etc/shadow, or application configuration files containing database credentials.
Application Source Code Access: In development environments, path traversal could expose source code files, API keys, or other sensitive information that shouldn't be publicly accessible.
Database File Access: SQLite or other database files stored on the filesystem could be downloaded, potentially exposing all application data.
Log File Access: System logs, application logs, or audit trails might contain sensitive information like user credentials, API keys, or personal data.
SSRF Amplification: Path traversal combined with Server-Side Request Forgery can allow attackers to read internal files and then make internal requests using the retrieved data.
Consider this vulnerable API endpoint:
app.get('/api/export', async (req, res) => {
const { format } = req.query;
const filePath = `/var/exports/${format}.json`;
// Vulnerable: no validation of format parameter
const data = await fs.readFile(filePath, 'utf8');
res.json(JSON.parse(data));
});An attacker could request /api/export?format=../../../../../etc/passwd to read system files.
How to Detect Path Traversal
Detecting path traversal requires both static code analysis and dynamic testing. Here's what to look for:
Static Code Analysis: Search for filesystem operations where user input is concatenated into paths without validation. Look for patterns like:
const filePath = basePath + userInput;
const filePath = `${basePath}/${userInput}`;
fs.readFile(userInput, 'utf8');
fs.readFileSync(path.join(basePath, userInput));Dynamic Testing: Test endpoints that accept file paths or parameters that might be used in file operations. Common test payloads include:
../
..\
....//
....\\
..%2F..
%2E%2E%2F
%252E%252E%252F
%2F%2E%2E%2F
file://
/proc/self/environ
/etc/passwd
/etc/shadow
C:\\Windows\win.inimiddleBrick's Detection Approach: middleBrick scans APIs for path traversal vulnerabilities by testing file path parameters with various traversal payloads and monitoring for unexpected file access. The scanner attempts to access known sensitive files and checks if the API returns content that shouldn't be accessible. It also analyzes the OpenAPI specification to identify endpoints that might be vulnerable based on their path parameters and HTTP methods.
middleBrick's black-box scanning approach tests the actual runtime behavior without requiring source code access, making it effective for detecting path traversal in production APIs.
Prevention & Remediation
Preventing path traversal requires a defense-in-depth approach:
Input Validation: Validate file paths against a whitelist of allowed values. Never accept arbitrary file paths from users.
const allowedFormats = ['csv', 'json', 'xml'];
const format = req.query.format;
if (!allowedFormats.includes(format)) {
return res.status(400).json({ error: 'Invalid format' });
}
const filePath = path.join('/var/exports', `${format}.json`);
Canonical Path Resolution: Use path.resolve() or path.normalize() and verify the resulting path is within the intended directory.
const safeReadFile = async (basePath, relativePath) => {
const fullPath = path.resolve(basePath, relativePath);
if (!fullPath.startsWith(basePath)) {
throw new Error('Path traversal attempt detected');
}
return await fs.readFile(fullPath, 'utf8');
};
Deny by Default: Use a deny list of characters and patterns that are never allowed in file paths.
const isSafePath = (path) => {
const denyList = ['../', '..\\', '%2E%2E%2F'];
return !denyList.some(pattern => path.includes(pattern));
};
Least Privilege: Run your application with the minimum necessary filesystem permissions. Use chroot jails or containers to limit filesystem access.
Security Headers: Implement Content Security Policy and other headers to prevent certain types of attacks, though these are less relevant for pure API endpoints.
Real-World Impact
Path traversal vulnerabilities have caused significant security incidents. In 2021, a path traversal flaw in Apache Log4j (CVE-2021-44228, though primarily a different vulnerability) highlighted how file system access issues can have widespread impact. More directly, path traversal has been exploited in numerous API breaches.
A notable example is the 2019 Capital One breach, where an SSRF vulnerability combined with path traversal allowed attackers to access credentials and sensitive data from the cloud environment. While the primary vulnerability was SSRF, path traversal techniques were used to navigate the filesystem.
In 2020, a path traversal vulnerability in a popular Node.js framework allowed attackers to read arbitrary files from the server, exposing API keys and database credentials stored in configuration files. The vulnerability affected thousands of applications using the framework.
middleBrick's scanning helps prevent these incidents by identifying path traversal vulnerabilities before they can be exploited. With middleBrick's 10-second self-service scanning, you can find and fix these vulnerabilities before attackers do, without the weeks-long wait for traditional penetration testing.
The financial impact of path traversal can be severe: data breaches, regulatory fines (GDPR, CCPA), reputational damage, and the cost of incident response. middleBrick's continuous monitoring in the Pro plan ensures your APIs remain protected even as code changes over time.