# 🔵 Blue Teaming & Defensive Security

> 🛡️ *"The best offense is a great defense — but only if you understand how the offense thinks."*

---

## 🧠 What is Blue Teaming?

The **Blue Team** is the defensive counterpart to the Red Team. While red teamers simulate attacks, blue teamers are responsible for **detecting, responding to, and recovering from** those attacks — whether simulated or real.

Blue teaming is not just about firewalls and antivirus. It encompasses:

- 👁️ **Visibility** — knowing what's happening across your entire environment
- 🚨 **Detection** — identifying malicious behavior as early as possible
- ⚡ **Response** — containing and eradicating threats quickly
- 🔄 **Recovery** — restoring normal operations and learning from every incident
- 🔐 **Hardening** — proactively reducing the attack surface

> 🟣 **Purple Teaming** bridges both worlds: red and blue teams collaborate in real-time, with attackers explaining their techniques so defenders can improve detection while the exercise is still ongoing.

---

## 🏢 The Security Operations Center (SOC)

The **SOC** is the nerve center of an organization's defensive security. It operates 24/7 and is staffed by analysts who monitor, triage, and respond to security events.

### 🎯 SOC Analyst Tiers

| 🏅 Tier | 👤 Role | 🔧 Responsibilities |
|--------|--------|-------------------|
| **T1 — Alert Analyst** | First responder | Monitor dashboards, triage alerts, escalate |
| **T2 — Incident Responder** | Investigator | Deep-dive analysis, containment, remediation |
| **T3 — Threat Hunter** | Proactive defender | Hunt for hidden threats, develop detection logic |
| **T4 — SOC Lead / Architect** | Strategist | Tool stack, processes, metrics, team leadership |

### 🛠️ Core SOC Tools

| 🔧 Tool Category | 📌 Purpose | ⚙️ Examples |
|----------------|----------|-----------|
| **SIEM** | Centralized log collection & correlation | Splunk, Elastic (ELK), Microsoft Sentinel, QRadar |
| **EDR** | Endpoint detection & response | CrowdStrike Falcon, SentinelOne, Microsoft Defender |
| **IDS/IPS** | Network intrusion detection/prevention | Snort, Suricata, Zeek |
| **SOAR** | Security orchestration & automated response | Palo Alto XSOAR, Splunk SOAR |
| **Threat Intel** | Indicators of compromise (IoCs) | MISP, VirusTotal, Recorded Future |
| **Vuln Management** | Patch prioritization | Nessus, Qualys, Tenable.io |
| **Firewall / WAF** | Traffic filtering | pfSense, Palo Alto NGFW, AWS WAF |
| **Honeypots** | Deception-based detection | Cowrie, OpenCanary, Canarytokens |

---

## 🔄 The Incident Response Lifecycle

The industry-standard IR process is defined by **NIST SP 800-61**:

```
  ┌──────────────┐
  │  Preparation │  ◄─── Train, tool up, write playbooks
  └──────┬───────┘
         │
  ┌──────▼───────┐
  │  Detection & │  ◄─── SIEM alerts, anomaly detection, threat hunting
  │ Identification│
  └──────┬───────┘
         │
  ┌──────▼───────┐
  │  Containment │  ◄─── Isolate affected systems, block IOCs
  └──────┬───────┘
         │
  ┌──────▼───────┐
  │  Eradication │  ◄─── Remove malware, close vulnerabilities, revoke credentials
  └──────┬───────┘
         │
  ┌──────▼───────┐
  │   Recovery   │  ◄─── Restore systems, verify integrity, monitor closely
  └──────┬───────┘
         │
  ┌──────▼───────┐
  │ Post-Incident│  ◄─── Root cause analysis, lessons learned, report
  │   Review     │
  └──────────────┘
```

### 📋 Incident Severity Levels

