Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Select an option

  • Save z0rs/7852ca1d8cac740539aeb05b16b48ea1 to your computer and use it in GitHub Desktop.

Select an option

Save z0rs/7852ca1d8cac740539aeb05b16b48ea1 to your computer and use it in GitHub Desktop.

🦅 OpenClaw — Personal AI Security Assistant

Full Installation & Configuration Guide for Arch Linux

SOC Blue Team + Red Team Functions

Ethical Notice: This guide is strictly for authorized environments — personal labs, CTF platforms, intentionally vulnerable systems (DVWA, Juice Shop, Metasploitable), and authorized penetration testing engagements. Never use these tools against systems you do not own or have explicit written permission to test.


📋 TABLE OF CONTENTS

  1. System Prerequisites
  2. Directory Structure Setup
  3. Core AI Layer (Ollama + Local LLM)
  4. OpenClaw Agent Installation
  5. Red Team Tools Installation
  6. Blue Team Tools Installation
  7. SOC Agent Configuration
  8. Pentest Agent Configuration
  9. Lab Environments Setup
  10. Automation Scripts
  11. Security Hardening
  12. OpenClaw Systemd Service

1. SYSTEM PREREQUISITES

1.1 Update System

sudo pacman -Syu --noconfirm

1.2 Install Base Build Dependencies

sudo pacman -S --noconfirm \
  base-devel git curl wget unzip \
  python python-pip python-virtualenv \
  nodejs npm go rust \
  docker docker-compose \
  net-tools iproute2 tcpdump \
  jq yq htop btop \
  openssh fail2ban \
  vim neovim tmux

1.3 Install yay (AUR Helper) if not present

cd /tmp
git clone https://aur.archlinux.org/yay.git
cd yay
makepkg -si --noconfirm
cd ~

1.4 Enable Docker

sudo systemctl enable --now docker
sudo usermod -aG docker $USER
newgrp docker

2. DIRECTORY STRUCTURE SETUP

2.1 Create Full Lab Directory Tree

mkdir -p ~/ai-security-lab/{agents/{openclaw,soc-agent,pentest-agent},\
tools/{recon,web,network,exploitation,forensics,blue-team},\
labs/{dvwa,juice-shop,metasploitable,ctfs},\
scans/{nmap,nuclei,web-scans},\
recon/{domains,subdomains,dns,assets},\
reports/{vulnerabilities,pentest,incident-response},\
logs/{agent,soc,scans},\
scripts/{automation,recon,scanning,reporting},\
datasets/{wordlists,payloads,threat-intel}}

2.2 Create OpenClaw Core Files

mkdir -p ~/ai-security-lab/agents/openclaw/{config,memory,prompts,modules}
touch ~/ai-security-lab/agents/openclaw/config/openclaw.conf
touch ~/ai-security-lab/agents/openclaw/prompts/soc_system.txt
touch ~/ai-security-lab/agents/openclaw/prompts/pentest_system.txt

2.3 Verify Structure

tree ~/ai-security-lab -L 3

3. CORE AI LAYER

3.1 Install Ollama (Local LLM Backend)

curl -fsSL https://ollama.com/install.sh | sh
sudo systemctl enable --now ollama

3.2 Pull Recommended Security-Capable Models

# Primary model — best for security reasoning
ollama pull mistral

# Alternative — lighter weight
ollama pull llama3

# Code-specialized (for exploit scripting support)
ollama pull codellama

3.3 Verify Ollama

ollama list
curl http://localhost:11434/api/tags

3.4 Install Python AI Libraries

pip install --break-system-packages \
  ollama \
  openai \
  langchain \
  langchain-community \
  rich \
  typer \
  pydantic \
  httpx \
  aiofiles \
  python-dotenv \
  schedule \
  watchdog

4. OPENCLAW AGENT INSTALLATION

4.1 Create OpenClaw Main Agent Script

cat > ~/ai-security-lab/agents/openclaw/openclaw.py << 'OPENCLAW_EOF'
#!/usr/bin/env python3
"""
OpenClaw - Personal AI Security Assistant
Hybrid SOC Blue Team + Red Team Agent
"""

