Runtime Security Patterns

Overview

Runtime security patterns for production environments including real-time monitoring, automated incident response, audit trail generation, and security tool integration.

Real-time Security Monitoring

// security/realtime-monitor.ts
export class SecurityMonitor {
  private alertThresholds = {
    failedLogins: 5,
    apiRateLimit: 1000,
    errorRate: 0.05,
    responseTime: 5000
  };
  
  async monitorSecurity(): Promise<void> {
    const monitors = [
      this.monitorAuthAttempts(),
      this.monitorAPIUsage(),
      this.monitorSystemHealth(),
      this.monitorDataAccess()
    ];
    
    await Promise.all(monitors);
  }
  
  private async monitorAuthAttempts() {
    const stream = this.getLogStream('auth');
    
    stream.on('data', async (log) => {
      if (log.type === 'failed-login') {
        const attempts = await this.countFailedAttempts(log.user);
        
        if (attempts > this.alertThresholds.failedLogins) {
          await this.createIncident({
            type: 'suspicious-auth',
            severity: 'high',
            user: log.user,
            action: 'block-account'
          });
        }
      }
    });
  }
}

Incident Detection and Response

Detection Framework

// security/incident-detector.ts
interface SecurityIncident {
  id: string;
  type: IncidentType;
  severity: 'low' | 'medium' | 'high' | 'critical';
  timestamp: Date;
  source: string;
  affectedSystems: string[];
  indicators: string[];
  automaticActions: Action[];
}
 
export class IncidentDetector {
  private detectors: Map<string, Detector> = new Map([
    ['intrusion', new IntrusionDetector()],
    ['data-breach', new DataBreachDetector()],
    ['ddos', new DDoSDetector()],
    ['malware', new MalwareDetector()]
  ]);
  
  async detectIncidents(): Promise<SecurityIncident[]> {
    const incidents: SecurityIncident[] = [];
    
    for (const [type, detector] of this.detectors) {
      const detected = await detector.scan();
      incidents.push(...detected);
    }
    
    return this.prioritizeIncidents(incidents);
  }
}

Automated Response Playbooks

// security/response-playbooks.ts
export class IncidentResponseOrchestrator {
  async executePlaybook(incident: SecurityIncident): Promise<ResponseResult> {
    const playbook = this.selectPlaybook(incident.type);
    
    const steps = [
      this.containIncident,
      this.collectEvidence,
      this.notifyStakeholders,
      this.mitigateImpact,
      this.documentIncident
    ];
    
    for (const step of steps) {
      await step(incident);
    }
    
    return this.generateResponseReport(incident);
  }
  
  private async containIncident(incident: SecurityIncident) {
    switch (incident.type) {
      case 'intrusion':
        await this.blockIPAddresses(incident.indicators);
        await this.disableCompromisedAccounts(incident.affectedSystems);
        break;
      
      case 'data-breach':
        await this.revokeAccessTokens(incident.affectedSystems);
        await this.enableEmergencyMode();
        break;
      
      case 'ddos':
        await this.enableDDoSProtection();
        await this.scaleInfrastructure();
        break;
    }
  }
}

Claude Code Integration

// .claude/incident-response-hook.ts
export const incidentResponseHook: ClaudeHook = {
  name: 'incident-response',
  trigger: 'custom:security-incident',
  
  async execute(context, incident: SecurityIncident) {
    // 1. Immediate containment
    await context.runCommand(`npm run security:contain -- --incident-id=${incident.id}`);
    
    // 2. Collect forensic data
    const evidence = await context.runCommand('npm run security:collect-evidence');
    
    // 3. Create incident ticket
    await context.runCommand(`gh issue create --title "Security Incident: ${incident.type}" --body "${evidence}"`);
    
    // 4. Deploy patches if available
    if (incident.patches) {
      await context.runCommand('git checkout -b security/incident-response');
      await context.applyPatches(incident.patches);
      await context.runCommand('npm test');
      await context.createPR({
        title: `Security: Emergency patch for ${incident.type}`,
        priority: 'urgent'
      });
    }
    
    // 5. Send notifications
    await context.notify({
      channels: ['slack', 'pagerduty'],
      message: `Security incident detected: ${incident.type}`,
      severity: incident.severity
    });
  }
};

