Path traversal

Path traversal through unvalidated filesystem paths

Description

Set a server-controlled base for uploads and downloads. Absolute paths, parent components, and links can otherwise direct file operations outside the intended directory.

Potential impact

Reads may expose configuration or source code. Writes and deletions can damage files the service depends on, including files it later executes.

Remediation

  • For filenames, use an allow-list or a strict naming rule. Reject empty names, absolute paths, and disallowed parent traversal.
  • For an existing file, join the path with path.resolve and resolve links with fs.realpathSync. Use path.relative from the real base to verify that the target is a descendant.
  • Restrict writes to the directory tree so files or links cannot change between the check and the open. Limit the process’s file permissions and keep real paths out of error responses.

Examples

Before

javascript
const express = require('express');
const fs = require('fs');
const path = require('path');
const app = express();

// Before: joining input alone permits traversal with ..
app.get('/view', (req, res) => {
  const name = req.query.f; // Example: ../../etc/passwd
  const unsafePath = path.join(__dirname, 'public', name);
  fs.createReadStream(unsafePath)
    .on('error', () => res.status(404).end('not found'))
    .pipe(res);
});

app.listen(3000);

After

javascript
const express = require('express');
const fs = require('fs');
const path = require('path');
const app = express();

// SAFE_ROOT must be server-managed and not modifiable by attackers
const SAFE_ROOT = fs.realpathSync(path.resolve(__dirname, 'public'));

function isInside(baseDir, targetPath) {
  const relative = path.relative(baseDir, targetPath);
  return (
    relative !== '' &&
    relative !== '..' &&
    !relative.startsWith('..' + path.sep) &&
    !path.isAbsolute(relative)
  );
}

app.get('/view', (req, res) => {
  const name = req.query.f;
  if (typeof name !== 'string') {
    return res.status(400).send('parameter f is required');
  }

  // Normalize the path and resolve symbolic links
  const candidate = path.resolve(SAFE_ROOT, name);
  let resolved;
  try {
    resolved = fs.realpathSync(candidate);
  } catch {
    return res.status(404).end('not found');
  }

  // Check the boundary: allow only descendants of SAFE_ROOT
  if (!isInside(SAFE_ROOT, resolved)) {
    return res.status(403).end('forbidden');
  }

  // Use only the validated path
  const stream = fs.createReadStream(resolved);
  stream.on('error', () => res.status(404).end('not found'));
  stream.pipe(res);
});

app.listen(3000);

isInside rejects SAFE_ROOT itself, paths outside the root, and absolute results from a different drive. The handler opens the checked resolved path. An absolute input inside the root also passes. If the endpoint accepts only relative paths, reject an absolute name before resolving it.

References