SSH iptables "limit" recipe. (tummy.com, ltd. Journal Entry)
tummy.com: we do linux

Sunday July 24, 2005 at 17:36
Subject: SSH iptables "limit" recipe.
Keywords: iptables, SSH, Technical
Posted by: Sean Reifschneider

Related entries:
   More SSH attack activity. by Sean Reifschneider, Saturday July 16, 2005 at 16:02
   Some iptables modules you probably don't know about. by Sean Reifschneider, Sunday July 17, 2005 at 18:42

I've been locking down SSH on some of our machines lately. In addition to turning off Password authentication and PAM, I've also set up an iptables connection rate limit. Here's what I've done to do that.

Unfortunately, Debian doesn't have the "hashlimit" module which I've spoken about here before. It does have the "limit" module though. The lines below are in the "iptables-restore" format. To run them manually you might just want to change the "-A" to "iptables -I" and run them in reverse order.

-A INPUT -m tcp -p tcp --dport 22 -m state --state ESTABLISHED,RELATED -j ACCEPT
-A INPUT -m tcp -p tcp -s 10.1.0.0/24 --dport 22 -j ACCEPT
-A INPUT -m tcp -p tcp --dport 22 -m state --state NEW -m limit --limit 3/min --limit-burst 3 -j ACCEPT
-A INPUT -m tcp -p tcp --dport 22 -j DROP

This assumes that you are running SSH on port 22. The second line allows the hosts on the network block 10.1.0.0/24 to connect an unlimited number of times. Do this for hosts that you would normally connect from. Then, in an emergency, you can get in from another machine, as long as someone else isn't hitting the machine more than 3 times per second.
(Post Reply)

Comment
David Komanek
Subject: ssh limit recipe with regard to IP ?
Thank you for the recipe, I successfully tried it. But it seems there is one problem - iptables are not binding the counted number of connections with the source ip address. Please, is there a way to slowdown connections to sshd only for the source addresses which made more then the specified number of attempts during the defined time period ?

Thank you very much.

Comment
Author: Sean Reifschneider
Subject: That's what this recipe does.
That's what this recipe does. In this example, it allows a burst of up to 3 SSH connection attempts from a given remote IP address, and once that's exceeded it will limit that IP to 3 attempts per minute. The burst recharges every time that the limit is not hit. This set of rules only gets invoked on the initial SSH connection establishment attempt, so it doesn't impact SSH connections after they are made.

Sean