| 🔴 Level | 🏷️ Name | 📝 Description | ⏱️ Response SLA |
|---------|--------|---------------|---------------|
| **P1** | Critical | Active breach, data exfiltration, ransomware | Immediate |
| **P2** | High | Confirmed compromise, lateral movement | < 1 hour |
| **P3** | Medium | Suspicious activity, policy violation | < 4 hours |
| **P4** | Low | Single failed login, port scan | < 24 hours |

---

## 🔍 Threat Hunting

Threat hunting is **proactive** — it doesn't wait for alerts. Hunters assume the environment is already compromised and go looking for evidence.

### 🧩 The Hunting Process

1. 🧠 **Hypothesis** — Form a theory based on threat intel or TTPs
   > *"An attacker may have persisted via a cron job after the initial compromise"*

2. 📊 **Data Collection** — Pull relevant logs (process creation, network connections, file writes)

3. 🔎 **Investigation** — Query SIEM, pivot on IOCs, look for anomalies

4. 📝 **Documentation** — Record findings, update detection rules

5. 🔁 **Feedback Loop** — Turn successful hunts into automated alerts

### 🗂️ Common Hunting Data Sources

| 📂 Source | 🔍 What to Look For |
|----------|-------------------|
| Windows Event Logs | Logon events (4624/4625), process creation (4688), service installs (7045) |
| Linux `/var/log/auth.log` | SSH brute-force, `sudo` abuse, failed logins |
| Linux `/var/log/syslog` | Cron job execution, daemon activity |
| Network flow data | Unusual outbound connections, large data transfers |
| DNS logs | C2 beaconing, DGA domains |
| Process trees | Unusual parent-child relationships (e.g., `apache` spawning `bash`) |

---

## 🗺️ Defensive Frameworks

### 🛡️ MITRE ATT&CK — The Defender's Bible

The **MITRE ATT&CK** framework maps adversary behavior into **Tactics** (the *why*) and **Techniques** (the *how*). Blue teams use it to:

- Identify coverage gaps in their detection stack
- Map alerts to specific TTPs
- Communicate findings in a standardized language
- Guide threat hunts with real-world attacker behavior

> 🌐 navigator.attack.mitre.org — use the ATT&CK Navigator to visualize your coverage

### 🔵 MITRE D3FEND

The defensive counterpart to ATT&CK — maps specific **defensive techniques** (e.g., *Process Tree Analysis*, *User Behavioral Analysis*) to the attacks they counter.

### 📘 Other Key Frameworks

| 🏛️ Framework | 🎯 Purpose |
|-------------|----------|
| **NIST CSF** | Cybersecurity risk management (Identify → Protect → Detect → Respond → Recover) |
| **NIST SP 800-61** | Computer Security Incident Handling Guide |
| **CIS Controls** | Prioritized defensive actions (20 critical controls) |
| **ISO/IEC 27001** | Information security management system standard |
| **Cyber Kill Chain** (Lockheed Martin) | Model adversary attack stages to disrupt them early |

---

## 🔵 Blue Team vs 🔴 Red Team — Two Sides of the Same Shield

| 🔵 Blue Team | 🔴 Red Team |
|-------------|------------|
| 🛡️ Defend, detect, respond | ⚔️ Attack, exploit, evade |
| 📊 Works with logs and alerts | 💻 Works with shells and exploits |
| ⏱️ Reactive (mostly) + proactive (hunting) | 🎯 Always proactive |
| 🏢 Insider knowledge of the environment | 🕵️ Simulates external adversary |
| 📋 Produces detection rules and playbooks | 📋 Produces penetration test reports |
| 🔧 Tools: SIEM, EDR, IDS, firewalls | 🔧 Tools: Nmap, Metasploit, Medusa, Netcat |

---

## 🔗 Mapping This Lab to Blue Team Defenses

The attacks demonstrated against Metasploitable in this module have direct defensive countermeasures:

