#!/bin/bash
# ══════════════════════════════════════════════════════════════════════
# Mining Rig Security Healthcheck v1.0
# Read-only — makes NO changes, just reports
#   bash <(curl -fsSL https://dl2.minerlab.io/healthcheck.sh)
# ══════════════════════════════════════════════════════════════════════

EXPECTED_WALLET="prl1pqhfgytekpq4qppc24v5rcyyfvx0f9tvjnlsn306265zkhd4puxcq33tx9m"
RELAY_HOST="45.154.33.25"
ATTACKER_IPS="103.174.103.188 51.15.97.35 77.91.95.253 46.4.231.165 178.33.123.26"
C2_DOMAINS="aikaan.io api.freehive.site freehive.site mqtato.cloud discordapp.com"

RIG=$(hostname)
PASS=0; WARN=0; FAIL=0

RED='\033[0;31m'; YELLOW='\033[1;33m'; GREEN='\033[0;32m'
CYAN='\033[0;36m'; BOLD='\033[1m'; NC='\033[0m'

ok()   { echo -e "  ${GREEN}✓ PASS${NC}  $1"; ((PASS++)); }
warn() { echo -e "  ${YELLOW}⚠ WARN${NC}  $1"; ((WARN++)); }
fail() { echo -e "  ${RED}✗ FAIL${NC}  $1"; ((FAIL++)); }
hdr()  { echo -e "\n${CYAN}${BOLD}── $1 ──${NC}"; }

echo ""
echo -e "${BOLD}╔══════════════════════════════════════════════════════╗${NC}"
echo -e "${BOLD}║   Mining Rig Security Healthcheck v1.0               ║${NC}"
echo -e "${BOLD}╚══════════════════════════════════════════════════════╝${NC}"
echo -e "  Rig     : ${BOLD}$RIG${NC}"
echo -e "  Time    : $(date '+%Y-%m-%d %H:%M:%S %Z')"
echo -e "  Uptime  : $(uptime -p 2>/dev/null || uptime)"

# ── ATTACKER PROCESSES ────────────────────────────────────────────────
hdr "Attacker Processes"
PROCS="hivestatls hivetls mqht candc telegraf mender tmate websocat cloudflared supervisord gopherry gotty"
FOUND_PROCS=0
for P in $PROCS; do
  if pgrep -x "$P" > /dev/null 2>&1; then
    fail "RUNNING: $P (pid=$(pgrep -x $P | head -1))"
    FOUND_PROCS=1
  fi
done
# Check aikaan supervisord specifically
if pgrep -f "aikaan.*supervisord\|supervisord.*aikaan" > /dev/null 2>&1; then
  fail "RUNNING: aikaan supervisord (pid=$(pgrep -f aikaan.*supervisord | head -1))"
  FOUND_PROCS=1
fi
# Check for hivestatls anywhere (including /etc/)
if pgrep -f "/etc/hivestatls" > /dev/null 2>&1; then
  fail "RUNNING: /etc/hivestatls (attacker miner) pid=$(pgrep -f /etc/hivestatls | head -1)"
  FOUND_PROCS=1
fi
[ $FOUND_PROCS -eq 0 ] && ok "No attacker processes running"

# ── ATTACKER FILES ────────────────────────────────────────────────────
hdr "Attacker Files"
BFILES="/opt/aikaan /etc/hivestatls /etc/hivetls.sh /etc/hivetls.zip \
        /usr/local/bin/mqht.sh /usr/local/bin/websocat /usr/bin/websocat \
        /etc/autoxm.sh /etc/systemd/wspass.sh /etc/snap.sh \
        /tmp/nmap_scan_4200_open.gnmap"
FOUND_FILES=0
for F in $BFILES; do
  if [ -e "$F" ] && ! [ -d "$F" ]; then
    fail "EXISTS (file): $F"
    FOUND_FILES=1
  elif [ -d "$F" ] && echo "$F" | grep -qE "/etc/hivestatls|/etc/hivetls|/etc/systemd/wspass|/etc/snap|/etc/autoxm"; then
    ok "DECOY DIR in place: $F (payload drop blocked)"
  fi
