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

// Define Modules and Tasks
const modules = [
    {
        id: 15,
        title: 'Introduction to IDS/IPS',
        description: 'Comprehensive guide to Intrusion Detection and Prevention Systems.',
        tasks: [
            { id: 77, title: 'IDS vs IPS: Architecture' },
            { id: 78, title: 'Detection Methodologies' },
            { id: 79, title: 'Network (NIDS) vs Host (HIDS)' },
            { id: 81, title: 'Zeek (Bro) Surveillance' },
            { id: 82, title: 'Alert Triage & Investigation' },
            { id: 83, title: 'Handling False Positives' }
        ]
    },
    {
        id: 16,
        title: 'Vulnerability Scanning',
        description: 'Master the Vulnerability Management Lifecycle.',
        tasks: [
            { id: 84, title: 'The Vulnerability Lifecycle' },
            { id: 85, title: 'Authenticated vs Unauthenticated' },
            { id: 86, title: 'Decoding CVSS Scores' },
            { id: 87, title: 'Nessus Operations' },
            { id: 88, title: 'Analyzing Scan Reports' },
            { id: 89, title: 'Patch Management Strategy' },
            { id: 90, title: 'Understanding CVEs' },
            { id: 91, title: 'Risk Response Strategies' },
            { id: 160, title: 'Module 16 Final Quiz' }
        ]
    },
    {
        id: 17,
        title: 'Web App Scanning (DAST)',
        description: 'Dynamic Application Security Testing deep dive.',
        tasks: [
            { id: 92, title: 'DAST Fundamentals' },
            { id: 93, title: 'OWASP Top 10 Deep Dive' },
            { id: 94, title: 'OWASP ZAP Mastery' },
            { id: 95, title: 'Advanced Spidering' },
            { id: 96, title: 'Active Scanning Mechanics' },
            { id: 97, title: ' Identifying DAST False Positives' },
            { id: 98, title: 'Effective Remediation Reporting' }
        ]
    }
];