import os
import sys
import json
import subprocess
from datetime import datetime
from pathlib import Path
import ollama
from rich.console import Console
from rich.panel import Panel
from rich.markdown import Markdown
from rich.prompt import Prompt

console = Console()

LAB_ROOT = Path.home() / "ai-security-lab"
LOG_DIR = LAB_ROOT / "logs" / "agent"
REPORT_DIR = LAB_ROOT / "reports"

LOG_DIR.mkdir(parents=True, exist_ok=True)

SYSTEM_PROMPT = """
You are OpenClaw, an elite cybersecurity AI assistant deployed on Arch Linux.
You support SOC Blue Team workflows AND Red Team penetration testing in authorized labs.

ETHICAL RULES:
- ONLY assist with systems the user owns or has explicit authorization for
- Authorized targets: local VMs, Docker containers, Metasploitable, DVWA, Juice Shop, CTFs
- NEVER assist with illegal hacking

SOC FUNCTIONS: Log monitoring, threat detection, SSH anomaly detection, file integrity, malware indicators
RED TEAM FUNCTIONS: Recon, enumeration, web vuln discovery, reporting (authorized labs only)

Always provide: clear steps, command examples, security explanations.
"""

def log_interaction(role: str, content: str):
    timestamp = datetime.now().strftime("%Y%m%d_%H%M%S")
    log_file = LOG_DIR / f"session_{datetime.now().strftime('%Y%m%d')}.jsonl"
    with open(log_file, "a") as f:
        f.write(json.dumps({"timestamp": timestamp, "role": role, "content": content}) + "\n")

def run_openclaw():
    console.print(Panel.fit(
        "[bold red]🦅 OpenClaw Security Assistant[/bold red]\n"
        "[dim]Hybrid SOC + Red Team | Arch Linux[/dim]",
        border_style="red"
    ))
    console.print("[bold yellow]⚠ Authorized environments only. Type 'exit' to quit.[/bold yellow]\n")

    messages = []

    while True:
        try:
            user_input = Prompt.ask("[bold cyan]openclaw[/bold cyan]")
        except (KeyboardInterrupt, EOFError):
            console.print("\n[yellow]Session ended.[/yellow]")
            break

        if user_input.lower() in ["exit", "quit", "q"]:
            console.print("[yellow]OpenClaw session closed.[/yellow]")
            break

        if not user_input.strip():
            continue

        messages.append({"role": "user", "content": user_input})
        log_interaction("user", user_input)

        try:
            with console.status("[bold green]OpenClaw thinking...[/bold green]"):
                response = ollama.chat(
                    model="mistral",
                    messages=[
                        {"role": "system", "content": SYSTEM_PROMPT},
                        *messages
                    ]
                )

            assistant_msg = response["message"]["content"]
            messages.append({"role": "assistant", "content": assistant_msg})
            log_interaction("assistant", assistant_msg)

            console.print("\n")
            console.print(Markdown(assistant_msg))
            console.print("\n")

        except Exception as e:
            console.print(f"[bold red]Error:[/bold red] {e}")

if __name__ == "__main__":
    run_openclaw()
OPENCLAW_EOF

chmod +x ~/ai-security-lab/agents/openclaw/openclaw.py

4.2 Create Launcher Alias

echo 'alias openclaw="python3 ~/ai-security-lab/agents/openclaw/openclaw.py"' >> ~/.bashrc
source ~/.bashrc

4.3 Test OpenClaw

openclaw

5. RED TEAM TOOLS

5.1 Reconnaissance Tools

# Nmap — Port scanner
sudo pacman -S --noconfirm nmap

# Masscan — Fast port scanner
sudo pacman -S --noconfirm masscan

# Amass — Subdomain enumeration
yay -S --noconfirm amass

# Subfinder — Passive subdomain discovery
go install -v github.com/projectdiscovery/subfinder/v2/cmd/subfinder@latest
export PATH=$PATH:~/go/bin
echo 'export PATH=$PATH:~/go/bin' >> ~/.bashrc

# Httpx — HTTP probe
go install -v github.com/projectdiscovery/httpx/cmd/httpx@latest