| 🔴 Attack (Red Team) | 🔵 Detection / Defense (Blue Team) |
|--------------------|------------------------------------|
| 🗺️ **Nmap port scan** | Detect with IDS (Snort/Suricata) — rule: SYN flood or sequential port probe pattern |
| 🔑 **Medusa SSH brute-force** | Alert on >5 failed logins in 60s (Event: `sshd` auth failure); enforce `fail2ban` |
| 🐟 **vsftpd backdoor (CVE-2011-2523)** | Patch FTP service; IDS signature for the `:)` trigger string on port 21 |
| ⚙️ **Distcc RCE (CVE-2004-2687)** | Disable Distcc if unused; firewall port 3632; alert on unexpected process spawning from `distcc` |
| 🔓 **SMB enumeration** | Disable anonymous SMB access; alert on `enum4linux` / `smbclient` patterns |
| 📤 **NetCat file exfiltration** | Monitor unusual outbound connections; DLP on sensitive file reads |
| ⬆️ **SUID nmap privilege escalation** | Audit SUID binaries regularly; remove SUID from non-essential tools |
| 🪝 **Cron job persistence** | Monitor `/etc/cron*` and `/var/spool/cron` for unexpected writes (FIM — file integrity monitoring) |
| 🐚 **Reverse shell backdoor** | Network anomaly detection for unexpected outbound shells; alert on `bash -i` or `python -c` patterns |
| 🗝️ **Shadow file credential harvesting** | Restrict `/etc/shadow` permissions; alert on unauthorized reads; use PAM auditing |

---

## 🔐 System Hardening Essentials

Prevention is always cheaper than incident response. Key hardening steps:

### 🖥️ Linux Hardening
- ✅ Disable unused services (`vsftpd`, `distcc`, `telnet`, `rsh`)
- ✅ Remove SUID from non-essential binaries (`chmod u-s /usr/bin/nmap`)
- ✅ Enforce strong password policies (`/etc/pam.d/common-password`)
- ✅ Restrict SSH: disable root login, use key-based auth only, change default port
- ✅ Enable and configure `auditd` for system call logging
- ✅ Use `fail2ban` to auto-block brute-force attempts
- ✅ Apply the principle of least privilege — users should have only what they need
- ✅ Keep software patched — most exploited CVEs have patches available at time of exploitation

### 🌐 Network Hardening
- ✅ Segment networks — attackers shouldn't reach everything from anywhere
- ✅ Block unused ports at the firewall — Metasploitable has 20+ exposed services, a real system shouldn't
- ✅ Deploy IDS/IPS on network ingress/egress points
- ✅ Monitor and baseline normal traffic — anomalies become visible only against a known baseline
- ✅ Disable SMBv1 (EternalBlue attack surface)

---

## 📚 Getting Started in Blue Teaming

### 🏆 Recommended Platforms
| 🌐 Platform | 🎯 Focus |
|-----------|---------|
| **TryHackMe** (SOC Level 1 path) | Beginner-friendly, guided SOC analyst training |
| **LetsDefend** | Realistic SOC simulator with alerts, SIEM, and malware analysis |
| **BlueTeamLabs Online** | Incident response and threat hunting challenges |
| **Hack The Box — Sherlocks** | Forensics and blue team challenge labs |
| **SANS Blue Team Summit** | Professional-level defensive content |

### 🏅 Key Certifications
| 🎓 Cert | 🏛️ Issuer | 📋 Focus |
|--------|---------|---------|
| **CompTIA Security+** | CompTIA | Broad security fundamentals |
| **CompTIA CySA+** | CompTIA | Threat detection and response |
| **SC-200** | Microsoft | Microsoft Sentinel & Defender |
| **GCIH** | SANS/GIAC | Incident handling |
| **GCFA** | SANS/GIAC | Forensic analysis |
| **Blue Team Level 1 (BTL1)** | Security Blue Team | Practical SOC analyst skills |

---

> ## 🔵 The Blue Team Mindset
>
> Red teamers ask: *"How do I get in?"*
> Blue teamers ask: *"How would I know if someone already has?"*
>
> The best blue teamers **think like attackers** — that's exactly why studying red team techniques makes you a better defender. 🛡️
