Untitled

 avatar
unknown
sh
9 months ago
1.6 kB
20
Indexable
#!/bin/bash
# /usr/local/bin/conn_watch.sh
# Bannt IPs mit mehr als THRESH Verbindungen zu :443
# Loggt nur, wenn eine IP neu gesperrt wurde.
THRESH=30
JAIL="plesk-permanent-ban"
LOG="/var/log/conn_watch_bans.log"
DATE() { date -u '+%Y-%m-%d %H:%M:%S UTC'; }

# root required
[ "$(id -u)" -eq 0 ] || { echo "$(DATE) - must run as root" >&2; exit 1; }

# ensure logfile exists & safe perms
touch "$LOG"
chmod 640 "$LOG"

# get IP counts (only established to :443)
ss -tanp | grep ':443' | grep ESTAB \
  | awk '{print $5}' \
  | sed -E 's/\[([0-9a-fA-F:]+)\]:[0-9]+/\1/; s/([0-9]+\.[0-9]+\.[0-9]+\.[0-9]+):[0-9]+/\1/' \
  | sort | uniq -c | sort -nr \
  | while read -r cnt ip; do
    [ -z "$ip" -o -z "$cnt" ] && continue

    # skip private/loopback/link-local/ULA
    if echo "$ip" | grep -Eq '^127\.|^::1$|^10\.|^192\.168\.|^172\.(1[6-9]|2[0-9]|3[0-1])\.|^fd|^fc|^fe80|^::ffff:10\.|^::ffff:192\.168\.|^::ffff:172\.'; then
      continue
    fi

    # only act when over threshold
    if [ "$cnt" -gt "$THRESH" ]; then
      # if already banned in jail -> skip
      if fail2ban-client status "$JAIL" 2>/dev/null | grep -q -w "$ip"; then
        continue
      fi

      # attempt ban
      if fail2ban-client set "$JAIL" banip "$ip" 2>/dev/null; then
        echo "$(DATE) - BANNED $ip (connections: $cnt) via $JAIL" >> "$LOG"
      else
        # falls Ban fehlschlägt, optional kurz ins Syslog (nicht ins spezial-Log)
        logger -t conn_watch "ERROR banning $ip (cnt=$cnt) in $JAIL"
      fi
    fi
  done
Editor is loading...
Leave a Comment