Path Traversal in Mongodb
How Path Traversal Manifests in Mongodb
Path traversal vulnerabilities in MongoDB contexts often occur when user input is used to construct file paths for GridFS operations, database exports, or when accessing configuration files. Unlike traditional web servers where path traversal might expose filesystem files, MongoDB path traversal can lead to unauthorized database operations, data exfiltration, or manipulation of system files.
A common MongoDB-specific scenario involves GridFS operations where filenames are constructed from user input without proper validation. Consider an application that allows users to upload files with custom names:
const { filename } = req.body;
const bucket = new mongodb.GridFSBucket(db);
const uploadStream = bucket.openUploadStream(filename);
// ... upload logic
An attacker could supply a filename like ../../../etc/passwd or ../../admin/collections/users.json, potentially writing data to unexpected locations or accessing sensitive files if the MongoDB process has filesystem access to those paths.
Another MongoDB-specific path traversal pattern occurs in database export operations. Applications might use user-controlled parameters to determine which collections to export:
const collectionName = req.query.collection;
const exportPath = `/exports/${collectionName}.json`;
// Export logic
If collectionName contains path traversal sequences like users/../../sensitive, the export might write to unintended directories or expose data from unauthorized collections.
Authentication bypass through path traversal is also possible in MongoDB configurations. Some applications use file paths to locate authentication credentials or configuration files. An attacker might manipulate these paths to load configuration from unexpected locations:
const authPath = `${process.cwd()}/config/${req.query.authFile}`;
const authConfig = require(authPath);
// Use authConfig for MongoDB connection
Here, a path traversal payload could load authentication credentials from arbitrary locations, potentially bypassing intended security controls.
Mongodb-Specific Detection
Detecting path traversal in MongoDB contexts requires specialized scanning that understands MongoDB's unique attack surface. Traditional web application scanners often miss MongoDB-specific patterns like GridFS operations, database export functions, and configuration file access.
middleBrick's MongoDB-specific scanning includes several key detection capabilities:
GridFS Filename Validation Testing - The scanner tests for improper validation of filenames in GridFS operations by attempting to upload files with path traversal payloads and checking if the operation succeeds or writes to unexpected locations.
Database Export Path Analysis - middleBrick examines export functionality for path traversal vulnerabilities by testing collection name parameters with traversal sequences and analyzing the resulting file paths.
Configuration File Access Testing - The scanner probes for path traversal in configuration file loading by attempting to access files outside intended directories and checking for successful reads or writes.
Authentication Bypass Detection - middleBrick tests for path traversal in authentication mechanisms by attempting to load credentials from unexpected locations and analyzing the application's response.
Here's how middleBrick's CLI can be used to scan a MongoDB-exposed API endpoint:
npx middlebrick scan https://api.example.com/mongodb
The scanner runs 12 parallel security checks including property authorization and input validation, specifically looking for MongoDB path traversal patterns. The output includes a security risk score (A-F) with severity levels and remediation guidance.
For automated detection in CI/CD pipelines, middleBrick's GitHub Action can be configured to fail builds when path traversal vulnerabilities are detected:
name: API Security Scan
on: [push, pull_request]
jobs:
security-scan:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v2
- name: Run middleBrick Scan
run: |
npx middlebrick scan https://staging.example.com/api --fail-on-severity=medium
This ensures path traversal vulnerabilities are caught before deployment to production environments.
Mongodb-Specific Remediation
Remediating path traversal vulnerabilities in MongoDB applications requires a defense-in-depth approach using MongoDB's built-in security features and proper input validation.
Input Validation and Sanitization - The most fundamental defense is validating and sanitizing user input before using it in file paths or database operations. For MongoDB applications, this means:
function validateFilename(filename) {
// Allow only alphanumeric, hyphens, underscores, and periods
const sanitized = filename.replace(/[^a-zA-Z0-9-_.]/g, '_');
// Prevent path traversal
if (sanitized.includes('..')) {
throw new Error('Invalid filename');
}
// Limit length and enforce naming conventions
if (sanitized.length > 255) {
throw new Error('Filename too long');
}
return sanitized;
}
// Usage in GridFS
const bucket = new mongodb.GridFSBucket(db);
const uploadStream = bucket.openUploadStream(validateFilename(req.body.filename));
Path Canonicalization - Always resolve paths to their canonical form before use:
const path = require('path');
function safePath(baseDir, userPath) {
const resolved = path.resolve(baseDir, userPath);
// Ensure the resolved path starts with the base directory
if (!resolved.startsWith(baseDir)) {
throw new Error('Path traversal detected');
}
return resolved;
}
// Example usage for export operations
const collectionName = req.query.collection;
const exportBase = '/safe/exports';
const exportPath = safePath(exportBase, `${collectionName}.json`);
MongoDB-Specific Security Features - Leverage MongoDB's built-in security features:
// Enable MongoDB's built-in access controls
const MongoClient = require('mongodb').MongoClient;
async function connectWithAuth() {
const client = new MongoClient(uri, {
auth: {
user: process.env.MONGO_USER,
password: process.env.MONGO_PASSWORD
}
});
await client.connect();
return client;
}
// Use MongoDB's role-based access control
async function setupRBAC() {
const adminDb = client.db('admin');
// Create application-specific user with limited permissions
await adminDb.addUser({
user: 'app_user',
pwd: 'strong_password',
roles: [
{ role: 'readWrite', db: 'application_data' },
{ role: 'read', db: 'audit_logs' }
]
});
}
Network-Level Controls - Implement network controls to limit MongoDB's filesystem access:
// Docker example - restrict filesystem access
{
"services": {
"mongodb": {
"image": "mongo:latest",
"volumes": [
"./data/db:/data/db:rw"
],
"cap_drop": ["ALL"],
"read_only": true
}
}
}
Monitoring and Logging - Implement comprehensive logging to detect path traversal attempts:
const fs = require('fs');
const path = require('path');
function secureWriteFile(filePath, data) {
const resolvedPath = path.resolve(filePath);
// Log suspicious patterns
if (resolvedPath.includes('..') || resolvedPath.includes('~')) {
console.warn(`Suspicious file path detected: ${resolvedPath}`);
// Additional monitoring/incident response
}
fs.writeFileSync(resolvedPath, data);
}
Related CWEs: inputValidation
| CWE ID | Name | Severity |
|---|---|---|
| CWE-20 | Improper Input Validation | HIGH |
| CWE-22 | Path Traversal | HIGH |
| CWE-74 | Injection | CRITICAL |
| CWE-77 | Command Injection | CRITICAL |
| CWE-78 | OS Command Injection | CRITICAL |
| CWE-79 | Cross-site Scripting (XSS) | HIGH |
| CWE-89 | SQL Injection | CRITICAL |
| CWE-90 | LDAP Injection | HIGH |
| CWE-91 | XML Injection | HIGH |
| CWE-94 | Code Injection | CRITICAL |