#!/usr/bin/env bash
set -u
export LC_ALL=C PATH=/usr/sbin:/usr/bin:/sbin:/bin
umask 077
if (( EUID != 0 )); then echo 'Run as root.' >&2; exit 1; fi
if (( $# > 1 )) || [[ ${1:-} != '' && ${1:-} != '--audit-only' ]]; then
  echo 'Usage: bash server-malware-check.sh [--audit-only]' >&2; exit 2
fi
bad_ip=151.244.30.60
bad_key='SHA256:juoX68SG4rUyUokyOyVl8+2xihlsQHXYVUuqEya4fck'
miner=/usr/lib/.systemj/systemd-journal-he
units=(z9mine.timer z9report.timer z9mine.service z9report.service systemd-journal-helper.service)
files=("$miner" /etc/cron.d/z9mine /etc/cron.d/z9report /etc/cron.d/zz-journald-guard /usr/lib/systemd/systemd-journal-guard /usr/local/bin/.z9report)
keys=(/root/.ssh/authorized_keys /root/.ssh/authorized_keys2)
report=$(mktemp -d /root/server-incident.XXXXXX) || exit 1
exec > >(tee "$report/report.log") 2>&1
failed=0
is_bad_key() {
  printf '%s\n' "$1" | ssh-keygen -lf - 2>/dev/null | awk -v fp="$bad_key" '$2==fp {hit=1} END{exit !hit}'
}
scan() {
  local f u p target line
  date -Is
  hostname
  uptime
  ps -eo pid,ppid,user,pcpu,comm --sort=-pcpu | head -12
  for f in "${files[@]}"; do
    if [[ -e $f || -L $f ]]; then stat -c 'KNOWN_FILE %n %a' "$f"; fi
  done
  for u in "${units[@]}"; do
    printf 'UNIT %s ' "$u"; systemctl is-active "$u" 2>/dev/null || :
  done
  for p in /proc/[0-9]*/exe; do
    target=$(readlink "$p") || continue
    case "$target" in
      "$miner"|"$miner (deleted)") printf 'KNOWN_PROCESS %s %s\n' "$p" "$target" ;;
      /tmp/*|/var/tmp/*|/dev/shm/*|*' (deleted)') printf 'REVIEW_PROCESS %s %s\n' "$p" "$target" ;;
    esac
  done
  for f in "${keys[@]}"; do
    [[ -f $f ]] || continue
    while IFS= read -r line || [[ -n $line ]]; do
      if is_bad_key "$line"; then printf 'KNOWN_KEY %s %s\n' "$f" "$bad_key"; fi
    done < "$f"
  done
  awk -F: '$3==0{print "UID0",$1}' /etc/passwd
  if command -v ss >/dev/null; then
    ss -Hntp state established | awk '/151[.]244[.]30[.]60|139[.]99[.]69[.]109|:10128/'
  fi
  if command -v journalctl >/dev/null; then
    timeout 12 journalctl -u ssh -u sshd --since '7 days ago' -q --no-pager 2>/dev/null |
      awk '/Accepted .*151[.]244[.]30[.]60/{n++} END{print "KNOWN_IP_SSH_LOGINS_7D",n+0}'
  fi
  find /etc/systemd/system /etc/cron.d /var/spool/cron -maxdepth 3 -type f -mtime -7 -print 2>/dev/null | head -30
}
echo '=== Before ==='
scan
if [[ ${1:-} == --audit-only ]]; then echo "Report: $report/report.log"; exit 0; fi

if ! command -v ssh-keygen >/dev/null; then echo 'Cannot inspect SSH keys: ssh-keygen unavailable'; failed=1
else
  for f in "${keys[@]}"; do
    [[ -f $f && ! -L $f ]] || continue
    tmp=$(mktemp /root/.ssh/.incident-key.XXXXXX) || { failed=1; continue; }
    count=0
    while IFS= read -r line || [[ -n $line ]]; do
      if is_bad_key "$line"; then ((count+=1)); else printf '%s\n' "$line" >> "$tmp"; fi
    done < "$f"
    if (( count )); then
      if cp -p -- "$f" "$report/$(basename "$f").before" && mv -- "$tmp" "$f"; then
        printf 'REMOVED_KEYS %s %s\n' "$f" "$count"
        if command -v restorecon >/dev/null; then restorecon "$f" || failed=1; fi
      else failed=1; fi
    fi
    if [[ -e $tmp ]]; then unlink "$tmp" || failed=1; fi
  done
fi

hit=0
for f in "${files[@]}"; do if [[ -e $f || -L $f ]]; then hit=1; fi; done
for p in /proc/[0-9]*/exe; do
  case "$(readlink "$p")" in "$miner"|"$miner (deleted)") hit=1 ;; esac
done
if (( hit )); then
  if command -v systemctl >/dev/null; then
    for u in "${units[@]}"; do
      timeout 15 systemctl stop "$u" 2>/dev/null || :
      f=/etc/systemd/system/$u
      if [[ -f $f && ! -L $f ]]; then mv -- "$f" "$report/$u" || failed=1; fi
      systemctl mask "$u" || failed=1
    done
    systemctl daemon-reload || failed=1
  else echo 'systemd unavailable; inspect startup configuration manually'; failed=1; fi
  for p in /proc/[0-9]*/exe; do
    case "$(readlink "$p")" in
      "$miner"|"$miner (deleted)") pid=${p#/proc/}; pid=${pid%/exe}; kill -TERM "$pid" || failed=1 ;;
    esac
  done
  for f in "${files[@]}"; do
    if [[ -e $f || -L $f ]]; then mv -- "$f" "$report/$(basename "$f")" || failed=1; fi
  done
fi

echo '=== Firewall ==='
svc=codex-persistent-incident-block.service
unit=/etc/systemd/system/$svc
if command -v ufw >/dev/null && ufw status | grep -q '^Status: active'; then
  if ! (grep -F "$bad_ip" /etc/ufw/user.rules 2>/dev/null | grep -Eq 'DROP|REJECT'); then
    ufw insert 1 deny from "$bad_ip" || failed=1
  fi
  if systemctl is-enabled ufw 2>/dev/null | grep -qx enabled &&
     iptables-save 2>/dev/null | grep -F "$bad_ip" | grep -Eq 'DROP|REJECT'; then
    echo 'BLOCK_LIVE_AND_BOOT_CONFIG_VERIFIED ufw'
  else echo 'UFW block or boot configuration unverified'; failed=1; fi
elif command -v systemctl >/dev/null && { command -v iptables >/dev/null || command -v nft >/dev/null; }; then
  if ipt=$(command -v iptables); then
    mode=iptables
    command="/bin/sh -c '$ipt -w 5 -C INPUT -s $bad_ip -j DROP || $ipt -w 5 -I INPUT 1 -s $bad_ip -j DROP'"
  else
    mode=nft
    nftbin=$(command -v nft)
    cfg=/etc/codex-incident-ip-block.nft
    if [[ ! -e $cfg ]]; then
      cat > "$cfg" <<'NFT'
table inet codex_persistent_incident {
 chain incoming {
  type filter hook input priority -25; policy accept;
  ip saddr 151.244.30.60 drop
 }
}
NFT
    fi
    command="/bin/sh -c '$nftbin list table inet codex_persistent_incident >/dev/null 2>&1 || $nftbin -f $cfg'"
  fi
  if [[ ! -e $unit ]]; then
    cat > "$unit" <<UNIT
[Unit]
Description=Persist confirmed incident SSH source block
After=ufw.service nftables.service firewalld.service netfilter-persistent.service
[Service]
Type=oneshot
RemainAfterExit=yes
ExecStart=$command
[Install]
WantedBy=multi-user.target
UNIT
    chmod 644 "$unit"
    systemctl daemon-reload || failed=1
  fi
  if systemctl enable --now "$svc" && systemctl is-enabled "$svc" && systemctl is-active "$svc"; then
    if { [[ $mode == iptables ]] && "$ipt" -w 5 -C INPUT -s "$bad_ip" -j DROP; } ||
       { [[ $mode == nft ]] && "$nftbin" list chain inet codex_persistent_incident incoming | grep -F "$bad_ip drop"; }; then
      echo "BLOCK_LIVE_AND_BOOT_CONFIG_VERIFIED $mode"
    else echo 'Firewall rule unverified'; failed=1; fi
  else failed=1; fi
else
  echo 'Supported firewall and systemd combination not found'; failed=1
fi

echo '=== After ==='
scan | tee "$report/after.log"
if grep -Eq '^KNOWN_(FILE|PROCESS|KEY) ' "$report/after.log"; then
  echo 'Known indicators remain; inspect the report.'; failed=1
fi
echo "Report: $report/report.log"
echo "Quarantine: $report"
exit "$failed"
