const winston = require('winston');
// Configure security logger
const securityLogger = winston.createLogger({
level: 'info',
format: winston.format.json(),
defaultMeta: { service: 'websocket-security' },
transports: [
new winston.transports.File({
filename: 'security-error.log',
level: 'error',
}),
new winston.transports.File({
filename: 'security-combined.log',
}),
],
});
// Security event types
const SecurityEvents = {
AUTH_FAILED: 'auth_failed',
RATE_LIMIT: 'rate_limit_exceeded',
INVALID_ORIGIN: 'invalid_origin',
MALICIOUS_PAYLOAD: 'malicious_payload',
DDOS_DETECTED: 'ddos_detected',
INJECTION_ATTEMPT: 'injection_attempt',
};
// Log security events
function logSecurityEvent(event, details) {
securityLogger.warn({
event,
timestamp: new Date().toISOString(),
...details,
});
// Alert on critical events
if (isCriticalEvent(event)) {
sendSecurityAlert(event, details);
}
}
// Monitor for suspicious patterns
class SecurityMonitor {
constructor() {
this.events = [];
this.patterns = new Map();
}
recordEvent(ip, event) {
const timestamp = Date.now();
this.events.push({ ip, event, timestamp });
// Track patterns per IP
if (!this.patterns.has(ip)) {
this.patterns.set(ip, []);
}
this.patterns.get(ip).push({ event, timestamp });
// Check for attack patterns
this.detectAttackPatterns(ip);
// Clean old events (keep last hour)
this.events = this.events.filter((e) => timestamp - e.timestamp < 3600000);
}
detectAttackPatterns(ip) {
const ipEvents = this.patterns.get(ip);
const recentEvents = ipEvents.filter(
(e) => Date.now() - e.timestamp < 60000 // Last minute
);
// Detect brute force
const authFailures = recentEvents.filter(
(e) => e.event === SecurityEvents.AUTH_FAILED
).length;
if (authFailures > 5) {
logSecurityEvent(SecurityEvents.DDOS_DETECTED, {
ip,
pattern: 'brute_force',
authFailures,
});
// Block IP
blacklistIP(ip);
}
// Detect injection attempts
const injectionAttempts = recentEvents.filter(
(e) => e.event === SecurityEvents.INJECTION_ATTEMPT
).length;
if (injectionAttempts > 3) {
logSecurityEvent(SecurityEvents.MALICIOUS_PAYLOAD, {
ip,
pattern: 'injection_attack',
attempts: injectionAttempts,
});
blacklistIP(ip);
}
}
}