Directory Traversal

Difficulty: Beginner

Question

What is a directory (path) traversal attack, and how do you safely serve files based on user input?

Answer

Directory traversal, also called path traversal or dot-dot-slash, is an attack where user input that is used to build a file path includes ../ sequences to climb out of the intended folder and read or write files elsewhere on the server, such as ../../etc/passwd or the app's .env file. It happens when code joins user input onto a base directory without checking where the final path ends up. The fix is to avoid using raw filenames from users, or to resolve the full path and verify it is still inside the allowed directory.

How the attack works

A typical vulnerable endpoint:

  • GET /download?file=report.pdf reads /var/app/uploads/report.pdf.
  • The attacker sends file=../../../etc/passwd.
  • The server builds /var/app/uploads/../../../etc/passwd, which the OS resolves to /etc/passwd, and sends it back.

High-value targets include .env files with database passwords and API keys, SSH keys, cloud credential files like ~/.aws/credentials, application source code, and on Windows paths like ..\..\Windows\win.ini. If the endpoint writes files (uploads, extracts), traversal can overwrite config or drop a web shell, turning it into remote code execution.

Why simple filters fail

Removing ../ from the string is not enough:

  • URL encoding: %2e%2e%2f, and double encoding %252e%252e%252f if the app decodes twice.
  • Nested sequences: ....// becomes ../ after a single replace.
  • Windows backslashes: ..\ and mixed ..\/.
  • Absolute paths: file=/etc/passwd. Node's path.join keeps it relative, but path.resolve and Python's os.path.join discard the base directory when given an absolute path.
  • Old null-byte tricks like ../../etc/passwd%00.pdf against outdated runtimes.

Real incidents show how easy this is to get wrong: Apache HTTP Server 2.4.49 shipped a path normalization bug (CVE-2021-41773) that allowed traversal with encoded dots.

Safe patterns

  1. Do not use user filenames at all: store files under generated IDs (uploads/7f3c...) and map IDs to files in the database, after checking that the user owns the file.
  2. Canonicalize and check containment: resolve the full path (path.resolve, realpath, Path.normalize() / toRealPath()) and confirm it starts with the base directory plus a path separator. Resolving symlinks with realpath closes symlink escapes.
  3. Use framework helpers: Express res.sendFile(name, { root }) and express.static reject traversal; Flask send_from_directory uses safe_join.
  4. Allowlist filenames: for example ^[a-zA-Z0-9_-]+\.pdf$.
  5. Least privilege: run the app as a user that cannot read sensitive system files, and keep secrets out of the web root.

Zip Slip: traversal through archives

When extracting a ZIP or TAR, entry names like ../../app/server.js can write outside the extraction folder. Apply the same resolve-and-check to every entry before writing, or use a library that does it for you.

Safe file serving check. Resolve first, then check containment; never filter the raw string.
  1. Receive filename from user: For example ../../etc/passwd.
  2. Resolve against base directory: path.resolve gives the absolute final path.
  3. Resolve symlinks with realpath: Stops links that point outside the folder.
  4. Check it starts with base + separator: Reject with 400 or 404 if not.
  5. Check the user may access it: Then stream the file.

Code examples

Vulnerable and safe file download in Node.js

import path from 'node:path';
import fs from 'node:fs/promises';

const BASE = path.resolve('/var/app/uploads');

// VULNERABLE: ?file=../../../etc/passwd escapes BASE
app.get('/bad', (req, res) => {
  res.sendFile(path.join(BASE, req.query.file));
});

// SAFE: resolve, follow symlinks, then check containment
app.get('/download', async (req, res) => {
  try {
    const target = await fs.realpath(path.resolve(BASE, String(req.query.file)));
    if (!target.startsWith(BASE + path.sep)) return res.sendStatus(404);
    res.sendFile(target);
  } catch {
    res.sendStatus(404);
  }
});

// Simpler: let Express enforce the root
app.get('/files/:name', (req, res) => {
  res.sendFile(req.params.name, { root: BASE }, (err) => err && res.sendStatus(404));
});

Checking the resolved path against BASE plus a separator defeats encoded and nested ../ tricks and also blocks lookalike siblings such as /var/app/uploads-old.

Probing for traversal during a security test

# Plain, encoded and double-encoded variants
curl -s 'https://staging.example.in/download?file=../../../../etc/passwd'
curl -s 'https://staging.example.in/download?file=..%2f..%2f..%2f..%2fetc%2fpasswd'
curl -s 'https://staging.example.in/download?file=..%252f..%252f..%252fetc%252fpasswd'
curl -s 'https://staging.example.in/download?file=....//....//....//etc/passwd'
# A safe endpoint returns 400/404 for all of these

Run tests like these only against systems you own or are authorized to test. Each variant targets a different flawed filter.

Key points

  • Traversal uses ../ in user-controlled paths to escape the intended directory
  • String filtering is bypassed by encoding, nesting, backslashes and absolute paths
  • Resolve the full path (and symlinks), then check it starts with base + separator
  • Prefer storing files under generated IDs instead of user-supplied names
  • Zip Slip applies the same bug to archive extraction

Common follow-up questions

  • Why is checking startsWith(BASE) without a trailing separator still unsafe?
  • What is Zip Slip and how would you prevent it?
  • How can a symlink bypass a path containment check?
  • How does path traversal on a write endpoint lead to remote code execution?

Interview tips

  • Give the resolve-then-check pattern rather than 'strip ../'; interviewers are listening for that
  • Mention the best design is not using user filenames at all
  • Bring up Zip Slip or write-side traversal to show you see beyond reading /etc/passwd

Concepts covered

Path Traversal, Dot-Dot-Slash, Path Canonicalization, Zip Slip, File Access Control

More Web Security (OWASP, JWT, XSS, CSRF) questions