Overview
Path Traversal (also known as Directory Traversal) allows an attacker to read arbitrary files on the server. The vulnerability occurs when an application uses user-supplied input to construct a path to a file or directory without proper validation. By using../ sequences, an attacker can navigate outside of the intended directory to access sensitive files anywhere on the server’s file system.
Business Impact
This vulnerability can lead to the complete disclosure of application source code, configuration files containing credentials, business data, and sensitive operating system files. This information leak is often a precursor to a full system compromise.Reference Details
CWE ID: CWE-22
OWASP Top 10 (2021): A01:2021 - Broken Access Control
Severity: High
Framework-Specific Analysis and Remediation
No framework can automatically protect against this logical vulnerability. The developer is always responsible for sanitizing and validating user input before using it in any file system operation. The core principle is to ensure the final, resolved (canonical) path of the requested file is located within the expected, secure base directory.- Python
- Java
- .NET(C#)
- PHP
- Node.js
- Ruby
Framework Context
Django does not provide a specific file-serving view for arbitrary files, forcing developers to write their own. This is where vulnerabilities are often introduced. The key is to use Python’sos.path module to safely construct and validate paths.Vulnerable Scenario 1: A Document Download View
An endpoint allows users to download invoices by providing a filename.Vulnerable Scenario 2: Dynamic Template Loading
A feature loads a custom user theme template based on a cookie value.Mitigation and Best Practices
Never trust the filename. Useos.path.basename to strip any directory information. Then, construct the full path and use os.path.abspath to resolve it to its canonical form. Finally, check that this resolved path starts with the secure base directory’s path.Secure Code Example
Testing Strategy
Write integration tests that request files using path traversal payloads (../, ..%2f, etc.). The tests should assert that the application returns a 404 Not Found or 403 Forbidden response, not the content of the targeted sensitive file.