// Content Map
const lessons = {
    // --- Module 15: IDS/IPS ---
    77: {
        content: `# IDS vs IPS: Architecture Deep Dive

Understanding the difference between **Detection** and **Prevention** is fundamental to network defense architecture.

## Intrusion Detection System (IDS)
An IDS is a visibility tool. Think of it as a security camera.
*   **Placement**: It is typically deployed **Out-of-Band** via a SPAN port (Port Mirroring) or a network TAP.
*   **Mechanism**: It receives a *copy* of the traffic. It does not sit in the direct line of communication.
*   **Failure Mode**: "Fail Open". If the IDS crashes or gets overloaded, the network traffic keeps flowing unimpeded. You just lose visibility.
*   **Use Case**: Monitoring, compliance, forensics, and networks where latency cannot be introduced.

## Intrusion Prevention System (IPS)
An IPS is a control tool. Think of it as a bouncer or a border guard.
*   **Placement**: It is deployed **Inline**. All traffic MUST pass through it to reach the destination.
*   **Mechanism**: It inspects packets in real-time. If a packet matches a block rule, the IPS drops it immediately.
*   **Failure Mode**: "Fail Closed" (or "Fail Open" depending on config). If an inline IPS fails, it can sever the internet connection for the entire building.
*   **Use Case**: Stopping exploits, blocking element malware command & control, protecting critical servers from known attacks.

## Critical Considerations
1.  **Latency**: IPS adds latency because every packet must be inspected before forwarding. IDS adds zero latency to the production link.
2.  **Risk of Blocking**: A false positive on an IDS creates an annoyance (an alert). A false positive on an IPS creates an outage (blocking legitimate business traffic).`,
        questions: [
            ['Which system is typically deployed "Inline"?', 'IPS', 'Intrusion Prevention', ['IDS', 'IPS', 'SIEM', 'TAP']],
            ['What happens if an Out-of-Band IDS crashes?', 'Traffic continues (Fail Open)', 'Loss of visibility only', ['Network outage', 'Traffic continues (Fail Open)', 'Firewall locks down', 'Servers reboot']],
            ['Why is IPS riskier than IDS?', 'Can block legitimate traffic', 'Business interruption', ['It is more expensive', 'It is slower', 'Can block legitimate traffic', 'It uses more power']]
        ]
    },
    78: {
        content: `# Detection Methodologies

How does the box know what "bad" looks like? There are two primary schools of thought.

## 1. Signature-Based Detection
This is the traditional method, similar to antivirus.
*   **How it works**: The vendor provides a database of known "signatures". A signature might be a specific hex string in a payload, a specific file hash, or a specific sequence of requests.
*   **Example**: "If a packet contains \`User-Agent: SqlMap\`, alert immediately."
*   **Pros**: Extremely fast, low CPU usage, VERY low false positive rate (if the rule is written well).
*   **Cons**: Completely blind to "Zero-Day" attacks or modified attacks. If the attacker changes one byte of the exploit, the signature might fail.

## 2. Anomaly-Based (Behavioral) Detection
This uses baselining and statistical models.
*   **How it works**: The system learns what "normal" is for your network (e.g., "The marketing server usually sends 50MB of data a day").
*   **The Alert**: If the marketing server suddenly sends 50GB of data to an IP in Russia, that is an **anomaly**.
*   **Pros**: Can detect brand new, never-before-seen attacks (Zero-Days) and data exfiltration.
*   **Cons**: High "False Positive" rate. Legitimate changes in business behavior (e.g., a new backup job) look like anomalies and trigger alerts.

## Hybrid Approach
Modern Next-Gen Firewalls (NGFW) and IDS use both. They use signatures for the easy stuff and anomaly detection for the complex threats.`,
        questions: [
            ['Which detection method is best for known threats?', 'Signature-Based', 'Fast and accurate', ['Anomaly-Based', 'Signature-Based', 'Heuristic', 'AI']],
            ['What is the main advantage of Anomaly detection?', 'Detecting Zero-Days', 'Unknown threats', ['Speed', 'Low cost', 'Detecting Zero-Days', 'Low false positives']],
            ['What triggers an anomaly alert?', 'Deviation from baseline', 'Unusual behavior', ['A signature match', 'A blacklisted IP', 'Deviation from baseline', 'A specific file hash']]
        ]
    },
    79: {
        content: `# Network (NIDS) vs Host (HIDS)

Defense in Depth requires monitoring both the wire and the endpoint.

## Network IDS (NIDS)
*   **Deployed**: At network choke points (Switch Core, Gateway, DMZ).
*   **Visibility**: Sees packet headers, payloads (if unencrypted), and flow data.
*   **Blind Spot**: **Encryption**. 80-90% of modern web traffic is HTTPS. A NIDS cannot see the payload of an HTTPS packet unless you configure "SSL Inspection" (Man-in-the-Middle), which is complex and resource-intensive.
*   **Tools**: Snort, Suricata, Zeek.

## Host IDS (HIDS)
*   **Deployed**: Agents installed directly on servers and workstations (e.g., Windows, Linux).
*   **Visibility**: It sits *after* the decryption happens. It can see:
    *   Decrypted logs.
    *   File Integrity (Did critical system files change?).
    *   Process Monitoring (Is powershell.exe spawning strange children?).
    *   Registry changes.
*   **Blind Spot**: It only sees the host it is installed on. It has no "big picture" of the network.
*   **Tools**: OSSEC, Wazuh, CrowdStrike (EDR/HIDS hybrid).

## The Winning Combo
You generally need both. NIDS for identifying lateral movement and scanning; HIDS for detecting malware execution and system modification.`,
        questions: [
            ['What is the major blind spot of NIDS today?', 'Encrypted Traffic (HTTPS)', 'Encryption', ['Speed', 'Encrypted Traffic (HTTPS)', 'UDP Packets', 'IPv6']],
            ['Where does HIDS sit in the encryption chain?', 'After decryption', 'On the host', ['Before encryption', 'After decryption', 'In the router', 'On the switch']],
            ['Which capability is unique to HIDS?', 'File Integrity Monitoring', 'FIM', ['Packet Capture', 'Flow Analysis', 'File Integrity Monitoring', 'DDoS Protection']]
        ]
    },
    81: {
        content: `# Zeek (Bro) Surveillance

**Zeek** (formerly Bro) is fundamentally different from Snort. While Snort looks for *signatures* of attacks, Zeek looks for *state* and generates *metadata*.

## The Transaction Log Model
Zeek turns network traffic into tab-separated ASCII logs. It effectively "summarizes" the network.

### conn.log (The most important log)
Every single network connection creates ONE entry in \`conn.log\`.
*   **uid**: Unique ID for the connection.
*   **id.orig_h**: Source IP.
*   **id.resp_h**: Dest IP.
*   **proto**: TCP/UDP.
*   **service**: HTTP, SSH, DNS, etc.
*   **duration**: How long it lasted.
*   **orig_bytes / resp_bytes**: How much data was moved.

### Why is this powerful?
If you see a connection in \`conn.log\` from an HR Laptop to a Russian IP on port 443 that lasted 4 hours and transferred 2GB of data:
*   **Snort** might be silent (if the traffic was encrypted and matched no malware signatures).
*   **Zeek** gives you the evidence of "Data Exfiltration" just by the metadata (Byte count + Location + Duration).

## Protocol Logs
*   **http.log**: Records every URL requested, User-Agent, Status Code.
*   **dns.log**: Records every DNS query and answer.
*   **software.log**: Zeek analyzes User-Agents to verify what software is running on your network (e.g., "Java 1.6", "Chrome 80").`,
        questions: [
            ['How does Zeek primarily store data?', 'Transaction Logs', 'Metadata', ['Full Packet Capture', 'Transaction Logs', 'SQL Database', 'Binary Blobs']],
            ['Which log file contains the volume of data transferred?', 'conn.log', 'Connection', ['files.log', 'conn.log', 'http.log', 'stats.log']],
            ['Can Zeek detect anomalies in encrypted traffic?', 'Yes (via metadata)', 'Byte counts', ['No', 'Yes (via metadata)', 'Only if decrypted', 'Never']]
        ]
    },
    82: {
        content: `# Alert Triage & Investigation

You are a SOC Analyst. The IDS dashboard just lit up. What do you do?

## The Triage Workflow

### Step 1: Validation (Is it real?)
Check the **Packet Capture (PCAP)** or the raw payload string.
*   *Alert*: "SQL Injection Detected"
*   *Payload*: \`uid=1' OR '1'='1\` -> **True Positive**.
*   *Payload*: \`Subject: How to fix SQL Injection\` (Email body) -> **False Positive**.

### Step 2: Contextualization (Did it work?)
Check the **Server Response**.
*   *Request*: \`GET /etc/passwd\`
*   *Response Code*: \`404 Not Found\` -> **Attempt Failed**. (Severity: Low).
*   *Response Code*: \`200 OK\` + Response Body contains "root:x:0:0" -> **SUCCESSFUL COMPROMISE**. (Severity: CRITICAL).
*   *Response Code*: \`500 Internal Error\` -> **Possible Denial of Service** or Blind Injection.

### Step 3: Scoping (Who else?)
*   Search the **Source IP**: Did they attack other servers?
*   Search the **Signature**: Did this attack hit other hosts from different IPs?

### Step 4: Remediation
*   Block the IP.
*   Isolate the victim host if compromised.`,
        questions: [
            ['What is the best way to tell if an attack succeeded?', 'Check the Server Response', 'Response Code', ['Check the Source IP', 'Check the Server Response', 'Check the Timestamp', 'Check the Rule ID']],
            ['If a payload appears in an email body triggering an alert, it is likely a?', 'False Positive', 'Context mismatch', ['True Positive', 'False Positive', 'Zero Day', 'Insider Threat']],
            ['A "404 Not Found" response generally indicates?', 'Attempt Failed', 'Target does not exist', ['Successful Hack', 'Attempt Failed', 'Server Offline', 'IDS Failure']]
        ]
    },
    83: {
        content: `# Handling False Positives

IDS/IPS requires constant maintenance. Tuned rules are effective; untuned rules are noise.

## Common Noise Sources
1.  **Vulnerability Scanners**: Your own Nessus scanner is *designed* to look like an attacker. It will trigger thousands of "SQL Injection" and "Port Scan" alerts.
    *   *Fix*: **Whitelisting** (Ignore traffic FROM the scanner IP).
2.  **Load Balancers**: Health checks often look like attacks or port scans.
3.  **High-Speed Transfers**: Large file backups can trigger "Denial of Service" heuristics.
4.  **Software Updates**: P2P updates (like Windows Delivery Optimization) can trigger "Botnet" signatures.

## Tuning Strategies
1.  **Disable the Rule**: If the rule is garbage (e.g., "Alert on all ICMP"), simply turn it off.
2.  **Suppress/Threshold**: "Only alert if this happens 10 times in 60 seconds."
3.  **Modify the Signature**: Make it more specific. Add \`http_uri\` or \`depth\` options to restrict where it looks.
4.  **IP Suppression**: "Alert on this rule, EXCEPT if Source IP is [Backup-Server]."`,
        questions: [
            ['What is the standard solution for internal scanners triggering alerts?', 'Whitelisting', 'Ignoring IP', ['Blocking them', 'Whitelisting', 'Counter-attacking', 'Disabling the IDS']],
            ['What technique limits alerts to "X times per minute"?', 'Thresholding', 'Suppression', ['Whitelisting', 'Thresholding', 'Dropping', 'Sampling']],
            ['Why might P2P updates trigger alerts?', 'Look like Botnet traffic', 'Behavior', ['They are viruses', 'Look like Botnet traffic', 'They are unencrypted', 'They are slow']]
        ]
    },

    // --- Module 16: Vulnerability Scanning ---
    84: {
        content: `# The Vulnerability Lifecycle

Vulnerability Management (VM) is not a "scan and done" process. It is a continuous lifecycle.

## 1. Discovery (Asset Management)
You cannot scan what you don't know exists.
*   **Shadow IT**: Servers spun up by developers without IT knowledge.
*   **Goal**: Find every live IP on the network.

## 2. Assessment (Scanning)
Running the actual tools (Nessus, Qualys, Rapid7) to identify CVEs.

## 3. Prioritization
You will have 10,000 findings. You can only fix 50 this week. Which 50?
*   Use CVSS scores.
*   Use Threat Intel (Is this vulnerability actually being exploited in the wild?).
*   Context (Is this server internet-facing or buried in a secure VLAN?).

## 4. Remediation
*   **Patch**: Apply the update.
*   **Configuration**: Change the setting (e.g., "Disable SSLv3").
*   **Retire**: Turn off the old server.

## 5. Verification
**Always re-scan.** IT might *say* they patched it, but the patch might have failed, or required a reboot that didn't happen.`,
        questions: [
            ['What is the first step before you can scan?', 'Discovery / Asset Management', 'Knowing what to scan', ['Remediation', 'Prioritization', 'Discovery / Asset Management', 'Reporting']],
            ['Why is "Verification" necessary after patching?', 'To ensure patch was applied correctly', 'Trust but verify', ['It isn\'t', 'To ensure patch was applied correctly', 'To double billing', 'To slow down IT']],
            ['What is "Shadow IT"?', 'Unknown/Unmanaged assets', 'Hidden servers', ['Hacker tools', 'Unknown/Unmanaged assets', 'Dark mode', 'VPNs']]
        ]
    },
    85: {
        content: `# Authenticated vs Unauthenticated

This is the most common point of confusion in VM.

## Unauthenticated Scan (External View)
The scanner acts like a stranger on the network.
*   It sends packets to ports (TCP 80, 443, 22).
*   It looks at **Banners**: "Server: Apache/2.4.49".
*   **Problem**: Banners lie. Security admins often hide versions or fake them ("Server: GoAway").
*   **Result**: High False Positives, Low Accuracy.

## Authenticated Scan (Credentialed View)
You give the scanner a Service Account (Username/Password).
*   The scanner attempts to log in via SSH (Linux) or SMB/WMI (Windows).
*   Once inside, it runs commands: \`rpm -qa\` or checks \`HKLM\\Software\\Microsoft\`.
*   It sees the **exact** installed KB versions and DLLs.
*   **Result**: 100% Accuracy (mostly) on missing patches. It is the Gold Standard.

## When to use which?
*   **External Perimeter**: Unauthenticated (simulate a hacker).
*   **Internal Compliance**: Authenticated (audit actual patch status).`,
        questions: [
            ['Which scan type is less accurate finding missing patches?', 'Unauthenticated', 'External', ['Authenticated', 'Unauthenticated', 'Agent-based', 'Internal']],
            ['How does an authenticated scan check for patches?', 'Logs in and checks files/registry', 'Commands', ['Guesses', 'Checks headers', 'Logs in and checks files/registry', 'Port scan']],
            ['What is a common issue with "Banner Grabbing"?', 'Banners can act or lie', 'Inaccurate', ['It causes crashes', 'Banners can act or lie', 'It requires passwords', 'It is too slow']]
        ]
    },
    86: {
        content: `# Decoding CVSS Scores

**CVSS (Common Vulnerability Scoring System)** is the industry standard for rating severity. You will usually see CVSS v3.1.

## The Vector String
A score comes from a string like: \`CVSS:3.1/AV:N/AC:L/PR:N/UI:N/S:U/C:H/I:H/A:H\`

### Base Metrics (The "Intrinsic" Properties)
1.  **Attack Vector (AV)**:
    *   **Network (N)**: Remotely exploitable (Wormable). **BAD**.
    *   **Local (L)**: Attacker needs physical access or login.
2.  **Attack Complexity (AC)**:
    *   **Low (L)**: Easy to pull off. **BAD**.
    *   **High (H)**: Requires race conditions or perfect timing.
3.  **Privileges Required (PR)**:
    *   **None (N)**: Any unauth user can exploit. **BAD**.
    *   **High (H)**: Only admins can exploit.
4.  **User Interaction (UI)**:
    *   **None (N)**: Happens automatically. **BAD**.
    *   **Required (R)**: Victim must click a link.
5.  **Scope (S)**:
    *   **Changed (C)**: Exploit on one component impacts others (VM escape). **BAD**.

## The CIA Triad Impact
*   **Confidentiality (C)**: Data leaked?
*   **Integrity (I)**: Data modifed?
*   **Availability (A)**: System crashed?`,
        questions: [
            ['What does "AV:N" stand for?', 'Attack Vector: Network', 'Remote', ['Attack Vector: None', 'Attack Vector: Network', 'Anti-Virus: None', 'Admin View: No']],
            ['Which metric indicates user interaction is NOT needed?', 'UI:N', 'Automatic', ['UI:R', 'UI:N', 'PR:N', 'AV:L']],
            ['A "Scope Change" (S:C) usually implies what?', 'Breaking out of sandbox/VM', 'Higher impact', ['Local only', 'Breaking out of sandbox/VM', 'Lower score', 'Network only']]
        ]
    },
    87: {
        content: `# Nessus Operations

**Tenable Nessus** is the scanner you will likely use.

## Deploying Scanners
*   **Nessus Professional**: A standalone scanner.
*   **Tenable.sc / Tenable.io**: The management console that controls many scanners.
*   **Zones**: You put a scanner inside each network segment (e.g., DMZ Scanner, Corp Scanner) so you don't scan through a firewall, which can block packets and slow down scanning.

## Policy Creation
You almost never run a "Default" scan.
1.  **Discovery**: "Host Discovery" (Ping sweep).
2.  **Basic Network Scan**: Checks common ports and services.
3.  **Advanced Scan**: Allows tuning timeouts and congestion.
4.  **Credentialed Patch Audit**: Focused solely on missing updates.

## Scanning Etiquette
*   **Notification**: Tell the NOC/SOC before you scan. Scans can knock over fragile legacy servers (especially printers and SCADA systems).
*   **Timing**: Scan workstations during the day (so they are on), scan Servers at night (to avoid load impact).`,
        questions: [
            ['Why should you place local scanners in each network segment?', 'To avoid scanning through firewalls', 'Efficiency', ['To waste money', 'To avoid scanning through firewalls', 'Because Nessus requires it', 'To use more IPs']],
            ['Which scan policy is best for solely finding live hosts?', 'Host Discovery', 'Ping sweep', ['Basic Network Scan', 'Web App Scan', 'Host Discovery', 'Malware Scan']],
            ['Why avoid scanning SCADA/Printers with aggressive policies?', 'They are fragile and can crash', 'Stability', ['They have no vulns', 'They are fragile and can crash', 'They are strictly read-only', 'Nessus cannot scan them']]
        ]
    },
    88: {
        content: `# Analyzing Scan Reports

A raw Nessus report is 100 pages of data. Your job is to make it readable.

## Filtering the Noise
1.  **Filter by Severity**: Focus on Critical and High first.
2.  **Filter by Exploitability**: Nessus has a flag "Exploit Available: Yes". This means there is a public script (Metasploit) that can hack this *right now*. **Prioritize these above all else.**

## Reading a Finding
Example: **"SSL Certificate Cannot Be Trusted"**
*   **Description**: The server's certificate is self-signed or expired.
*   **Risk**: Users might be MITM'd.
*   **Port**: 443/TCP.
*   **Solution**: Purchase a valid cert from a CA.

## VPR (Vulnerability Priority Rating)
Modern Tenable uses VPR. This modifies the CVSS score based on real-world threat intel.
*   *Old CVSS*: 9.8 (Critical).
*   *Real World*: This bug existed for 10 years and nobody uses it.
*   *VPR*: 5.0 (Medium).
*   **Benefit**: Reduces upgrade fatigue.`,
        questions: [
            ['If "Exploit Available" is Yes, what does that mean?', 'Hackable tools exist publicly', 'Urgent', ['It is theoretical', 'Hackable tools exist publicly', 'It is a zero-day', 'It involves money']],
            ['What does VPR add to the standard CVSS score?', 'Real-world threat context', 'Intel', ['Nothing', 'Real-world threat context', 'User opinion', 'Randomness']],
            ['What is the first filter you should typically apply?', 'Severity (Crit/High)', 'Triage', ['Low/Info', 'Severity (Crit/High)', 'Port 80', 'Name']]
        ]
    },
    89: {
        content: `# Patch Management Strategy

The scanner found the bugs. Now, Ops must fix them. This is often where conflict happens (Security vs Ops).

## The Patching Cycle
1.  **Release**: Vendor (Microsoft/Adobe) releases Patch Tuesday updates.
2.  **Test**: Ops deploys patches to a "Dev" group.
    *   *Goal*: Ensure the server reboots and the application (Exhange/SQL) starts.
3.  **Pilot**: Deploy to roughly 10% of users/servers.
4.  **Production**: Deploy to everyone.
5.  **Emergency**: For Zero-Days (Log4j), skip testing and deploy immediately (Break-Glass scenario).

## Rollback Plan
Always ask: "If this patch Blue Screens the server, how do we uninstall it?"
*   Snapshot VM before patching.
*   Have uninstall scripts ready.

## SLAs (Service Level Agreements)
Companies usually define required timelines:
*   Critical: 7 Days.
*   High: 30 Days.
*   Medium: 90 Days.`,
        questions: [
            ['What is a "Pilot" group in patching?', 'A small test subset of production', 'Canary', ['The IT team', 'A small test subset of production', 'The CEO', 'The printers']],
            ['Why might you skip testing for an "Emergency" patch?', 'Immediate exploitation risk', 'Zero Day', ['Too lazy', 'Immediate exploitation risk', 'Patches never fail', 'Vendor guarantee']],
            ['What allows you to recover if a patch kills a server?', 'Snapshots / Rollback Plan', 'Backup', ['Reinstalling OS', 'Snapshots / Rollback Plan', 'SLA', 'Vulnerability Scan']]
        ]
    },
    90: {
        content: `# Understanding CVEs

**CVE (Common Vulnerabilities and Exposures)** is a list of publicly disclosed cybersecurity flaws. It is maintained by MITRE.

## Format
**CVE-YYYY-NNNN**
*   **YYYY**: The year it was assigned.
*   **NNNN**: Unique ID.

## NVD (National Vulnerability Database)
The NVD is the US Government repository that adds metadata to the CVE (CVSS scores, affected software lists).

## CWE (Common Weakness Enumeration)
While CVE is a *specific* instance (e.g., "Buffer Overflow in Chrome v80"), **CWE** is the *category* of error (e.g., "CWE-119: Memory Corruption").
*   Developers study CWEs to learn how to write secure code.
*   Security Analysts track CVEs to patch specific systems.`,
        questions: [
            ['Who maintains the CVE list?', 'MITRE', 'Organization', ['Microsoft', 'MITRE', 'Google', 'NSA']],
            ['What is the difference between CVE and CWE?', 'CVE is specific instance, CWE is category', 'Instance vs Class', ['They are the same', 'CVE is for Windows, CWE for Linux', 'CVE is specific instance, CWE is category', 'CWE is a score']],
            ['What database adds scoring (CVSS) to the CVEs?', 'NVD', 'National Vuln DB', ['MITRE', 'OWASP', 'NVD', 'CISA']]
        ]
    },
    91: {
        content: `# Risk Response Strategies

You found a vulnerability. It cannot be patched. What now?

## 1. Remediation (Mitigation)
Fix the issue. Patch it, change the config, or add a firewall rule. This is the goal.

## 2. Transference
Shift the financial risk to someone else.
*   **Cyber Insurance**: If we get hacked, they pay.
*   **Outsourcing**: "We pay Amazon AWS to secure the physical servers."

## 3. Avoidance
Stop the activity that causes the risk.
*   "We are shutting down this legacy web server because it is too risky."

## 4. Acceptance
The business decides the profit is worth the risk.
*   *Scenario*: a $10M/year factory machine runs Windows XP. It cannot be upgraded.
*   *Action*: Leadership signs a "Risk Acceptance Form" acknowledging they understand they might get hacked.
*   *Constraint*: Must be reviewed annually. Usually requires **Compensating Controls** (e.g., Air-gapping the machine).`,
        questions: [
            ['Which strategy involves shutting down a risky system?', 'Avoidance', 'Stop activity', ['Acceptance', 'Transference', 'Avoidance', 'Mitigation']],
            ['Buying insurance is an example of?', 'Transference', 'Moving risk', ['Acceptance', 'Avoidance', 'Transference', 'Patching']],
            ['If you Accept a risk, what is usually required?', 'Compensating Controls / Sign-off', 'Paperwork', ['Nothing', 'Compensating Controls / Sign-off', 'Patching', 'Ignoring it']]
        ]
    },
    160: {
        content: `# Module 16 Final Quiz

This final test evaluates your understanding of the **Vulnerability Management** module.

## Instructions
*   This quiz contains **20 Questions**.
*   It covers all topics: Lifecycle, Authentication, CVSS, Nessus, Reporting, Patching, CVEs, and Risk.
*   There is no time limit, but try to answer without looking up the answers.

## Key Concepts Reviewed
*   **Lifecycle**: Discovery -> Assessment -> Prioritization -> Remediation -> Verification.
*   **CVSS**: Base metrics (AV, AC, PR, UI, S, C, I, A).
*   **Scans**: Auth vs Unauth, Internal vs External.
*   **Reports**: Filter by Severity and Exploitability.
*   **Remediation**: Patches, Workarounds, and Risk Acceptance.

Good Luck!`,
        questions: [
            // Lifecycle & Basics
            ['What is the verified first step in the Vulnerability Management Lifecycle?', 'Asset Discovery', 'Finding the machines', ['Remediation', 'Asset Discovery', 'Scanning', 'Reporting']],
            ['Why is "Verification" critical after patching?', 'To ensure the patch actually fixed the issue', 'Trust but verify', ['It increases billable hours', 'To ensure the patch actually fixed the issue', 'To verify the server is fast', 'It is not critical']],
            ['What term describes unknown/unmanaged systems on a network?', 'Shadow IT', 'Hidden', ['Dark Web', 'Shadow IT', 'Hidden Services', 'Honeypots']],

            // Auth vs Unauth
            ['Which scan type allows the scanner to log into the target?', 'Authenticated Scan', 'Credentialed', ['Unauthenticated Scan', 'Stealth Scan', 'Authenticated Scan', 'Passive Scan']],
            ['Which scan is better for an accurate inventory of installed software?', 'Authenticated Scan', 'Registry access', ['Unauthenticated Scan', 'Port Scan', 'Authenticated Scan', 'Ping Sweep']],
            ['What is the main drawback of relying on "Banner Grabbing"?', 'Banners can be fake or suppressed', 'Accuracy', ['It is illegal', 'Banners can be fake or suppressed', 'It crashes servers', 'It takes too long']],
            
            // CVSS
            ['In CVSS, what does "AV:N" indicate?', 'Attack Vector: Network', 'Remote', ['Attack Vector: None', 'Attack Vector: Network', 'Anti-Virus: None', 'Available: No']],
            ['Which CVSS metric measures if the attacker needs someone to click a link?', 'User Interaction (UI)', 'Interaction', ['Privileges Required (PR)', 'Attack Complexity (AC)', 'User Interaction (UI)', 'Scope (S)']],
            ['A "Scope Change" (S:C) in CVSS means expecting what?', 'Impact extending beyond the vulnerable component', 'VM Escape', ['Impact extending beyond the vulnerable component', 'Scope is confidential', 'System crash', 'No impact']],

            // Nessus & Operations
            ['Where should you place a scanner to avoid firewall interference?', 'In the same network segment/zone as the target', 'Local', ['On the internet', 'In the same network segment/zone as the target', 'In the DMZ only', 'On a distinct VLAN']],
            ['Which scan policy determines if a host is simply alive?', 'Host Discovery', 'Ping', ['Basic Network Scan', 'Host Discovery', 'Malware Scan', 'Web App Scan']],
            ['Why do we avoid aggressive scans on SCADA/ICS systems?', 'They are fragile and may crash', 'Availability', ['They are secure by default', 'They are fragile and may crash', 'They are mostly air-gapped', 'Nessus cannot see them']],

            // Reports & Patching
            ['What is the most important attribute when prioritizing patches?', 'Exploitability (Is there a script?)', 'Risk', ['CVSS Score only', 'Alphabetical Order', 'Exploitability (Is there a script?)', 'Vendor Name']],
            ['What does Tenable VPR add to the analysis?', 'Real-time threat context', 'Prediction', ['Nothing', 'Real-time threat context', 'Color coding', 'PDF export']],
            ['What is an "Emergency" patch typically reserved for?', 'Zero-Day exploits', 'Log4j scenario', ['Routine updates', 'Feature releases', 'Zero-Day exploits', 'UI fixes']],
            ['Why must you have a "Rollback Plan" before patching?', 'To recover if the patch breaks the server', 'Safety', ['To uninstall viruses', 'To recover if the patch breaks the server', 'Compliance requires it', 'It is optional']],

            // CVEs & Risk
            ['Who maintains the official CVE list?', 'MITRE', 'The list owner', ['NIST', 'MITRE', 'Microsoft', 'Google']],
            ['What is the difference between CVE and CWE?', 'CVE is the specific flaw, CWE is the category', 'Instance vs Type', ['They are identical', 'CVE is for software, CWE for hardware', 'CVE is the specific flaw, CWE is the category', 'CWE is the score']],
            ['If you cannot patch a system, but isolate it with a firewall, this is called?', 'Remediation (Mitigation)', 'Compensating Control', ['Acceptance', 'Remediation (Mitigation)', 'Transference', 'Avoidance']],
            ['Buying Cyber Insurance is an example of which risk strategy?', 'Transference', 'Shifting costs', ['Avoidance', 'Acceptance', 'Transference', 'Mitigation']]
        ]
    },


    // --- Module 17: Web App Scanning (DAST) ---
    92: {
        content: `# DAST Fundamentals

**DAST (Dynamic Application Security Testing)** evaluates an application by attacking it while it is running.

## White Box vs Black Box
*   **SAST (Static - White Box)**: Looks at the source code. "This variable isn't sanitized."
*   **DAST (Dynamic - Black Box)**: Looks at the behavior. "I sent a quote to the input and the database crashed."

## How DAST works
1.  **Crawl**: Finds every page and form.
2.  **Audit**: Injects thousands of payloads (SQLi, XSS, Path Traversal) into every input.
3.  **Analyze**: Checks HTTP response for signs of success (reflected payload, error messages, time delays).

## Pros & Cons
*   **Pro**: Low false positives compared to SAST. It finds things that are actually exploitable.
*   **Pro**: Technology agnostic. It attacks Java, Python, and PHP exactly the same way.
*   **Con**: Late in the pipeline. You only find bugs after the app is built.`,
        questions: [
            ['Does DAST require source code access?', 'No (Black Box)', 'Dynamic', ['Yes', 'No (Black Box)', 'Sometimes', 'Only for Javascript']],
            ['Which testing method happens "running" against a live app?', 'DAST', 'Dynamic', ['SAST', 'DAST', 'Unit Testing', 'Linting']],
            ['Why is DAST considered "Technology Agnostic"?', 'HTTP is universal', 'Attacks inputs', ['It knows all languages', 'HTTP is universal', 'It compiles code', 'It uses AI']]
        ]
    },
    93: {
        content: `# OWASP Top 10 Deep Dive

The **OWASP Top 10** is the standard awareness document for web security.

## A01: Broken Access Control
Users acting outside of their permissions.
*   *Example*: Changing \`id=10\` to \`id=11\` in the URL and seeing someone else's account.

## A02: Cryptographic Failures
Previously "Sensitive Data Exposure".
*   *Example*: Storing passwords in plain text, using old algorithms (MD5), or transmitting data over HTTP.

## A03: Injection
*   *Example*: SQL Injection, Command Injection, LDAP Injection.
*   *Defense*: Use Parameterized Queries.

## A07: Identification and Authentication Failures
*   *Example*: allowing "admin / admin" default credentials, or not implementing Multi-Factor Auth (MFA).`,
        questions: [
            ['Which vulnerability category covers IDOR (Insecure Direct Object Reference)?', 'Broken Access Control', 'Permissions', ['Injection', 'Broken Access Control', 'Cryptographic Failures', 'Logging Failures']],
            ['What is the best defense against Injection?', 'Parameterized Queries', 'Prepared Statements', ['Firewalls', 'Parameterized Queries', 'Encryption', 'Antivirus']],
            ['Storing passwords in plain text falls under which category?', 'Cryptographic Failures', 'Crypto', ['Injection', 'Cryptographic Failures', 'Access Control', 'Design Flaws']]
        ]
    },
    94: {
        content: `# OWASP ZAP Mastery

**ZAP (Zed Attack Proxy)** is the world's most popular free DAST tool.

## Key Modes
1.  **Desktop UI**: For manual penetration testing and complex configuration.
2.  **HUD (Heads Up Display)**: Injects ZAP controls directly into your browser (Firefox) so you can hack while you browse.
3.  **Docker/CI**: ZAP can be run headless in a Jenkins pipeline to scan code automatically on commit.

## Contexts & Scope
**Critical**: You must define **Contexts**.
*   This tells ZAP "Only attack \`example.com\`".
*   If you don't define scope, ZAP might follow a link to \`google.com\` or \`facebook.com\` and start attacking them! (This is illegal).

## Add-ons
ZAP has a marketplace.
*   *Fuzzers*: Advanced payload lists.
*   *Retire.js*: Checks Javascript libraries for old versions.`,
        questions: [
            ['What feature prevents ZAP from attacking the entire internet?', 'Scope / Contexts', 'Limits', ['Firewall', 'Scope / Contexts', 'VPN', 'Cables']],
            ['What is the ZAP HUD?', 'Browser overlay for testing', 'UI', ['A report format', 'Browser overlay for testing', 'A CI pipeline', 'A virus']],
            ['Can ZAP be integrated into CI/CD pipelines?', 'Yes (Headless/Docker)', 'Automation', ['No, GUI only', 'Yes (Headless/Docker)', 'Only on Windows', 'Cost extra']]
        ]
    },
    95: {
        content: `# Advanced Spidering

Use standard spidering for static sites. Use **AJAX Spider** for modern apps.

## The Problem with "Modern" Web
In the old days, every click loaded a new URL (\`/page1.html\`, \`/page2.html\`).
Today, React/Angular/Vue apps are **Single Page Applications (SPAs)**.
*   You click a button, Javascript fetches data, and changes the text. The URL might stay the same (or use a hash \`#\`).
*   A traditional spider sees 1 page.
*   An **AJAX Spider** launches a headless browser (Firefox/Chrome), clicks every button, renders the DOM, and captures the traffic.
*   NOTE: AJAX Spiders are slower but necessary for React/Vue apps.

## Robots.txt
Spiders check \`robots.txt\`.
*   *White Hat*: Respects "Disallow: /admin".
*   *Black Hat*: Uses it as a map to find the secret "/admin" folder.`,
        questions: [
            ['Why do traditional spiders fail on React apps?', 'Content loads via JS/DOM', 'SPA', ['React is secure', 'Content loads via JS/DOM', 'URLs are encrypted', 'Firewalls block them']],
            ['What does an AJAX spider use to crawl?', 'A headless browser', 'Rendering', ['Curl', 'Wget', 'A headless browser', 'Guessing']],
            ['How might an attacker use robots.txt?', 'To find hidden/disallowed paths', 'Recon', ['To obey rules', 'To find hidden/disallowed paths', 'To crash server', 'To find emails']]
        ]
    },
    96: {
        content: `# Active Scanning Mechanics

Active Scanning is where the "Attack" happens.

## The Payloads
ZAP/Burp creates thousands of requests.
*   **Time-Based SQLi**: \`WAITFOR DELAY '0:0:5'\` (It measures if the server pauses for 5 seconds).
*   **Reflected XSS**: \`<script>alert(1)</script>\` (It checks if the HTML response contains this exact string).
*   **Path Traversal**: \`../../../../etc/passwd\` (It checks if the response contains "root:x:0").

## Danger Zone
Active scanning can:
1.  **Delete Data**: If it spiders a "Delete User" link, it will click it.
2.  **Flood Email**: If it spiders a "Contact Us" form, it will submit it 500 times.
3.  **Lock Accounts**: If it attacks a login page, it will trigger the "5 failed attempts" lockout policy.

**Best Practice**: Never scan Prod. Scan a Staging environment with dummy data.`,
        questions: [
            ['Why is Active Scanning risky in Production?', 'Can delete data or cause DoS', 'Destructive', ['It is slow', 'Can delete data or cause DoS', 'It costs money', 'It is illegal in Prod']],
            ['How does a Time-Based SQLi test verify the vuln?', 'Measures server delay', 'Timing', ['Checks error text', 'Measures server delay', 'Crashing server', 'Downloading DB']],
            ['If a scanner hits a "Contact Us" form, what happens?', 'Floods inbox with junk', 'Spam', ['Nothing', 'Floods inbox with junk', 'Hacks email', 'Server reboots']]
        ]
    },
    97: {
        content: `# Identifying DAST False Positives

DAST tools are "guessers". They are often wrong.

## Common FP Scenarios
1.  **Reflected Input (Not XSS)**:
    *   *Scan*: Sends \`<script>\`.
    *   *Server*: Responds \`Your search for <script> found 0 results\`.
    *   *Tool*: "XSS Found!"
    *   *Reality*: The server set the header \`Content-Type: text/plain\` or used output encoding. The script will render as text, not code. **False Positive**.
2.  **Custom 404s**:
    *   *Scan*: Requests \`/admin/..//../etc/passwd\`.
    *   *Server*: Returns a custom "Page Not Found" page (Status 200 OK).
    *   *Tool*: "File Inclusion Found!" (Because it got a 200 OK instead of a 404). **False Positive**.

## Verification
You **must** confirm findings with \`curl\` or Repeater before reporting them. Manual validation is the mark of a pro.`,
        questions: [
            ['If a payload appears in the response, is it always XSS?', 'No, headers/encoding matter', 'False Positive', ['Yes', 'No, headers/encoding matter', 'Only in Chrome', 'Never']],
            ['Why do Custom 404 pages confuse scanners?', 'They return 200 OK status', 'Status Code', ['They are hidden', 'They return 200 OK status', 'They are slow', 'They are encrypted']],
            ['What defines a professional analyst reporting DAST results?', 'Manual Verification', 'Curating', ['Copy-Pasting', 'Manual Verification', 'Ignoring Lows', 'Running in background']]
        ]
    },
    98: {
        content: `# Effective Remediation Reporting

Developers fix bugs. You just find them. If your report is bad, the bug stays.

## The Golden Rules
1.  **No PDF Dumps**: Do not email a 500-page XML export.
2.  **Proof of Concept (PoC)**: "Paste this URL into the browser to see the alert box."
3.  **Risk Explanation**: Don't just say "XSS". Say "An attacker can steal customer session cookies."
4.  **Code Tracing (Hybrid)**: If you have access to code, point to the file: "See \`login.php\` line 42."

## Prioritization
Group vulnerabilities.
*   Instead of "100 XSS Vulnerabilities", report "**Systemic lack of output encoding** in the search module."

## Conclusion
The goal of DAST is not a clean report; it is a clean application.`,
        questions: [
            ['What is better than reporting 100 individual bugs?', 'Reporting the systemic root cause', 'Grouping', ['Reporting 1000 bugs', 'Reporting the systemic root cause', 'Ignoring them', 'Quitting']],
            ['What helps a developer understand "Why" they should fix it?', 'Risk Explanation', 'Impact', ['CVSS Score', 'Risk Explanation', 'Manager threats', 'Compliance laws']],
            ['What is a "PoC" in reporting?', 'Proof of Concept (Reproduction steps)', 'Evidence', ['Point of Contact', 'Proof of Concept (Reproduction steps)', 'Piece of Code', 'Priority of Criticality']]
        ]
    }
};


