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

const overview = {
    id: 29,
    title: 'Network Traffic Analysis',
    description: 'Learn to capture and analyze network packets for threat detection.',
    learning_path_id: 4
};

const tasks = [
    { id: 291, title: 'Why Analyze Network Traffic?' },
    { id: 292, title: 'Packet Capture Fundamentals' },
    { id: 293, title: 'Wireshark Essentials' },
    { id: 294, title: 'Analyzing TCP/HTTP Traffic' },
    { id: 295, title: 'Detecting Malicious Traffic' },
    { id: 296, title: 'Zeek (Bro) for Network Logs' },
    { id: 297, title: 'Final Quiz' }
];

const lessons = {
    291: {
        content: `# Why Analyze Network Traffic?

**Network Traffic Analysis (NTA)** is inspecting packets flowing through your network to detect threats.

## Use Cases
*   **Threat Detection**: Find C2 beacons, data exfiltration.
*   **Incident Investigation**: "What did the attacker download?"
*   **Troubleshooting**: "Why is the server slow?"
*   **Compliance**: Audit network activity.

## What You Can See
*   **Source/Destination IPs**: Who is talking to whom.
*   **Ports**: What services are being used.
*   **Protocol**: HTTP, DNS, SMB, etc.
*   **Payload**: The actual data (if not encrypted).

## Limitations
*   **Encryption (TLS)**: Payload is hidden.
*   **Volume**: Capturing everything generates massive data.
*   **Privacy**: May capture sensitive user data.`,
        questions: [
            ['What does NTA stand for?', 'Network Traffic Analysis', 'NTA', ['Network Threat Assessment', 'Network Traffic Analysis', 'New Technology Application', 'None']],
            ['What limits your ability to see packet content?', 'Encryption (TLS)', 'Hidden', ['Speed', 'Encryption (TLS)', 'Color', 'Size']],
            ['What can you determine from packet headers?', 'Source/Destination IPs and ports', 'Metadata', ['File contents', 'Source/Destination IPs and ports', 'Passwords', 'Nothing']]
        ]
    },
    292: {
        content: `# Packet Capture Fundamentals

## How Packets are Captured
1.  **Network Tap**: Hardware device that copies all traffic.
2.  **Port Mirroring (SPAN)**: Switch sends a copy of traffic to a monitoring port.
3.  **Host-Based**: Capture on the endpoint itself (tcpdump, Wireshark).

## PCAP Format
**PCAP (Packet Capture)** is the standard file format for captured packets.
*   **.pcap**: Original format (libpcap).
*   **.pcapng**: Next Generation (supports more metadata).

## Key Tools
*   **tcpdump**: CLI packet capture on Linux.
*   **Wireshark**: GUI packet analysis.
*   **tshark**: CLI version of Wireshark.
*   **NetworkMiner**: Extracts files from pcaps.

## Example: Capture with tcpdump
\`\`\`bash
sudo tcpdump -i eth0 -w capture.pcap -c 1000
\`\`\`
*   \`-i eth0\`: Capture on interface eth0.
*   \`-w capture.pcap\`: Write to file.
*   \`-c 1000\`: Stop after 1000 packets.`,
        questions: [
            ['What is a SPAN port?', 'A switch port that mirrors traffic for monitoring', 'Mirror', ['A special cable', 'A switch port that mirrors traffic for monitoring', 'A firewall rule', 'An IP address']],
            ['What file format stores captured packets?', 'PCAP', 'Packet file', ['PDF', 'PCAP', 'DOCX', 'MP4']],
            ['Which tool is a GUI for packet analysis?', 'Wireshark', 'GUI', ['tcpdump', 'Wireshark', 'grep', 'nmap']]
        ]
    },
    293: {
        content: `# Wireshark Essentials

**Wireshark** is the most popular network protocol analyzer.

## Key Features
*   **Live Capture**: Capture packets in real-time.
*   **Filtering**: Display only relevant packets.
*   **Dissectors**: Decode protocols (HTTP, DNS, SMB).
*   **Follow Stream**: Reconstruct TCP conversations.

## Display Filters (Essential)
| Filter | Purpose |
|--------|---------|
| \`ip.addr == 192.168.1.1\` | Traffic to/from IP |
| \`tcp.port == 80\` | HTTP traffic |
| \`http.request\` | HTTP requests only |
| \`dns\` | DNS queries/responses |
| \`tcp.flags.syn == 1\` | SYN packets (connection starts) |
| \`frame contains "password"\` | Search for keyword |

## Right-Click Magic
*   **Follow > TCP Stream**: See the conversation.
*   **Export Objects > HTTP**: Extract downloaded files.
*   **Apply as Filter**: Quick filtering.`,
        questions: [
            ['What Wireshark feature reconstructs a conversation?', 'Follow TCP Stream', 'Conversation', ['Export', 'Follow TCP Stream', 'Filter', 'Capture']],
            ['What is a "Display Filter" used for?', 'Showing only relevant packets', 'Focus', ['Capturing packets', 'Showing only relevant packets', 'Deleting packets', 'Encrypting packets']],
            ['Which filter shows only DNS traffic?', 'dns', 'Protocol', ['tcp', 'udp', 'dns', 'http']]
        ]
    },
    294: {
        content: `# Analyzing TCP/HTTP Traffic

## The TCP Handshake
\`\`\`
Client              Server
  |---- SYN ---->    |   (Step 1: Request connection)
  |<--- SYN+ACK ----|   (Step 2: Acknowledge + confirm)
  |---- ACK ---->    |   (Step 3: Connection established)
\`\`\`
*   **Filter**: \`tcp.flags.syn == 1 && tcp.flags.ack == 0\` (Find new connections)

## HTTP Analysis
*   **Request**: \`GET /index.html HTTP/1.1\`
*   **Response**: \`HTTP/1.1 200 OK\`

## Suspicious HTTP Indicators
*   Long User-Agent strings (buffer overflow attempts).
*   Unusual HTTP methods (PROPFIND, CONNECT).
*   Encoded payloads in URLs (\`%3C%3E\` = \`<>\`).
*   HTTP on weird ports (8080, 8888).

## Extracting Files
*   **File > Export Objects > HTTP**: Lists all files transferred.
*   Useful for extracting malware samples.`,
        questions: [
            ['What is the first step of the TCP handshake?', 'SYN', 'Start', ['ACK', 'FIN', 'SYN', 'RST']],
            ['How can you extract files from HTTP traffic in Wireshark?', 'Export Objects > HTTP', 'File extraction', ['Copy paste', 'Export Objects > HTTP', 'Print', 'Screenshot']],
            ['What might a very long User-Agent string indicate?', 'Buffer overflow attempt', 'Attack', ['Normal traffic', 'Buffer overflow attempt', 'Slow browser', 'Mobile device']]
        ]
    },
    295: {
        content: `# Detecting Malicious Traffic

## Indicators of Malicious Activity
1.  **Beaconing**: Regular, timed connections (C2 heartbeat).
2.  **DNS Tunneling**: Very long subdomains, high query volume.
3.  **Large Data Transfers**: Unexpected outbound data.
4.  **Known-Bad IPs/Domains**: Match against Threat Intelligence.
5.  **Unusual Ports**: SSH on port 443, HTTP on 22.
6.  **Self-Signed Certificates**: Common for C2 servers.

## Example: Detecting C2
\`\`\`
Filter: dns.qry.name contains "dga" or tcp.dstport == 4444
\`\`\`
*   Port 4444 is default for Metasploit/Meterpreter.
*   DGA (Domain Generation Algorithm) creates random-looking domains.

## PCAP Challenge
If you see:
*   Regular 60-second intervals to the same IP.
*   Small packets outbound, larger responses.
*   Self-signed cert.

**Verdict**: Likely C2 Beacon.`,
        questions: [
            ['What is "Beaconing"?', 'Regular, timed connections to a C2 server', 'Heartbeat', ['Random traffic', 'Regular, timed connections to a C2 server', 'Fast traffic', 'Encrypted traffic']],
            ['Why is port 4444 suspicious?', 'Default Metasploit/Meterpreter port', 'Known bad', ['It is slow', 'Default Metasploit/Meterpreter port', 'It is encrypted', 'It is common']],
            ['What does DGA stand for?', 'Domain Generation Algorithm', 'Random domains', ['Data Gathering API', 'Domain Generation Algorithm', 'Dynamic Gateway Access', 'Direct Gateway Address']]
        ]
    },
    296: {
        content: `# Zeek (Bro) for Network Logs

**Zeek** (formerly Bro) is a powerful network analysis framework.

## Zeek vs Wireshark
*   **Wireshark**: Deep packet inspection, GUI, interactive.
*   **Zeek**: Generates logs, automated, scriptable, better for large volumes.

## Zeek Logs
Zeek creates structured logs for each protocol:
*   **conn.log**: All connections (source, dest, ports, bytes).
*   **dns.log**: DNS queries and responses.
*   **http.log**: HTTP requests (method, URI, user-agent).
*   **ssl.log**: TLS connections (certificate info).
*   **files.log**: Files transferred.

## Example: conn.log Entry
\`\`\`
ts              orig_h        orig_p   resp_h        resp_p   proto   service   duration   bytes
1609459200.0    192.168.1.10  54321    8.8.8.8       53       udp     dns       0.1        100
\`\`\`

## Use Case
*   Feed Zeek logs into a SIEM for correlation and alerting.`,
        questions: [
            ['What was Zeek formerly known as?', 'Bro', 'Old name', ['Wireshark', 'Bro', 'tcpdump', 'Snort']],
            ['Which Zeek log tracks all network connections?', 'conn.log', 'Connections', ['http.log', 'dns.log', 'conn.log', 'ssl.log']],
            ['How is Zeek different from Wireshark?', 'Zeek generates structured logs, better for automation', 'Logs', ['Zeek has GUI', 'Zeek generates structured logs, better for automation', 'Zeek is slower', 'No difference']]
        ]
    },
    297: {
        content: `# Final Quiz

Test your Network Traffic Analysis skills.`,
        questions: [
            ['What tool is used for command-line packet capture on Linux?', 'tcpdump', 'CLI', ['Wireshark', 'tcpdump', 'Nmap', 'Netcat']],
            ['Which Wireshark filter shows HTTP requests?', 'http.request', 'HTTP', ['tcp.port', 'http.request', 'dns', 'frame']],
            ['What is the TCP handshake sequence?', 'SYN, SYN-ACK, ACK', 'Three-way', ['ACK, SYN, FIN', 'SYN, SYN-ACK, ACK', 'FIN, ACK, RST', 'None']],
            ['What does beaconing traffic indicate?', 'Possible C2 communication', 'Malware', ['Normal browsing', 'Possible C2 communication', 'File download', 'Email']],
            ['Which Zeek log tracks DNS queries?', 'dns.log', 'DNS', ['conn.log', 'http.log', 'dns.log', 'files.log']],
            ['What file format stores captured packets?', 'PCAP', 'Capture', ['CSV', 'PCAP', 'JSON', 'XML']]
        ]
    }
};

