In order to securely handle files and prevent file-based attacks, developers should follow these key practices:
1. Validate File Types
Ensure only allowed file types are uploaded (e.g., images, PDFs). Check MIME type and extension.
const allowedTypes = ['image/jpeg', 'image/png'];
if (!allowedTypes.includes(file.mimetype)) {
throw new Error('Invalid file type');
}
2. Limit File Size
Set file size limits to avoid excessive uploads. This protects against Denial-of-Service (DoS) attacks.
const maxSize = 5 * 1024 * 1024; // 5 MB
if (file.size > maxSize) {
throw new Error('File size exceeds limit');
}
3. Sanitize File Paths
Avoid directory traversal attacks by sanitizing file paths and using safe storage locations.
const path = require('path');
const safePath = path.resolve(__dirname, 'uploads', path.basename(file.name));
4. Set Correct Permissions
Store files with minimal read/write permissions and ensure they are not executable.
chmod 644 file.txt # Read/write for owner, read-only for others
5. Store Files in Separate Directory
- Use a directory specifically for file uploads, outside the web root, to prevent direct access.
- Example: Store files in /var/uploads and serve via a controlled access endpoint.