/**
 * Malware Incident Response Playbook
 *
 * Comprehensive playbook for responding to malware incidents including
 * detection, containment, eradication, and recovery procedures.
 *
 * This playbook uses automated actions from the actions module that
 * provide real implementations with rollback capabilities.
 */
import { createLogger } from '../../../common/logger.js';
import { IncidentType, IncidentSeverity, NotificationChannel, StepType, } from '../types.js';
const logger = createLogger({ component: 'incident-response' });
// ============================================================================
// Playbook Definition
// ============================================================================
/**
 * Malware response steps using automated actions
 *
 * Steps are designed to:
 * - Verify malware indicators before taking containment actions
 * - Isolate affected systems to prevent lateral movement
 * - Collect malware samples and forensic evidence
 * - Eradicate malware and clean infected systems
 * - Restore systems to clean state with verification
 * - Document lessons learned and update detection signatures
 */
const malwareSteps = [
    // Phase 1: Detection and Verification
    {
        id: 'mw-step-1',
        name: 'Verify Malware Indicators',
        type: StepType.MANUAL,
        description: `
      Verify the malware alert is legitimate:
      1. Review the initial detection alert (AV, EDR, IDS/IPS)
      2. Confirm the malware detection is a true positive
      3. Identify the malware type (trojan, ransomware, worm, rootkit, etc.)
      4. Determine initial infection vector if possible
      5. Identify affected systems and scope of infection
      6. Document initial findings including file hashes, paths, and behaviors

      Mark this step complete once verification is done.
    `,
        requiresApproval: false,
        onFailure: 'halt',
    },
    // Phase 2: Immediate Containment (Automated)
    {
        id: 'mw-step-2',
        name: 'Isolate Affected Systems',
        type: StepType.AUTOMATED,
        description: 'Automatically isolate affected systems from the network to prevent malware spread and C2 communication. This action blocks network access while preserving system state for forensics.',
        actionId: 'isolate-system', // Uses the isolate-system action
        timeout: 120000, // 2 minutes
        requiresApproval: true, // Requires approval due to high impact
        approvers: ['security-lead', 'incident-commander'],
        onFailure: 'halt',
        retryAttempts: 2,
        dependencies: ['mw-step-1'],
        metadata: {
            rollbackOnFailure: true,
            notifyOnComplete: true,
            preserveForForensics: true,
        },
    },
    {
        id: 'mw-step-3',
        name: 'Block C2 Infrastructure',
        type: StepType.AUTOMATED,
        description: 'Block identified command and control (C2) IP addresses and domains at firewall, proxy, and DNS levels to prevent malware communication.',
        actionId: 'block-ip', // Uses the block-ip action
        timeout: 60000, // 1 minute
        requiresApproval: false, // Critical - execute immediately after isolation
        onFailure: 'continue', // Continue even if some blocks fail
        retryAttempts: 3,
        dependencies: ['mw-step-2'],
        metadata: {
            blockType: 'c2_infrastructure',
            includeKnownIOCs: true,
        },
    },
    {
        id: 'mw-step-4',
        name: 'Enable Enhanced Monitoring',
        type: StepType.AUTOMATED,
        description: 'Activate enhanced security monitoring including increased logging, EDR telemetry, network traffic analysis, and detection rules for the specific malware family.',
        actionId: 'scale-monitoring', // Uses the scale-monitoring action
        timeout: 180000, // 3 minutes
        requiresApproval: false,
        onFailure: 'continue',
        dependencies: ['mw-step-2'],
        metadata: {
            monitoringProfile: 'malware_incident',
            enableNetworkCapture: true,
        },
    },
    // Phase 3: Evidence Collection (Automated)
    {
        id: 'mw-step-5',
        name: 'Collect Malware Samples and Evidence',
        type: StepType.AUTOMATED,
        description: 'Collect and preserve forensic evidence including malware samples, memory dumps, system logs, network captures, and file system artifacts.',
        actionId: 'collect-evidence', // Uses the collect-evidence action
        timeout: 900000, // 15 minutes - memory dumps take time
        requiresApproval: false,
        onFailure: 'halt', // Critical for investigation and eradication
        dependencies: ['mw-step-2'],
        metadata: {
            evidenceTypes: ['malware_samples', 'memory_dump', 'logs', 'network_capture', 'file_system'],
            preserveChainOfCustody: true,
            calculateHashes: true,
        },
    },
    {
        id: 'mw-step-5b',
        name: 'Quarantine Malicious Files',
        type: StepType.MANUAL,
        description: `
      Quarantine identified malicious files:
      1. Move malware samples to secure quarantine storage
      2. Preserve file metadata and timestamps
      3. Calculate and record file hashes (MD5, SHA1, SHA256)
      4. Document file locations and paths
      5. Ensure quarantine prevents execution
      6. Backup quarantined files for analysis

      Note: Automated quarantine should have captured samples.
      This step verifies and handles any missed files.
    `,
        requiresApproval: false,
        onFailure: 'continue',
        dependencies: ['mw-step-5'],
    },
    // Phase 4: Notification (Automated)
    {
        id: 'mw-step-6',
        name: 'Notify Security Stakeholders',
        type: StepType.AUTOMATED,
        description: 'Send automated notifications to security team, IT operations, and relevant stakeholders about the malware incident.',
        actionId: 'notify-stakeholders', // Uses the notify-stakeholders action
        timeout: 120000, // 2 minutes
        requiresApproval: false,
        onFailure: 'continue',
        retryAttempts: 3,
        dependencies: ['mw-step-1'],
    },
    // Phase 5: Investigation (Manual)
    {
        id: 'mw-step-7',
        name: 'Malware Analysis',
        type: StepType.MANUAL,
        description: `
      Analyze the malware to understand its capabilities:
      1. Perform static analysis (strings, imports, packing)
      2. Perform dynamic analysis in sandbox environment
      3. Identify malware family and variant
      4. Document malware capabilities:
         - Persistence mechanisms
         - C2 communication methods
         - Data exfiltration capabilities
         - Lateral movement techniques
         - Credential theft functionality
      5. Extract indicators of compromise (IOCs)
      6. Check threat intelligence for known malware

      Use the samples collected in Step 5 for analysis.
    `,
        requiresApproval: false,
        onFailure: 'continue',
        dependencies: ['mw-step-5'],
    },
    {
        id: 'mw-step-8',
        name: 'Determine Infection Scope',
        type: StepType.MANUAL,
        description: `
      Determine the full scope of the infection:
      1. Scan all systems for identified IOCs
      2. Review network logs for C2 communication patterns
      3. Check for lateral movement to other systems
      4. Identify all affected systems and accounts
      5. Assess data exposure and exfiltration
      6. Create comprehensive infection timeline
      7. Document attack chain from initial infection

      This determines the full eradication scope.
    `,
        requiresApproval: false,
        onFailure: 'halt',
        dependencies: ['mw-step-5', 'mw-step-7'],
    },
    {
        id: 'mw-step-8b',
        name: 'Check for Credential Theft',
        type: StepType.MANUAL,
        description: `
      Assess if credentials were compromised:
      1. Review malware capabilities for credential theft
      2. Check for credential dumping activity
      3. Analyze memory dumps for exposed credentials
      4. Review authentication logs for suspicious activity
      5. Identify potentially compromised accounts
      6. Document all affected credentials

      If credentials were compromised, flag for revocation.
    `,
        requiresApproval: false,
        onFailure: 'continue',
        dependencies: ['mw-step-7'],
    },
    // Phase 6: Credential Revocation (if needed)
    {
        id: 'mw-step-9',
        name: 'Revoke Compromised Credentials',
        type: StepType.AUTOMATED,
        description: 'Revoke all potentially compromised credentials including passwords, API keys, tokens, and certificates that may have been exposed to the malware.',
        actionId: 'revoke-credentials', // Uses the revoke-credentials action
        timeout: 180000, // 3 minutes
        requiresApproval: true,
        approvers: ['security-lead', 'identity-team'],
        onFailure: 'halt',
        retryAttempts: 2,
        dependencies: ['mw-step-8b'],
        metadata: {
            revokeType: 'malware_exposure',
            forcePasswordReset: true,
        },
    },
    // Phase 7: Eradication (Manual with Approvals)
    {
        id: 'mw-step-10',
        name: 'Remove Malware',
        type: StepType.MANUAL,
        description: `
      Remove malware from all affected systems:
      1. Terminate malicious processes
      2. Remove malware files and artifacts
      3. Clean registry entries and scheduled tasks
      4. Remove persistence mechanisms:
         - Startup entries
         - Services
         - WMI subscriptions
         - Browser extensions
      5. Clean infected documents/files
      6. Remove any dropped payloads
      7. Document all removal actions

      Requires security lead approval before proceeding.
    `,
        requiresApproval: true,
        approvers: ['security-lead'],
        onFailure: 'halt',
        dependencies: ['mw-step-8'],
    },
    {
        id: 'mw-step-11',
        name: 'Clean Infected Files',
        type: StepType.MANUAL,
        description: `
      Clean or restore infected files:
      1. Identify all infected documents and files
      2. Attempt to disinfect recoverable files
      3. Restore infected files from clean backups
      4. Verify restored files are malware-free
      5. Remove irrecoverable infected files
      6. Document all file operations
    `,
        requiresApproval: false,
        onFailure: 'continue',
        dependencies: ['mw-step-10'],
    },
    {
        id: 'mw-step-12',
        name: 'Verify Eradication',
        type: StepType.MANUAL,
        description: `
      Verify complete malware removal:
      1. Run full system scans with updated signatures
      2. Scan for all identified IOCs
      3. Check for persistence mechanism remnants
      4. Review running processes and services
      5. Analyze network traffic for C2 communication
      6. Confirm clean state on all affected systems
      7. Document verification results

      Systems must pass verification before recovery.
    `,
        requiresApproval: false,
        onFailure: 'halt',
        dependencies: ['mw-step-10', 'mw-step-11'],
    },
    // Phase 8: Recovery (Manual with Approvals)
    {
        id: 'mw-step-13',
        name: 'Restore Systems',
        type: StepType.MANUAL,
        description: `
      Restore systems to normal operation:
      1. Apply all security patches and updates
      2. Restore from clean backups if necessary
      3. Rebuild systems that cannot be cleaned
      4. Reinstall applications from trusted sources
      5. Restore user data from verified clean backups
      6. Update security software and signatures
      7. Document all restoration activities

      Requires incident commander approval.
    `,
        requiresApproval: true,
        approvers: ['incident-commander', 'operations-lead'],
        onFailure: 'halt',
        dependencies: ['mw-step-12'],
    },
    {
        id: 'mw-step-14',
        name: 'Verify Clean State',
        type: StepType.MANUAL,
        description: `
      Perform final verification of clean system state:
      1. Run comprehensive security scans
      2. Verify all IOCs are absent
      3. Confirm network traffic is clean
      4. Test system functionality
      5. Verify security controls are operational
      6. Monitor for 24-48 hours for reinfection
      7. Document clean state confirmation
    `,
        requiresApproval: false,
        onFailure: 'halt',
        dependencies: ['mw-step-13'],
    },
    {
        id: 'mw-step-15',
        name: 'Remove Network Isolation',
        type: StepType.MANUAL,
        description: `
      Restore network access to cleaned systems:
      1. Coordinate with automation rollback for isolation
      2. Gradually restore network connectivity
      3. Re-enable disabled services
      4. Restore normal firewall rules (keep C2 blocks)
      5. Monitor network traffic closely
      6. Confirm service availability
      7. Verify user access is restored

      This step triggers rollback of isolation measures.
    `,
        requiresApproval: true,
        approvers: ['incident-commander', 'security-lead'],
        onFailure: 'halt',
        dependencies: ['mw-step-14'],
    },
    // Phase 9: Post-Incident (Manual)
    {
        id: 'mw-step-16',
        name: 'Update Detection Signatures',
        type: StepType.MANUAL,
        description: `
      Update security systems with new intelligence:
      1. Add new IOCs to detection systems:
         - File hashes
         - IP addresses and domains
         - Registry keys
         - Mutex names
         - YARA rules
      2. Update antivirus signatures
      3. Create EDR detection rules
      4. Update SIEM correlation rules
      5. Share indicators with threat intelligence platform
      6. Notify security vendors if necessary
    `,
        requiresApproval: false,
        onFailure: 'continue',
        dependencies: ['mw-step-7'],
    },
    {
        id: 'mw-step-17',
        name: 'Post-Incident Review',
        type: StepType.MANUAL,
        description: `
      Conduct comprehensive post-incident review:
      1. Schedule post-mortem meeting with all responders
      2. Document complete incident timeline
      3. Analyze initial infection vector
      4. Identify security gaps that allowed infection
      5. Evaluate response effectiveness
      6. Document lessons learned:
         - What worked well
         - What could be improved
         - Detection gaps
         - Response gaps
      7. Create final incident report
    `,
        requiresApproval: false,
        onFailure: 'continue',
        dependencies: ['mw-step-15'],
    },
    {
        id: 'mw-step-18',
        name: 'Implement Preventive Measures',
        type: StepType.MANUAL,
        description: `
      Implement measures to prevent future infections:
      1. Address identified security gaps
      2. Update security policies if needed
      3. Implement additional security controls
      4. Enhance email/web filtering
      5. Update user training based on infection vector
      6. Review and update backup procedures
      7. Schedule follow-up security assessment
      8. Update this playbook with improvements
    `,
        requiresApproval: false,
        onFailure: 'continue',
        dependencies: ['mw-step-17'],
    },
];
const triggerConditions = [
    {
        field: 'type',
        operator: 'equals',
        value: IncidentType.MALWARE,
    },
];
const notifications = [
    {
        channel: NotificationChannel.SLACK,
        target: '#security-incidents',
        enabled: true,
        retryAttempts: 3,
        retryDelayMs: 5000,
    },
    {
        channel: NotificationChannel.SLACK,
        target: '#soc-team',
        enabled: true,
        retryAttempts: 3,
        retryDelayMs: 5000,
    },
    {
        channel: NotificationChannel.PAGERDUTY,
        target: 'security-oncall',
        severityFilter: [IncidentSeverity.P1, IncidentSeverity.P2],
        enabled: true,
        retryAttempts: 3,
        retryDelayMs: 5000,
    },
    {
        channel: NotificationChannel.EMAIL,
        target: 'security@company.com',
        enabled: true,
        retryAttempts: 3,
        retryDelayMs: 5000,
    },
    {
        channel: NotificationChannel.EMAIL,
        target: 'it-operations@company.com',
        severityFilter: [IncidentSeverity.P1, IncidentSeverity.P2],
        enabled: true,
        retryAttempts: 3,
        retryDelayMs: 5000,
    },
];
const escalation = {
    enabled: true,
    levels: [
        {
            level: 1,
            afterMinutes: 15,
            targets: ['security-team', 'soc-team'],
            channels: [NotificationChannel.SLACK, NotificationChannel.PAGERDUTY],
            message: 'Malware incident not acknowledged within 15 minutes - immediate response required',
        },
        {
            level: 2,
            afterMinutes: 30,
            targets: ['security-lead', 'incident-commander'],
            channels: [NotificationChannel.SLACK, NotificationChannel.PAGERDUTY, NotificationChannel.EMAIL],
            message: 'Malware incident escalating - leadership attention needed for containment',
        },
        {
            level: 3,
            afterMinutes: 60,
            targets: ['ciso', 'cto'],
            channels: [NotificationChannel.PAGERDUTY, NotificationChannel.EMAIL, NotificationChannel.SMS],
            message: 'Critical malware incident - executive escalation required',
        },
    ],
    maxLevel: 3,
    resetOnAcknowledge: true,
};
// ============================================================================
// Export Playbook
// ============================================================================
export const malwarePlaybook = {
    id: 'playbook-malware-v1',
    name: 'Malware Incident Response',
    description: `
    Comprehensive playbook for responding to malware incidents.
    Covers detection verification, system isolation, evidence collection,
    malware analysis, eradication, recovery, and post-incident activities.
    Designed to minimize spread while preserving forensic evidence.
  `.trim(),
    version: '1.0.0',
    triggerConditions,
    steps: malwareSteps,
    notifications,
    escalation,
    enabled: true,
    tags: ['malware', 'edr', 'containment', 'forensics', 'critical'],
    createdAt: new Date('2024-01-01'),
    updatedAt: new Date('2024-01-15'),
};
export default malwarePlaybook;
//# sourceMappingURL=malware.js.map