# DNSx — DNS toolkit
go install -v github.com/projectdiscovery/dnsx/cmd/dnsx@latest

5.2 Web Testing Tools

# Nuclei — Vulnerability scanner
go install -v github.com/projectdiscovery/nuclei/v3/cmd/nuclei@latest

# Update Nuclei templates
nuclei -update-templates

# FFUF — Web fuzzer
go install -v github.com/ffuf/ffuf/v2@latest

# Gobuster — Directory/DNS brute forcer
go install -v github.com/OJ/gobuster/v3@latest

# Nikto — Web server scanner
sudo pacman -S --noconfirm nikto

5.3 Injection & Exploitation Tools

# SQLMap — SQL injection automation
sudo pacman -S --noconfirm sqlmap

# Metasploit Framework
yay -S --noconfirm metasploit

# Initialize Metasploit database
sudo systemctl start postgresql
sudo msfdb init

5.4 Password Tools

sudo pacman -S --noconfirm hydra john hashcat

5.5 Wireless Tools

sudo pacman -S --noconfirm aircrack-ng
yay -S --noconfirm kismet

5.6 Download Wordlists & Payloads

# SecLists
cd ~/ai-security-lab/datasets/wordlists
git clone --depth 1 https://github.com/danielmiessler/SecLists.git

# PayloadsAllTheThings
cd ~/ai-security-lab/datasets/payloads
git clone --depth 1 https://github.com/swisskyrepo/PayloadsAllTheThings.git

6. BLUE TEAM TOOLS

6.1 Intrusion Detection

# Suricata — IDS/IPS
sudo pacman -S --noconfirm suricata

# Update Suricata rules
sudo suricata-update

# Enable Suricata
sudo systemctl enable --now suricata

6.2 Zeek (Network Analysis Framework)

yay -S --noconfirm zeek

6.3 Fail2Ban (Brute Force Protection)

sudo pacman -S --noconfirm fail2ban

# Configure SSH jail
sudo tee /etc/fail2ban/jail.local << 'EOF'
[DEFAULT]
bantime  = 3600
findtime = 600
maxretry = 3

[sshd]
enabled = true
port    = ssh
logpath = %(sshd_log)s
backend = systemd
EOF

sudo systemctl enable --now fail2ban

6.4 OSQuery (Host Monitoring)

yay -S --noconfirm osquery
sudo systemctl enable --now osqueryd

6.5 Wazuh Agent (SIEM)

# Install Wazuh agent (connects to Wazuh manager)
yay -S --noconfirm wazuh-agent

# Configure Wazuh (update MANAGER_IP to your Wazuh server)
sudo tee /var/ossec/etc/ossec.conf << 'EOF'
<ossec_config>
  <client>
    <server>
      <address>127.0.0.1</address>
      <port>1514</port>
      <protocol>tcp</protocol>
    </server>
  </client>
  <syscheck>
    <disabled>no</disabled>
    <frequency>43200</frequency>
    <directories>/etc,/usr/bin,/usr/sbin</directories>
    <directories>/bin,/sbin,/boot</directories>
  </syscheck>
  <rootcheck>
    <disabled>no</disabled>
  </rootcheck>
  <active-response>
    <disabled>no</disabled>
  </active-response>
</ossec_config>
EOF

6.6 Forensics Tools

# Volatility — Memory forensics
pip install --break-system-packages volatility3

# Autopsy dependencies
sudo pacman -S --noconfirm sleuthkit

# Binwalk — Firmware analysis
sudo pacman -S --noconfirm binwalk

# Foremost — File carving
sudo pacman -S --noconfirm foremost

# Strings, file, hexdump
sudo pacman -S --noconfirm binutils

6.7 OpenVAS (Vulnerability Scanning)

yay -S --noconfirm openvas
sudo gvm-setup
sudo gvm-start

7. SOC AGENT CONFIGURATION

7.1 Create SOC Agent Script

cat > ~/ai-security-lab/agents/soc-agent/soc_agent.py << 'SOC_EOF'
#!/usr/bin/env python3
"""
OpenClaw SOC Agent — Blue Team Monitoring
"""

