Arbitrary File Creation
Description
This vulnerability occurs when an application fails to properly validate user-supplied input used in file creation operations. Attackers can exploit this weakness by injecting directory traversal sequences (such as '../') combined with specific filenames to create files in arbitrary locations on the server's filesystem. This bypasses intended access controls and allows unauthorized file system manipulation through the application.
Remediation
Implement the following security controls to prevent arbitrary file creation:
1. Input Validation and Sanitization:
• Reject any input containing directory traversal sequences (../, .\, etc.)
• Use an allowlist approach to accept only known-safe characters
• Validate that filenames match expected patterns
// Example: Validate and sanitize filename input
function sanitizeFilename(userInput) {
// Remove path traversal sequences
const sanitized = userInput.replace(/\.\.\/|\.\.\\/g, '');
// Allow only alphanumeric, dash, underscore, and dot
if (!/^[a-zA-Z0-9_\-\.]+$/.test(sanitized)) {
throw new Error('Invalid filename');
}
return sanitized;
}2. Use Secure File Operations:
• Utilize built-in functions that resolve canonical paths and prevent traversal
• Restrict file creation to specific, predefined directories
• Verify the resolved path stays within allowed boundaries
// Example: Restrict file creation to safe directory
const path = require('path');
const SAFE_DIR = '/var/app/uploads';
function createSafeFile(filename) {
const sanitized = sanitizeFilename(filename);
const fullPath = path.join(SAFE_DIR, sanitized);
// Verify the resolved path is within safe directory
const resolvedPath = path.resolve(fullPath);
if (!resolvedPath.startsWith(path.resolve(SAFE_DIR))) {
throw new Error('Path traversal detected');
}
return resolvedPath;
}3. Apply Principle of Least Privilege:
• Run the application with minimal filesystem permissions
• Use operating system controls to restrict write access to only necessary directories