18. Security Logging & Threat Monitoring
You cannot respond to security incidents you don't know about. Attackers often spend weeks inside systems before being detected. Security logging and monitoring are essential for detecting breaches, investigating incidents, and maintaining compliance.
Detection is Prevention
You cannot prevent every attack. But with proper monitoring, you can detect attacks early, limit damage, and learn from incidents. Most breaches are discovered by third parties, not internal monitoring — this should not be you.
What Events Should You Log?
Not every event is equally important. Logging everything creates noise and makes it hard to find real threats. Focus on security-relevant events.
MUST LOG (High Priority): - Failed login attempts (with IP, timestamp, username) - Successful logins (especially from new devices/locations) - Password changes - 2FA enable/disable events - Role and permission changes - Sensitive data access (PII, payment info) - API key creation and revocation - Account lockout events - Admin actions (user deletion, system configuration) DO NOT LOG (Ever): - Passwords (in any form) - Full credit card numbers - Session tokens or API keys - Personal data unnecessarily Consider Logging (Medium Priority): - All authentication attempts - API requests to sensitive endpoints - Configuration changes - User profile updates
What is Structured Logging?
Traditional log messages like User 123 logged in are hard to search and analyze. Structured logging uses JSON format, making logs machine-readable and searchable.
BAD (Unstructured):
[2024-01-15 10:30:45] User 123 logged in from 192.168.1.1
GOOD (Structured JSON):
{
"timestamp": "2024-01-15T10:30:45Z",
"eventType": "LOGIN_SUCCESS",
"userId": 123,
"ipAddress": "192.168.1.1",
"userAgent": "Mozilla/5.0...",
"requestId": "req_abc123"
}
Building a Security Logger
Let's create a reusable security logging function that captures all important context automatically.
const winston = require('winston'); // Configure Winston for JSON logging const securityLogger = winston.createLogger({ level: 'info', format: winston.format.json(), transports: [ new winston.transports.File({ filename: 'logs/security.log' }), new winston.transports.Console() ] }); function logSecurityEvent(eventType, userId, details, req) { const logEntry = { timestamp: new Date().toISOString(), eventType: eventType, userId: userId, ipAddress: req.ip || req.headers['x-forwarded-for'], userAgent: req.headers['user-agent'], requestId: req.id, url: req.url, method: req.method, details: details }; securityLogger.info(JSON.stringify(logEntry)); // For critical events, also send to alerting system if (eventType === 'ROLE_CHANGED' || eventType === 'PASSWORD_CHANGED') { sendToAlertingSystem(logEntry); } } // Usage example app.post('/api/login', async (req, res) => { const user = await authenticateUser(req.body.email, req.body.password); if (!user) { logSecurityEvent('LOGIN_FAILED', req.body.email, { reason: 'Invalid credentials', email: req.body.email }, req); return res.status(401).json({ error: 'Invalid credentials' }); } logSecurityEvent('LOGIN_SUCCESS', user.id, { method: 'password', deviceInfo: req.headers['user-agent'] }, req); // Continue with login... });
Detecting Brute Force Attacks
Brute force attacks are easy to detect: many failed logins from the same IP in a short time. We can use Redis to track failure counts and trigger alerts.
const Redis = require('ioredis'); const redis = new Redis(); async function checkForBruteForce(ip, email) { const key = `failed_logins:${ip}`; const count = await redis.incr(key); // Set expiration to 5 minutes on first failure if (count === 1) { await redis.expire(key, 300); } // Alert if 10+ failures in 5 minutes if (count >= 10) { await sendAlert({ severity: 'HIGH', type: 'BRUTE_FORCE_DETECTED', ip: ip, attempts: count, targetEmail: email, timestamp: new Date().toISOString() }); // Optional: Temporarily block the IP await redis.setex(`blocked:${ip}`, 3600, 'true'); } return count; } app.post('/api/login', async (req, res) => { const { email, password } = req.body; // Check if IP is blocked const isBlocked = await redis.get(`blocked:${req.ip}`); if (isBlocked) { return res.status(429).json({ error: 'Too many attempts. Try again later.' }); } const user = await authenticateUser(email, password); if (!user) { const failCount = await checkForBruteForce(req.ip, email); logSecurityEvent('LOGIN_FAILED', email, { reason: 'Invalid credentials', failCount }, req); return res.status(401).json({ error: 'Invalid credentials' }); } // Clear failure count on successful login await redis.del(`failed_logins:${req.ip}`); // Continue with login... });
Invalid credentials) whether the email exists or the password is wrong. This prevents user enumeration attacks.Detecting Unusual Login Locations
A login from a new country or device could indicate account compromise. We can detect these anomalies by comparing with previous login history.
async function isUnusualLogin(userId, ipAddress, userAgent) { // Get user's last 10 successful logins const previousLogins = await db.securityLogs.find({ userId: userId, eventType: 'LOGIN_SUCCESS', timestamp: { $gt: new Date(Date.now() - 30 * 24 * 60 * 60 * 1000) } }).sort({ timestamp: -1 }).limit(10); if (previousLogins.length === 0) { return { isUnusual: false, reason: null }; } // Check if IP is new const previousIPs = [...new Set(previousLogins.map(l => l.ipAddress))]; const isNewIP = !previousIPs.includes(ipAddress); // Check if User-Agent is new const previousUserAgents = [...new Set(previousLogins.map(l => l.userAgent))]; const isNewUserAgent = !previousUserAgents.includes(userAgent); if (isNewIP && isNewUserAgent) { return { isUnusual: true, reason: 'New device and new IP address' }; } if (isNewIP) { return { isUnusual: true, reason: 'New IP address' }; } return { isUnusual: false, reason: null }; } app.post('/api/login', async (req, res) => { const user = await authenticateUser(req.body.email, req.body.password); if (user) { const { isUnusual, reason } = await isUnusualLogin(user.id, req.ip, req.headers['user-agent']); if (isUnusual) { // Send email notification to user await sendSecurityEmail(user.email, 'unusual_login', { ip: req.ip, userAgent: req.headers['user-agent'], reason: reason, timestamp: new Date().toISOString() }); logSecurityEvent('UNUSUAL_LOGIN_DETECTED', user.id, { ip: req.ip, userAgent: req.headers['user-agent'], reason: reason }, req); } // Continue with login... } });
Alerting on Suspicious Patterns
Beyond brute force, watch for other attack patterns. Use Redis to track various metrics and trigger alerts when thresholds are exceeded.
async function checkForSuspiciousActivity(ip, userId, eventType) { const now = Date.now(); const windowMs = 60 * 1000; // 1 minute // Track multiple event types const keys = { rapidPasswordChanges: `password_changes:${userId}`, rapidRoleChanges: `role_changes:${userId}`, rapid2FADisable: `2fa_disable:${userId}`, rapidApiKeyCreation: `api_key_creation:${ip}` }; const count = await redis.incr(keys[eventType]); if (count === 1) { await redis.expire(keys[eventType], Math.floor(windowMs / 1000)); } const alerts = { rapidPasswordChanges: { threshold: 3, severity: 'HIGH', message: 'Multiple password changes in short period' }, rapidRoleChanges: { threshold: 2, severity: 'CRITICAL', message: 'Multiple role changes detected' }, rapid2FADisable: { threshold: 2, severity: 'HIGH', message: '2FA disabled multiple times' }, rapidApiKeyCreation: { threshold: 10, severity: 'MEDIUM', message: 'Suspicious API key creation rate' } }; const alert = alerts[eventType]; if (count >= alert.threshold) { await sendAlert({ severity: alert.severity, type: eventType.toUpperCase(), message: alert.message, ip: ip, userId: userId, count: count, windowMs: windowMs }); // For critical events, lock the account if (alert.severity === 'CRITICAL') { await db.users.updateOne( { _id: userId }, { $set: { accountLocked: true, lockReason: alert.message, lockTime: new Date() } } ); } } return count; } // Usage in endpoints app.post('/api/users/:id/role', requireRole(['ADMIN']), async (req, res) => { await checkForSuspiciousActivity(req.ip, req.params.id, 'rapidRoleChanges'); // ... role change logic }); app.post('/api/2fa/disable', requireAuth, async (req, res) => { await checkForSuspiciousActivity(req.ip, req.user.id, 'rapid2FADisable'); // ... 2FA disable logic });
Protecting Logs from Tampering
Sophisticated attackers will try to erase logs after a breach. Protect your logs with these strategies.
Log Protection Best Practices: 1. Write-Once Storage: - Send logs to a separate, write-only service - Use immutable storage like AWS S3 Object Lock - Application cannot modify or delete logs 2. Forward to SIEM: - Send logs to a centralized Security Information and Event Management system - SIEM provides tamper-evident storage and real-time alerting 3. Cryptographic Signing: - Sign each log entry with HMAC - Verify integrity when reading logs - Detect any tampering attempts 4. Separate Credentials: - Use different credentials for writing logs - Application cannot delete logs - Logging service has its own authentication 5. Regular Backups: - Backup logs to different region or cloud provider - Test restoration regularly - Keep backups for compliance period (1-7 years)
// Example: HMAC-signed logs const crypto = require('crypto'); const LOG_SECRET = process.env.LOG_SIGNING_SECRET; function createSignedLogEntry(logData) { const logString = JSON.stringify(logData); const signature = crypto .createHmac('sha256', LOG_SECRET) .update(logString) .digest('hex'); return { ...logData, signature: signature }; } function verifyLogEntry(logEntry) { const { signature, ...logData } = logEntry; const expectedSignature = crypto .createHmac('sha256', LOG_SECRET) .update(JSON.stringify(logData)) .digest('hex'); return signature === expectedSignature; } // When logging const signedLog = createSignedLogEntry(logData); await writeToImmutableStorage(signedLog); // When reading logs (during investigation) const logEntry = await readFromStorage(); if (!verifyLogEntry(logEntry)) { console.error('LOG TAMPERING DETECTED!'); // Trigger security incident response }
Compliance and Retention
Different regulations require different log retention periods. Plan your storage accordingly.
Retention Requirements by Regulation: GDPR (General Data Protection Regulation): - Security logs: 6-12 months (recommended) - Consent logs: Until consent is withdrawn PCI-DSS (Payment Card Industry): - Audit logs: 1 year minimum - Last 3 months immediately available HIPAA (Health Insurance Portability and Accountability Act): - Security logs: 6 years - Access logs: 6 years SOX (Sarbanes-Oxley): - Audit logs: 7 years General Best Practices: - Hot storage (fast access): 30-90 days - Cold storage (archived): 1-7 years - Regular backup verification - Test restoration process annually
Security Logging Checklist
Implementation Checklist: □ All authentication events logged (success/failure) □ All authorization changes logged □ Sensitive data access logged □ Admin actions logged □ Logs include IP, User-Agent, timestamp, request ID □ Logs are structured JSON □ Logs are sent to separate storage □ Logs cannot be deleted by application □ Alerts configured for suspicious patterns □ Retention policy defined and implemented □ Regular backup verification □ Incident response plan for log analysis □ Log signing implemented (tamper detection)
Knowledge Check
Ready to test your understanding of 18. Security Logging & Threat Monitoring?