Path Traversal Prevention
Preventing attackers from accessing files and directories outside the intended scope by manipulating file path inputs.
Description
Path traversal (also known as directory traversal) is a vulnerability that allows attackers to access files on the server outside the intended directory by manipulating file path inputs. By injecting sequences like ../ (dot-dot-slash), encoded variants (%2e%2e%2f), or null bytes, attackers can navigate up the directory tree to read sensitive files such as /etc/passwd, application configuration files, source code, or private keys. In severe cases, path traversal can lead to arbitrary file write and remote code execution.
The vulnerability typically arises when applications use user-supplied input to construct file paths for operations like file serving, file uploads, template rendering, or log file access. Common vulnerable patterns include direct use of request parameters in fs.readFile(), path.join() with unvalidated user input, and dynamic require()/import() with user-controlled paths. Even path.join() can be exploited because it resolves ../ sequences rather than rejecting them.
Prevention requires multiple strategies: validating that the resolved path stays within the expected base directory (using path.resolve() and checking it starts with the allowed prefix), using an allowlist of permitted files or paths rather than accepting arbitrary input, stripping or rejecting path separator characters and ../ sequences from input, running the application with minimal filesystem permissions, and using chroot jails or containerization to limit the filesystem scope accessible to the process.
Prompt Snippet
Prevent path traversal by resolving the full canonical path and validating it stays within the allowed base directory: const resolved = path.resolve(baseDir, userInput); if (!resolved.startsWith(baseDir + path.sep)) throw new ForbiddenError(). Never pass raw user input to fs.readFile(), fs.createReadStream(), or path.join() without validation. Reject inputs containing ../, ..\\ , null bytes (\x00), or URL-encoded variants. Use an allowlist of permitted filenames when possible. In Docker, mount upload/asset directories as read-only volumes and run the application as a non-root user. Configure static file serving middleware (express.static) with a strict root and dotfiles: 'deny'.
Tags
Related Terms
File Upload Security
Security measures to prevent malicious file uploads from compromising the server, other users, or the application.
Input Validation & Sanitization
The practice of verifying and cleaning all user-supplied data before processing to prevent injection attacks and data corruption.
Principle of Least Privilege
A security principle requiring that every user, process, and system component be granted only the minimum permissions necessary to perform its function.