fix(security): implement file upload security enhancements
- Add path traversal protection with secureStatic middleware - Implement proper MIME type validation for all file uploads - Add content-based file validation (magic numbers) - Create comprehensive fileSecurityUtils for secure file operations - Update adminPhotos.js with enhanced validation - Update adminSettings.js for secure logo/favicon uploads - Addresses file upload vulnerabilities from security scan 🤖 Generated with [Claude Code](https://claude.ai/code) Co-Authored-By: Claude <noreply@anthropic.com>
This commit is contained in:
@@ -0,0 +1,46 @@
|
||||
const path = require('path');
|
||||
const express = require('express');
|
||||
const { safePathJoin, isPathSafe } = require('../utils/fileSecurityUtils');
|
||||
|
||||
/**
|
||||
* Create a secure static file serving middleware that prevents path traversal attacks
|
||||
* @param {string} basePath - The base directory to serve files from
|
||||
* @param {Object} options - Express static options
|
||||
* @returns {Function} - Express middleware
|
||||
*/
|
||||
function secureStatic(basePath, options = {}) {
|
||||
const normalizedBase = path.resolve(basePath);
|
||||
|
||||
return (req, res, next) => {
|
||||
// Get the requested file path
|
||||
const requestedPath = req.path;
|
||||
|
||||
// Validate the path doesn't contain dangerous patterns
|
||||
if (!isPathSafe(requestedPath)) {
|
||||
console.warn(`Potential path traversal attempt blocked: ${requestedPath}`);
|
||||
return res.status(403).json({ error: 'Access denied' });
|
||||
}
|
||||
|
||||
try {
|
||||
// Validate the full path is within the base directory
|
||||
const fullPath = safePathJoin(normalizedBase, requestedPath);
|
||||
|
||||
// If validation passes, use express.static
|
||||
const staticMiddleware = express.static(normalizedBase, {
|
||||
...options,
|
||||
// Disable directory listing for security
|
||||
index: false,
|
||||
// Don't allow dotfiles
|
||||
dotfiles: 'deny'
|
||||
});
|
||||
|
||||
return staticMiddleware(req, res, next);
|
||||
} catch (error) {
|
||||
// Path traversal detected
|
||||
console.error(`Path traversal blocked: ${requestedPath}`, error.message);
|
||||
return res.status(403).json({ error: 'Access denied' });
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
module.exports = secureStatic;
|
||||
Reference in New Issue
Block a user