Apache: Limit the Number of Requests/Traffic per IP

apache-2.2bandwidthiprequests

I would like to only allow one IP to use up to, say 1GB, of traffic per day, and if that limit is exceeded, all requests from that IP are then dropped until the next day. However, a more simple solution where the connection is dropped after a certain amount of requests would suffice.

Is there already some sort of module that can do this? Or perhaps I can achieve this through something like iptables?

Thanks

Best Answer

This is my iptables solution for this kind of issue. Adjust --seconds --hitcount as you need, also iptables table.

iptables -A FORWARD -m state --state NEW -m recent --rcheck --seconds 600 --hitcount 5 --name ATACK --rsource -j REJECT --reject-with icmp-port-unreachable
iptables -A FORWARD -d 192.168.0.113/32 -o eth1 -p tcp -m tcp --dport 80 -m recent --set --name ATACK --rsource -j ACCEPT

Explained:

  1. iptables check if source IP is listed on /proc/net/ipt_recent/ATACK file for 5 or more times in 600 seconds interval and if it's a NEW request. If it is, do a reject; else

  2. iptables check if request is destinated to port 80. If so, print IP and timestamp to /proc/net/ipt_recent/ATACK and forward packet.

It's working fine for my needs.