Server directory traversal
Description
A directory traversal vulnerability allows attackers to access files and directories outside the web server's intended root directory by manipulating file path references. This occurs when an application accepts user-supplied input to construct file paths without proper validation, enabling attackers to use special character sequences (such as '../') to navigate the file system hierarchy and access restricted resources.
Remediation
Implement the following security controls to prevent directory traversal attacks:
1. Input Validation: Use an allowlist approach to validate all user-supplied input that references file paths. Only permit alphanumeric characters and explicitly required characters.
2. Path Canonicalization: Normalize and resolve all file paths to their canonical form, then verify they remain within the intended directory:
// Example in Java
String basePath = "/var/www/files";
File baseDir = new File(basePath).getCanonicalFile();
File requestedFile = new File(baseDir, userInput).getCanonicalFile();
if (!requestedFile.getPath().startsWith(baseDir.getPath())) {
throw new SecurityException("Invalid file path");
}3. Filter Metacharacters: Remove or reject directory traversal sequences including '../', '..\', URL-encoded variants (%2e%2e%2f), and null bytes.
4. Use Safe APIs: Utilize framework-provided functions that handle file access securely and prevent path traversal by design.
5. Principle of Least Privilege: Configure the web server to run with minimal file system permissions, restricting access to only necessary directories.