Thursday, January 1, 2026

Building an AI-Powered Purple Team Lab: From Zero to Automated Incident Response on Kali Linux (WSL)

Modern cybersecurity training is divided between offensive experimentation (Red Team) and enterprise monitoring (Blue Team). Setting up a dedicated environment typically demands separate physical servers or costly cloud instances.

By unifying Kali Linux inside Windows Subsystem for Linux (WSL), I wanted to show an enterprise-grade Wazuh SIEM cluster via Docker, and a local reasoning model (DeepSeek-R1 via Ollama), we built a self-contained, 100% private, zero-cost Purple Team and AI-driven SOC laboratory.

This is the complete breakdown of the entire architecture, how each component was configured from scratch, how the attack and defense mechanisms interact, and the exact commands to run and control the environment.

1. Laboratory Architecture Overview

The system operates across three interconnected layers inside a single machine:

 ┌─────────────────────────────────────────────────────────────────────────────┐
 │                            Windows Host System                              │
 │            Web Browser: https://localhost:443 (Wazuh Dashboard)            │
 └──────────────────────────────────────▲──────────────────────────────────────┘
                                        │ (Port 443 / SSL)
 ┌──────────────────────────────────────┼──────────────────────────────────────┐
 │ Kali Linux (WSL2 Host)               │                                      │
 │                                      │                                      │
 │  ┌─────────────────────────┐         │                                      │
 │  │    Red Team Engine      │         │                                      │
 │  │   - Hydra Brute-Force   │──┐      │                                      │
 │  │   - PentestGPT / SGPT   │  │      │                                      │
 │  └─────────────────────────┘  ▼      │                                      │
 │                     ┌──────────────┐ │   ┌────────────────────────────────┐ │
 │                     │ Wazuh Agent  ├─┼──►│     Wazuh Cluster (Docker)     │ │
 │                     │  (Telemetry) │ │   │ - wazuh.manager (Rule Engine)  │ │
 │                     └──────────────┘ │   │ - wazuh.indexer (OpenSearch)   │ │
 │                                      │   │ - wazuh.dashboard (Kibana/UI)  │ │
 │                                      │   └───────────────┬────────────────┘ │
 │                                                          │                  │
 │  ┌─────────────────────────┐    Raw JSON Alerts (Lvl 10) │                  │
 │  │   AI SOC Analyst Engine │◄────────────────────────────┘                  │
 │  │   (soc_analyst.py)      │                                                │
 │  │            │            │                                                │
 │  │            ▼ (HTTP API) │                                                │
 │  │   Ollama / DeepSeek-R1  │                                                │
 │  └─────────────────────────┘                                                │
 └─────────────────────────────────────────────────────────────────────────────┘
  • Attacker (Red Team): Kali Linux utilities (Hydra, rockyou wordlist) and AI copilots (PentestGPT, Shell-GPT) creating offensive vectors.

  • Defender (Blue Team): Wazuh Agent monitoring host events, forwarding logs to the multi-container Wazuh Manager and Indexer.

  • Orchestrator & Analyst (AI SOC): A Python pipeline interrogating Wazuh's alert index and feeding critical security incidents into a local DeepSeek-R1 model for instant mitigation reporting.

2. The Step-by-Step Construction Story


1. Local AI Engine Setup (Red/Blue Copilot)

  • Deployed Ollama running the DeepSeek-R1 (8B) model directly inside the Kali Linux (WSL) terminal.

  • Configured offensive CLI assistants (PentestGPT, Shell-GPT) to automate tasks with zero external data exposure.

2. SIEM & SOC Infrastructure Deployment (Wazuh Stack)

  • Configured the Docker engine and adjusted kernel virtual memory limits (vm.max_map_count=262144).

  • Deployed the multi-container Wazuh 4.9.0 cluster (wazuh.manager, wazuh.indexer, wazuh.dashboard) with internal TLS/SSL certificates.

  • Established access to the centralized management console from the Windows host browser via https://localhost:443.

3. Host Telemetry & Endpoint Monitoring (Wazuh Agent)

  • Installed and registered the wazuh-agent package on Kali Linux.

  • Connected the host sensor (RolandR19) to the local Docker manager (127.0.0.1), confirming its Active status on the dashboard.

