Programster's Blog

Tutorials focusing on Linux, programming, and open-source

Rate Limit Requests with Iptables

You can rate limit connections to your server by IP so that no single IP can create more than X connections per Y period before being blocked. These can be any type of connection, based on port.

Below is my example that will limit the number of connections to my web server to prevent a brute force attack against my wordpress site. You can tweak the variables at the top of the script to your liking. The below example will block an IP that makes 10 new connection requests, each within 100 seconds of each other. The attacker will be blocked for no more than 100 seconds though.

#!/bin/bash
IPT=/sbin/iptables
# Max connection in seconds
TIME_PERIOD=100
# Max connections per IP
BLOCKCOUNT=100

# default action can be DROP or REJECT
DACTION="DROP"
$IPT -A INPUT -p tcp --dport 80 -i eth0 -m state --state NEW -m recent --set
$IPT -A INPUT -p tcp --dport 80 -i eth0 -m state --state NEW -m recent --update --seconds $TIME_PERIOD --hitcount $BLOCKCOUNT -j $DACTION

$IPT -A INPUT -p tcp --dport 443 -i eth0 -m state --state NEW -m recent --set
$IPT -A INPUT -p tcp --dport 443 -i eth0 -m state --state NEW -m recent --update --seconds $TIME_PERIOD --hitcount $BLOCKCOUNT -j $DACTION

Make sure to run the script with sudo/root privileges on startup.

Test It

Copy the IP of your webserver into the script below and run it. Then try to go to your website and you should fail to connect. You will be able to reconnect after the time period has passed (and you don't keep trying to connect).

#!/bin/bash
ip="PLUG YOUR IP ADDRESS IN HERE (NOT HOSTNAME)"
port="80"
for i in {1..100}
do
  # do nothing just connect and exit
  echo "exit" | nc ${ip} ${port};
done

Proxies

If you are using a proxy, then all requests will be coming from that one IP. You should add this to your proxy instead of your webserver.

References

Last updated: 4th August 2021
First published: 16th August 2018