File tampering
Description
This vulnerability occurs when an application writes user-controlled input directly to files on the server without proper validation or sanitization. The scanner detected that data submitted by users is being written to the filesystem, which could allow attackers to modify file contents or create malicious files. This alert requires manual verification as the severity depends on which files are affected and whether the input is sanitized. The risk is particularly high if user input can be written to executable files (such as PHP, JSP, or ASP files) or configuration files within the application directory.
Remediation
Implement the following security controls to prevent file tampering attacks:
1. Avoid Writing User Input to Files: Redesign the application to avoid writing user-controlled data directly to files whenever possible. Consider using databases or secure storage mechanisms instead.
2. Implement Strict Input Validation:
• Validate all user input against a whitelist of allowed characters and patterns
• Reject any input containing path traversal sequences (../, .\, etc.)
• Limit input length to expected values
// Example: Validate filename input
if (!preg_match('/^[a-zA-Z0-9_-]+\.txt$/', $filename)) {
throw new Exception('Invalid filename');
}3. Sanitize File Content: If user input must be written to files, encode or escape special characters based on the file type:
// Example: Sanitize content before writing $sanitized_content = htmlspecialchars($user_input, ENT_QUOTES, 'UTF-8'); file_put_contents($safe_path, $sanitized_content);
4. Use Secure File Paths:
• Never allow users to control file paths or filenames directly
• Store files outside the web root directory when possible
• Use a whitelist approach with predefined file locations
// Example: Use safe file path construction
$safe_directory = '/var/app/data/';
$safe_filename = basename($user_filename); // Remove path components
$full_path = $safe_directory . $safe_filename;
// Verify the resolved path is still within safe directory
if (strpos(realpath($full_path), realpath($safe_directory)) !== 0) {
throw new Exception('Invalid file path');
}5. Set Appropriate File Permissions: Ensure written files have restrictive permissions and cannot be executed by the web server
6. Implement File Type Restrictions: Never write user input to executable file types (.php, .jsp, .aspx, .py, etc.)