4. Purple Team Attack Simulation (Hydra)

  • Extracted the /usr/share/wordlists/rockyou.txt password dictionary.

  • Initialized the host SSH daemon (sshd) and executed an automated password-spraying attack using Hydra against root.

  • Validated live detection in Wazuh: captured 280+ failed login events, triggered critical Level 10 alerts (Rule 2502), and mapped the activity to MITRE ATT&CK T1110 (Brute Force).

5. Active Response & Automated AI SOC Triage

  • Configured Active Response (firewall-drop) in ossec.conf to automatically drop malicious source IPs via firewall rules upon brute-force detection.

  • Built and executed ~/soc_analyst.py, pulling recent high-severity JSON alerts from Wazuh and prompting DeepSeek-R1 to generate structured L3 incident reports and remediation playbooks.

6. Terminal Environment Optimization

  • Installed and configured the thefuck auto-correction utility inside the Bash shell configuration (~/.bashrc).


Here are the exact commands to start, run, and operate every single tool and step from your laboratory directly inside your Kali Linux terminal.


Here are the exact commands to download, install, and configure every single component of your laboratory from scratch on Kali Linux (WSL).

1. Local AI Engine (Ollama & DeepSeek-R1)

  • Download and install the Ollama engine:

    Bash
    curl -fsSL https://ollama.com/install.sh | sh
    
  • Download DeepSeek-R1 model weights (~4.9 GB):

    Bash
    ollama pull deepseek-r1:8b
    
  • Install Shell-GPT (CLI Copilot):

    Bash
    pipx install shell-gpt
    

2. SIEM & SOC Infrastructure (Docker & Wazuh Cluster)

  • Download and install Docker, Docker Compose, and Git:

    Bash
    sudo apt update && sudo apt install -y docker.io docker-compose git
    
  • Configure Docker permissions and kernel virtual memory:

    Bash
    sudo usermod -aG docker $USER
    sudo sysctl -w vm.max_map_count=262144
    echo 'vm.max_map_count=262144' | sudo tee -a /etc/sysctl.conf
    
  • Clone the Wazuh single-node deployment repository (v4.9.0):

    Bash
    cd ~
    git clone https://github.com/wazuh/wazuh-docker.git -b v4.9.0 --depth=1
    
  • Generate internal TLS certificates and pull Docker container images (~3.2 GB):

    Bash
    cd ~/wazuh-docker/single-node
    docker-compose -f generate-indexer-certs.yml run --rm generator
    docker-compose up -d
    

3. Host Telemetry Sensor (Wazuh Agent)

  • Download the official Wazuh agent Debian package (.deb):

    Bash
    wget https://packages.wazuh.com/4.x/apt/pool/main/w/wazuh-agent/wazuh-agent_4.9.0-1_amd64.deb
    
  • Install the agent and link it to the local Manager:

    Bash
    sudo WAZUH_MANAGER="127.0.0.1" dpkg -i ./wazuh-agent_4.9.0-1_amd64.deb
    

4. Attack Tools & Wordlists (Hydra & SSH)

  • Install Hydra and OpenSSH server (if not present):

    Bash
    sudo apt install -y hydra openssh-server
    
  • Decompress the default RockYou wordlist:

    Bash
    sudo gunzip -k /usr/share/wordlists/rockyou.txt.gz
    

5. Automated AI SOC Analyst Script (Python & Requests)

  • Install the Python HTTP client package via APT:

    Bash
    sudo apt install -y python3-requests
    
  • Create the AI SOC Analyst script (soc_analyst.py):

    Bash
    cat << 'EOF' > ~/soc_analyst.py
    import json
    import subprocess
    import requests
    
    OLLAMA_URL = "http://localhost:11434/api/generate"
    MODEL = "deepseek-r1:8b"
    
    def get_recent_critical_alerts(limit=5):
        cmd = ["docker", "exec", "single-node-wazuh.manager-1", "tail", "-n", "300", "/var/ossec/logs/alerts/alerts.json"]
        try:
            raw_output = subprocess.check_output(cmd).decode("utf-8")
        except Exception as e:
            return []
    
        critical_alerts = []
        for line in raw_output.strip().split("\n"):
            if not line:
                continue
            try:
                alert = json.loads(line)
                if alert.get("rule", {}).get("level", 0) >= 10:
                    critical_alerts.append({
                        "timestamp": alert.get("timestamp"),
                        "agent": alert.get("agent", {}).get("name"),
                        "rule_id": alert.get("rule", {}).get("id"),
                        "level": alert.get("rule", {}).get("level"),
                        "description": alert.get("rule", {}).get("description"),
                        "mitre": alert.get("rule", {}).get("mitre", {}),
                        "full_log": alert.get("full_log", alert.get("data", {}))
                    })
            except json.JSONDecodeError:
                continue
        return critical_alerts[-limit:]
    
    def analyze_with_deepseek(alerts):
        if not alerts:
            print("[*] No critical alerts (Level >= 10) found.")
            return
        prompt = f"You are a Senior L3 SOC Analyst. Analyze these Wazuh alerts and provide a structured incident report:\n{json.dumps(alerts, indent=2)}"
        payload = {"model": MODEL, "prompt": prompt, "stream": True}
        try:
            response = requests.post(OLLAMA_URL, json=payload, stream=True)
            for chunk in response.iter_lines():
                if chunk:
                    data = json.loads(chunk.decode("utf-8"))
                    print(data.get("response", ""), end="", flush=True)
        except Exception as e:
            print(f"Error: {e}")
    
    if __name__ == "__main__":
        analyze_with_deepseek(get_recent_critical_alerts())
    EOF
    