async function createModules15to17() {
    try {
        console.log('🚀 Creating Expanded Modules 15, 16, 17...\n');

        for (const mod of modules) {
            console.log(`Processing Module ${mod.id}: ${mod.title}`);
            // Update Module
            await db.query(`UPDATE modules SET title = ?, description = ? WHERE id = ?`, 
                [mod.title, mod.description, mod.id]);

            // Update/Verify Tasks
            for (const t of mod.tasks) {
                await db.query(`INSERT INTO tasks (id, module_id, title, is_active, display_order) VALUES (?, ?, ?, 1, ?) ON DUPLICATE KEY UPDATE title = VALUES(title), is_active=1`,
                    [t.id, mod.id, t.title, t.id]);
            }
        }

        let totalLessons = 0;
        // Populate Lessons
        for (const [idStr, lesson] of Object.entries(lessons)) {
            const taskId = parseInt(idStr);
            // Clean
            await db.query('DELETE FROM lesson_content WHERE task_id = ?', [taskId]);
            await db.query('DELETE FROM lesson_questions WHERE task_id = ?', [taskId]);

            // Insert Content
            await db.query('INSERT INTO lesson_content (task_id, content, content_type, reading_time_minutes) VALUES (?, ?, ?, ?)',
                [taskId, lesson.content, 'markdown', 15]); // Increased reading time

            // Insert Questions
            // Removed Math.min(..., 3) limit to allow unlimited questions for the quiz
            for (let j = 0; j < lesson.questions.length; j++) {
                const q = lesson.questions[j];
                const options = q[3] ? JSON.stringify(q[3]) : null;
                await db.query('INSERT INTO lesson_questions (task_id, question_text, correct_answer, question_order, hint, options, case_sensitive) VALUES (?, ?, ?, ?, ?, ?, ?)',
                    [taskId, q[0], q[1], j + 1, q[2], options, 0]);
            }
            totalLessons++;
        }

        console.log(`\n✅ Deep-Dive Modules 15-17 Created! (${totalLessons} lessons)\n`);
        process.exit(0);

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

createModules15to17();
