Directory traversal
Description
A directory traversal vulnerability allows attackers to access files and directories outside the intended web root directory by manipulating file path references. Attackers exploit this weakness by using special character sequences (such as '../') in user-supplied input to navigate the server's file system. This vulnerability occurs when applications fail to properly validate and sanitize file path parameters before using them to access resources.
Remediation
Implement the following security controls to prevent directory traversal attacks:
1. Input Validation: Use an allowlist approach to validate all user-supplied file paths against a predefined set of permitted values. Reject any input containing directory traversal sequences such as '../', '..\', or encoded variations.
2. Path Canonicalization: Resolve file paths to their canonical (absolute) form and verify they remain within the intended directory. Example:
// Java example
String basePath = "/var/www/files";
File requestedFile = new File(basePath, userInput);
String canonicalPath = requestedFile.getCanonicalPath();
if (!canonicalPath.startsWith(basePath)) {
throw new SecurityException("Invalid file path");
}3. Use Safe APIs: Utilize framework-provided functions that handle file access securely, avoiding direct concatenation of user input with file paths.
4. Principle of Least Privilege: Configure the web server and application to run with minimal file system permissions, restricting access to only necessary directories.