Block SSH brute-force attacks

Florian Engelhardt
Aug 19, 2016 · 2 min read

… or at least slow them down (using iptables on Linux)

When having a server with the port 22 open to the internet, you will find a sheer endless number of login tries from various sources. 99% of these are just brute-force or dictionary attacks.

As i do not want my log files to boil over with all these failed logins, i searched for a solution to block them out or at least slow them down.

Here is what it did:

# cleanup
iptables -F
iptables -X SSH_CHECK

# set rules
iptables -N SSH_CHECK
iptables -A SSH_CHECK -m recent --set --name SSH
iptables -A SSH_CHECK -m recent --update --seconds 60 --hitcount 2 --name SSH -j DROP
iptables -A SSH_CHECK -m recent --update --seconds 3600 --hitcount 10 --name SSH -j DROP

iptables -A INPUT -p tcp -s 1.2.3.4 -j ACCEPT
iptables -A INPUT -p tcp --dport 22 -m state --state NEW -j SSH_CHECK

I am creating a new chain called SSH_CHECK to which i pass on every tcp packet received on port 22 that is in state new (aka syn packet). The source ip address is logged and if the same address occurs two or more times in the last minute or ten or more times in the last hour that packet is dropped.

I also added a rule to bypass the SSH_CHECK chain if the source ip address equals 1.2.3.4 (replace that with your static ip or just ditch that line).

To be honest, i am not blocking brute-force attacks, but the attacker (or attacking script) can only try one password per minute or nine passwords per hour.

And at last: it is generally a good advice to turn of password authentication in your ssh server as well es root login. Add the following to your /etc/ssh/sshd_config file or change it to read as follows:

PasswordAuthentication no
PermitRootLogin no
PubkeyAuthentication yes
Florian Engelhardt

Written by

i’m a proud Dad of four kids, Husband, Linux and Vim user, PHP-Developer, Software-Architect, Technical-consultant, Founder, Geek. https://dotbox.org