6. Terminal Auto-Correction (thefuck)

  • Download and install the system package:

    Bash
    sudo apt install -y thefuck
    
  • Inject the alias into Bash configuration:

    Bash
    echo 'eval $(thefuck --alias)' >> ~/.bashrc
    source ~/.bashrc


1. Local AI Engine (Ollama & DeepSeek-R1)

  • Start Ollama background server:

    Bash
    ollama serve
    
  • Launch interactive terminal session with DeepSeek-R1:

    Bash
    ollama run deepseek-r1:8b
    
  • Run Shell-GPT / PentestGPT (if querying from CLI):

    Bash
    sgpt "Explain how to secure an SSH service against brute force"
    

2. SIEM & SOC Stack (Wazuh Docker Cluster)

  • Apply kernel memory configuration (required once per reboot):

    Bash
    sudo sysctl -w vm.max_map_count=262144
    
  • Start all 3 Wazuh containers (Manager, Indexer, Dashboard):

    Bash
    cd ~/wazuh-docker/single-node
    docker-compose start
    

    (If starting from a completely fresh/stopped build: docker-compose up -d)

  • Check container health:

    Bash
    docker-compose ps
    
  • Access Web Dashboard: Open your Windows browser at https://localhost:443 (Credentials: admin / SecretPassword).

  • Stop the cluster to free ~4 GB RAM:

    Bash
    cd ~/wazuh-docker/single-node
    docker-compose stop
    

3. Host Telemetry Sensor (Wazuh Agent)

  • Start the agent service:

    Bash
    sudo systemctl start wazuh-agent
    
  • Check connection status to Manager:

    Bash
    sudo systemctl status wazuh-agent
    
  • Stop the agent service:

    Bash
    sudo systemctl stop wazuh-agent
    

4. Purple Team Attack Simulation (Hydra SSH)

  • Start target SSH service on host:

    Bash
    sudo systemctl start ssh
    
  • Decompress password dictionary (if not done yet):

    Bash
    sudo gunzip -k /usr/share/wordlists/rockyou.txt.gz
    
  • Launch the brute-force attack:

    Bash
    head -n 50 /usr/share/wordlists/rockyou.txt > /tmp/test_passwords.txt
    hydra -l root -P /tmp/test_passwords.txt 127.0.0.1 ssh -t 2 -W 1
    
  • Stop SSH service after testing:

    Bash
    sudo systemctl stop ssh
    

5. Active Response & Automated AI SOC Triage

  • Restart Manager to apply Active Response rules (firewall-drop):

    Bash
    docker exec -it single-node-wazuh.manager-1 /var/ossec/bin/wazuh-control restart
    
  • Execute the AI SOC Analyst script (DeepSeek-R1):

    Bash
    python3 ~/soc_analyst.py
    
  • Monitor real-time Wazuh alert logs directly in the terminal:

    Bash
    docker exec -it single-node-wazuh.manager-1 tail -f /var/ossec/logs/alerts/alerts.json
    

6. Terminal Environment Optimization (thefuck)

  • Reload Bash configuration:

    Bash
    source ~/.bashrc
    
  • Trigger auto-correction after any failed command:

    Bash
    fuck
    

No comments:

Post a Comment

Generated Code to the Test Across Two Continents

When literary discipline intersects with computational logic, experimentation takes on a distinctively methodical tone. That is precisely th...