Spaces:
Paused
Paused
File size: 11,476 Bytes
c904036 1db35f1 c904036 1db35f1 c904036 | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 | /**
* Comprehensive Security Middleware
* Handles various security concerns and provides protection against common attacks
*/
const { logger } = require('./errorHandler');
// Redis client will be passed from the main app
let redisClient = null;
// Function to set Redis client
function setRedisClient(client) {
redisClient = client;
}
/**
* Brute force protection middleware
*/
function bruteForceProtection(maxAttempts = 5, windowMs = 15 * 60 * 1000) {
return async (req, res, next) => {
try {
// Bypass for privileged roles
if (req.user && (req.user.role === 'admin' || req.user.role === 'verifier' || req.user.role === 'host' || req.user.roles?.includes('verifier') || req.user.roles?.includes('platformAdmin'))) {
return next();
}
const identifier = req.ip || req.connection.remoteAddress;
const endpoint = req.originalUrl;
const key = `bruteforce:${identifier}:${endpoint}`;
const attempts = await redisClient.get(key);
const attemptCount = attempts ? parseInt(attempts) : 0;
if (attemptCount >= maxAttempts) {
logger.warn(`Brute force attempt blocked for ${identifier} on ${endpoint}`);
return res.status(429).json({
error: 'Too many failed attempts. Please try again later.',
retryAfter: Math.ceil(windowMs / 1000)
});
}
// Increment attempt counter
if (redisClient && redisClient.isOpen) {
await redisClient.setEx(key, Math.ceil(windowMs / 1000), (attemptCount + 1).toString());
}
next();
} catch (error) {
logger.error('Brute force protection error:', error);
next(); // Continue on error
}
};
}
/**
* Request size validation middleware
*/
function requestSizeValidation(maxSize = '1mb') {
return (req, res, next) => {
const contentLength = parseInt(req.headers['content-length'] || '0');
const maxSizeBytes = parseSize(maxSize);
if (contentLength > maxSizeBytes) {
logger.warn(`Request size exceeded: ${contentLength} bytes from ${req.ip}`);
return res.status(413).json({
error: 'Request entity too large',
maxSize
});
}
next();
};
}
/**
* Parse size string to bytes
*/
function parseSize(size) {
const units = { 'b': 1, 'kb': 1024, 'mb': 1024 * 1024, 'gb': 1024 * 1024 * 1024 };
const match = size.toLowerCase().match(/^(\d+(?:\.\d+)?)\s*(b|kb|mb|gb)$/);
if (match) {
const value = parseFloat(match[1]);
const unit = match[2];
return value * units[unit];
}
return parseInt(size) || 1024 * 1024; // Default to 1MB
}
/**
* SQL injection prevention middleware
*/
function sqlInjectionProtection(req, res, next) {
const dangerousPatterns = [
/(\b(union|select|insert|update|delete|drop|create|alter|exec|execute)\b)/i,
/(--|\/\*|\*\/|xp_|sp_|@@|char\(|nchar\(|varchar\(|nvarchar\(|cast\(|convert\(|declare\s+@)/i,
/(\b(and|or)\s+\d+\s*=\s*\d+)/i,
/(\b(and|or)\s+['"]\w+['"]\s*=\s*['"]\w+['"])/i
];
const checkValue = (value) => {
if (typeof value === 'string') {
for (const pattern of dangerousPatterns) {
if (pattern.test(value)) {
logger.warn(`Potential SQL injection attempt from ${req.ip}: ${value}`);
return false;
}
}
}
return true;
};
const checkObject = (obj) => {
for (const [, value] of Object.entries(obj)) {
if (typeof value === 'object' && value !== null) {
if (!checkObject(value)) return false;
} else if (!checkValue(value)) {
return false;
}
}
return true;
};
// Check body, query, and params
if (req.body && !checkObject(req.body)) {
return res.status(400).json({ error: 'Invalid input detected' });
}
if (req.query && !checkObject(req.query)) {
return res.status(400).json({ error: 'Invalid query parameters' });
}
if (req.params && !checkObject(req.params)) {
return res.status(400).json({ error: 'Invalid path parameters' });
}
next();
}
/**
* NoSQL injection prevention middleware
*/
function noSqlInjectionProtection(req, res, next) {
const dangerousPatterns = [
/\$where/i,
/\$ne/i,
/\$gt/i,
/\$lt/i,
/\$gte/i,
/\$lte/i,
/\$in/i,
/\$nin/i,
/\$regex/i,
/\$options/i,
/\$text/i,
/\$search/i
];
const checkValue = (value) => {
if (typeof value === 'string') {
for (const pattern of dangerousPatterns) {
if (pattern.test(value)) {
logger.warn(`Potential NoSQL injection attempt from ${req.ip}: ${value}`);
return false;
}
}
}
return true;
};
const checkObject = (obj) => {
for (const [, value] of Object.entries(obj)) {
if (typeof value === 'object' && value !== null) {
if (!checkObject(value)) return false;
} else if (!checkValue(value)) {
return false;
}
}
return true;
};
// Check body, query, and params
if (req.body && !checkObject(req.body)) {
return res.status(400).json({ error: 'Invalid input detected' });
}
if (req.query && !checkObject(req.query)) {
return res.status(400).json({ error: 'Invalid query parameters' });
}
if (req.params && !checkObject(req.params)) {
return res.status(400).json({ error: 'Invalid path parameters' });
}
next();
}
/**
* XSS protection middleware
*/
function xssProtection(req, res, next) {
const xssPatterns = [
/<script\b[^<]*(?:(?!<\/script>)<[^<]*)*<\/script>/gi,
/javascript:/gi,
/on\w+\s*=/gi,
/<iframe\b[^<]*(?:(?!<\/iframe>)<[^<]*)*<\/iframe>/gi,
/<object\b[^<]*(?:(?!<\/object>)<[^<]*)*<\/object>/gi,
/<embed\b[^<]*(?:(?!<\/embed>)<[^<]*)*<\/embed>/gi
];
const checkValue = (value) => {
if (typeof value === 'string') {
for (const pattern of xssPatterns) {
if (pattern.test(value)) {
logger.warn(`Potential XSS attempt from ${req.ip}: ${value}`);
return false;
}
}
}
return true;
};
const checkObject = (obj) => {
for (const [, value] of Object.entries(obj)) {
if (typeof value === 'object' && value !== null) {
if (!checkObject(value)) return false;
} else if (!checkValue(value)) {
return false;
}
}
return true;
};
// Check body, query, and params
if (req.body && !checkObject(req.body)) {
return res.status(400).json({ error: 'Invalid input detected' });
}
if (req.query && !checkObject(req.query)) {
return res.status(400).json({ error: 'Invalid query parameters' });
}
if (req.params && !checkObject(req.params)) {
return res.status(400).json({ error: 'Invalid path parameters' });
}
next();
}
/**
* Security logging middleware
*/
function securityLogging(req, res, next) {
const securityEvents = [];
// Check for suspicious patterns
const suspiciousPatterns = [
{ pattern: /\.\.\//, name: 'Path traversal attempt' },
{ pattern: /<script/i, name: 'XSS attempt' },
{ pattern: /union\s+select/i, name: 'SQL injection attempt' },
{ pattern: /\$where/i, name: 'NoSQL injection attempt' },
{ pattern: /eval\s*\(/i, name: 'Code injection attempt' },
{ pattern: /document\.cookie/i, name: 'Cookie theft attempt' }
];
const checkValue = (value, source) => {
if (typeof value === 'string') {
for (const { pattern, name } of suspiciousPatterns) {
if (pattern.test(value)) {
securityEvents.push({
type: name,
source,
value: value.substring(0, 100), // Truncate for logging
ip: req.ip,
userAgent: req.get('User-Agent'),
timestamp: new Date().toISOString()
});
}
}
}
};
const checkObject = (obj, source) => {
for (const [key, value] of Object.entries(obj)) {
if (typeof value === 'object' && value !== null) {
checkObject(value, `${source}.${key}`);
} else {
checkValue(value, `${source}.${key}`);
}
}
};
// Check all input sources
if (req.body) checkObject(req.body, 'body');
if (req.query) checkObject(req.query, 'query');
if (req.params) checkObject(req.params, 'params');
// Log security events
if (securityEvents.length > 0) {
logger.warn('Security events detected:', {
ip: req.ip,
userAgent: req.get('User-Agent'),
url: req.originalUrl,
method: req.method,
events: securityEvents
});
}
next();
}
/**
* Rate limiting for security endpoints
*/
function securityRateLimit(windowMs = 15 * 60 * 1000, max = 5) {
return async (req, res, next) => {
try {
// Bypass for privileged roles
if (req.user && (req.user.role === 'admin' || req.user.role === 'verifier' || req.user.role === 'host' || req.user.roles?.includes('verifier') || req.user.roles?.includes('platformAdmin'))) {
return next();
}
const identifier = req.ip || req.connection.remoteAddress;
const endpoint = req.originalUrl;
const key = `security:${identifier}:${endpoint}`;
const attempts = await redisClient.get(key);
const attemptCount = attempts ? parseInt(attempts) : 0;
if (attemptCount >= max) {
logger.warn(`Security rate limit exceeded for ${identifier} on ${endpoint}`);
return res.status(429).json({
error: 'Too many security-related requests. Please try again later.',
retryAfter: Math.ceil(windowMs / 1000)
});
}
// Increment attempt counter
if (redisClient && redisClient.isOpen) {
await redisClient.setEx(key, Math.ceil(windowMs / 1000), (attemptCount + 1).toString());
}
next();
} catch (error) {
logger.error('Security rate limiting error:', error);
next(); // Continue on error
}
};
}
/**
* Comprehensive security middleware stack
*/
function securityMiddleware(options = {}) {
const {
enableBruteForceProtection = true,
enableRequestSizeValidation = true,
enableSqlInjectionProtection = true,
enableNoSqlInjectionProtection = true,
enableXssProtection = true,
enableSecurityLogging = true,
enableSecurityRateLimit = true,
maxRequestSize = '1mb',
bruteForceMaxAttempts = 5,
bruteForceWindowMs = 15 * 60 * 1000,
securityRateLimitWindowMs = 15 * 60 * 1000,
securityRateLimitMax = 5
} = options;
const middleware = [];
if (enableRequestSizeValidation) {
middleware.push(requestSizeValidation(maxRequestSize));
}
if (enableSqlInjectionProtection) {
middleware.push(sqlInjectionProtection);
}
if (enableNoSqlInjectionProtection) {
middleware.push(noSqlInjectionProtection);
}
if (enableXssProtection) {
middleware.push(xssProtection);
}
if (enableSecurityLogging) {
middleware.push(securityLogging);
}
if (enableBruteForceProtection) {
middleware.push(bruteForceProtection(bruteForceMaxAttempts, bruteForceWindowMs));
}
if (enableSecurityRateLimit) {
middleware.push(securityRateLimit(securityRateLimitWindowMs, securityRateLimitMax));
}
return middleware;
}
module.exports = {
bruteForceProtection,
requestSizeValidation,
sqlInjectionProtection,
noSqlInjectionProtection,
xssProtection,
securityLogging,
securityRateLimit,
securityMiddleware,
setRedisClient,
parseSize
};
|