#!/bin/sh
# Fuego Red Team: local agent-box check.            https://fuegoredteam.com/check
#
# Looks for AI agents, model servers, databases and dashboards on this machine that listen on
# every network interface (reachable from outside) instead of only localhost, and checks the
# OpenClaw / Hermes / SSH settings that most often leave a box open.
#
# It only READS. It changes nothing, installs nothing, and sends nothing anywhere.
# Read it first if you like:  curl -fsSL https://fuegoredteam.com/check.sh | less
set -u

if [ -t 1 ]; then R=$(printf '\033[31m'); Y=$(printf '\033[33m'); G=$(printf '\033[32m'); D=$(printf '\033[2m'); B=$(printf '\033[1m'); N=$(printf '\033[0m')
else R=""; Y=""; G=""; D=""; B=""; N=""; fi
BAD=0; WARN=0; OK=0
bad()  { BAD=$((BAD+1));  printf '%s✕ %s%s\n' "$R" "$1" "$N"; [ -n "${2:-}" ] && printf '%s  fix: %s%s\n' "$D" "$2" "$N"; return 0; }
warn() { WARN=$((WARN+1)); printf '%s! %s%s\n' "$Y" "$1" "$N"; [ -n "${2:-}" ] && printf '%s  fix: %s%s\n' "$D" "$2" "$N"; return 0; }
ok()   { OK=$((OK+1));    printf '%s✓ %s%s\n' "$G" "$1" "$N"; }
have() { command -v "$1" >/dev/null 2>&1; }

printf '%sFuego local check%s %s· reads only, sends nothing · %s%s\n\n' "$B" "$N" "$D" "$(uname -s)" "$N"

# port|name|severity|fix
SERVICES='18789|OpenClaw gateway|bad|openclaw config set gateway.bind loopback  (then restart; use gateway.bind tailnet for remote access)
8642|Hermes Agent API|warn|set API_SERVER_HOST=127.0.0.1 in ~/.hermes/.env and restart hermes
9119|Hermes dashboard|warn|start it with --host 127.0.0.1 and reach it over Tailscale
11434|Ollama|bad|set OLLAMA_HOST=127.0.0.1 and restart ollama
1234|LM Studio server|bad|turn off "Serve on Local Network" in LM Studio, or: lms server start --bind 127.0.0.1
5678|n8n|warn|set N8N_LISTEN_ADDRESS=127.0.0.1, or put n8n behind Tailscale / Cloudflare Access
8080|Open WebUI / LocalAI / Weaviate (8080)|warn|bind it to 127.0.0.1 (Docker: -p 127.0.0.1:8080:8080)
3000|Open WebUI / Flowise / dev server (3000)|warn|bind it to 127.0.0.1 (Docker: -p 127.0.0.1:3000:3000)
3001|AnythingLLM|warn|bind it to 127.0.0.1 (Docker: -p 127.0.0.1:3001:3001) and set a password
7860|Langflow / Gradio / Stable Diffusion WebUI|bad|set LANGFLOW_HOST=127.0.0.1, or start the web UI without --listen
8188|ComfyUI (no login)|bad|start ComfyUI without --listen
4000|LiteLLM proxy|warn|bind to 127.0.0.1 and set a master_key
8000|vLLM / Chroma (8000)|warn|vLLM: --host 127.0.0.1 --api-key ...; Chroma: chroma run --host localhost
6333|Qdrant|warn|set service.host 127.0.0.1 and service.api_key in the Qdrant config
8888|Jupyter|bad|start Jupyter without --ip=0.0.0.0, and keep the token on
2375|Docker API (unencrypted)|bad|remove tcp://0.0.0.0:2375 from the Docker daemon hosts and restart docker
5432|PostgreSQL|bad|listen_addresses = '"'"'localhost'"'"' in postgresql.conf (Docker: -p 127.0.0.1:5432:5432)
3306|MySQL|bad|bind-address = 127.0.0.1 in my.cnf (Docker: -p 127.0.0.1:3306:3306)
6379|Redis|bad|bind 127.0.0.1 + requirepass in redis.conf (Docker: -p 127.0.0.1:6379:6379)
27017|MongoDB|bad|net.bindIp: 127.0.0.1 in mongod.conf, and enable authorization
9200|Elasticsearch|bad|network.host: 127.0.0.1 and xpack.security.enabled: true'

