highCode Injection

Path Traversal (Directory Traversal)

What Is This Vulnerability?

Path traversal attacks exploit insufficient validation of file paths to access files and directories outside the intended scope. By injecting sequences like ../ into file path parameters, attackers can read sensitive files such as /etc/passwd, application source code, or configuration files containing database credentials.

Why It Happens

Applications that serve user-uploaded files or allow users to specify filenames often construct file paths by joining a base directory with user input. Without normalizing and validating the resulting path, dot-dot-slash sequences escape the intended directory and traverse the filesystem.

Example Code

Vulnerableroutes/files.ts
app.get("/files/:name", (req, res) => {
  const filePath = `./uploads/${req.params.name}`;
  res.sendFile(filePath, { root: process.cwd() });
});
Fixedroutes/files.ts
import path from "path";

const UPLOADS_DIR = path.resolve("./uploads");

app.get("/files/:name", (req, res) => {
  const filePath = path.resolve(UPLOADS_DIR, req.params.name);

  if (!filePath.startsWith(UPLOADS_DIR)) {
    return res.status(400).send("Invalid file path");
  }

  res.sendFile(filePath);
});

How Hackers Exploit It

Attackers send requests like GET /files/../../etc/passwd or use URL-encoded variants like %2e%2e%2f to bypass basic filters. If the application runs with sufficient privileges, they can read any file on the system including .env files, private keys, and database credentials. In some cases, path traversal can also be used to overwrite critical files.

How to Fix It

Always resolve the full path using path.resolve() and verify the result starts with the intended base directory. Strip or reject any input containing .. segments. Use a chroot or container filesystem to limit the blast radius. Set file permissions so the application user can only access the files it needs.

Frequently Asked Questions

What files do attackers typically target with path traversal?
Common targets include /etc/passwd for user enumeration, .env files for database and API credentials, SSH private keys, application source code, and configuration files. On Windows, attackers target files like C:\Windows\win.ini or web.config.
Does URL encoding bypass path traversal protections?
It can. Attackers use URL encoding (%2e%2e%2f for ../), double encoding, or null bytes to evade simple string-matching filters. This is why you should normalize and resolve paths rather than trying to filter out specific character sequences.
Can path traversal lead to remote code execution?
Yes. If the attacker can write files (via a file upload vulnerability combined with path traversal), they may overwrite application code, cron jobs, or SSH authorized_keys files to achieve code execution on the server.

Related Security Topics

Check Your Code for This Vulnerability

Run a free scan to check if your site is affected by path traversal (directory traversal).