Path Traversal
Example 1: Java
Vulnerable Code:
javaCopy codeString fileName = request.getParameter("fileName");
File file = new File("/var/www/html/" + fileName);Reason for vulnerability: User input can contain path traversal sequences to access restricted files.
Fixed Code:
javaCopy codeString fileName = request.getParameter("fileName");
File file = new File("/var/www/html/" + Paths.get(fileName).normalize().toString());
if (!file.getCanonicalPath().startsWith("/var/www/html/")) {
throw new SecurityException("Invalid file path");
}Reason for fix: Normalize the file path and check it is within the allowed directory.
Example 2: Python
Vulnerable Code:
pythonCopy code@app.route('/read_file')
def read_file():
file_name = request.args.get('file_name')
with open('/var/www/html/' + file_name, 'r') as f:
return f.read()Reason for vulnerability: User input can contain path traversal sequences to access restricted files.
Fixed Code:
Reason for fix: Normalize the file path and check it is within the allowed directory.
Python Example
Vulnerable Code:
Reason for Vulnerability:
This code allows an attacker to access files outside the intended directory using path traversal sequences.
Fixed Code:
Reason for Fix:
The fixed code validates the filename, uses os.path.join(), and checks if the resulting path is within the allowed directory.
Java Example
Vulnerable Code:
Reason for Vulnerability:
This code allows an attacker to access files outside the intended directory using path traversal sequences.
Fixed Code:
Reason for Fix:
The fixed code normalizes paths and checks if the resulting path is within the allowed directory to prevent path traversal.
C# Example
Vulnerable Code:
Reason for Vulnerability:
This code allows an attacker to access files outside the intended directory using path traversal sequences.
Fixed Code:
Last updated