How to use IPTables to Rate Limit using the Recent Module

If you have a sever that must have SSH open to the world, at a minimum we encourage you to consider throttling all requests. It is hard to think of a legitimate reason why any IP should be allowed more than 4 - 5 consecutive NEW connection requests within a specific time frame (e.g., 1 minute).

This is where utility programs like IPTables come in handy.

Rate Limiting with Recent Module

There is more than one way to skin this cat, but for the sake of simplicity we'll use the Recent module in IPTables (another option is hash-limit).

Step 1: Create rule to Track IPs

First, you want to create a rule that tracks the IP's. This file will be used to compare requests and helps keep a running tally on the timestamp.

iptables -I INPUT -p tcp --dport 22 -m conntrack --ctstate NEW -m recent --name ssh-list --set 
-m comment --comment "Track New SSH Attempts"

Step 2: Create rule to Check IPs

Second, you create a rule that checks the IP against the new list and checks it against a specific condition.

In our example, we will look for consecutive NEW requests that exceed 6 attempts from the same IP in a 1 minute time frame.

iptables -I INPUT -p tcp --dport 22 -m conntrack --ctstate NEW -m recent --name ssh-list --update 
--seconds 60 --hitcount 6 -j DROP -m comment --comment "drop excessive SSH attempts"

The --seconds option will identify the time period in which the condition is being checked. So if the user attempts more than 5 attempts within the 60 seconds, they will have to wait for the minute to be up before trying again. It sets the time period to check in and the time period they are blocked.

The end result will generate rules like the following in your IPTables:

root@test:~# iptables -nL
Chain INPUT (policy ACCEPT)
target     prot opt source               destination
DROP       tcp  --              tcp dpt:22 ctstate NEW recent: UPDATE seconds: 60 hit_count: 6 name: ssh-list side: source mask: /* drop excessive SSH attempts */
           tcp  --              tcp dpt:22 ctstate NEW recent: SET name: ssh-list side: source mask: /* Track New SSH Attempts */

If you are curious about the IPs making connection attempts, you can always check them here:

cat /proc/net/xt_recent/ssh-list

Depending on your configuration, you could then create new blocks that last longer than the identified time period manually (essentially creating your own block list). You could easily create your blocklist using our Free IP reputation checker that shows you the latest IP's attempting brute force attempts.

Posted in   Security_Tips   Security   Linux   IPTables     by noc_team

Improve Your Websites Speed and Security