Using iptables to rate limit incoming connections

We all know various ways of blocking dictionary attack that happened through ssh such as disabling direct root login, blocking default 22 port etc. Besides this we can also make use of iptables in a smarter way to achieve the result. Lets see how to accomplish this.

We make use of a recent module that add IP addresses to a list, which can then be used in the future to test connection attempts against. Let’s make things clear using an example. Consider the following two iptables command.

# iptables -I INPUT -p tcp –dport 22 -i eth0 -m state –state NEW -m recent –set

# iptables -I INPUT -p tcp –dport 22 -i eth0 -m state –state NEW -m recent
–update –seconds 60 –hitcount 4 -j DROP

Here the –set parameter in the first line will make sure that the IP address of the host which initiated the connection will be added to the “recent list”, where it will be tested again in the second rule.

Its in the second rule that actual magic happens

–update flag tests whether the IP address is in the list of recent connections, in our case each new connection on port 22 will be in the list because we used the –set flag to add it in the preceding rule.

–seconds flag is used to make sure that the IP address is only going to match if the last connection was within the time frame given.

–hitcount flag works in a similar way - matching only if the given count of connection attempts is greater than or equal to the number given.

So in total the result of above command is to DROP a connection from an IP address which initiated the connection that has previously been added to the list that sent a packet in the past 60 seconds and sent more than 4 packets in total.

We can change the connection limit by modifying the hit count.

One Response to “Using iptables to rate limit incoming connections”

  1. 2traverseon 13 Jan 2022 at 2:06 am

    1charwoman…

Trackback URI | Comments RSS

Leave a Reply

You must be logged in to post a comment.