import subprocess
import json
import re
from datetime import datetime
from pathlib import Path
from rich.console import Console
from rich.table import Table

console = Console()
LOG_DIR = Path.home() / "ai-security-lab" / "logs" / "soc"
LOG_DIR.mkdir(parents=True, exist_ok=True)

def get_failed_ssh_logins(limit=20):
    """Detect SSH brute force attempts"""
    cmd = ["journalctl", "-u", "sshd", "-n", str(limit), "--no-pager", "-o", "short"]
    result = subprocess.run(cmd, capture_output=True, text=True)
    lines = result.stdout.splitlines()
    failures = [l for l in lines if "Failed password" in l or "Invalid user" in l]
    return failures

def get_sudo_events(limit=20):
    """Detect privilege escalation events"""
    cmd = ["journalctl", "-n", str(limit), "--no-pager", "-o", "short",
           "--grep", "sudo"]
    result = subprocess.run(cmd, capture_output=True, text=True)
    return result.stdout.splitlines()

def check_listening_ports():
    """List all listening ports"""
    result = subprocess.run(["ss", "-tlnp"], capture_output=True, text=True)
    return result.stdout

def check_running_processes():
    """List suspicious processes"""
    result = subprocess.run(["ps", "aux", "--sort=-%cpu"], capture_output=True, text=True)
    return result.stdout.splitlines()[:20]

def check_fail2ban_status():
    """Check Fail2ban banned IPs"""
    result = subprocess.run(["sudo", "fail2ban-client", "status", "sshd"],
                            capture_output=True, text=True)
    return result.stdout

def run_soc_report():
    timestamp = datetime.now().strftime("%Y-%m-%d %H:%M:%S")
    console.print(f"\n[bold blue]🔵 SOC MONITORING REPORT — {timestamp}[/bold blue]\n")

    # SSH failures
    console.print("[bold yellow]━━ SSH FAILED LOGINS ━━[/bold yellow]")
    failures = get_failed_ssh_logins()
    if failures:
        for line in failures:
            console.print(f"  [red]⚠[/red] {line}")
    else:
        console.print("  [green]✓ No failed SSH logins detected[/green]")

    # Sudo events
    console.print("\n[bold yellow]━━ PRIVILEGE ESCALATION (SUDO) ━━[/bold yellow]")
    sudo_events = get_sudo_events()
    if sudo_events:
        for line in sudo_events[:10]:
            console.print(f"  [yellow]→[/yellow] {line}")
    else:
        console.print("  [green]✓ No sudo events[/green]")

    # Listening ports
    console.print("\n[bold yellow]━━ LISTENING PORTS ━━[/bold yellow]")
    ports = check_listening_ports()
    console.print(ports)

    # Fail2ban
    console.print("\n[bold yellow]━━ FAIL2BAN STATUS ━━[/bold yellow]")
    f2b = check_fail2ban_status()
    console.print(f2b if f2b else "  [dim]Fail2ban not active or permission denied[/dim]")

    # Save report
    report_file = LOG_DIR / f"soc_report_{datetime.now().strftime('%Y%m%d_%H%M%S')}.json"
    report = {
        "timestamp": timestamp,
        "ssh_failures": failures,
        "sudo_events": sudo_events,
        "ports": ports
    }
    with open(report_file, "w") as f:
        json.dump(report, f, indent=2)
    console.print(f"\n[dim]Report saved: {report_file}[/dim]")

if __name__ == "__main__":
    run_soc_report()
SOC_EOF

chmod +x ~/ai-security-lab/agents/soc-agent/soc_agent.py
echo 'alias soc-report="python3 ~/ai-security-lab/agents/soc-agent/soc_agent.py"' >> ~/.bashrc

8. PENTEST AGENT CONFIGURATION

8.1 Create Pentest Recon Script

cat > ~/ai-security-lab/agents/pentest-agent/recon.sh << 'RECON_EOF'
#!/usr/bin/env bash
# OpenClaw Pentest Agent — Recon Automation
# USAGE: ./recon.sh <target_domain_or_ip> [--type web|network]
# AUTHORIZED ENVIRONMENTS ONLY

