Ban offending IP addresses – fail2ban

This post is over 3 years old, so please keep in mind that some of its content might not be relevant anymore.

If you have logwatch installed (or you read auth.log file) you can find lots of entries mentioning login attempts/attacks.
Something like:

Nov 20 06:30:43 serverName sshd[63467]: Address 91.191.166.95 maps to 91-191-166-95.netdirekt.com.tr, but this does not map back to the address - POSSIBLE BREAK-IN ATTEMPT!

or

Nov 20 00:47:45 serverName sshd[24617]: Invalid user fluffy from 221.179.34.37
Nov 20 00:47:55 serverName sshd[24640]: Invalid user oracle from 221.179.34.37
Nov 20 00:47:58 serverName sshd[24642]: Invalid user www from 221.179.34.37
Nov 20 00:48:04 serverName sshd[24668]: Invalid user postmaster from 221.179.34.37
Nov 20 00:48:14 serverName sshd[24690]: Invalid user file from 221.179.34.37
Nov 20 00:48:17 serverName sshd[24692]: Invalid user oracle from 221.179.34.37
Nov 20 00:48:23 serverName sshd[24712]: Invalid user dany from 221.179.34.37
Nov 20 00:48:26 serverName sshd[24715]: Invalid user dan from 221.179.34.37
Nov 20 00:48:29 serverName sshd[24717]: Invalid user postgresql from 221.179.34.37
Nov 20 00:48:33 serverName sshd[24719]: Invalid user postgres from 221.179.34.37
Nov 20 00:48:40 serverName sshd[24739]: Invalid user admin from 221.179.34.37
Nov 20 00:48:43 serverName sshd[24750]: Invalid user guest from 221.179.34.37
Nov 20 00:48:46 serverName sshd[24759]: Invalid user admin from 221.179.34.37
Nov 20 00:48:53 serverName sshd[24763]: Invalid user qwerty from 221.179.34.37
Nov 20 00:48:56 serverName sshd[24781]: Invalid user sun from 221.179.34.37
Nov 20 00:49:00 serverName sshd[24783]: Invalid user linux from 221.179.34.37

I’ve got hundreds (if not thousands) of these.
As you can see, all login attempts from different users come from the same IP address.
fail2ban would block this type of attack as you can set it to block/ban an IP address for X days after Y failed login attempts.

On Debian/Ubuntu the installation is as easy as:

apt-get install fail2ban

Now create a copy of the configuration file:

cp /etc/fail2ban/jail.conf /etc/fail2ban/jail.local

Set the IPs you want fail2ban to ignore and modify the “bantime” (in seconds) and “maxretry” if you want:

[DEFAULT]
# "ignoreip" can be an IP address, a CIDR mask or a DNS host
ignoreip = 127.0.0.1 192.168.0.0/24
bantime  = 3600
maxretry = 5

After changing the configuration file restart the service.
service fail2ban restart

To keep an eye on it you can check the log file “/var/log/fail2ban.log” or the iptables

iptables -L

Should you want to “unban” a particular IP address you can run the iptables command with the “line-numbers” flag on like

iptables -L --line-numbers

Check the chain called “fail2ban-ssh”, find the rule you want to delete and run the following command (replacing “line-number”):

iptables -D fail2ban-ssh <>

Enjoy!

Leave a Reply

Your email address will not be published. Required fields are marked *