VibeSecurity

Web attacks

What is Path traversal?

Path traversal is an attack where someone puts sequences such as ../ into a file name your server uses, so it reads or writes files outside the folder it was meant to stay in. It is also called directory traversal.

Some routes take a file name from the request, for example to download an invoice, show an uploaded image or load a template. If the code joins that name onto a folder path and opens the result, a name such as ../../.env walks up out of the folder and points at a file the app never meant to share.

On a server, that can expose environment files, source code, configuration and system files. Where the route writes files, such as an upload handler that trusts the original file name, the attacker may be able to overwrite application files instead. Encoded versions of the dots and slashes are used to slip past simple text filters, so searching for ../ and removing it is not a reliable fix.

The safest approach is not to use user input as a path at all. Store files under generated ids and look the real location up in your database. If a name must be accepted, resolve the full path first and confirm it still sits inside the intended folder before opening it, and run the app with a user account that can reach only what it needs.

Resolve the path, then check it stayed inside the folder
import path from "node:path";

const base = path.resolve("uploads");
const target = path.resolve(base, requestedName);

if (!target.startsWith(base + path.sep)) {
  throw new Error("Invalid file name");
}

Related terms

Sources

  1. 1.OWASP: Path Traversal
  2. 2.MITRE CWE-22: Path Traversal