CWE-25: Path Traversal: '/../filedir'
Learn about CWE-25 (Path Traversal: '/../filedir'), its security impact, exploitation methods, and prevention guidelines.
What is Path Traversal: '/../filedir'?
• Overview: Path Traversal (CWE-25) occurs when an application uses user input to create a file path without properly sanitizing it, allowing attackers to manipulate the path to access files outside the intended directory.
• Exploitation Methods:
- Attackers can input special character sequences like "/../" to navigate out of the restricted directory.
- Common attack patterns include inserting "../" sequences in file path inputs to gain access to critical system files.
• Security Impact:
- Direct consequences include unauthorized access to sensitive files, such as configuration files, passwords, or system files.
- Potential cascading effects involve compromise of system integrity and data breaches.
- Business impact can include loss of customer trust, legal repercussions, and financial losses.
• Prevention Guidelines:
- Specific code-level fixes include normalizing paths to remove directory traversal sequences and validating input against a whitelist of allowed file paths.
- Security best practices involve restricting file access to specific directories using chroot or similar mechanisms and avoiding user input for file paths whenever possible.
- Recommended tools and frameworks include using libraries or functions specifically designed for secure file path handling and incorporating static analysis tools to detect path traversal vulnerabilities during development.
Technical Details
Likelihood of Exploit: Not specified
Affected Languages: Not Language-Specific
Affected Technologies: Not specified
Vulnerable Code Example
import os
from flask import Flask, request, send_file
app = Flask(__name__)
@app.route('/download', methods=['GET'])
def download_file():
# Vulnerable code: User input is directly used to construct the file path
filename = request.args.get('filename') # User input is not validated
file_path = os.path.join('/var/www/files', filename) # Potential path traversal
return send_file(file_path) # Sends the file back to the user
Explanation:
- Line 12: The
filename
is taken directly from the user input without any validation or sanitization. - Line 13: The input is used to construct a file path. An attacker can exploit this by providing a path like
../../../../etc/passwd
to access sensitive files outside the intended directory. - Line 14: The file at the constructed path is sent back to the user, potentially exposing sensitive data.
How to fix Path Traversal: '/../filedir'?
To mitigate the Path Traversal vulnerability:
- Validate and Sanitize User Input: Ensure the input is a valid filename without directory traversal characters.
- Use Safe Libraries/Functions: Utilize libraries or functions that abstract away file path construction and enforce directory restrictions.
- Restrict File Access: Limit file access to a predefined directory using canonicalization checks.
- Error Handling: Gracefully handle errors and do not expose sensitive information in error messages.
Fixed Code Example
import os
from flask import Flask, request, send_file, abort
app = Flask(__name__)
def is_safe_path(base_path, user_input_path, follow_symlinks=True):
# Canonicalize paths and ensure the resulting path is within the base directory
if follow_symlinks:
abs_base = os.path.realpath(base_path)
abs_user_input = os.path.realpath(os.path.join(base_path, user_input_path))
else:
abs_base = os.path.abspath(base_path)
abs_user_input = os.path.abspath(os.path.join(base_path, user_input_path))
return abs_user_input.startswith(abs_base)
@app.route('/download', methods=['GET'])
def download_file():
filename = request.args.get('filename')
# Validate the filename to prevent path traversal
if not filename or '..' in filename or filename.startswith('/'):
abort(400, "Invalid filename.") # Return error for invalid filenames
file_path = os.path.join('/var/www/files', filename)
# Check if the file path is safe
if not is_safe_path('/var/www/files', filename):
abort(403, "Access denied.") # Deny access if path traversal is detected
return send_file(file_path)
Explanation:
- Lines 12-20: Introduces a helper function
is_safe_path
to check if the resolved path is within the allowed directory. It usesos.path.realpath
to handle symbolic links securely. - Lines 22-24: Validates filename input to ensure it does not contain any directory traversal characters or start with a slash.
- Lines 26-29: Uses
is_safe_path
to check for safe file paths and aborts with a 403 status if the path is potentially harmful. - Line 31: If checks pass, the file is safely sent to the user.
This improved example ensures that the code is secure against path traversal attacks by validating the user input and checking the resolved file path against the intended directory.