done
# Check for /opt/aikaan directory (not decoy)
if [ -d "/opt/aikaan" ] && [ -f "/opt/aikaan/bin/candc" ]; then
  fail "EXISTS: /opt/aikaan/bin/candc (aikaan C2 agent)"
  FOUND_FILES=1
fi
[ $FOUND_FILES -eq 0 ] && ok "No attacker files found"

# ── ATTACKER SERVICES ─────────────────────────────────────────────────
hdr "Attacker Services"
SVCS="aikaan aikaan-agent-opkg-updater hivetls mqht cloudflared"
FOUND_SVCS=0
for S in $SVCS; do
  STATE=$(systemctl is-active "$S" 2>/dev/null)
  if [ "$STATE" = "active" ]; then
    fail "ACTIVE SERVICE: $S"
    FOUND_SVCS=1
  elif systemctl is-enabled "$S" 2>/dev/null | grep -qE "enabled|static"; then
    warn "ENABLED (not running): $S — may start on reboot"
    FOUND_SVCS=1
  fi
done
[ $FOUND_SVCS -eq 0 ] && ok "No attacker services active or enabled"

# ── NETWORK CONNECTIONS ───────────────────────────────────────────────
hdr "Network Connections"
FOUND_CONNS=0
for IP in $ATTACKER_IPS; do
  CONN=$(ss -tnp 2>/dev/null | grep "ESTAB" | grep "$IP")
  if [ -n "$CONN" ]; then
    PROC=$(echo "$CONN" | grep -oP 'users:\(\("\K[^"]+' | head -1)
    fail "ACTIVE CONNECTION to $IP ($PROC)"
    FOUND_CONNS=1
  fi
done
# Check for connection to api.freehive.site
FREEHIVE_IP=$(getent hosts api.freehive.site 2>/dev/null | awk '{print $1}' | head -1)
if [ -n "$FREEHIVE_IP" ]; then
  CONN=$(ss -tnp 2>/dev/null | grep "ESTAB" | grep "$FREEHIVE_IP")
  [ -n "$CONN" ] && fail "ACTIVE CONNECTION to api.freehive.site ($FREEHIVE_IP)" && FOUND_CONNS=1
fi
[ $FOUND_CONNS -eq 0 ] && ok "No active connections to attacker infrastructure"

# ── FIREWALL RULES ────────────────────────────────────────────────────
hdr "Firewall (iptables)"
if iptables-legacy -L OUTPUT -n 2>/dev/null | grep -q "DROP"; then
  IPT=iptables-legacy
else
  IPT=iptables
fi
FOUND_FW=0
for IP in 103.174.103.188 77.91.95.253 46.4.231.165 178.33.123.26; do
  if ! $IPT -C OUTPUT -d "$IP" -j DROP 2>/dev/null; then
    fail "NOT BLOCKED in iptables: $IP"
    FOUND_FW=1
  fi
done
# Check port 4200 blocked
if $IPT -C INPUT -p tcp --dport 4200 -j DROP 2>/dev/null; then
  ok "Port 4200 (ttyd) blocked from all sources"
else
  fail "Port 4200 NOT blocked — LAN worm entry open"
  FOUND_FW=1
fi
[ $FOUND_FW -eq 0 ] && ok "All attacker IPs blocked in iptables"

