June 15, 2014

How to block IPs easily

A few days ago I finally got my own server. But 20 minutes after setting it up, this started (in /var/log/auth.log):
Jun 13 22:13:49 vserver sshd[4468]: Failed password for root from <IP> port 15931 ssh2
Jun 13 22:13:53 vserver sshd[4468]: Failed password for root from <IP> port 15931 ssh2
Jun 13 22:13:56 vserver sshd[4468]: Failed password for root from <IP> port 15931 ssh2
Jun 13 22:13:58 vserver sshd[4468]: Failed password for root from <IP> port 15931 ssh2
Jun 13 22:14:01 vserver sshd[4468]: Failed password for root from <IP> port 15931 ssh2
Jun 13 22:14:05 vserver sshd[4468]: Failed password for root from <IP> port 15931 ssh2
My first action, of course, was disabling the "root" account and searching for "iptables block ip". And that's what I found:

iptables -A INPUT -s <IP> -j DROP

(you can show your rules via "iptables -L")
This works pretty well, but after some minutes, they start trying to log in from another IP but they used the same ip range: a.b.c.*
After some more google'ing i found the following command:

iptables -I INPUT -m range --src-range <ip-range> -j DROP

you can use this command for example (that's one of the ip address ranges I am getting "attacked"):

iptables -I INPUT -m range --src-range 116.10.191.1-116.10.191.255 -j DROP

To act quicker I recommend setting up two scripts, put them somewhere like "/opt/security" ...:

#1 (blockip.sh):

#!/bin/bash
iptables -A INPUT -s $1 -j DROP

 #2 (blockiprange.sh):

#!/bin/bash
iptables -I INPUT -m iprange --src-range $1 -j DROP

... and setup two bash aliases in ~/.bashrc:

alias blockip="/opt/security/blockip.sh "
alias blockiprange="/opt/security/blockiprange.sh "
After setting up you can easily ban an ip (range) with just typing "blockip <ip>" ("blockiprange <iprange>")!