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

async function updateLessonContent(taskId, title, content) {
    try {
        await db.query('UPDATE lesson_content SET content = ? WHERE task_id = ?', [content, taskId]);
        console.log(`✅ Updated: [${taskId}] ${title}`);
    } catch (error) {
        console.error(`❌ Error updating [${taskId}] ${title}:`, error.message);
    }
}

const lessons = [
    {
        id: 354,
        title: "Identifying Beaconing",
        content: `# 📡 Identifying Beaconing

Malware must "phone home" to receive commands. This periodic check-in is called a beacon.

## 📝 The Raw Log (Suricata/Zeek)

\`\`\`json
{
  "timestamp": "2024-03-15T12:00:00Z",
  "src_ip": "192.168.1.105",
  "dest_ip": "45.33.2.1",
  "proto": "TCP",
  "service": "http",
  "host": "api.weather-updates.xyz",
  "uri": "/sync/status?id=49201",
  "bytes_out": 450,
  "bytes_in": 1200,
  "flow_duration": 20
}
\`\`\`
*(This exact log repeats every 60 seconds +/- 2 seconds)*

## 🕵️‍♂️ Investigation Steps

### Step 1: Check Temporal Pattern
* **Filter**: \`src_ip=192.168.1.105 AND dest_ip=45.33.2.1\`.
* **Visualize**: Look at a timeline graph.
* **Result**: You see rigid spikes every 1 minute. Humans are random; machines are precise.

### Step 2: Analyze the Domain
* **Domain**: \`api.weather-updates.xyz\`.
* **Reputation**: Check VirusTotal/UrlScan.
* **Age**: Created 2 days ago? Suspicious.

### Step 3: Payload Size
* **Bytes**: Identical size (450 bytes) every time. Likely a "heartbeat" message ("I'm alive, nothing to report").
`
    },
    {
        id: 355,
        title: "Data Exfiltration Detection",
        content: `# 📤 Data Exfiltration Detection

The "smash and grab". Attackers stealing your database.

## 📝 The Raw Log (Netflow)

\`\`\`text
Start Time          Src IP          Dst IP          Proto   Bytes Out    Bytes In
---------------------------------------------------------------------------------
14:00:22            10.10.50.5      104.22.1.5      TCP     4,500,000,000  500
\`\`\`

## 🕵️‍♂️ Investigation Steps

### Step 1: The Ratio
* **Bytes Out**: 4.5 GB.
* **Bytes In**: 500 Bytes.
* **Analysis**: This is a massive UPLOAD.

### Step 2: The Destination
* **IP**: \`104.22.1.5\`.
* **Whois**: Is it Dropbox? Google Drive? Or an unknown VPS in a foreign country?
* even if it is Google Drive, is this \`Finance-Server\` authorized to talk to cloud storage?

### Step 3: Protocol Analysis
* If this was over **UDP Port 53** (DNS), it's a guaranteed breach (DNS Tunneling). DNS packets should be tiny.
`
    },
    {
        id: 356,
        title: "Analyzing PCAP Files",
        content: `# 🦈 Analyzing PCAP Files

Sometimes logs aren't enough. You need the full packet capture.

## 📝 The Raw Data (HTTP Stream)

\`\`\`http
GET /images/logo.png.exe HTTP/1.1
Host: business-supply.com
User-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64)
Accept: */*

HTTP/1.1 200 OK
Content-Type: application/octet-stream
Content-Length: 40960

MZ......................@.............................................
\`\`\`

## 🕵️‍♂️ Investigation Steps

### Step 1: The Request
* **URL**: \`/images/logo.png.exe\`.
* **Trick**: Double extension! The user likely saw \`logo.png\` but Windows hid the \`.exe\`.

### Step 2: The Response (Magic Bytes)
* **Header**: \`MZ\` (4D 5A).
* **Meaning**: This is the file signature for a **Windows Executable**.
* **Analysis**: The server claimed it sent an image, but it sent a program.

### Step 3: Extraction
* In Wireshark: **File > Export Objects > HTTP**.
* Save the file (in a sandbox!).
* Hash it and check VirusTotal.
`
    },
    {
        id: 357,
        title: "Detecting C2 Traffic",
        content: `# 💀 Detecting C2 Traffic

Command and Control (C2) is how the hacker controls the botnet.

## 📝 The Raw Log (Proxy Log)

\`\`\`text
10.0.0.5 - - [15/Mar/2024:14:22:01] "GET /search?q=base64_encoded_command HTTP/1.1" 200 450 "Mozilla/4.0"
10.0.0.5 - - [15/Mar/2024:14:22:05] "POST /submit_results HTTP/1.1" 200 20 "Mozilla/4.0"
\`\`\`

## 🕵️‍♂️ Investigation Steps

### Step 1: User Agent
* **Value**: \`Mozilla/4.0\`.
* **Issue**: This is ANCIENT (Internet Explorer 6 era). Modern Chrome is Mozilla/5.0. Barely anything legitimate uses 4.0 anymore. This is a default setting in some malware kits.

### Step 2: The Conversation
* **GET**: The bot asks "What should I do?"
* **POST**: The bot executes the command and sends results back.

### Step 3: Decode
* Take the \`q\` parameter value (if logged) and Base64 decode it.
* \`d2hvYW1p\` -> \`whoami\`.
`
    },
    {
        id: 358,
        title: "Firewall Log Analysis",
        content: `# 🔥 Firewall Log Analysis

The firewall is the bouncer.

## 📝 The Raw Log (Cisco ASA)

\`\`\`text
%ASA-4-106023: Deny tcp src outside:103.4.9.1/4444 dst inside:192.168.1.20/3389 by access-group "OUTSIDE_IN"
%ASA-4-106023: Deny tcp src outside:103.4.9.1/4444 dst inside:192.168.1.20/3389 by access-group "OUTSIDE_IN"
... (Repeats 500 times)
\`\`\`

## 🕵️‍♂️ Investigation Steps

### Step 1: Direction
* **Source**: Outside (Internet).
* **Dest**: Inside (Internal).
* **Action**: **Deny**.
* **Analysis**: The firewall is doing its job.

### Step 2: Port Analysis
* **Dst Port**: 3389 (RDP - Remote Desktop).
* **Significance**: The attacker is brute-forcing RDP. DO NOT OPEN RDP TO THE INTERNET.

### Step 3: Pivot
* Check your VPN logs for this IP (\`103.4.9.1\`).
* Did they manage to authenticate anywhere else?
* **Block**: Add this IP to your blocklist/Blackhole.
`
    }
];

// Execute Updates
(async () => {
    console.log('🚀 Updating Module 2 (Network) with Raw Logs...');
    for (const lesson of lessons) {
        await updateLessonContent(lesson.id, lesson.title, lesson.content);
    }
    console.log('✨ Module 2 Update Complete.');
    process.exit(0);
})();
