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:


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

if (($count > 500000));
    /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;
        if ((${tracks[$i]} > 10000));
         /sbin/ipset -A ddos ${ips[$i]}
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