CWE-641: Improper Restriction of Names for Files and Other Resources
Learn about CWE-641 (Improper Restriction of Names for Files and Other Resources), its security impact, exploitation methods, and prevention guidelines.
What is Improper Restriction of Names for Files and Other Resources?
• Overview: Improper Restriction of Names for Files and Other Resources (CWE-641) occurs when a software application constructs file or resource names based on input from another component without adequately validating or sanitizing the input, leading to potential security vulnerabilities.
• Exploitation Methods:
- Attackers can exploit this vulnerability by injecting malicious characters or scripts into input fields that influence the file/resource names.
- Common attack patterns include cross-site scripting (XSS) through file names, directory traversal, or exploiting parsers with specially crafted names.
• Security Impact:
- Direct consequences of successful exploitation might include unauthorized execution of scripts, disclosure of sensitive information, or control over server file operations.
- Potential cascading effects include the execution of arbitrary code, resulting in compromised system integrity and data breaches.
- Business impact can be severe, leading to loss of customer trust, legal liabilities, and financial losses due to data theft or service disruption.
• Prevention Guidelines:
- Specific code-level fixes include validating and sanitizing all inputs used for naming resources, ensuring they conform to expected formats and removing or encoding special characters.
- Security best practices involve implementing strict input validation and encoding practices, and regularly reviewing and testing code for vulnerabilities.
- Recommended tools and frameworks include static and dynamic analysis tools to detect and mitigate input validation issues, and web application firewalls to filter out malicious payloads.
Technical Details
Likelihood of Exploit:
Affected Languages: Not Language-Specific
Affected Technologies: Not specified
Vulnerable Code Example
import os
def read_file(filename):
# Vulnerable: Using user input directly to construct file path
# This allows for traversal attacks if the filename includes "../"
filepath = os.path.join('/secure/data', filename)
with open(filepath, 'r') as file:
return file.read()
# Example usage
user_input = '../etc/passwd'
print(read_file(user_input))
In this vulnerable code example, an attacker could exploit the lack of input validation to perform a directory traversal attack. By manipulating the filename
parameter, such as using ../
, an attacker can access files outside the intended directory. This can lead to unauthorized access to sensitive files on the server.
How to fix Improper Restriction of Names for Files and Other Resources?
To fix this vulnerability, we must ensure that user input is sanitized and validated before being used to construct file paths. One effective method is to compare the final resolved file path against an expected directory to ensure it doesn't escape the designated directory. We can also use a whitelist of allowed filenames to ensure only expected files are accessed, preventing directory traversal attacks.
Fixed Code Example
import os
def read_file_safe(filename):
# Define a whitelist of allowed filenames
allowed_filenames = {'file1.txt', 'file2.txt'}
# Validate filename against whitelist
if filename not in allowed_filenames:
raise ValueError("Invalid filename")
# Construct the full file path safely
secure_base_path = '/secure/data'
filepath = os.path.join(secure_base_path, filename)
filepath = os.path.abspath(filepath)
# Ensure that the final path is within the secure base path
if not filepath.startswith(os.path.abspath(secure_base_path) + os.sep):
raise ValueError("Access denied")
with open(filepath, 'r') as file:
return file.read()
# Example usage
try:
user_input = 'file1.txt'
print(read_file_safe(user_input))
except ValueError as e:
print(e)
In the fixed code example, we introduced a whitelist to control which files can be accessed. We also ensure that the resolved file path starts with the secure base path plus the system-specific path separator, effectively preventing directory traversal attacks. This approach ensures that even if an attacker tries to manipulate the filename, they cannot escape the designated directory or access unauthorized files. Additionally, using os.sep
ensures compatibility across different operating systems.