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

const overview = {
    id: 37,
    title: 'Memory Forensics',
    description: 'Analyze volatile memory to uncover malware, rootkits, and attacker artifacts.',
    learning_path_id: 4
};

const tasks = [
    { id: 371, title: 'Why Memory Forensics?' },
    { id: 372, title: 'Memory Acquisition Techniques' },
    { id: 373, title: 'Volatility Framework Deep Dive' },
    { id: 374, title: 'Process Analysis & Injection Detection' },
    { id: 375, title: 'Hunting Rootkits & Hidden Processes' },
    { id: 376, title: 'Final Quiz' }
];

const lessons = {
    371: {
        content: `# Why Memory Forensics?

Disk forensics misses what only lives in RAM.

## What Lives Only in Memory?
*   **Encryption Keys**: BitLocker, TrueCrypt keys decrypted in RAM.
*   **Fileless Malware**: Never touches disk, lives in process memory.
*   **Injected Code**: Shellcode in legitimate processes.
*   **Network Connections**: Active connections not logged elsewhere.
*   **Decrypted Data**: SSL/TLS session keys, decrypted payloads.
*   **User Credentials**: Plaintext passwords (Mimikatz targets).

## When to Capture Memory?
*   **Before shutdown**: RAM is volatile; power off = data lost.
*   **During live incident**: Capture before containment actions.
*   **Malware analysis**: Dump memory of infected VM.

## Limitations
*   **Size**: Memory can be 64GB+; large files to analyze.
*   **Volatility**: Changes constantly; capture is a snapshot.
*   **Anti-Forensics**: Attackers may detect and wipe on capture.`,
        questions: [
            ['Why is memory forensics critical for fileless malware?', 'Fileless malware never touches disk; only exists in RAM', 'Volatile', ['It is faster', 'Fileless malware never touches disk; only exists in RAM', 'Disk is encrypted', 'Memory is smaller']],
            ['When should you capture memory during an incident?', 'Before shutdown or containment actions', 'Early', ['After formatting', 'Before shutdown or containment actions', 'Next week', 'Never']],
            ['What happens to RAM when power is removed?', 'Data is lost (volatile memory)', 'Gone', ['Data is saved', 'Data is lost (volatile memory)', 'Data is compressed', 'Data is encrypted']]
        ]
    },
    372: {
        content: `# Memory Acquisition Techniques

Getting the memory dump is the first step.

## Live Acquisition (Preferred)
*   **Why live?**: System is running; capture volatile state.
*   **Tools**:
    *   **WinPMEM**: Open-source, kernel driver.
    *   **FTK Imager**: GUI-based, includes memory option.
    *   **DumpIt**: One-click executable.
    *   **LiME (Linux Memory Extractor)**: For Linux systems.

## Cold Boot Attack
*   RAM retains data briefly after power off (seconds to minutes with cooling).
*   Boot from USB, dump residual RAM.
*   Mostly academic; live acquisition is preferred.

## Hibernation File (hiberfil.sys)
*   Windows hibernation saves RAM to disk.
*   Can be converted to raw memory dump for analysis.

## Virtual Machine Snapshots
*   VMware \`.vmem\` files are memory dumps.
*   VirtualBox \`.sav\` files similarly contain RAM.

## Acquisition Best Practices
*   Run tool from external USB (avoid writing to evidence disk).
*   Calculate hash of memory dump immediately.
*   Document tool, version, timestamp.`,
        questions: [
            ['Which tool captures Linux memory?', 'LiME (Linux Memory Extractor)', 'Linux', ['WinPMEM', 'LiME (Linux Memory Extractor)', 'DumpIt', 'FTK Imager']],
            ['What is hiberfil.sys?', 'Windows hibernation file containing RAM contents', 'Sleep', ['A log file', 'Windows hibernation file containing RAM contents', 'A virus', 'A backup file']],
            ['Why run acquisition tool from external USB?', 'Avoid writing to evidence disk and altering it', 'Integrity', ['Faster speed', 'Avoid writing to evidence disk and altering it', 'USB is encrypted', 'No reason']]
        ]
    },
    373: {
        content: `# Volatility Framework Deep Dive

**Volatility** is the gold standard for memory analysis.

## Getting Started
\`\`\`bash
# Volatility 3 syntax
vol -f memory.dmp windows.info
vol -f memory.dmp windows.pslist
\`\`\`

## Essential Plugins
| Plugin | Purpose |
|--------|---------|
| \`windows.pslist\` | List processes (EPROCESS) |
| \`windows.psscan\` | Find hidden/unlinked processes |
| \`windows.cmdline\` | Command line arguments |
| \`windows.dlllist\` | DLLs loaded by process |
| \`windows.malfind\` | Find injected code |
| \`windows.netscan\` | Active network connections |
| \`windows.handles\` | Open handles (files, registry) |
| \`windows.filescan\` | Scan for FILE_OBJECT structures |
| \`windows.hashdump\` | Extract password hashes |

## Volatility 2 vs 3
*   **Vol2**: Python 2, profile-based (specify OS version).
*   **Vol3**: Python 3, auto-detects OS, plugin-based.

## Finding the Right Profile (Vol2)
\`\`\`bash
volatility -f memory.dmp imageinfo
# Returns suggested profiles like Win10x64_19041
\`\`\``,
        questions: [
            ['Which plugin finds hidden/unlinked processes?', 'psscan', 'Hidden', ['pslist', 'psscan', 'cmdline', 'dlllist']],
            ['What does malfind detect?', 'Injected code in process memory', 'Injection', ['Network connections', 'Injected code in process memory', 'File hashes', 'Passwords']],
            ['What is the difference between pslist and psscan?', 'pslist walks linked list; psscan scans all memory for process structs', 'Scan vs Walk', ['No difference', 'pslist walks linked list; psscan scans all memory for process structs', 'psscan is faster', 'pslist finds hidden processes']]
        ]
    },
    374: {
        content: `# Process Analysis & Injection Detection

Attackers hide in legitimate processes.

## Common Injection Techniques
*   **DLL Injection**: Load malicious DLL into target process.
*   **Process Hollowing**: Start suspended process, replace code.
*   **Reflective DLL Injection**: DLL loaded from memory, not disk.
*   **Thread Hijacking**: Hijack existing thread to run shellcode.

## Detection with Volatility

### 1. Compare pslist vs psscan
*   Process in psscan but not pslist? → Unlinked (hidden).

### 2. Check Parent-Child Relationships
*   \`svchost.exe\` parent should be \`services.exe\`.
*   \`cmd.exe\` spawned by \`winword.exe\`? → Suspicious.

### 3. Malfind for Injected Code
\`\`\`bash
vol -f memory.dmp windows.malfind
\`\`\`
*   Looks for memory regions with PAGE_EXECUTE_READWRITE that contain code.
*   MZ header (PE file) in unexpected memory? → Injected.

### 4. Hollowfind / Process Hollowing Detection
*   Compare on-disk executable to in-memory image.
*   Mismatch? → Hollowed.

## VAD (Virtual Address Descriptor) Analysis
*   VADs describe memory regions of a process.
*   Executable + writable + no associated file = Suspicious.`,
        questions: [
            ['What is Process Hollowing?', 'Starting a process suspended and replacing its code', 'Replace', ['Loading a DLL', 'Starting a process suspended and replacing its code', 'Killing a process', 'Debugging']],
            ['What memory protection is suspicious when combined with code?', 'PAGE_EXECUTE_READWRITE', 'RWX', ['PAGE_READONLY', 'PAGE_EXECUTE_READWRITE', 'PAGE_NOACCESS', 'PAGE_WRITECOPY']],
            ['How do you detect unlinked/hidden processes?', 'Compare pslist (linked) vs psscan (scanned)', 'Compare', ['Run antivirus', 'Compare pslist (linked) vs psscan (scanned)', 'Reboot', 'Check Task Manager']]
        ]
    },
    375: {
        content: `# Hunting Rootkits & Hidden Processes

Rootkits modify the OS to hide their presence.

## Rootkit Types
*   **User-mode**: Hooks API calls in user space.
*   **Kernel-mode**: Modifies kernel structures (DKOM, SSDT hooks).
*   **Bootkits**: Infect bootloader, load before OS.

## DKOM (Direct Kernel Object Manipulation)
*   Rootkit unlinks process from EPROCESS list.
*   \`pslist\` won't see it; \`psscan\` will.

## SSDT Hooking
*   **SSDT (System Service Descriptor Table)**: Maps syscalls to kernel functions.
*   Rootkit replaces pointers to intercept syscalls.
*   **Detection**: \`ssdt\` plugin shows hooked entries.

## Volatility Rootkit Detection Plugins
| Plugin | Purpose |
|--------|---------|
| \`windows.ssdt\` | Detect SSDT hooks |
| \`windows.callbacks\` | Registered kernel callbacks |
| \`windows.driverirp\` | IRP hooks in drivers |
| \`windows.modscan\` | Find hidden kernel modules |

## IOCs from Memory
*   Extract malicious DLLs: \`windows.dumpfiles\`.
*   Extract executables from VAD: \`windows.vadinfo\` + \`windows.dumpfiles\`.
*   Calculate hashes, submit to VirusTotal.`,
        questions: [
            ['What does DKOM stand for?', 'Direct Kernel Object Manipulation', 'Kernel', ['Dynamic Kernel Object Mode', 'Direct Kernel Object Manipulation', 'Driver Kernel Object Manager', 'None']],
            ['How does a rootkit hide a process using DKOM?', 'Unlinks the process from the EPROCESS linked list', 'Unlink', ['Deletes the executable', 'Unlinks the process from the EPROCESS linked list', 'Renames the process', 'Encrypts the process']],
            ['Which Volatility plugin detects SSDT hooks?', 'ssdt', 'Hooks', ['pslist', 'netscan', 'ssdt', 'malfind']]
        ]
    },
    376: {
        content: `# Final Quiz

Test your Memory Forensics skills.`,
        questions: [
            ['What type of malware only exists in RAM?', 'Fileless malware', 'Memory-only', ['Ransomware', 'Fileless malware', 'Worm', 'Trojan']],
            ['Which tool is used for Linux memory acquisition?', 'LiME', 'Linux', ['WinPMEM', 'DumpIt', 'LiME', 'FTK Imager']],
            ['What does malfind detect?', 'Injected code in process memory', 'Injection', ['Files', 'Injected code in process memory', 'Passwords', 'Network']],
            ['What is DKOM?', 'Direct Kernel Object Manipulation', 'Rootkit', ['Dynamic Kernel Mode', 'Direct Kernel Object Manipulation', 'Driver Object Manager', 'None']],
            ['pslist walks the linked list; psscan...', 'Scans all memory for process structures', 'Scan', ['Is the same', 'Scans all memory for process structures', 'Is faster', 'Only works on Linux']],
            ['What memory protection suggests injected code?', 'PAGE_EXECUTE_READWRITE', 'RWX', ['PAGE_READONLY', 'PAGE_EXECUTE_READWRITE', 'PAGE_GUARD', 'PAGE_NOACCESS']]
        ]
    }
};

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