# ── 1. what is listening on every interface ──────────────────────────────────────
OS=$(uname -s)
LISTEN=""; PARTIAL=""
# Try each source until one answers. netstat sees every user's sockets; lsof without sudo sees only yours.
if [ "$OS" = "Linux" ] && have ss; then LISTEN=$(ss -ltnH 2>/dev/null | awk '{print $4}'); fi
if [ -z "$LISTEN" ] && have netstat; then LISTEN=$(netstat -an 2>/dev/null | awk '/LISTEN/ && $1 ~ /^tcp/ {print $4}'); fi
if [ -z "$LISTEN" ] && have lsof; then
  LISTEN=$(lsof -nP -iTCP -sTCP:LISTEN 2>/dev/null | awk 'NR>1{print $9}')
  [ "$(id -u)" != 0 ] && PARTIAL=1
fi
# Normalize "0.0.0.0:11434", "*:11434", "[::]:11434", "*.11434" (BSD netstat) to "ADDR PORT".
PAIRS=$(printf '%s\n' "$LISTEN" | sed -E 's/^\[?([^]]*)\]?[:.]([0-9]+)$/\1 \2/' | sort -u)

public_port() { # $1=port → prints the public bind address if it listens on all interfaces
  printf '%s\n' "$PAIRS" | awk -v p="$1" '$2==p && ($1=="0.0.0.0" || $1=="*" || $1=="::" || $1=="" || $1=="*%"){print $1; exit}'
}
local_port() {
  printf '%s\n' "$PAIRS" | awk -v p="$1" '$2==p{print $1; exit}'
}

printf '%sServices%s\n' "$B" "$N"
if [ -z "$LISTEN" ]; then
  warn "Couldn't list listening ports (no ss, lsof or netstat). Try running with sudo."
else
  FOUND=0
  OLDIFS=$IFS; IFS='
'
  for line in $SERVICES; do
    IFS='|' read -r port name sev fix <<EOF
$line
EOF
    pub=$(public_port "$port"); loc=$(local_port "$port")
    if [ -n "$pub" ]; then
      FOUND=1
      if [ "$sev" = "bad" ]; then bad "$name listens on all interfaces (port $port)" "$fix"
      else warn "$name listens on all interfaces (port $port)" "$fix"; fi
    elif [ -n "$loc" ]; then
      FOUND=1; ok "$name only listens on $loc (port $port)"
    fi
  done
  IFS=$OLDIFS
  [ "$FOUND" = 0 ] && ok "None of the 21 agent/model/database ports we know are listening"
  [ -n "$PARTIAL" ] && printf '%s  note: without sudo, services run by other users may not show. For the full picture: curl -fsSL https://fuegoredteam.com/check.sh | sudo sh%s\n' "$D" "$N"
fi

# ── 2. Docker publishes ports straight past ufw ─────────────────────────────────
if have docker && docker ps >/dev/null 2>&1; then
  PUB=$(docker ps --format '{{.Names}}	{{.Ports}}' 2>/dev/null | grep -E '(0\.0\.0\.0|\[::\]|:::):[0-9]+->' || true)
  if [ -n "$PUB" ]; then
    # heredoc, not a pipe: a piped while-loop runs in a subshell and would lose the WARN count.
    while IFS='	' read -r cname ports; do
      p=$(printf '%s' "$ports" | grep -oE '(0\.0\.0\.0|\[::\]|:::):[0-9]+' | sed -E 's/.*://' | sort -u | tr '\n' ' ')
      warn "Docker container '$cname' publishes port(s) ${p}on all interfaces" "use -p 127.0.0.1:PORT:PORT (or \"127.0.0.1:PORT:PORT\" in compose). Docker's published ports skip ufw rules."
    done <<DOCKERPORTS
$PUB
DOCKERPORTS
  else ok "No Docker container publishes ports on all interfaces"; fi
fi

# ── 3. OpenClaw ────────────────────────────────────────────────────────────────
printf '\n%sAgents%s\n' "$B" "$N"
OC="${OPENCLAW_CONFIG_PATH:-$HOME/.openclaw/openclaw.json}"
if [ -f "$OC" ]; then
  bind=$(grep -oE '"?bind"?[[:space:]]*:[[:space:]]*"[a-z]+"' "$OC" | head -1 | sed -E 's/.*"([a-z]+)"$/\1/')
  mode=$(grep -oE '"?mode"?[[:space:]]*:[[:space:]]*"(none|token|password|trusted-proxy)"' "$OC" | head -1 | sed -E 's/.*"([a-z-]+)"$/\1/')
  case "$bind" in
    ""|loopback) ok "OpenClaw gateway.bind is ${bind:-default (loopback)}" ;;
    tailnet) ok "OpenClaw gateway.bind is tailnet (private network only)" ;;
    *) bad "OpenClaw gateway.bind is \"$bind\": reachable from other machines" "openclaw config set gateway.bind loopback  (or tailnet)" ;;
  esac
  if [ "$mode" = "none" ]; then bad "OpenClaw gateway auth is turned off (gateway.auth.mode = none)" "openclaw config set gateway.auth.mode token, then openclaw doctor"
  else ok "OpenClaw gateway auth is on (${mode:-token})"; fi
  if have openclaw; then printf '%s  next: run "openclaw security audit --deep" for OpenClaw'"'"'s full built-in audit%s\n' "$D" "$N"; fi
