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

async function createModules456() {
    try {
        console.log('Creating Modules 4, 5, and 6 lessons...\n');

        // =====MODULE 4: Introduction to SOC Operations (Tasks 19-23) =====
        console.log('=== MODULE 4: SOC Operations ===\n');

        // Task 19: SIEM Basics
        const task19 = `# SIEM Basics - Security Information and Event Management

SIEM platforms are the central nervous system of a SOC, collecting and correlating security events from across your infrastructure.

## What is SIEM?

Combines:
- **SIM** (Security Information Management) - Log collection and storage
- **SEM** (Security Event Management) - Real-time monitoring and alerting

## Popular SIEM Platforms

- **Splunk** - Industry leader, powerful but expensive
- **Elastic Stack (ELK)** - Open source, flexible
- **QRadar** - IBM enterprise solution
- **Microsoft Sentinel** - Cloud-native Azure SIEM
- **ArcSight** - HP enterprise platform

## Key SIEM Functions

### 1. Log Collection
Gathers logs from:
- Firewalls
- Servers
- Endpoints
- Applications
- Network devices

### 2. Normalization
Converts different log formats into standardized format for analysis.

### 3. Correlation
Links related events across different sources to detect patterns.

### 4. Alerting
Triggers notifications when suspicious activity detected.

## Basic SIEM Query (Splunk SPL)

\`\`\`spl
index=security sourcetype=firewall 
| stats count by src_ip 
| where count > 100
\`\`\`

## SOC Analyst Daily Tasks

- Review SIEM alerts
- Investigate suspicious events
- Create new detection rules
- Update dashboards
- Document incidents`;

        await db.query('INSERT INTO lesson_content (task_id, content, content_type, reading_time_minutes) VALUES (?, ?, ?, ?)',
            [19, task19, 'markdown', 9]);

        const task19Q = [
            [19, 'Log correlation platform?', 'SIEM', 1, 'Security monitoring', 0],
            [19, 'Industry leader SIEM?', 'Splunk', 2, 'Most popular', 0],
            [19, 'Open source SIEM?', 'Elastic Stack', 3, 'ELK stack', 0],
            [19, 'SIEM query language?', 'SPL', 4, 'Search Processing Language', 0],
            [19, 'Microsoft cloud SIEM?', 'Sentinel', 5, 'Azure native', 0]
        ];
        for (const q of task19Q) {
            await db.query('INSERT INTO lesson_questions (task_id, question_text, correct_answer, question_order, hint, case_sensitive) VALUES (?, ?, ?, ?, ?, ?)', q);
        }
        console.log('✓ Task 19: SIEM Basics\n');

        // Task 20: Log Analysis
        const task20 = `# Log Analysis Fundamentals

Logs are the detective's notebook of cybersecurity. Learning to analyze them effectively is crucial for SOC analysts.

## Common Log Sources

### System Logs (Linux)
- \`\`\`/var/log/syslog\`\`\` - General system messages
- \`\`\`/var/log/auth.log\`\`\` - Authentication attempts
- \`\`\`/var/log/apache2/access.log\`\`\` - Web server logs

### Windows Event Logs
- Security Log (Event ID 4624 = successful login)
- System Log
- Application Log

### Network Logs
- Firewall logs
- IDS/IPS alerts
- DNS queries

## Key Log Fields

- **Timestamp** - When did it happen?
- **Source IP** - Who initiated?
- **Destination IP** - Where did it go?
- **User** - Which account?
- **Action** - What happened?
- **Result** - Success or failure?

## Log Analysis Techniques

### Baselining
Understand normal behavior to spot anomalies.

### Time-based Analysis
Look for patterns:
- After-hours activity
- Rapid succession of events
- Geographic anomalies

### Correlation
Connect events across different sources:
\`\`\`
Failed login (firewall) 
→ VPN connection (VPN log) 
→ File access (file server log)
\`\`\`

## Red Flags in Logs

🚨 Multiple failed logins from same IP
🚨 Successful login after many failures
🚨 Access from unusual locations
🚨 Large data transfers
🚨 Service account activity at odd hours
🚨 Privilege escalation attempts

## Example: Failed Login Analysis

\`\`\`
Dec 25 03:42:15 Failed password for admin from 203.0.113.44
Dec 25 03:42:17 Failed password for admin from 203.0.113.44
Dec 25 03:42:19 Failed password for admin from 203.0.113.44
Dec 25 03:42:21 Accepted password for admin from 203.0.113.44
\`\`\`

**Analysis:** Brute force attack succeeded after 3 attempts. Investigate immediately!`;

        await db.query('INSERT INTO lesson_content (task_id, content, content_type, reading_time_minutes) VALUES (?, ?, ?, ?)',
            [20, task20, 'markdown', 8]);

        const task20Q = [
            [20, 'Linux auth log?', '/var/log/auth.log', 1, 'Authentication attempts', 0],
            [20, 'Successful login event?', '4624', 2, 'Windows Event ID', 0],
            [20, 'Understanding normal behavior?', 'Baselining', 3, 'Establish normal', 0],
            [20, 'Multiple failed logins?', 'Brute force', 4, 'Password attack', 0],
            [20, 'General Linux log?', 'syslog', 5, 'System messages', 0]
        ];
        for (const q of task20Q) {
            await db.query('INSERT INTO lesson_questions (task_id, question_text, correct_answer, question_order, hint, case_sensitive) VALUES (?, ?, ?, ?, ?, ?)', q);
        }
        console.log('✓ Task 20: Log Analysis\n');

        // Task 21: Alert Triage
        const task21 = `# Alert Triage and Investigation

SOCs generate hundreds of alerts daily. Effective triage separates critical incidents from false positives.

## Alert Triage Process

### 1. Initial Review (30 seconds)
- Alert severity
- Source system
- Affected asset
- Quick decision: Investigate or close?

### 2. Context Gathering (2-5 minutes)
- User information
- Asset criticality
- Recent related alerts
- Baseline behavior

### 3. Investigation (5-30 minutes)
- Review logs
- Check threat intelligence
- Analyze indicators
- Determine true/false positive

### 4. Response Decision
- Escalate to Tier 2/3
- Create incident ticket
- Close as false positive
- Add to watchlist

## Alert Severity Levels

**Critical** - Immediate action required
- Active breach detected
- Ransomware encryption
- Data exfiltration

**High** - Investigate within 1 hour
- Malware detection
- Suspicious PowerShell
- Lateral movement

**Medium** - Investigate within 4 hours
- Policy violations
- Unusual access patterns
- Port scans

**Low** - Investigate within 24 hours
- Minor policy violations
- Benign anomalies

## Common False Positives

- Legitimate admin activity
- Scanning by security tools
- Software updates triggering alerts
- Known safe IPs flagged

## Investigation Checklist

✓ Check user's recent activity
✓ Verify asset is online
✓ Review related alerts
✓ Check threat intelligence feeds
✓ Examine raw logs
✓ Determine business context
✓ Document findings

## Time Management

**Don't spend 30 minutes on a low-priority alert when critical alerts are waiting!**

Prioritize:
1. Critical/Active threats
2. High-value assets
3. Recent alerts
4. Clear indicators of compromise`;

        await db.query('INSERT INTO lesson_content (task_id, content, content_type, reading_time_minutes) VALUES (?, ?, ?, ?)',
            [21, task21, 'markdown', 7]);

        const task21Q = [
            [21, 'First alert review time?', '30 seconds', 1, 'Quick initial check', 0],
            [21, 'Active breach severity?', 'Critical', 2, 'Highest priority', 0],
            [21, 'Investigate high alerts when?', '1 hour', 3, 'Time window', 0],
            [21, 'Legitimate activity flagged?', 'False positive', 4, 'Not a real threat', 0],
            [21, 'Alert classification process?', 'Triage', 5, 'Initial sorting', 0]
        ];
        for (const q of task21Q) {
            await db.query('INSERT INTO lesson_questions (task_id, question_text, correct_answer, question_order, hint, case_sensitive) VALUES (?, ?, ?, ?, ?, ?)', q);
        }
        console.log('✓ Task 21: Alert Triage\n');

        // Task 22: Malware Analysis Basics
        const task22 = `# Malware Analysis Basics

Understanding malware behavior is essential for SOC analysts to respond effectively to threats.

## Types of Malware

### Viruses
- Attaches to files
- Spreads when file is executed
- Requires user interaction

### Worms
- Self-replicating
- Spreads automatically
- No user interaction needed

### Trojans
- Disguised as legitimate software
- Creates backdoor access
- Example: Remote Access Trojan (RAT)

### Ransomware
- Encrypts files
- Demands payment
- Examples: WannaCry, Ryuk

### Spyware
- Monitors user activity
- Steals credentials
- Keyloggers

### Rootkits
- Hides malware presence
- OS-level access
- Very difficult to detect

## Analysis Approaches

### Static Analysis
- Examine file without running it
- Hash checksums (MD5, SHA256)
- Strings extraction
- Check VirusTotal

### Dynamic Analysis
- Run in isolated sandbox
- Monitor behavior
- Network connections
- File system changes

## Indicators of Compromise (IOCs)

**File-based:**
- File hashes (SHA256)
- File names
- File paths

**Network-based:**
- IP addresses
- Domain names
- URLs
- Email addresses

**Registry keys** (Windows)
**Mutexes** (Unique identifiers)

## Basic Analysis Tools

**VirusTotal** - Multi-engine malware scanner
\`\`\`
Upload file or provide hash
Check detection rate
\`\`\`

**Strings (Linux)**
\`\`\`bash
strings malware.exe | grep -i http
\`\`\`

**File hash**
\`\`\`bash
sha256sum suspicious_file.exe
\`\`\`

## Safety First!

⚠️ **Never analyze malware on production systems!**

✅ Use isolated lab VMs
✅ Disconnect from network
✅ Take snapshots before analysis
✅ Use sandbox environments`;

        await db.query('INSERT INTO lesson_content (task_id, content, content_type, reading_time_minutes) VALUES (?, ?, ?, ?)',
            [22, task22, 'markdown', 9]);

        const task22Q = [
            [22, 'Self-replicating malware?', 'Worm', 1, 'Spreads automatically', 0],
            [22, 'File encryption malware?', 'Ransomware', 2, 'Demands payment', 0],
            [22, 'Analysis without execution?', 'Static analysis', 3, 'Safe examination', 0],
            [22, 'Multi-scanner service?', 'VirusTotal', 4, 'Online checker', 0],
            [22, 'Compromise indicators?', 'IOCs', 5, 'Threat evidence', 0]
        ];
        for (const q of task22Q) {
            await db.query('INSERT INTO lesson_questions (task_id, question_text, correct_answer, question_order, hint, case_sensitive) VALUES (?, ?, ?, ?, ?, ?)', q);
        }
        console.log('✓ Task 22: Malware Analysis\n');

        // Task 23: SOC Tools and Workflows
        const task23 = `# SOC Tools and Workflows

Modern SOCs rely on integrated tool stacks to detect, investigate, and respond to threats efficiently.

## Core SOC Tool Categories

### 1. SIEM (Central Hub)
- Splunk, Elastic, QRadar
- Log aggregation and correlation
- Primary investigation platform

### 2. EDR (Endpoint Detection)
- CrowdStrike Falcon
- SentinelOne
- Microsoft Defender
- Carbon Black

### 3. Threat Intelligence
- MISP - Malware Information Sharing
- AlienVault OTX
- Threat feeds

### 4. Ticketing System
- ServiceNow
- Jira
- TheHive

### 5. SOAR (Security Orchestration)
- Automates repetitive tasks
- Incident response playbooks
- Integration hub

## Typical SOC Workflow

**Morning:**
1. Review overnight alerts (30 min)
2. Check security dashboards
3. Read threat intelligence reports

**During Day:**
4. Investigate alerts as they arrive
5. Escalate incidents to Tier 2
6. Document findings in tickets
7. Update detection rules
8. Collaborate with team

**End of Day:**
9. Handoff open cases to next shift
10. Update shift notes
11. Review metrics

## Alert Investigation Workflow

\`\`\`
Alert Received
    ↓
Initial Triage (Is it real?)
    ↓
Context Gathering (User, Asset, History)
    ↓
Log Analysis (What happened?)
    ↓
Threat Intel Check (Known bad?)
    ↓
Decision:
    ├→ False Positive (Close)
    ├→ Benign Anomaly (Monitor)
    ├→ Confirmed Threat (Escalate)
    └→ Need More Info (Investigate Further)
\`\`\`

## Communication Tools

- **Slack/Teams** - Team chat
- **Email** - External communication
- **Conference calls** - Major incidents
- **War rooms** - Critical response

## Documentation Best Practices

✅ Document everything
✅ Use timestamps
✅ Include screenshots
✅ Note all actions taken
✅ Link related tickets

## Handoff Checklist

When ending shift:
- Update all open tickets
- Note investigation status
- Highlight urgent items
- Share context with next analyst`;

        await db.query('INSERT INTO lesson_content (task_id, content, content_type, reading_time_minutes) VALUES (?, ?, ?, ?)',
            [23, task23, 'markdown', 8]);

        const task23Q = [
            [23, 'Endpoint detection tool?', 'EDR', 1, 'Endpoint Detection Response', 0],
            [23, 'Incident ticket system?', 'ServiceNow', 2, 'ITSM platform', 0],
            [23, 'Security automation platform?', 'SOAR', 4, 'Orchestration tool', 0],
            [23, 'Threat sharing platform?', 'MISP', 3, 'Malware Information Sharing', 0],
            [23, 'First triage step?', 'Is it real', 5, 'True or false positive', 0]
        ];
        for (const q of task23Q) {
            await db.query('INSERT INTO lesson_questions (task_id, question_text, correct_answer, question_order, hint, case_sensitive) VALUES (?, ?, ?, ?, ?, ?)', q);
        }
        console.log('✓ Task 23: SOC Tools\n');
        console.log('✅ Module 4 complete!\n');

        // ===== MODULE 5: Threat Intelligence (Tasks 24-28) =====
        console.log('=== MODULE 5: Threat Intelligence ===\n');

        // Task 24: Threat Intelligence Fundamentals
        const task24 = `# Threat Intelligence Fundamentals

Threat Intelligence transforms raw data about threats into actionable insights that improve your security posture.

## What is Threat Intelligence?

Evidence-based knowledge about existing or emerging threats that helps organizations make informed security decisions.

## Types of Threat Intelligence

### 1. Strategic
- **Audience:** Executives, board members
- **Focus:** High-level trends, risks
- **Format:** Reports, briefs
- **Example:** "Ransomware targeting healthcare increased 300%"

### 2. Operational
- **Audience:** SOC managers
- **Focus:** Threat actor TTPs (Tactics, Techniques, Procedures)
- **Format:** Campaign analysis
- **Example:** "APT29 using COVID-themed phishing"

### 3. Tactical
- **Audience:** SOC analysts, defenders
- **Focus:** IOCs (Indicators of Compromise)
- **Format:** IP lists, hashes, domains
- **Example:** "Block these 50 malicious IPs"

### 4. Technical
- **Audience:** Incident responders
- **Focus:** Detailed malware analysis
- **Format:** Technical reports
- **Example:** "Trojan X uses port 8443 for C2"

## Threat Intelligence Lifecycle

1. **Planning** - Define requirements
2. **Collection** - Gather data from sources
3. **Processing** - Normalize and organize
4. **Analysis** - Find patterns and meaning
5. **Dissemination** - Share with stakeholders
6. **Feedback** - Refine based on use

## Common Sources

**Open Source (OSINT):**
- VirusTotal
- AlienVault OTX
- Abuse.ch
- MITRE ATT&CK

**Commercial:**
- CrowdStrike Intelligence
- Recorded Future
- Mandiant Threat Intelligence

**Community:**
- ISACs (Information Sharing Centers)
- Peer organizations
- Forums

## Using Threat Intelligence

✓ Block known malicious IPs
✓ Create detection rules
✓ Prioritize vulnerabilities
✓ Inform training programs
✓ Guide security investments`;

        await db.query('INSERT INTO lesson_content (task_id, content, content_type, reading_time_minutes) VALUES (?, ?, ?, ?)',
            [24, task24, 'markdown', 9]);

        const task24Q = [
            [24, 'IOC intelligence type?', 'Tactical', 1, 'Actionable indicators', 0],
            [24, 'Executive intelligence type?', 'Strategic', 2, 'High-level trends', 0],
            [24, 'Threat actor framework?', 'MITRE ATT&CK', 3, 'TTPs database', 0],
            [24, 'Free threat feed?', 'AlienVault OTX', 4, 'Open Threat Exchange', 0],
            [24, 'Compromise indicators?', 'IOCs', 5, 'Threat evidence', 0]
        ];
        for (const q of task24Q) {
            await db.query('INSERT INTO lesson_questions (task_id, question_text, correct_answer, question_order, hint, case_sensitive) VALUES (?, ?, ?, ?, ?, ?)', q);
        }
        console.log('✓ Task 24: Threat Intelligence\n');

        // Due to length, creating remaining tasks more concisely...
        // Task 25-28 and Module 6 tasks will follow same pattern

        console.log('\n✅ Modules 4-5 initial tasks created\n');
        console.log('Creating remaining tasks...\n');

        // Quick batch for remaining tasks (25-31)
        const remainingTasks = [
            // Module 5 continued
            {
                id: 25, title: 'MITRE ATT&CK Framework', content: `# MITRE ATT&CK Framework

The industry-standard knowledge base of adversary tactics and techniques.

## What is ATT&CK?

**A**dversarial **T**actics, **T**echniques, and **C**ommon **K**nowledge

## The 14 Tactics

1. **Reconnaissance** - Gather info about target
2. **Resource Development** - Establish infrastructure
3. **Initial Access** - Get into network
4. **Execution** - Run malicious code
5. **Persistence** - Maintain foothold
6. **Privilege Escalation** - Gain higher privileges
7. **Defense Evasion** - Avoid detection
8. **Credential Access** - Steal passwords
9. **Discovery** - Learn about environment
10. **Lateral Movement** - Move through network
11. **Collection** - Gather data
12. **Command and Control** - Communication
13. **Exfiltration** - Steal data
14. **Impact** - Disrupt operations

## Using ATT&CK

- Map detections to techniques
- Identify coverage gaps
- Threat hunting priorities
- Red team exercises

## Example Technique

**T1566.001 - Phishing: Spearphishing Attachment**

Detection: Email with suspicious attachment`,
                questions: [
                    ['ATT&CK full form?', 'Adversarial Tactics Techniques', 'Threat framework'],
                    ['First tactic?', 'Reconnaissance', 'Info gathering'],
                    ['Password stealing tactic?', 'Credential Access', 'Steal accounts'],
                    ['Moving through network?', 'Lateral Movement', 'Spread internally'],
                    ['Data theft tactic?', 'Exfiltration', 'Steal data']
                ]
            },
            {
                id: 26, title: 'Indicators of Compromise', content: `# Indicators of Compromise (IOCs)

Artifacts that indicate a potential security breach.

## Types of IOCs

### Network IOCs
- IP addresses
- Domain names
- URLs
- Email addresses

### File IOCs
- MD5/SHA256 hashes
- File names
- File sizes
- Registry keys (Windows)

### Behavioral IOCs
- Unusual login times
- Large data transfers
- Privilege escalation
- Unexpected processes

## IOC Formats

**STIX** - Structured Threat Information Expression
**OpenIOC** - Open Indicators of Compromise
**YARA** - Pattern matching rules

## Using IOCs

\`\`\`
1. Receive IOC from threat feed
2. Search SIEM for matches
3. If found → Investigate
4. Block at firewall/EDR
5. Document findings
\`\`\`

## IOC Sharing

- ThreatConnect
- MISP
- AlienVault OTX
- ISACs`,
                questions: [
                    ['Network compromise indicator?', 'IP address', 'Malicious source'],
                    ['File identifier?', 'Hash', 'SHA256 fingerprint'],
                    ['Threat expression standard?', 'STIX', 'Structured format'],
                    ['Pattern matching rules?', 'YARA', 'Malware detection'],
                    ['IOC sharing platform?', 'MISP', 'Community sharing']
                ]
            },
            {
                id: 27, title: 'Threat Hunting', content: `# Proactive Threat Hunting

Actively searching for threats that evade existing security tools.

## What is Threat Hunting?

Proactive, hypothesis-driven search for threats hiding in your environment.

## Hunt Methodologies

### Hypothesis-Based
"I believe attackers are using PowerShell for lateral movement"

### IOC-Based
Search for known bad indicators

### Analytics-Based
Use machine learning to find anomalies

## Hunt Process

1. **Hypothesis** - What are you looking for?
2. **Investigation** - Search logs, endpoints
3. **Pattern Analysis** - Find anomalies
4. **Discovery** - Confirm threat or benign
5. **Response** - Contain if threat found
6. **Enrichment** - Improve detections

## Common Hunt Scenarios

🔍 Unusual PowerShell usage
🔍 Rare external connections
🔍 Service account anomalies
🔍 File creation in suspicious locations
🔍 Network beaconing patterns

## Tools

- SIEM queries
- EDR telemetry
- Packet captures
- Memory forensics

## Hunt Metrics

- Hunts per week
- Threats discovered
- New detections created
- Mean time to discover`,
                questions: [
                    ['Proactive threat search?', 'Threat hunting', 'Active searching'],
                    ['Hunt methodology?', 'Hypothesis-based', 'Theory-driven'],
                    ['Regular C2 communication?', 'Beaconing', 'Periodic callbacks'],
                    ['Suspicious script language?', 'PowerShell', 'Windows automation'],
                    ['Hunt data source?', 'EDR telemetry', 'Endpoint data']
                ]
            },
            {
                id: 28, title: 'Threat Intelligence Platforms', content: `# Threat Intelligence Platforms (TIP)

Centralized systems for managing threat intelligence at scale.

## What is a TIP?

Platform that aggregates, correlates, and manages threat intelligence from multiple sources.

## Popular TIPs

- **MISP** - Open source, community focus
- **ThreatConnect** - Commercial, full-featured
- **Anomali** - Enterprise TIP
- **ThreatQuotient** - Analyst-centric

## TIP Features

### Data Aggregation
Collect from 100+ feeds automatically

### Normalization
Standardize different formats

### Enrichment
Add context to indicators

### Scoring
Prioritize threats by relevance

### Integration
Push to SIEM, firewall, EDR

### Collaboration
Share with partners, community

## MISP Example

\`\`\`
1. Import IOCs from AlienVault
2. MISP enriches with VirusTotal
3. Auto-correlate with existing events
4. Export to Splunk as blocklist
5. Share with partner SOCs
\`\`\`

## Benefits

✓ Centralized intelligence management
✓ Automated indicator processing
✓ Faster threat response
✓ Better collaboration
✓ Reduced false positives`,
                questions: [
                    ['Intelligence platform?', 'TIP', 'Threat Intel Platform'],
                    ['Open source TIP?', 'MISP', 'Community platform'],
                    ['Commercial TIP option?', 'ThreatConnect', 'Enterprise solution'],
                    ['Standardize different formats?', 'Normalization', 'Data formatting'],
                    ['Add context to IOCs?', 'Enrichment', 'Additional data']
                ]
            },
            // Module 6: Incident Response
            {
                id: 29, title: 'Incident Response Basics', content: `# Incident Response Fundamentals

Structured approach to handling security incidents effectively.

## Incident Response Lifecycle

### 1. Preparation
- Create IR plan
- Assemble team
- Deploy tools
- Conduct drills

### 2. Detection & Analysis
- Monitor alerts
- Validate incidents
- Determine scope
- Assign severity

### 3. Containment
- **Short-term:** Isolate affected systems
- **Long-term:** Temporary fixes, rebuild

### 4. Eradication
- Remove malware
- Close vulnerabilities
- Reset compromised credentials

### 5. Recovery
- Restore systems
- Verify clean
- Monitor for reinfection

### 6. Lessons Learned
- Post-incident review
- Update procedures
- Improve defenses

## Incident Severity Levels

**P1/Critical** - Active breach, data loss
**P2/High** - Contained threat, potential impact
**P3/Medium** - Policy violation, low risk
**P4/Low** - Informational

## IR Team Roles

- **Incident Commander** - Overall coordination
- **Security Analyst** - Investigation
- **Forensics** - Evidence collection
- **Communications** - Stakeholder updates
- **Legal** - Compliance, law enforcement

## First Responder Actions

1. Don't panic!
2. Document everything
3. Preserve evidence
4. Follow playbook
5. Communicate clearly`,
                questions: [
                    ['IR first phase?', 'Preparation', 'Plan ahead'],
                    ['Isolate systems?', 'Containment', 'Stop spread'],
                    ['Remove threat?', 'Eradication', 'Clean systems'],
                    ['Active breach severity?', 'Critical', 'Highest priority'],
                    ['Post-incident review?', 'Lessons Learned', 'Improve processes']
                ]
            },
            {
                id: 30, title: 'Digital Forensics', content: `# Digital Forensics Basics

Scientific process of collecting and analyzing digital evidence.

## Forensics Principles

### 1. Preserve Evidence
Never work on original - use copies!

### 2. Chain of Custody
Document who handled evidence and when

### 3. Document Everything
Photos, notes, timestamps

### 4. Follow Legal Standards
Ensure admissibility in court

## Evidence Types

**Volatile** (Lost when powered off):
- RAM contents
- Network connections
- Running processes

**Non-Volatile** (Persistent):
- Hard drives
- USB drives
- Log files

## Collection Order (Volatility)

1. CPU registers, cache
2. RAM memory
3. Network state
4. Running processes
5. Disk drives
6. Backup media
7. Logs

## Forensic Tools

**Disk Imaging:**
- FTK Imager
- dd (Linux)
- Autopsy

**Memory Analysis:**
- Volatility
- Rekall

**Network:**
- Wireshark
- tcpdump

## Live Response

Collecting evidence from running system:

\`\`\`bash
# Capture network connections
netstat -an > network.txt

# List processes
ps aux > processes.txt

# Capture memory
dd if=/dev/mem of=memory.img
\`\`\`

## Best Practices

✓ Use write blockers
✓ Hash evidence files
✓ Work on copies
✓ Maintain chain of custody
✓ Document methodology`,
                questions: [
                    ['Work on original evidence?', 'Never', 'Always use copies'],
                    ['Evidence documentation?', 'Chain of custody', 'Who handled when'],
                    ['Memory analysis tool?', 'Volatility', 'RAM examination'],
                    ['Disk imaging tool?', 'FTK Imager', 'Forensic copy'],
                    ['Lost when powered off?', 'Volatile', 'Temporary data']
                ]
            },
            {
                id: 31, title: 'Incident Response Playbooks', content: `# Incident Response Playbooks

Step-by-step guides for responding to specific incident types.

## What is a Playbook?

Documented procedures for handling common security incidents consistently.

## Common Playbooks

### Ransomware Response
1. Isolate infected systems
2. Identify ransomware variant
3. Check backups
4. Notify stakeholders
5. Do not pay ransom!
6. Restore from backup
7. Patch vulnerabilities

### Phishing Response
1. Verify phishing email
2. Block sender
3. Search for similar emails
4. Notify affected users
5. Reset compromised credentials
6. User education

### Data Breach
1. Contain breach
2. Assess data exposed
3. Notify legal/compliance
4. Document timeline
5. External notifications (if required)
6. Credit monitoring

### DDoS Attack
1. Identify attack type
2. Activate DDoS mitigation
3. Contact ISP
4. Implement rate limiting
5. Monitor for secondary attacks

## Playbook Components

**Trigger:** When to use this playbook
**Roles:** Who does what
**Steps:** Detailed actions
**Tools:** Required resources
**Communication:** Who to notify
**Success Criteria:** When is it resolved?

## Creating Playbooks

1. Identify common scenarios
2. Document current response
3. Improve and standardize
4. Test with tabletop exercises
5. Update based on lessons learned

## Automation

Use SOAR platforms to:
- Auto-execute playbook steps
- Enrich alerts
- Create tickets
- Send notifications

## Example Step

**Step 3: Isolate Affected Host**
- Action: Disable network adapter
- Command: \`\`\`sudo ifconfig eth0 down\`\`\`
- Validation: Ping fails
- Next: Proceed to Step 4`,
                questions: [
                    ['Incident procedure guide?', 'Playbook', 'Response steps'],
                    ['Ransomware advice?', 'Do not pay', 'No ransom'],
                    ['DDoS countermeasure?', 'Rate limiting', 'Slow requests'],
                    ['Isolate host command?', 'ifconfig down', 'Disable network'],
                    ['Automated response platform?', 'SOAR', 'Orchestration tool']
                ]
            }
        ];

        for (const task of remainingTasks) {
            await db.query('INSERT INTO lesson_content (task_id, content, content_type, reading_time_minutes) VALUES (?, ?, ?, ?)',
                [task.id, task.content, 'markdown', 8]);

            for (let i = 0; i < task.questions.length; i++) {
                const q = task.questions[i];
                await db.query('INSERT INTO lesson_questions (task_id, question_text, correct_answer, question_order, hint, case_sensitive) VALUES (?, ?, ?, ?, ?, ?)',
                    [task.id, q[0], q[1], i + 1, q[2], 0]);
            }
            console.log(`✓ Task ${task.id}: ${task.title}`);
        }

        console.log('\n✅ ✅ ✅ ALL LESSONS COMPLETE! ✅ ✅ ✅');
        console.log('\nTotal: 31 lessons across 6 modules');
        console.log('- Module 1: Introduction to Cybersecurity (5)');
        console.log('- Module 2: Linux Command Line (8)');
        console.log('- Module 3: Network Security (5)');
        console.log('- Module 4: SOC Operations (5)');
        console.log('- Module 5: Threat Intelligence (5)');
        console.log('- Module 6: Incident Response (3)');

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

createModules456();
