#!/bin/sh
# HT CYBERCOP shared list of attacking addresses for fail2ban (https://assbook.net).
# fail2ban reads logs, not lists: this script keeps a separate jail «cybercop» in step with the list — bans new
# addresses for 2 days and lifts the ban from those that left the list. Run it as root from cron, hourly:
#   17 * * * * root /usr/local/sbin/cybercop-fail2ban.sh
# The list is fetched at most once an hour; a repeat within the hour is refused by the server.
set -eu
URL=https://assbook.net/list.txt
DIR=/var/lib/cybercop-fail2ban
JAIL=cybercop
mkdir -p "$DIR"
if [ ! -f /etc/fail2ban/jail.d/cybercop.conf ]; then
  printf '[Definition]\nfailregex = ^CYBERCOP-NEVER-MATCHES <HOST>$\n' > /etc/fail2ban/filter.d/cybercop.conf
  touch /var/log/cybercop-fail2ban.log
  printf '[cybercop]\nenabled = true\nfilter = cybercop\nlogpath = /var/log/cybercop-fail2ban.log\nbackend = auto\nbantime = 2d\nmaxretry = 1\n' \
    > /etc/fail2ban/jail.d/cybercop.conf
  fail2ban-client reload >/dev/null
fi
code=$(curl -sS -o "$DIR/list.new" -w '%{http_code}' -z "$DIR/list.txt" -R "$URL" || echo 000)
[ "$code" = 200 ] || { rm -f "$DIR/list.new"; exit 0; }   # 304: unchanged; 429: too early; other: try next hour
grep -v '^#' "$DIR/list.new" | sed '/^$/d' | sort -u > "$DIR/new.sorted"
[ -f "$DIR/old.sorted" ] || : > "$DIR/old.sorted"
comm -13 "$DIR/old.sorted" "$DIR/new.sorted" | xargs -r -n 200 fail2ban-client set "$JAIL" banip >/dev/null
comm -23 "$DIR/old.sorted" "$DIR/new.sorted" | xargs -r -n 200 fail2ban-client set "$JAIL" unbanip >/dev/null 2>&1 || true
mv "$DIR/new.sorted" "$DIR/old.sorted"
mv "$DIR/list.new" "$DIR/list.txt"
