Admins eHow SysAdmin Tips & Tricks

July 23, 2014

How to block ongoing DDOS attack on Linux Server

Filed under: General — admin @ 10:44 am

DDOS attacks are one of hardest types of network attacks to encounter and stop. Usually the attacker uses many different IPs to request legitimate resources from your network to the point of exhaustion of your system resources and takes it down.
If you can somehow filter the IP addresses of the attacker on your system, then it is possible to block them in iptables easily and stop the attack.
In my case the attacker was attacking a website hosted on a dedicated IP address, so I was easily able to filter the attacker IP addresses by following command :

netstat -n | grep a.b.c.d | awk '{print $5}' | grep -Eo '([0-9]{1,3}\.){3}[0-9]{1,3}' | sort | uniq

a.b.c.d : IP address of my server which the victim website was hosted on
You may do all kinds of filtering using grep and awk.
After I identified attacker IP addresses, blocking them was easy. first create a file named block and put it in /usr/bin with following contents :

#!/bin/bash
iptables -I INPUT -s $1/32 -j DROP

make it executable :

chmod +x /usr/bin/block

then run the following command :

netstat -n | grep a.b.c.d | awk '{print $5}' | grep -Eo '([0-9]{1,3}\.){3}[0-9]{1,3}' | sort | uniq | xargs -n1 block

It will automatically block all attacker IPs in server firewall.
You may run the command every 5-10 minutes until the attack stops completely.
The problem of this approach is that you may end up blocking some legitimate users mixed with attacker IPs, but it is still better than having your whole server down indefinitely.
Also after the attack stops, you can remove all firewall rules or simply reboot your server and everything will be good 🙂

Edit :
In fact you can turn this into a real one liner without creating block file :D, here it is :

netstat -n | grep a.b.c.d | awk '{print $5}' | grep -Eo '([0-9]{1,3}\.){3}[0-9]{1,3}' | sort | uniq | xargs -n1 -I {} iptables -I INPUT -s {}/32 -j DROP

Powered by WordPress