3 Hours

18. Security Logging & Threat Monitoring

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.

Text
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
Compliance Note: Regulations like GDPR, PCI-DSS, and HIPAA have specific logging requirements. Security logs often need to be retained for 1-7 years and must be tamper-proof.

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.

Text
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"
}
Why JSON? JSON logs can be ingested by log aggregation tools (ELK, Datadog, Splunk) and searched with queries like 'eventType:LOGIN_FAILED AND ipAddress:1.2.3.4'.

Building a Security Logger

Let's create a reusable security logging function that captures all important context automatically.

JavaScript
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...
});
Request ID: Generate a unique ID for each request. This allows you to trace all logs related to a single user action across multiple services.

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.

JavaScript
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...
});
Don't reveal too much: Always return the same error message (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.

JavaScript
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...
    }
});
User Notification: Always notify users about logins from new devices or locations. This allows them to detect unauthorized access quickly.

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.

JavaScript
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.

Text
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)
JavaScript
// 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.

Text
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
Pro Tip: Document your logging and retention policies. During a security audit, you will need to prove you are logging properly and retaining logs for the required period.

Security Logging Checklist

Text
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)
Remember: Logs are evidence. Treat them like any other critical asset — protect them, back them up, and control access to them.

Knowledge Check

Ready to test your understanding of 18. Security Logging & Threat Monitoring?

Back