Audit Trail Generation

Tamper-Proof Storage

// security/audit-storage.ts
import { createHash } from 'crypto';
 
export class TamperProofAuditStorage {
  private blockchain: AuditBlock[] = [];
  
  async store(event: AuditEvent): Promise<void> {
    const block: AuditBlock = {
      index: this.blockchain.length,
      timestamp: Date.now(),
      data: event,
      previousHash: this.getLatestBlock()?.hash || '0',
      hash: ''
    };
    
    block.hash = this.calculateHash(block);
    
    // Store in multiple locations
    await Promise.all([
      this.storeInDatabase(block),
      this.storeInS3(block),
      this.storeInSIEM(block)
    ]);
    
    this.blockchain.push(block);
  }
  
  private calculateHash(block: AuditBlock): string {
    return createHash('sha256')
      .update(block.index + block.timestamp + JSON.stringify(block.data) + block.previousHash)
      .digest('hex');
  }
  
  async verifyIntegrity(): Promise<boolean> {
    for (let i = 1; i < this.blockchain.length; i++) {
      const current = this.blockchain[i];
      const previous = this.blockchain[i - 1];
      
      if (current.previousHash !== previous.hash) {
        return false;
      }
      
      if (current.hash !== this.calculateHash(current)) {
        return false;
      }
    }
    
    return true;
  }
}

Audit Analysis

export class AuditAnalyzer {
  async analyzeAuditTrail(timeRange: TimeRange): Promise<AuditReport> {
    const events = await this.getEvents(timeRange);
    
    return {
      summary: {
        totalEvents: events.length,
        uniqueUsers: this.countUniqueUsers(events),
        failedAttempts: this.countFailures(events),
        suspiciousActivities: this.detectAnomalies(events)
      },
      
      userActivity: this.analyzeUserActivity(events),
      
      securityMetrics: {
        authenticationRate: this.calculateAuthRate(events),
        errorRate: this.calculateErrorRate(events),
        accessPatterns: this.analyzeAccessPatterns(events)
      },
      
      compliance: {
        dataAccess: this.auditDataAccess(events),
        privilegedActions: this.auditPrivilegedActions(events),
        configChanges: this.auditConfigChanges(events)
      },
      
      recommendations: this.generateRecommendations(events)
    };
  }
  
  private detectAnomalies(events: AuditEvent[]): Anomaly[] {
    const anomalies: Anomaly[] = [];
    
    // Detect unusual access patterns
    const accessByHour = this.groupByHour(events);
    for (const [hour, count] of accessByHour) {
      if (this.isUnusualHour(hour) && count > 10) {
        anomalies.push({
          type: 'unusual-access-time',
          severity: 'medium',
          details: `${count} events during unusual hours`
        });
      }
    }
    
    // Detect rapid-fire events
    const userEvents = this.groupByUser(events);
    for (const [user, userEvents] of userEvents) {
      if (this.detectRapidFire(userEvents)) {
        anomalies.push({
          type: 'rapid-fire-activity',
          severity: 'high',
          user,
          details: 'Unusually high activity rate detected'
        });
      }
    }
    
    return anomalies;
  }
}

Security Tool Integration

Tool Orchestration

// security/tool-orchestrator.ts
interface SecurityTool {
  name: string;
  type: 'sast' | 'dast' | 'dependency' | 'container';
  execute: (config: ToolConfig) => Promise<ToolResult>;
  parseResults: (output: any) => SecurityFinding[];
}
 
export class SecurityToolOrchestrator {
  private tools: Map<string, SecurityTool> = new Map([
    ['snyk', new SnykIntegration()],
    ['sonarqube', new SonarQubeIntegration()],
    ['trivy', new TrivyIntegration()],
    ['zap', new ZAPIntegration()],
    ['semgrep', new SemgrepIntegration()]
  ]);
  
