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

const overview = {
    id: 26,
    title: 'Malware Analysis Basics',
    description: 'Learn to safely analyze malware: Static, Dynamic, and Behavioral techniques.',
    learning_path_id: 3
};

const tasks = [
    { id: 261, title: 'Malware Categories' },
    { id: 262, title: 'Static vs Dynamic Analysis' },
    { id: 263, title: 'Setting Up a Safe Lab' },
    { id: 264, title: 'Static Analysis Tools' },
    { id: 265, title: 'Dynamic Analysis (Sandboxing)' },
    { id: 266, title: 'Identifying IOCs from Malware' },
    { id: 267, title: 'Final Quiz' }
];

const lessons = {
    261: {
        content: `# Malware Categories

**Malware** = Malicious Software. Designed to damage, disrupt, or gain unauthorized access.

## Types of Malware
1.  **Virus**: Attaches to a legitimate file. Spreads when the file is shared/executed.
2.  **Worm**: Self-replicating. Spreads across networks *without* user interaction.
3.  **Trojan**: Disguised as legitimate software. "Trojan Horse" - looks safe, is malicious.
4.  **Ransomware**: Encrypts your files, demands payment for the decryption key.
5.  **Spyware**: Secretly collects information (keystrokes, screenshots).
6.  **Rootkit**: Hides deep in the OS to maintain persistent, hidden access.
7.  **RAT (Remote Access Trojan)**: Gives attacker full remote control of the victim machine.

## Modern Threats
*   **Fileless Malware**: Lives in memory (RAM), no file on disk. Very hard to detect.
*   **Cryptominer**: Uses your CPU/GPU to mine cryptocurrency for the attacker.`,
        questions: [
            ['Which malware type encrypts your files and demands payment?', 'Ransomware', 'Ransom', ['Spyware', 'Ransomware', 'Worm', 'Virus']],
            ['What makes a Worm different from a Virus?', 'Worms spread without user interaction', 'Self-replicating', ['Worms are bigger', 'Worms spread without user interaction', 'Viruses are newer', 'No difference']],
            ['What is "Fileless Malware"?', 'Malware that lives in RAM, not on disk', 'Memory-only', ['Malware with no code', 'Malware that lives in RAM, not on disk', 'Malware that is deleted', 'Malware on USB']]
        ]
    },
    262: {
        content: `# Static vs Dynamic Analysis

## Static Analysis
Analyzing malware **without running it**.
*   **What you do**: Examine the file structure, strings, imports, metadata.
*   **Tools**: \`file\`, \`strings\`, \`PEStudio\`, \`Detect It Easy (DIE)\`.
*   **Pros**: Safe. The malware never executes.
*   **Cons**: Limited. Obfuscated/packed malware hides its true behavior.

## Dynamic Analysis
Analyzing malware **by running it** in a controlled environment.
*   **What you do**: Execute in a sandbox, observe behavior (network connections, file writes, registry changes).
*   **Tools**: \`Any.Run\`, \`Hybrid Analysis\`, \`Cuckoo Sandbox\`.
*   **Pros**: Sees what the malware *actually* does.
*   **Cons**: Risky if the sandbox escapes. Some malware detects sandboxes and hides.

## Behavioral Analysis
A subset of Dynamic. Focuses on *what* the malware does rather than *how*.
*   Example: "The sample created 50 files in /tmp and connected to 192.168.1.1."`,
        questions: [
            ['What is Static Analysis?', 'Examining malware without executing it', 'Not running', ['Running malware in a sandbox', 'Examining malware without executing it', 'Asking the malware questions', 'Deleting the malware']],
            ['What is a major risk of Dynamic Analysis?', 'Sandbox escape', 'Containment failure', ['It is too slow', 'Sandbox escape', 'It is too expensive', 'Nothing']],
            ['What tool is commonly used for strings extraction?', 'strings command', 'Text', ['Wireshark', 'strings command', 'Nmap', 'Burp Suite']]
        ]
    },
    263: {
        content: `# Setting Up a Safe Lab

**NEVER run malware on your personal computer.**

## Requirements
1.  **Isolated Network**: The malware VM should NOT be able to reach the internet or your home network.
    *   Use **Host-Only** networking in VirtualBox/VMware.
2.  **Disposable VM**: Use snapshots. After analysis, revert to a clean state.
3.  **Separate Machine (Ideal)**: A dedicated old laptop for analysis.

## Recommended Setup
*   **Host OS**: Windows or macOS with no sensitive data.
*   **Guest VM 1 (Analysis)**: Windows 10/11 (most malware targets Windows).
*   **Guest VM 2 (REMnux)**: Linux distro pre-configured for malware analysis.
*   **Networking**: Host-Only Adapter. No NAT, No Bridged.

## FlareVM
A Windows VM image pre-configured by Mandiant with all analysis tools installed.
*   Install: \`git clone https://github.com/mandiant/flare-vm\` then run installer script.`,
        questions: [
            ['Why should you use "Host-Only" networking for a malware lab?', 'To prevent the malware from reaching the internet', 'Isolation', ['It is faster', 'To prevent the malware from reaching the internet', 'It is default', 'For gaming']],
            ['What is FlareVM?', 'A pre-configured Windows VM for malware analysis', 'Mandiant tool', ['A virus', 'A pre-configured Windows VM for malware analysis', 'A firewall', 'An antivirus']],
            ['What should you do BEFORE running malware in a VM?', 'Take a snapshot', 'Snapshot', ['Delete all files', 'Take a snapshot', 'Turn off the firewall', 'Install games']]
        ]
    },
    264: {
        content: `# Static Analysis Tools

## 1. File Identification
*   **\`file\` (Linux)**: Identifies file type. \`file malware.exe\` -> "PE32 executable".
*   **Detect It Easy (DIE)**: GUI tool, identifies packers/obfuscation.

## 2. Strings Extraction
*   **\`strings\` (Linux)**: \`strings malware.exe | grep http\` -> Finds hardcoded URLs.
*   Look for: IP addresses, domain names, registry keys, suspicious function names.

## 3. PE Header Analysis (Windows EXE)
*   **PEStudio**: Free tool for inspecting PE headers, imports, and suspicious indicators.
*   **What to look for**:
    *   **Imports**: If it imports \`VirtualAlloc\`, \`CreateRemoteThread\`, it might be injecting code.
    *   **Sections**: A section named ".UPX" indicates UPX packing.
    *   **Entropy**: High entropy (>7.0) suggests encryption/packing.

## 4. Hashing
*   **Calculate Hash**: \`sha256sum malware.exe\`
*   **Check VirusTotal**: Paste the hash. Has it been seen before? What do vendors call it?`,
        questions: [
            ['What does high entropy (>7.0) in a file suggest?', 'The file is packed or encrypted', 'Obfuscation', ['It is small', 'The file is packed or encrypted', 'It is safe', 'It is old']],
            ['If a PE file imports "VirtualAlloc", what might it be doing?', 'Memory allocation for code injection', 'Injection', ['Playing music', 'Memory allocation for code injection', 'Deleting files', 'Printing documents']],
            ['Why hash a malware sample before analysis?', 'To check VirusTotal for known info', 'Lookup', ['To delete it', 'To check VirusTotal for known info', 'To run it', 'To rename it']]
        ]
    },
    265: {
        content: `# Dynamic Analysis (Sandboxing)

Execute the malware in a controlled environment and observe.

## Online Sandboxes
*   **Any.Run**: Interactive sandbox. You can click buttons, interact with the malware.
*   **Hybrid Analysis (Falcon Sandbox)**: Automated. Upload file, get report.
*   **Joe Sandbox**: Very detailed reports.
*   **VirusTotal Behavior**: Limited dynamic analysis, but free.

## What to Observe
1.  **Processes Created**: Did it spawn cmd.exe or powershell.exe?
2.  **Network Connections**: What IPs/domains did it call?
3.  **File System Changes**: What did it write? (e.g., dropped a second payload).
4.  **Registry Changes**: Did it add a Run key for persistence?
5.  **DNS Requests**: Did it resolve a suspicious domain?

## Anti-Sandbox Techniques
Malware may detect it's in a sandbox and refuse to run:
*   Checks VM artifacts (VirtualBox files, VMware processes).
*   Checks for user activity (mouse movement, open apps).
*   Sleeps for a long time (sandbox timeout).`,
        questions: [
            ['What is Any.Run used for?', 'Interactive malware sandboxing', 'Sandbox', ['Static analysis', 'Interactive malware sandboxing', 'Coding', 'Email']],
            ['If malware adds a "Run" registry key, what is it likely achieving?', 'Persistence (auto-start)', 'Persistence', ['Deleting files', 'Persistence (auto-start)', 'Playing music', 'Updating']],
            ['How might malware detect it is in a sandbox?', 'Looking for VM artifacts or lack of user activity', 'Evasion', ['By asking the user', 'Looking for VM artifacts or lack of user activity', 'By checking the calendar', 'By running fast']]
        ]
    },
    266: {
        content: `# Identifying IOCs from Malware

**IOC (Indicators of Compromise)** = Evidence that malware has interacted with a system.

## Types of IOCs from Malware Analysis
1.  **File Hashes**: MD5, SHA1, SHA256 of the malware sample (and any dropped files).
2.  **IP Addresses**: C2 servers the malware contacted.
3.  **Domains**: Domain names resolved by the malware.
4.  **URLs**: Specific URLs for payload download or C2 communication.
5.  **Registry Keys**: Keys created for persistence.
6.  **File Paths**: Where the malware copies itself (e.g., \`C:\\Users\\Public\\update.exe\`).
7.  **Mutex Names**: A unique string the malware creates to avoid running twice.

## Reporting IOCs
After analysis, you should produce a report with:
*   **Sample Metadata**: Filename, size, hashes.
*   **Verdict**: Malicious, Suspicious, Clean.
*   **IOC List**: All indicators extracted.
*   **MITRE ATT&CK** Mapping: What techniques did the malware use?`,
        questions: [
            ['What does IOC stand for?', 'Indicators of Compromise', 'Evidence', ['Internet of Computers', 'Indicators of Compromise', 'Input Output Control', 'Internal Office Command']],
            ['What is a "Mutex" in malware context?', 'A unique name to prevent multiple instances', 'Single instance', ['A virus type', 'A unique name to prevent multiple instances', 'A password', 'A file extension']],
            ['Which framework maps malware techniques?', 'MITRE ATT&CK', 'Tactics', ['NIST', 'MITRE ATT&CK', 'ISO 27001', 'PCI DSS']]
        ]
    },
    267: {
        content: `# Final Quiz

Test your understanding of Malware Analysis fundamentals.`,
        questions: [
            // Types
            ['Which malware hides deep in the OS to maintain persistent access?', 'Rootkit', 'Hidden', ['Worm', 'Trojan', 'Rootkit', 'Virus']],
            ['Which attack gives an attacker full remote control?', 'RAT (Remote Access Trojan)', 'Remote', ['Rootkit', 'Spyware', 'RAT (Remote Access Trojan)', 'Worm']],
            
            // Analysis Methods
            ['Running malware in a sandbox is called:', 'Dynamic Analysis', 'Execute', ['Static Analysis', 'Dynamic Analysis', 'Passive Analysis', 'Code Review']],
            ['Examining a file without executing it is:', 'Static Analysis', 'Safe', ['Dynamic Analysis', 'Static Analysis', 'Behavioral Analysis', 'Reverse Engineering']],
            
            // Tools & Techniques
            ['What does PEStudio analyze?', 'Windows PE (Executable) files', 'EXE', ['Linux binaries', 'Windows PE (Executable) files', 'Network packets', 'JSON files']],
            ['If malware "sleeps" for a long time, what might it be doing?', 'Evading sandbox analysis', 'Timeout', ['Updating', 'Evading sandbox analysis', 'Nothing suspicious', 'Downloading updates']]
        ]
    }
};

async function createModule26() {
    try {
        console.log('🚀 Creating Module 26: Malware Analysis Basics...\n');

        console.log(`Processing Module ${overview.id}: ${overview.title}`);
        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), learning_path_id = VALUES(learning_path_id)`, 
            [overview.id, overview.title, overview.description, 26, 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), is_active=1`,
                [t.id, overview.id, t.title, t.id]);
        }

        let totalLessons = 0;
        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', 15]);

            for (let j = 0; j < lesson.questions.length; j++) {
                const q = lesson.questions[j];
                const options = q[3] ? JSON.stringify(q[3]) : null;
                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], options, 0]);
            }
            totalLessons++;
        }

        console.log(`\n✅ Module 26 (Malware Analysis) Created! (${totalLessons} lessons)\n`);
        process.exit(0);

    } catch (error) {
        console.error('Error:', error);
        process.exit(1);
    }
}

createModule26();