set -euo pipefail

TARGET="${1:-}"
MODE="${2:---type web}"
TIMESTAMP=$(date +%Y%m%d_%H%M%S)
LAB="$HOME/ai-security-lab"
RECON_DIR="$LAB/recon"
SCAN_DIR="$LAB/scans"
REPORT_DIR="$LAB/reports/pentest"

if [[ -z "$TARGET" ]]; then
  echo "Usage: $0 <target> [--type web|network]"
  echo "Example: $0 192.168.1.100 --type network"
  exit 1
fi

echo ""
echo "=============================================="
echo "  🦅 OpenClaw Pentest Recon Agent"
echo "  Target : $TARGET"
echo "  Mode   : $MODE"
echo "  Time   : $TIMESTAMP"
echo "  ⚠ Authorized environments only"
echo "=============================================="
echo ""

read -p "Confirm this is an authorized target? (yes/no): " CONFIRM
if [[ "$CONFIRM" != "yes" ]]; then
  echo "Aborted. Authorized environments only."
  exit 1
fi

SCAN_OUTPUT="$SCAN_DIR/nmap/${TARGET}_${TIMESTAMP}"
mkdir -p "$SCAN_OUTPUT" "$RECON_DIR/domains" "$REPORT_DIR"

# Step 1: Port scan
echo "[*] Step 1: Running Nmap scan..."
nmap -sV -sC -oA "$SCAN_OUTPUT/nmap_full" "$TARGET" --max-rate 500 -T3

# Step 2: Web scan (if applicable)
if [[ "$MODE" == "--type web" ]]; then
  echo "[*] Step 2: Running Nikto web scan..."
  nikto -h "$TARGET" -output "$SCAN_DIR/web-scans/${TARGET}_nikto_${TIMESTAMP}.txt" 2>/dev/null || true

  echo "[*] Step 3: Running Gobuster directory enumeration..."
  WORDLIST="$LAB/datasets/wordlists/SecLists/Discovery/Web-Content/common.txt"
  if [[ -f "$WORDLIST" ]]; then
    gobuster dir -u "http://$TARGET" -w "$WORDLIST" \
      -o "$SCAN_DIR/web-scans/${TARGET}_gobuster_${TIMESTAMP}.txt" \
      -t 20 --timeout 10s 2>/dev/null || true
  else
    echo "  [!] SecLists wordlist not found. Skipping Gobuster."
  fi

  echo "[*] Step 4: Running Nuclei scan..."
  nuclei -u "http://$TARGET" \
    -o "$SCAN_DIR/nuclei/${TARGET}_nuclei_${TIMESTAMP}.txt" \
    -severity low,medium,high,critical \
    -rate-limit 30 2>/dev/null || true
fi

# Step 3: Generate markdown report
REPORT_FILE="$REPORT_DIR/recon_${TARGET}_${TIMESTAMP}.md"
cat > "$REPORT_FILE" << REPORT
# Penetration Test Recon Report
**Target:** $TARGET  
**Date:** $TIMESTAMP  
**Mode:** $MODE  

## Scope & Authorization
> This scan was conducted on an authorized target in a controlled lab environment.

