This how to article will go over stopping a DDoS attack when all you have access to is the targeted Linux host using netfilter and iptables. The two methods are either to simply drop packets from the offending IP/range or to only allow the offending IP/range X number of requests per second, if the range exceeds the requests per second rate traffic is dropped from the range.
*NOTE This method is for small attacks on services you are running on your Linux host. For large attacks using your gateway’s (firewall, load balancer, switch, or router) anti DDoS features maybe necessary or even having your ISP mitigating maybe the only option. I do often see attacks on HTTP from a hundred hosts or so and this article works on that scale.
Here is a example of a script for dropping packets from a offending IP/range lets say for our purposes the range is 206.250.230.0/24
#!/bin/bash
/sbin/iptables -I INPUT 1 -s 206.250.230.0/24 -j DROP
/sbin/iptables -I OUTPUT 1 -d 206.250.230.0/24 -j DROP
/sbin/iptables -I FORWARD 1 -s 206.250.230.0/24 -j DROP
/sbin/iptables -I FORWARD 1 -d 206.250.230.0/24 -j DROP
Here is a example of a script for dropping packets from a offending IP/range if it exceeds 30 requests per second lets say for our purposes the range is 206.250.230.0/24
#!/bin/bash
/sbin/iptables -I INPUT 1 -m limit --limit 30/sec -s 206.250.230.0/24 -j ACCEPT
/sbin/iptables -I INPUT 2 -s 206.250.230.0/24 -j DROP
/sbin/iptables -I OUTPUT 1 -m limit --limit 30/sec -d 206.250.230.0/24 -j ACCEPT
/sbin/iptables -I OUTPUT 2 -d 206.250.230.0/24 -j DROP
/sbin/iptables -I FORWARD 1 -m limit --limit 30/sec -s 206.250.230.0/24 -j ACCEPT
/sbin/iptables -I FORWARD 2 -s 206.250.230.0/24 -j DROP
/sbin/iptables -I FORWARD 1 -m limit --limit 30/sec -d 206.250.230.0/24 -j ACCEPT
/sbin/iptables -I FORWARD 2 -d 206.250.230.0/24 -j DROP
You can see your changes applied by running iptables -L command as seen below:
-bash-4.1# iptables -L
Chain INPUT (policy ACCEPT)
target prot opt source destination
ACCEPT all -- 206.250.230.0/24 anywhere limit: avg 30/sec burst 5
DROP all -- 206.250.230.0/24 anywhere
Chain FORWARD (policy ACCEPT)
target prot opt source destination
ACCEPT all -- anywhere 206.250.230.0/24 limit: avg 30/sec burst 5
DROP all -- anywhere 206.250.230.0/24
ACCEPT all -- 206.250.230.0/24 anywhere limit: avg 30/sec burst 5
DROP all -- 206.250.230.0/24 anywhere
Chain OUTPUT (policy ACCEPT)
target prot opt source destination
ACCEPT all -- anywhere 206.250.230.0/24 limit: avg 30/sec burst 5
DROP all -- anywhere 206.250.230.0/24