#!/bin/bash
# =============================================================
#  xmrig_cleanup.sh — Kill, remove, and block XMRig on a VPS
#  Run as root or with sudo.
#  Schedule: add to root crontab to re-run periodically.
# =============================================================

LOG="/var/log/xmrig_cleanup.log"
TIMESTAMP=$(date '+%Y-%m-%d %H:%M:%S')

log() {
    echo "[$TIMESTAMP] $*" | tee -a "$LOG"
}

log "====== XMRig cleanup started ======"

# ------------------------------------------------------------------
# 1. Kill any running xmrig processes
# ------------------------------------------------------------------
log "--- Checking for running xmrig processes ---"

PIDS=$(pgrep -f xmrig 2>/dev/null)

if [ -n "$PIDS" ]; then
    log "Found xmrig PIDs: $PIDS — killing them..."
    for PID in $PIDS; do
        # Log the binary path before killing
        BIN_PATH=$(readlink -f /proc/"$PID"/exe 2>/dev/null)
        log "  PID $PID -> binary: ${BIN_PATH:-unknown}"
        kill -9 "$PID" 2>/dev/null && log "  Killed PID $PID" || log "  Could not kill PID $PID (may already be gone)"
    done
else
    log "No running xmrig processes found."
fi

# ------------------------------------------------------------------
# 2. Find and delete xmrig binaries
# ------------------------------------------------------------------
log "--- Searching for xmrig binaries on disk ---"

# Common locations attackers drop it
SEARCH_PATHS=("/tmp" "/var/tmp" "/dev/shm" "/root" "/home" "/opt" "/usr/local/bin" "/usr/bin")

for DIR in "${SEARCH_PATHS[@]}"; do
    while IFS= read -r -d '' FILE; do
        log "  Removing binary: $FILE"
        rm -f "$FILE" && log "  Deleted: $FILE" || log "  Failed to delete: $FILE"
    done < <(find "$DIR" -maxdepth 5 -name "xmrig" -o -name "xmrig*" -type f -print0 2>/dev/null)
done

# Full filesystem scan (slower, but thorough)
log "  Running full filesystem scan (this may take a moment)..."
while IFS= read -r -d '' FILE; do
    log "  Removing binary: $FILE"
    rm -f "$FILE"
done < <(find / \
    -path /proc -prune -o \
    -path /sys -prune -o \
    -name "xmrig" -type f -print0 2>/dev/null)

# ------------------------------------------------------------------
# 3. Disable and remove systemd services
# ------------------------------------------------------------------
log "--- Checking systemd services ---"

# Cast a wide net — miners often use disguised service names
SUSPICIOUS_PATTERNS=("xmrig" "monero" "miner" "stratum" "moneroocean")

for PATTERN in "${SUSPICIOUS_PATTERNS[@]}"; do
    while IFS= read -r SERVICE; do
        SERVICE=$(echo "$SERVICE" | awk '{print $1}')
        [ -z "$SERVICE" ] && continue
        log "  Disabling service: $SERVICE"
        systemctl disable --now "$SERVICE" 2>/dev/null
        # Remove the unit file
        UNIT_FILE=$(systemctl show -p FragmentPath "$SERVICE" 2>/dev/null | cut -d= -f2)
        if [ -f "$UNIT_FILE" ]; then
            rm -f "$UNIT_FILE"
            log "  Deleted unit file: $UNIT_FILE"
        fi
    done < <(systemctl list-unit-files --type=service 2>/dev/null | grep -i "$PATTERN")
done

systemctl daemon-reload 2>/dev/null

# ------------------------------------------------------------------
# 4. Clean crontabs
# ------------------------------------------------------------------
log "--- Scanning crontabs ---"

# Root crontab
ROOT_CRON=$(crontab -l 2>/dev/null)
if echo "$ROOT_CRON" | grep -qi "xmrig"; then
    log "  Found xmrig in root crontab — removing..."
    crontab -l 2>/dev/null | grep -vi "xmrig" | crontab -
    log "  Root crontab cleaned."
else
    log "  Root crontab is clean."
fi

# All user crontabs
for USER_HOME in /home/*; do
    USERNAME=$(basename "$USER_HOME")
    USER_CRON=$(crontab -l -u "$USERNAME" 2>/dev/null)
    if echo "$USER_CRON" | grep -qi "xmrig"; then
        log "  Found xmrig in crontab for user '$USERNAME' — removing..."
        crontab -l -u "$USERNAME" 2>/dev/null | grep -vi "xmrig" | crontab -u "$USERNAME" -
        log "  Crontab for '$USERNAME' cleaned."
    fi
done

# System-wide cron files
for CRON_FILE in /etc/crontab /etc/cron.d/* /etc/cron.daily/* /etc/cron.hourly/* /etc/cron.weekly/* /etc/cron.monthly/*; do
    [ -f "$CRON_FILE" ] || continue
    if grep -qi "xmrig" "$CRON_FILE" 2>/dev/null; then
        log "  Found xmrig reference in $CRON_FILE — removing lines..."
        sed -i '/xmrig/Id' "$CRON_FILE"
    fi
done

# ------------------------------------------------------------------
# 5. Clean rc.local and init.d
# ------------------------------------------------------------------
log "--- Checking rc.local and init scripts ---"

if [ -f /etc/rc.local ] && grep -qi "xmrig" /etc/rc.local; then
    log "  Removing xmrig from /etc/rc.local"
    sed -i '/xmrig/Id' /etc/rc.local
fi

for INIT_SCRIPT in /etc/init.d/*; do
    [ -f "$INIT_SCRIPT" ] || continue
    if grep -qi "xmrig" "$INIT_SCRIPT"; then
        log "  Found xmrig reference in $INIT_SCRIPT — removing..."
        rm -f "$INIT_SCRIPT"
        update-rc.d "$(basename "$INIT_SCRIPT")" remove 2>/dev/null
    fi
done

# ------------------------------------------------------------------
# 6. Check for suspicious outbound connections to mining ports
# ------------------------------------------------------------------
log "--- Checking for suspicious network connections ---"

MINING_PORTS="3333|4444|5555|7777|8888|14444|45560|3256"
SUSPICIOUS=$(ss -tupn 2>/dev/null | grep -E "$MINING_PORTS")

if [ -n "$SUSPICIOUS" ]; then
    log "  WARNING: Suspicious connections found (possible mining pool traffic):"
    echo "$SUSPICIOUS" | while IFS= read -r LINE; do
        log "    $LINE"
    done
else
    log "  No suspicious mining connections detected."
fi

# ------------------------------------------------------------------
# 7. Final confirmation
# ------------------------------------------------------------------
log "--- Final check ---"

REMAINING=$(pgrep -af xmrig 2>/dev/null)
if [ -n "$REMAINING" ]; then
    log "  WARNING: xmrig may still be running: $REMAINING"
else
    log "  Confirmed: no xmrig processes running."
fi

log "====== XMRig cleanup complete. Log: $LOG ======"