else printf '%s- OpenClaw not found (%s)%s\n' "$D" "$OC" "$N"; fi

# ── 4. Hermes Agent ────────────────────────────────────────────────────────────
HE="$HOME/.hermes/.env"
if [ -f "$HE" ]; then
  en=$(grep -E '^[[:space:]]*API_SERVER_ENABLED[[:space:]]*=' "$HE" | tail -1 | sed -E 's/.*=[[:space:]]*"?([^"]*)"?.*/\1/' | tr 'A-Z' 'a-z')
  host=$(grep -E '^[[:space:]]*API_SERVER_HOST[[:space:]]*=' "$HE" | tail -1 | sed -E 's/.*=[[:space:]]*"?([^"]*)"?.*/\1/')
  if [ "$en" = "true" ] && [ -n "$host" ] && [ "$host" != "127.0.0.1" ] && [ "$host" != "localhost" ]; then
    warn "Hermes API server is enabled on $host" "set API_SERVER_HOST=127.0.0.1 in $HE unless something remote needs it"
  else ok "Hermes API server is off or local-only"; fi
else printf '%s- Hermes Agent not found (%s)%s\n' "$D" "$HE" "$N"; fi

# ── 5. the box itself ──────────────────────────────────────────────────────────
printf '\n%sThis machine%s\n' "$B" "$N"
if [ "$OS" = "Linux" ]; then
  if have ufw; then
    st=$(ufw status 2>/dev/null | head -1)
    case "$st" in
      *inactive*) warn "Firewall (ufw) is installed but inactive" "sudo ufw allow OpenSSH && sudo ufw enable" ;;
      *active*) ok "Firewall (ufw) is active" ;;
      *) printf '%s- ufw status needs root (sudo ufw status)%s\n' "$D" "$N" ;;
    esac
  elif have firewall-cmd; then
    firewall-cmd --state >/dev/null 2>&1 && ok "Firewall (firewalld) is running" || warn "firewalld is not running" "sudo systemctl enable --now firewalld"
  else warn "No ufw or firewalld found" "on a VPS, use your provider's cloud firewall or install ufw"; fi
  SSHD=/etc/ssh/sshd_config
  if [ -r "$SSHD" ]; then
    eff=$( (cat "$SSHD"; cat /etc/ssh/sshd_config.d/*.conf 2>/dev/null) | grep -iE '^[[:space:]]*(PasswordAuthentication|PermitRootLogin)[[:space:]]' )
    printf '%s\n' "$eff" | grep -qiE '^[[:space:]]*PasswordAuthentication[[:space:]]+yes' && warn "SSH allows password logins" "set PasswordAuthentication no and use SSH keys"
    printf '%s\n' "$eff" | grep -qiE '^[[:space:]]*PermitRootLogin[[:space:]]+yes' && warn "SSH allows root login with a password" "set PermitRootLogin prohibit-password"
  fi
elif [ "$OS" = "Darwin" ]; then
  FW=/usr/libexec/ApplicationFirewall/socketfilterfw
  if [ -x "$FW" ]; then
    "$FW" --getglobalstate 2>/dev/null | grep -q "enabled" && ok "macOS firewall is on" || warn "macOS firewall is off" "System Settings → Network → Firewall → turn on"
  fi
  if have launchctl; then
    oh=$(launchctl getenv OLLAMA_HOST 2>/dev/null)
    case "$oh" in 0.0.0.0*|"*"*) warn "OLLAMA_HOST is set to $oh for apps" "launchctl unsetenv OLLAMA_HOST (or set 127.0.0.1) and restart Ollama" ;; esac
  fi
fi
if have tailscale && tailscale status >/dev/null 2>&1; then ok "Tailscale is running (private access without public ports)"
else printf '%s- Tailscale not running. It is the easiest way to reach your agent without opening ports: https://tailscale.com%s\n' "$D" "$N"; fi

# ── summary ────────────────────────────────────────────────────────────────────
printf '\n%s%d to fix%s · %s%d to review%s · %s%d fine%s\n' "$R" "$BAD" "$N" "$Y" "$WARN" "$N" "$G" "$OK" "$N"
printf '%sListening on all interfaces only matters if your firewall, router or cloud provider lets the port through.\n' "$D"
printf 'To see what the internet actually sees, every night: https://fuegoredteam.com%s\n' "$N"
