HIGH path traversalexpressmongodb

Path Traversal in Express with Mongodb

Path Traversal in Express with Mongodb — how this specific combination creates or exposes the vulnerability

Path Traversal in an Express service that uses Mongodb typically occurs when user-controlled path segments are used to build filesystem paths or to construct dynamic query selectors without proper validation or sanitization. An attacker can supply sequences like ../../../etc/passwd or encoded variants to escape a intended directory scope. Even when data is stored in Mongodb, the application may expose these traversal risks through file operations (e.g., reading uploaded assets, logs, or backups) or through unsafe construction of query filters that reference document paths.

Consider an Express endpoint that builds a filesystem path from a user-supplied parameter:

const path = require('path');
const fs = require('fs');
app.get('/files/:filename', (req, res) => {
  const filePath = path.join('/var/uploads', req.params.filename);
  fs.readFile(filePath, (err, data) => {
    if (err) return res.status(404).send('Not found');
    res.send(data);
  });
});

An attacker can request /files/../../../etc/passwd and read arbitrary files if the application does not normalize and validate the input. If the file content or metadata is later stored in Mongodb (for example, as a file manifest), traversal attempts may be logged or reflected in responses, increasing exposure.

Another scenario involves using user input to dynamically query Mongodb with dot notation that can be abused for traversal-like behavior. For example, an endpoint that accepts a field path to retrieve a nested document might concatenate user input into the query:

app.get('/doc/:field', async (req, res) => {
  const fieldPath = req.params.field; // e.g., 'user.profile.email'
  const doc = await db.collection('items').findOne({ [fieldPath]: { $exists: true } });
  res.json(doc);
});

If the application does not validate fieldPath, an attacker can supply values like __proto__ or crafted nested keys that affect object prototype resolution or bypass intended access control, leading to unauthorized data exposure. This is not filesystem traversal but a form of data traversal that mirrors the same class of vulnerability.

Additionally, if the Express app exposes endpoints that construct Mongodb connection strings or database/collection names from user input (e.g., multi-tenant identifiers), traversal-style injection can lead to unintended database or collection selection. Always treat user input as untrusted and avoid building filesystem paths or query selectors by string concatenation.

Mongodb-Specific Remediation in Express — concrete code fixes

To mitigate Path Traversal risks when Express interacts with Mongodb, enforce strict input validation, avoid dynamic path construction, and use safe patterns for accessing nested fields. Below are concrete, safe implementations.

1. Safe file serving with path normalization and allowlist

Resolve paths with path.resolve and validate against an allowlist of permitted files or a strict pattern. Do not rely solely on path.join without canonicalization.

const path = require('path');
const fs = require('fs');
app.get('/files/:filename', (req, res) => {
  const base = path.resolve('/var/uploads');
  const unsafe = path.resolve(base, req.params.filename);
  if (!unsafe.startsWith(base)) {
    return res.status(403).send('Forbidden');
  }
  fs.readFile(unsafe, (err, data) => {
    if (err) return res.status(404).send('Not found');
    res.send(data);
  });
});

2. Validate field paths for Mongodb queries

Do not directly interpolate user input into query selectors. Use a schema-aware library or an allowlist to ensure only intended fields are accessible. For nested field access, prefer explicit projection or a controlled mapping.

const validFields = new Set(['email', 'profile.name', 'profile.age']);
app.get('/doc/:field', async (req, res) => {
  const field = req.params.field;
  if (!validFields.has(field)) {
    return res.status(400).send('Invalid field');
  }
  // Use aggregation or explicit projection for nested fields
  const doc = await db.collection('items').findOne(
    { _id: ObjectId('...') },
    { projection: { [field]: 1, _id: 0 } }
  );
  res.json(doc || null);
});

3. Avoid dynamic database/collection names from user input

If multi-tenancy requires selecting a database or collection, map tenant identifiers to known values rather than concatenating them.

const tenantMap = {
  'tenantA': 'db_abc',
  'tenantB': 'db_xyz'
};
app.get('/tenant/:id/data', async (req, res) => {
  const dbName = tenantMap[req.params.id];
  if (!dbName) return res.status(400).send('Invalid tenant');
  const client = await MongoClient.connect(uri);
  const db = client.db(dbName);
  const data = await db.collection('records').find({}).toArray();
  client.close();
  res.json(data);
});

These practices reduce the attack surface by ensuring that user input cannot escape intended boundaries when interacting with the filesystem or Mongodb. Combine these measures with runtime security scanning to detect regressions early.

Related CWEs: inputValidation

CWE IDNameSeverity
CWE-20Improper Input Validation HIGH
CWE-22Path Traversal HIGH
CWE-74Injection CRITICAL
CWE-77Command Injection CRITICAL
CWE-78OS Command Injection CRITICAL
CWE-79Cross-site Scripting (XSS) HIGH
CWE-89SQL Injection CRITICAL
CWE-90LDAP Injection HIGH
CWE-91XML Injection HIGH
CWE-94Code Injection CRITICAL

Frequently Asked Questions

Can Path Traversal in Express with Mongodb lead to direct database injection?
Direct NoSQL injection is different from filesystem path traversal, but unsafe construction of query selectors using user input can lead to unauthorized data access. Validate and restrict field paths to prevent traversal-like data exposure.
Does middleBrick detect Path Traversal risks in Express APIs?
middleBrick scans unauthenticated attack surfaces and includes checks such as Input Validation and Property Authorization. It reports findings with severity, guidance, and mappings to frameworks like OWASP API Top 10 to help you triage and remediate.