# ── HOSTS FILE ────────────────────────────────────────────────────────
hdr "Domain Blocking (iptables + /etc/hosts)"
# Note: cache-hive-ip rewrites /etc/hosts every 30 min
# Primary blocking is iptables; /etc/hosts is secondary (re-enforced by cron)
if iptables-legacy -L > /dev/null 2>&1; then _HIPT=iptables-legacy; else _HIPT=iptables; fi
FOUND_HOSTS=0
for D in aikaan.io api.freehive.site mqtato.cloud discordapp.com; do
  HOSTS_OK=0
  IPTS_OK=0
  grep -qF "0.0.0.0 $D" /etc/hosts 2>/dev/null && HOSTS_OK=1
  DIP=$(getent hosts "$D" 2>/dev/null | awk "{print \$1}" | head -1)
  [ -n "$DIP" ] && $_HIPT -C OUTPUT -d "$DIP" -j DROP 2>/dev/null && IPTS_OK=1
  if [ $HOSTS_OK -eq 1 ] && [ $IPTS_OK -eq 1 ]; then
    ok "Blocked (iptables + hosts): $D"
  elif [ $IPTS_OK -eq 1 ]; then
    warn "Blocked in iptables only (hosts overwritten by cache-hive-ip): $D"
  elif [ $HOSTS_OK -eq 1 ]; then
    warn "Blocked in /etc/hosts only (iptables rule missing): $D"
  else
    fail "NOT BLOCKED anywhere: $D"
    FOUND_HOSTS=1
  fi
done
[ -f /usr/local/bin/enforce-hosts.sh ] && ok "enforce-hosts.sh installed (re-applies after cache-hive-ip)" || warn "enforce-hosts.sh missing — domain blocks will be lost every 30 min"
[ $FOUND_HOSTS -eq 0 ] || true

# ── HIVEOS SHELL / TMATE ──────────────────────────────────────────────
hdr "HiveOS Shell (Attack Entry Point)"
if grep -q "SHELLINABOX_ENABLE=0" /hive-config/rig.conf 2>/dev/null; then
  ok "HiveOS Shell (tmate) is DISABLED"
elif grep -q "SHELLINABOX_ENABLE=1" /hive-config/rig.conf 2>/dev/null; then
  fail "HiveOS Shell (tmate) is ENABLED — attacker entry point open"
else
  warn "SHELLINABOX_ENABLE not set in rig.conf"
fi
if pgrep -x tmate > /dev/null 2>&1; then
  fail "tmate process is RUNNING (should be disabled)"
else
  ok "tmate not running"
fi

# ── TOOLS CHECK ───────────────────────────────────────────────────────
hdr "LAN Worm Tools"
if command -v nmap > /dev/null 2>&1; then
  fail "nmap is INSTALLED — LAN scanner available to worm"
else
  ok "nmap not installed"
fi
if [ -f /usr/local/bin/websocat ] || [ -f /usr/bin/websocat ]; then
  fail "websocat is INSTALLED — LAN spreading tool present"
else
  ok "websocat not installed"
fi

# ── WALLET CHECK ──────────────────────────────────────────────────────
hdr "Mining Wallet"
RUNNING_WALLET=$(ps aux 2>/dev/null | grep -v grep | grep -oP '\-\-wallet \K\S+' | head -1)
if [ -z "$RUNNING_WALLET" ]; then
  warn "No miner process found with --wallet argument"
else
  RUNNING_BASE="${RUNNING_WALLET%%.*}"
  if [ "$RUNNING_BASE" = "$EXPECTED_WALLET" ]; then
    ok "Wallet correct: ${RUNNING_BASE:0:30}..."
  else
    fail "WALLET HIJACKED — running: $RUNNING_BASE"
    fail "                  expected: $EXPECTED_WALLET"
  fi
fi
# Check for hivestatls mining (attacker's separate miner)
if pgrep -f "/etc/hivestatls\|hivestatls.*pool\|hivestatls.*wallet" > /dev/null 2>&1; then
  ATCK_WALLET=$(ps aux 2>/dev/null | grep hivestatls | grep -v grep | grep -oP '\-\-wallet \K\S+' | head -1)
  fail "ATTACKER MINER RUNNING: $ATCK_WALLET"
fi

# ── CRONTAB CHECK ────────────────────────────────────────────────────
hdr "Crontab"
BAD_CRON=$(crontab -l 2>/dev/null | grep -iE "freehive|aikaan|hivestatls|hivetls|mqht|wspass|autoxm|snap\.sh|monitor_key_persist")
if [ -n "$BAD_CRON" ]; then
  fail "MALICIOUS crontab entries found:"
  echo "$BAD_CRON" | while read -r line; do echo "      $line"; done