## Findings
- Nmap results: \`$SCAN_OUTPUT/nmap_full.nmap\`
- Web scan results: \`$SCAN_DIR/web-scans/\`
- Nuclei results: \`$SCAN_DIR/nuclei/\`

## Next Steps
- Review open ports and services
- Enumerate detected web applications
- Check for known CVEs on detected service versions
- Perform manual verification of Nuclei findings
REPORT

echo ""
echo "[✓] Recon complete."
echo "[✓] Report: $REPORT_FILE"
RECON_EOF

chmod +x ~/ai-security-lab/agents/pentest-agent/recon.sh
echo 'alias pentest-recon="~/ai-security-lab/agents/pentest-agent/recon.sh"' >> ~/.bashrc

9. LAB ENVIRONMENTS

9.1 DVWA (Damn Vulnerable Web App)

cd ~/ai-security-lab/labs/dvwa

# Pull DVWA Docker image
docker pull vulnerables/web-dvwa

# Create launch script
cat > start_dvwa.sh << 'EOF'
#!/bin/bash
echo "[*] Starting DVWA on http://localhost:80"
docker run --rm -d -p 80:80 --name dvwa vulnerables/web-dvwa
echo "[✓] DVWA running. Default credentials: admin/password"
EOF

chmod +x start_dvwa.sh
echo 'alias lab-dvwa="~/ai-security-lab/labs/dvwa/start_dvwa.sh"' >> ~/.bashrc

9.2 OWASP Juice Shop

cd ~/ai-security-lab/labs/juice-shop

cat > start_juiceshop.sh << 'EOF'
#!/bin/bash
echo "[*] Starting OWASP Juice Shop on http://localhost:3000"
docker run --rm -d -p 3000:3000 --name juiceshop bkimminich/juice-shop
echo "[✓] Juice Shop running at http://localhost:3000"
EOF

chmod +x start_juiceshop.sh
echo 'alias lab-juiceshop="~/ai-security-lab/labs/juice-shop/start_juiceshop.sh"' >> ~/.bashrc

9.3 Metasploitable 2

# Download Metasploitable via VirtualBox or run in Docker
cd ~/ai-security-lab/labs/metasploitable

cat > start_metasploitable.sh << 'EOF'
#!/bin/bash
echo "[*] Starting Metasploitable2 on http://localhost:8080"
docker run --rm -d -p 8080:80 -p 2222:22 --name metasploitable \
  tleemcjr/metasploitable2
echo "[✓] Metasploitable2 running."
echo "    Web: http://localhost:8080"
echo "    SSH: ssh msfadmin@localhost -p 2222 (pass: msfadmin)"
EOF

chmod +x start_metasploitable.sh
echo 'alias lab-msf2="~/ai-security-lab/labs/metasploitable/start_metasploitable.sh"' >> ~/.bashrc

9.4 Stop All Labs

cat > ~/ai-security-lab/labs/stop_all_labs.sh << 'EOF'
#!/bin/bash
echo "[*] Stopping all lab containers..."
docker stop dvwa juiceshop metasploitable 2>/dev/null || true
echo "[✓] All labs stopped."
EOF

chmod +x ~/ai-security-lab/labs/stop_all_labs.sh
echo 'alias lab-stop="~/ai-security-lab/labs/stop_all_labs.sh"' >> ~/.bashrc

10. AUTOMATION SCRIPTS

10.1 Daily SOC Monitor (Cron Job)

cat > ~/ai-security-lab/scripts/automation/daily_soc_monitor.sh << 'EOF'
#!/bin/bash
# Daily SOC monitoring automation
LOG="$HOME/ai-security-lab/logs/soc/daily_$(date +%Y%m%d).log"
echo "=== SOC Daily Report $(date) ===" > "$LOG"

# Failed SSH logins (last 24h)
echo "--- Failed SSH Logins ---" >> "$LOG"
journalctl -u sshd --since "24 hours ago" --no-pager | \
  grep -E "Failed password|Invalid user" >> "$LOG" 2>/dev/null || true

# Sudo usage
echo "--- Sudo Events ---" >> "$LOG"
journalctl --since "24 hours ago" --no-pager | \
  grep sudo >> "$LOG" 2>/dev/null || true

# Listening ports
echo "--- Listening Ports ---" >> "$LOG"
ss -tlnp >> "$LOG"

# Disk usage check
echo "--- Disk Usage ---" >> "$LOG"
df -h >> "$LOG"

# Fail2ban status
echo "--- Fail2ban ---" >> "$LOG"
fail2ban-client status 2>/dev/null >> "$LOG" || true

echo "Report: $LOG"
EOF

chmod +x ~/ai-security-lab/scripts/automation/daily_soc_monitor.sh

# Add to cron (runs daily at 07:00)
(crontab -l 2>/dev/null; echo "0 7 * * * ~/ai-security-lab/scripts/automation/daily_soc_monitor.sh") | crontab -

10.2 SSH Anomaly Detector

cat > ~/ai-security-lab/scripts/automation/ssh_anomaly_watch.sh << 'EOF'
#!/bin/bash
# Real-time SSH anomaly detection using journalctl
echo "[*] OpenClaw SSH Anomaly Watcher — CTRL+C to stop"
journalctl -fu sshd | while read -r line; do
  if echo "$line" | grep -qE "Failed password|Invalid user|authentication failure"; then
    TIMESTAMP=$(date '+%Y-%m-%d %H:%M:%S')
    IP=$(echo "$line" | grep -oE '[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}' | tail -1)
    echo "[$TIMESTAMP] ⚠ ALERT: Suspicious SSH activity from $IP"
    echo "  $line"
    echo "[$TIMESTAMP] $line" >> "$HOME/ai-security-lab/logs/soc/ssh_alerts.log"
  fi
done
EOF

chmod +x ~/ai-security-lab/scripts/automation/ssh_anomaly_watch.sh
echo 'alias watch-ssh="~/ai-security-lab/scripts/automation/ssh_anomaly_watch.sh"' >> ~/.bashrc

10.3 Weekly Vulnerability Scan Script

cat > ~/ai-security-lab/scripts/automation/weekly_vuln_scan.sh << 'EOF'
#!/bin/bash
# Weekly nuclei vulnerability scan against local lab
TARGET="${1:-localhost}"
DATE=$(date +%Y%m%d)
OUTPUT="$HOME/ai-security-lab/scans/nuclei/weekly_scan_${TARGET}_${DATE}.txt"

echo "[*] OpenClaw Weekly Vuln Scan — Target: $TARGET"
echo "[*] Output: $OUTPUT"

nuclei -u "http://$TARGET" \
  -o "$OUTPUT" \
  -severity low,medium,high,critical \
  -rate-limit 20 \
  -timeout 10

echo "[✓] Weekly scan complete: $OUTPUT"
EOF

chmod +x ~/ai-security-lab/scripts/automation/weekly_vuln_scan.sh

# Schedule weekly on Sunday 02:00
(crontab -l 2>/dev/null; echo "0 2 * * 0 ~/ai-security-lab/scripts/automation/weekly_vuln_scan.sh localhost") | crontab -

10.4 Reporting Generator

cat > ~/ai-security-lab/scripts/reporting/generate_report.sh << 'EOF'
#!/bin/bash
# Generate pentest Markdown report skeleton
TARGET="${1:-unknown_target}"
ANALYST="${2:-OpenClaw}"
DATE=$(date +%Y-%m-%d)
OUTPUT="$HOME/ai-security-lab/reports/pentest/report_${TARGET}_${DATE}.md"

cat > "$OUTPUT" << REPORT_TEMPLATE
# Penetration Test Report

| Field         | Detail            |
|---------------|-------------------|
| **Target**    | $TARGET           |
| **Analyst**   | $ANALYST          |
| **Date**      | $DATE             |
| **Status**    | In Progress       |

---

## Executive Summary

> Brief description of the assessment scope, methodology, and key outcomes.

---

## Scope

- **Authorized Targets:** $TARGET
- **Testing Type:** Internal Lab / CTF
- **Environment:** Controlled / Authorized

---

## Methodology

1. Passive Reconnaissance
2. Active Scanning (Nmap, Nuclei)
3. Enumeration
4. Exploitation (authorized targets only)
5. Post-exploitation Analysis
6. Reporting

---

## Findings

### [CRIT-001] — Critical Finding Title
**Severity:** Critical  
**CVSS:** X.X  
**Affected Component:** xxx  

**Description:**  
xxx

**Proof of Concept:**
\`\`\`
insert PoC commands here
\`\`\`

**Recommendation:**  
xxx

---

## Risk Summary

| ID       | Title     | Severity | Status     |
|----------|-----------|----------|------------|
| CRIT-001 | ...       | Critical | Open       |

---

## Recommendations

1. ...
2. ...
3. ...

---

## Appendix

- Nmap output: \`scans/nmap/\`
- Nuclei output: \`scans/nuclei/\`
REPORT_TEMPLATE

echo "[✓] Report generated: $OUTPUT"
EOF

chmod +x ~/ai-security-lab/scripts/reporting/generate_report.sh
echo 'alias gen-report="~/ai-security-lab/scripts/reporting/generate_report.sh"' >> ~/.bashrc

11. SECURITY HARDENING

11.1 SSH Hardening

sudo tee -a /etc/ssh/sshd_config.d/99-hardened.conf << 'EOF'
# OpenClaw SSH Hardening
PermitRootLogin no
PasswordAuthentication yes
MaxAuthTries 3
LoginGraceTime 20
AllowAgentForwarding no
X11Forwarding no
EOF

sudo systemctl restart sshd

11.2 Kernel Hardening (sysctl)

sudo tee /etc/sysctl.d/99-openclaw-hardening.conf << 'EOF'
# OpenClaw Kernel Hardening
# Network protection
net.ipv4.tcp_syncookies = 1
net.ipv4.conf.all.rp_filter = 1
net.ipv4.conf.default.rp_filter = 1
net.ipv4.icmp_echo_ignore_broadcasts = 1
net.ipv4.conf.all.accept_redirects = 0
net.ipv4.conf.all.send_redirects = 0
net.ipv6.conf.all.accept_redirects = 0

# Memory protection
kernel.randomize_va_space = 2
kernel.dmesg_restrict = 1
kernel.kptr_restrict = 2
fs.protected_hardlinks = 1
fs.protected_symlinks = 1
EOF

sudo sysctl --system

11.3 UFW Firewall Setup

sudo pacman -S --noconfirm ufw

sudo ufw default deny incoming
sudo ufw default allow outgoing
sudo ufw allow ssh
sudo ufw enable

sudo systemctl enable --now ufw
sudo ufw status verbose

12. SYSTEMD SERVICE

12.1 Create OpenClaw Background Service

sudo tee /etc/systemd/system/openclaw-monitor.service << 'EOF'
[Unit]
Description=OpenClaw Security Monitoring Agent
After=network.target

[Service]
Type=simple
User=%i
ExecStart=/usr/bin/python3 /home/%i/ai-security-lab/agents/soc-agent/soc_agent.py
Restart=on-failure
RestartSec=30
StandardOutput=journal
StandardError=journal

[Install]
WantedBy=multi-user.target
EOF

# Enable for current user
sudo systemctl enable --now "openclaw-monitor@${USER}"

QUICK REFERENCE — OPENCLAW COMMANDS

# Start OpenClaw AI assistant
openclaw

# Run SOC monitoring report
soc-report

# Watch SSH in real-time
watch-ssh

# Start lab environments
lab-dvwa
lab-juiceshop
lab-msf2
lab-stop        # stop all labs

# Run recon against authorized target
pentest-recon 192.168.56.101 --type web
pentest-recon 192.168.56.101 --type network

# Generate pentest report skeleton
gen-report "192.168.56.101" "YourName"

# Weekly vuln scan
~/ai-security-lab/scripts/automation/weekly_vuln_scan.sh

TOOL REFERENCE TABLE

Category Tool Install Method Purpose
AI Backend Ollama curl installer Local LLM inference
Recon nmap pacman Port/service scanning
Recon masscan pacman Fast port scanning
Recon subfinder go install Subdomain discovery
Recon amass yay Subdomain enumeration
Recon httpx go install HTTP probing
Web nuclei go install Vulnerability scanning
Web ffuf go install Web fuzzing
Web gobuster go install Dir/DNS brute force
Web nikto pacman Web server scanning
Injection sqlmap pacman SQL injection
Framework Metasploit yay Exploitation framework
Password hydra pacman Online brute force
Password hashcat pacman Password cracking
IDS suricata pacman Network IDS/IPS
IDS zeek yay Network analysis
Defense fail2ban pacman Brute force protection
Monitoring osquery yay Host monitoring
SIEM wazuh-agent yay Log/event management
Forensics volatility3 pip Memory forensics
Vuln Scan openvas yay Vulnerability assessment

OpenClaw Security Lab — Arch Linux | Authorized Environments Only
Generated: 2026 | Blue Team + Red Team Hybrid

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment