The script against DDOS attacks

I will give an example of a simple script against DDOS attacks for NAT servers.
The script is executed when the total number of “conntrack” connections is more than 500000, it saves to the text file the IP address which has the most “conntrack” connections, who has more than 10,000 – adds to the ipset list.

Script content:

#!/bin/bash

count=`cat /proc/sys/net/netfilter/nf_conntrack_count`

if (($count > 500000));
then
    /usr/sbin/conntrack -L | awk '{if ($5 ~ /src/) print $5; else if ($4 ~ /src/) print $4}' | sed "s/src=/ /g" | sort | uniq -c | sort -n | tail -n10 > /var/log/ddos.log

    tracks=($(awk '{print $1}' /var/log/ddos.log))
    ips=($(awk '{print $2}' /var/log/ddos.log))
    for i in seq 0 9;
    do
        if ((${tracks[$i]} > 10000));
        then
         /sbin/ipset -A ddos ${ips[$i]}
        fi
    done
fi
exit 0

Accordingly, an ipset list should be created, for example, with a timeout of 10 minutes after which the IP address is automatically removed from the list.

/sbin/ipset -N ddos iphash timeout 600

Well, let’s ban FORWARD to everyone who is on the ipset list:

/sbin/iptables -A FORWARD -m set --match-set ddos src -j DROP

See also my article:
How to detect DDOS attacks

Leave a comment

Leave a Reply