  async runSecuritySuite(): Promise<SecurityReport> {
    const results = await Promise.all([
      this.runSAST(),
      this.runDAST(),
      this.runDependencyScan(),
      this.runContainerScan()
    ]);
    
    return this.consolidateResults(results);
  }
}

OWASP ZAP Integration (DAST)

// integrations/zap.ts
export class ZAPIntegration implements SecurityTool {
  async execute(config: ToolConfig): Promise<ToolResult> {
    const zap = new ZAPClient(config.zapUrl);
    
    // Start ZAP spider
    await zap.spider.scan(config.targetUrl);
    await this.waitForSpider(zap);
    
    // Run active scan
    await zap.ascan.scan(config.targetUrl);
    await this.waitForScan(zap);
    
    // Get results
    const alerts = await zap.core.alerts({
      baseurl: config.targetUrl,
      start: 0,
      count: 1000
    });
    
    return this.processAlerts(alerts);
  }
  
  processAlerts(alerts: any[]): SecurityFinding[] {
    return alerts.map(alert => ({
      tool: 'zap',
      severity: this.mapRiskLevel(alert.risk),
      type: 'DAST',
      title: alert.name,
      description: alert.description,
      solution: alert.solution,
      evidence: alert.evidence,
      url: alert.url
    }));
  }
}

Runtime Protection Strategies

1. Rate Limiting

import rateLimit from 'express-rate-limit';
 
const limiter = rateLimit({
  windowMs: 15 * 60 * 1000, // 15 minutes
  max: 100, // Limit each IP to 100 requests per windowMs
  message: 'Too many requests from this IP',
  handler: (req, res) => {
    // Log potential DDoS attempt
    auditLogger.warn('Rate limit exceeded', {
      ip: req.ip,
      path: req.path,
      timestamp: new Date()
    });
    
    res.status(429).json({
      error: 'Too many requests'
    });
  }
});

2. Web Application Firewall (WAF)

export class WAFMiddleware {
  private rules = [
    { pattern: /<script[\s\S]*?>[\s\S]*?<\/script>/gi, type: 'XSS' },
    { pattern: /(\' OR \'1\'=\'1)/gi, type: 'SQL Injection' },
    { pattern: /\.\.\/|\.\.\\/, type: 'Path Traversal' }
  ];
  
  async protect(req: Request, res: Response, next: NextFunction) {
    const payload = JSON.stringify(req.body) + req.url + JSON.stringify(req.query);
    
    for (const rule of this.rules) {
      if (rule.pattern.test(payload)) {
        await this.logAttack(req, rule.type);
        return res.status(403).json({ error: 'Forbidden' });
      }
    }
    
    next();
  }
}

3. Runtime Application Self-Protection (RASP)

export class RASPProtection {
  async protectFunction(fn: Function, context: any) {
    return new Proxy(fn, {
      apply: async (target, thisArg, args) => {
        // Pre-execution checks
        await this.validateInputs(args);
        await this.checkSecurityContext();
        
        try {
          // Execute with monitoring
          const result = await target.apply(thisArg, args);
          
          // Post-execution validation
          await this.validateOutput(result);
          
          return result;
        } catch (error) {
          await this.handleSecurityException(error);
          throw error;
        }
      }
    });
  }
}

Recovery Procedures

class IncidentRecovery {
  async recoverFromIncident(incident: SecurityIncident): Promise<void> {
    // 1. Verify containment
    await this.verifyContainment(incident);
    
    // 2. Restore services
    await this.restoreServices(incident.affectedSystems);
    
    // 3. Validate security
    await this.runSecurityValidation();
    
    // 4. Monitor for recurrence
    await this.setupEnhancedMonitoring(incident);
    
    // 5. Update security measures
    await this.updateSecurityControls(incident);
  }
}

Best Practices

  1. Quick Detection: Monitor continuously for anomalies
  2. Automated Containment: Immediately isolate affected systems
  3. Evidence Preservation: Collect forensic data automatically
  4. Clear Communication: Notify stakeholders promptly
  5. Post-Incident Review: Learn and improve from each incident

See Also