#!/bin/bash
# ══════════════════════════════════════════════════════════════════════
# integrity-check.sh — Detect malware, tampered agent, blacklisted procs
# Runs every 5 minutes via cron
# ══════════════════════════════════════════════════════════════════════
source /etc/mining-monitor/config.conf 2>/dev/null || exit 1

LOG="${LOG_BASE}/integrity.log"
BASELINE="/etc/mining-monitor/agent_baseline.sha256"
TS=$(date '+%Y-%m-%d %H:%M:%S')
ANOMALY=0
MAX_LINES=10000

flag() { ANOMALY=1; echo "${TS} [ALERT] $1" >> "$LOG"; }

# ── 1. HiveOS agent SHA256 check ─────────────────────────────────────
if [ -f "$BASELINE" ]; then
    if ! sha256sum -c "$BASELINE" --quiet 2>/dev/null; then
        flag "AGENT TAMPERED — SHA256 mismatch vs baseline. Run: sha256sum -c ${BASELINE}"
    fi
fi

# ── 2. Blacklisted processes ─────────────────────────────────────────
for PROC in hivestatls hivetls mqht candc tmate gotty supervisord; do
    if pgrep -x "$PROC" > /dev/null 2>&1; then
        flag "BLACKLISTED PROCESS running: ${PROC} (PID: $(pgrep -x $PROC | tr '\n' ','))"
        # Auto-kill
        pkill -9 -x "$PROC" 2>/dev/null
        echo "${TS} [ACTION] Auto-killed: ${PROC}" >> "$LOG"
    fi
done

# ── 3. Blacklisted binaries on disk ──────────────────────────────────
for FILE in /etc/hivestatls /etc/hivetls.zip /etc/snap.zip \
            /etc/systemd/wspass.zip /opt/aikaan; do
    [ -e "$FILE" ] && flag "MALICIOUS FILE on disk: ${FILE}"
done

# ── 4. Blacklisted service files ─────────────────────────────────────
for SVC in /etc/systemd/system/{hivetls,mqht,aikaan}.service; do
    if [ -f "$SVC" ]; then
        flag "MALICIOUS SERVICE FILE: ${SVC}"
        systemctl stop "$(basename $SVC .service)" 2>/dev/null
        systemctl disable "$(basename $SVC .service)" 2>/dev/null
        rm -f "$SVC"
        systemctl daemon-reload
        echo "${TS} [ACTION] Removed service: ${SVC}" >> "$LOG"
    fi
done

# ── 5. Unexpected outbound connections ───────────────────────────────
# Block attacker C2 if not already blocked
iptables -C OUTPUT -d 103.174.103.188 -j DROP 2>/dev/null || \
    iptables -A OUTPUT -d 103.174.103.188 -j DROP 2>/dev/null

# ── 6. Root password re-enforcement ──────────────────────────────────
STORED_PASS=$(cat /etc/mining-monitor/rig_pass 2>/dev/null)
if [ -n "$STORED_PASS" ]; then
    echo "root:${STORED_PASS}" | chpasswd 2>/dev/null
fi

# ── Result ────────────────────────────────────────────────────────────
if [ "$ANOMALY" -eq 0 ]; then
    echo "${TS} [OK] Integrity check passed" >> "$LOG"
fi

# Rotate log
[ "$(wc -l < "$LOG" 2>/dev/null)" -gt $((MAX_LINES * 2)) ] && \
    tail -n "$MAX_LINES" "$LOG" > "${LOG}.tmp" && mv "${LOG}.tmp" "$LOG"
