x.sh

Bash
#!/bin/bash

interface=eth0
dumpdir=/
threshold=5000
sleep_interval=300
blackhole_duration=1200  # 20 minutes in seconds

while /bin/true; do
  pkt_old=$(grep $interface: /proc/net/dev | cut -d :  -f2 | awk '{ print $2 }')
  sleep 1
  pkt_new=$(grep $interface: /proc/net/dev | cut -d :  -f2 | awk '{ print $2 }')

  pkt=$((pkt_new - pkt_old))
  echo -ne "\r$pkt packets/s\033[0K"

  if [ $pkt -gt 5000 ]; then
    echo -e "\nOMFG, DoS detected! Capturing packets..."
    cap_file="$dumpdir/dump_$(date +"%H%M%S").cap"
    tcpdump -n -s0 -c 5000 -w "$cap_file" -i "$interface"

    echo "Analyzing captured packets..."
    offending_ips=$(tcpdump -nn -r "$cap_file" | awk '{print $3}' | cut -d '.' -f1-4 | sort | uniq -c | awk -v threshold=$threshold '$1 > threshold {print $2}')

    for ip in $offending_ips; do
      echo "Black-holing IP: $ip for 20 minutes."
      ip route add blackhole $ip
      (sleep $blackhole_duration; ip route del blackhole $ip) &
    done

    echo "Sleeping for $sleep_interval seconds."
    sleep $sleep_interval
  fi
done

Leave a Reply

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


©️ interdo.me