Block brute force attacks with iptables

I was checking my server logs today and found there are quite a lot of ssh brute force attempts recently, I did a quick grep

sudo grep 'invalid' /var/log/auth.log*|grep -v ";"|wc -l

And returns 2595. Looking further into this, turns out they are initialized by 43 unique IPs, 27 of them have more than 5 failure attempts.

username@host$ sudo grep 'invalid' /var/log/auth.log*|awk '{print $13}'|grep -v ";"|uniq -c -d|sort -n -r
    921 222.73.216.14
    447 213.135.111.248
    173 210.1.27.211
     97 89.202.2.46
     88 201.101.6.182
     80 213.175.195.184
     77 94.88.127.100
     61 85.18.113.158
     55 85.21.139.69
     55 61.129.60.23
     47 213.135.111.248
     39 200.55.199.117
     36 202.131.227.27
     25 218.202.225.69
     24 85.18.113.158
     18 220.164.144.133
     15 219.143.216.108
     14 210.99.39.150
     13 190.223.40.154
     13 189.75.180.183
     10 213.135.111.248

Interesting! What I did was to block all the ones with >= 10 failure attempts with iptables. I piped the ones greater than 10 into a text file and then use the below one-liner to append to the iptables.

for i in `cat blacklisted_ips`;	
   do sudo iptables -A INPUT -s $i -j DROP
done

rm blacklisted_ips

Certainly you can be more specific such as blocking these IPs from ssh or web. I just don't like to see them touch my box.

the above commands only apply to the ones attacked my box before, it however has nothing to do with any new ones.

Here is an easy solution:

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 90 --hitcount 10 --rttl --name SSH -j DROP

The rules are pretty self-explanatory, give it a try if you have no clue what they do

^ Top of Page