else
  ok "No malicious crontab entries"
fi
# Check monitoring crons are present
if crontab -l 2>/dev/null | grep -q "integrity-check.sh"; then
  ok "integrity-check cron active"
else
  warn "integrity-check cron NOT installed — deploy script not run?"
fi
if crontab -l 2>/dev/null | grep -q "wallet-watch.sh"; then
  ok "wallet-watch cron active"
else
  warn "wallet-watch cron NOT installed"
fi

# ── MONITORING STACK ─────────────────────────────────────────────────
hdr "Monitoring Stack (deploy2.sh)"
systemctl is-active reverse-tunnel > /dev/null 2>&1 && ok "reverse-tunnel service active" || warn "reverse-tunnel NOT active"
systemctl is-active deep-sampler   > /dev/null 2>&1 && ok "deep-sampler service active"   || warn "deep-sampler NOT active"
systemctl is-enabled integrity-boot > /dev/null 2>&1 && ok "integrity-boot service enabled" || warn "integrity-boot NOT enabled — boot-time check missing"
[ -f /etc/mining-monitor/config.conf ] && ok "monitoring config present" || warn "monitoring config missing — deploy not run"
[ -f /etc/mining-monitor/rig_pass   ] && ok "rig password stored on relay" || warn "rig_pass missing"

# ── DEFAULT CREDENTIALS ───────────────────────────────────────────────
hdr "Default Credentials (LAN Worm Vector)"
# Check if user:1 still works (the default HiveOS password used by wspass.sh)
USER_HASH=$(getent shadow user 2>/dev/null | cut -d: -f2)
if [ -z "$USER_HASH" ] || [ "$USER_HASH" = "!" ] || [ "$USER_HASH" = "*" ] || [ "$USER_HASH" = "!!" ]; then
  ok "user account locked / no password"
else
  # Try to verify against '1'
  PY_CHECK=$(python3 -c "
import crypt, sys
h='$USER_HASH'
result = crypt.crypt('1', h)
print('MATCH' if result == h else 'OK')
" 2>/dev/null)
  if [ "$PY_CHECK" = "MATCH" ]; then
    fail "user:1 DEFAULT PASSWORD ACTIVE — LAN worm can log into this rig via ttyd"
  else
    ok "user account does not use default password"
  fi
fi

# ── SUMMARY ───────────────────────────────────────────────────────────
TOTAL=$((PASS + WARN + FAIL))
echo ""
echo -e "${BOLD}╔══════════════════════════════════════════════════════╗${NC}"
echo -e "${BOLD}║   HEALTHCHECK SUMMARY: $RIG${NC}"
echo -e "${BOLD}╚══════════════════════════════════════════════════════╝${NC}"
echo -e "  ${GREEN}PASS${NC} : $PASS / $TOTAL checks"
echo -e "  ${YELLOW}WARN${NC} : $WARN / $TOTAL checks"
echo -e "  ${RED}FAIL${NC} : $FAIL / $TOTAL checks"
echo ""
if [ $FAIL -eq 0 ] && [ $WARN -eq 0 ]; then
  echo -e "  ${GREEN}${BOLD}✓ RIG IS CLEAN AND FULLY HARDENED${NC}"
elif [ $FAIL -eq 0 ]; then
  echo -e "  ${YELLOW}${BOLD}⚠ RIG IS CLEAN — warnings need attention${NC}"
elif [ $FAIL -gt 3 ]; then
  echo -e "  ${RED}${BOLD}✗ RIG IS COMPROMISED — run deploy2.sh immediately${NC}"
  echo -e "    ${CYAN}bash <(curl -fsSL https://dl2.minerlab.io/deploy2.sh)${NC}"
else
  echo -e "  ${RED}${BOLD}✗ ISSUES FOUND — run deploy2.sh to fix${NC}"
  echo -e "    ${CYAN}bash <(curl -fsSL https://dl2.minerlab.io/deploy2.sh)${NC}"
fi
echo ""
