Block brute force attacks with iptables

Because iptables comes standard with every Linux distribution we’ll skip right to setting up the specific firewall rules we need. In depth configuring of iptables takes a bit of understanding and is not within the scope of this article, but let’s take a look at these two statements:

sudo iptables -A INPUT -i eth0 -p tcp –dport 22 -m state –state NEW -m recent –set –name SSH
sudo iptables -A INPUT -i eth0 -p tcp –dport 22 -m state –state NEW -m recent –update –seconds 60 –hitcount 8 –rttl –name SSH -j DROP

The -i eth0 is the network interface to which ssh connections are made. Typically this is eth0, but maybe you need to change it.

That’s it! Together they will rate-limit all incoming SSH connections to 8 in a one minute window. Normal users will have no trouble logging in, but the brute force attacks will be dropped, limiting the number of possible account combinations from unlimited, to 8. That’s

failsafe

While you’re still testing, you might want to add the following line to your crontab

*/10 * * * * /sbin/iptables -F

This will flush all the rules every 10 minutes, just in case you lock yourself out. When you’re happy with the results of your work, remove the line from your crontab, and you’re in business.