Input Path Not Canonicalized
ID |
java.input_path_not_canonicalized |
Severity |
low |
Resource |
Path Resolution |
Language |
Java |
Tags |
CWE:180, NIST.SP.800-53 |
Rationale
Canonicalization refers to the process of converting a file path into a standard, straightforward format. This is important to prevent path traversal vulnerabilities, where an attacker might exploit improper path handling to access restricted files. Without canonicalization, paths like ../../../../etc/passwd
might allow access to sensitive system files outside the intended directory.
In Java, neglecting to canonicalize file paths can lead to serious vulnerabilities, especially when user input is involved in file operations. Consider the following vulnerable code:
import java.io.File;
import java.io.IOException;
public class FileHandler {
public void readFile(String userInput) throws IOException {
File file = new File(userInput);
if (file.exists()) {
// Potentially dangerous: Path not canonicalized
// Business logic using the file
}
}
}
In this example, the file path provided by userInput
is used directly without canonicalization, making it susceptible to manipulation through path traversal techniques.
Remediation
To remediate potential vulnerabilities related to non-canonicalized paths, follow these best practices:
-
Canonicalize Paths: Always convert file paths to their canonical form using
File.getCanonicalPath()
before any file operations. -
Restricted Directories: Implement checks to ensure canonical paths stay within designated, secure directories.
-
Access Controls: Apply proper access controls to prevent unauthorized reading and writing outside intended locations.
-
Input Validation: Validate and sanitize user inputs before using them for file path construction. Reject any input that does not conform to expected patterns.
By following these recommendations, you can protect your applications from path traversal and related vulnerabilities, ensuring more robust and secure file handling.