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
app.get("/files/:name", (req, res) => {
const filePath = `./uploads/${req.params.name}`;
res.sendFile(filePath, { root: process.cwd() });
});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.