monitor_dos.sh

sudo ipset create blackhole hash:ip

#!/bin/bash

# Define the threshold for packets
THRESHOLD=5000

# Define the IPset name
IPSET_NAME="blackhole"

# Define the log file
LOG_FILE="/var/log/iptables.log"

# Define the temporary file to store IPs
TEMP_FILE="/tmp/blackhole_ips.txt"

# Clear the temporary file
true > "$TEMP_FILE"

# Extract IPs with packet counts exceeding the threshold
iptables -vnL -x | awk -v threshold="$THRESHOLD" '
  /Chain/ { chain=$2 }
  /DROP/ && chain ~ /FORWARD|INPUT/ && $1 > threshold { print $8 }
' >> "$TEMP_FILE"

# Add IPs to the IPset if they are not already present
while read -r ip; do
  if ! sudo ipset test "$IPSET_NAME" "$ip" >/dev/null 2>&1; then
    sudo ipset add "$IPSET_NAME" "$ip"
  fi
done < "$TEMP_FILE"

# Apply blackhole route for IPs in the IPset
for ip in $(sudo ipset list "$IPSET_NAME" | grep -v "Name:"); do
  sudo ip route add blackhole "$ip" || true
done

# Clean up
rm "$TEMP_FILE"

chmod +x monitor_dos.sh
sudo ipset save > /etc/ipset.conf

sudo crontab -e
* * * * * /path/to/monitor_dos.sh

Leave a Reply

Your email address will not be published. Required fields are marked *