async function createModule() {
    try {
        console.log('🚀 Creating Module 29: Network Traffic Analysis...\n');
        console.log(`Processing Module ${overview.id}: ${overview.title}`);
        await db.query(`INSERT INTO modules (id, title, description, display_order, learning_path_id) VALUES (?, ?, ?, ?, ?) ON DUPLICATE KEY UPDATE title = VALUES(title), description = VALUES(description), learning_path_id = VALUES(learning_path_id)`, 
            [overview.id, overview.title, overview.description, overview.id, overview.learning_path_id]);
        for (const t of tasks) {
            await db.query(`INSERT INTO tasks (id, module_id, title, is_active, display_order) VALUES (?, ?, ?, 1, ?) ON DUPLICATE KEY UPDATE title = VALUES(title), module_id = VALUES(module_id), is_active=1`,
                [t.id, overview.id, t.title, t.id]);
        }
        for (const [idStr, lesson] of Object.entries(lessons)) {
            const taskId = parseInt(idStr);
            await db.query('DELETE FROM lesson_content WHERE task_id = ?', [taskId]);
            await db.query('DELETE FROM lesson_questions WHERE task_id = ?', [taskId]);
            await db.query('INSERT INTO lesson_content (task_id, content, content_type, reading_time_minutes) VALUES (?, ?, ?, ?)',
                [taskId, lesson.content, 'markdown', 15]);
            for (let j = 0; j < lesson.questions.length; j++) {
                const q = lesson.questions[j];
                const options = q[3] ? JSON.stringify(q[3]) : null;
                await db.query('INSERT INTO lesson_questions (task_id, question_text, correct_answer, question_order, hint, options, case_sensitive) VALUES (?, ?, ?, ?, ?, ?, ?)',
                    [taskId, q[0], q[1], j + 1, q[2], options, 0]);
            }
        }
        console.log(`✅ Module 29 Created!\n`);
        process.exit(0);
    } catch (error) {
        console.error('Error:', error);
        process.exit(1);
    }
}
createModule();
