Secure your server with fail2ban
Let’s say that you have a public Linux server on the internet and that it is technically possible for everyone to connect to it using ssh. In this scenario, it is probably appropriate to protect it from who tries to guess the password obsessively making an impressive number of repeated attempts.
(Yes, I know that you are thinking that if the ssh key is present on the client side, then typing in the password is no longer a problem; anyway I do not like this way of using ssh, since I don’t want to worry if I lose my smartphone or my notebook.)
Well, in brief fail2ban is an intrusion prevention software against brute-force attacks, written in the Python, that scans your logs and bans evil IPs using iptables. Here is a 5-minute installation and configuration guide for Ubuntu and derivative distros.
Installation:
apt install iptables # maybe it's installed yet apt install fail2ban
The configuration directory is
/etc/fail2ban/
Do not edit the file jail.conf; just create a new file named jail.local and put the follownig content in it:
[ssh] enabled = true port = ssh filter = sshd logpath = /var/log/auth.log maxretry = 3 bantime = 900 ignoreip = 192.168.1.2where
- logpath is the name of the logfile that fail2ban checks for failed login attempts
- maxretry is the maximum number of failed login attempts before a host is blocked by fail2ban (default 3)
- bantime is the number of seconds that a remote host will be blocked by fail2ban (dafault=600), but I prefer 15 minutes
- findtime is the time period in seconds in which we’re counting retries (default=600)
- ignoreip is the list of IP addresses that can not be blocked by fail2ban; here I used my static desktop IP
And now restart the service using
systemctl restart fail2ban
Now you can try to login with the wrong password and your ssh client IP will be blocked!!! You can monitor the status of the bans with some commands:
systemctl status fail2ban # prints the service process status fail2ban-client status ssh # prints info about banned IPs iptables -L # alternative way to print info about banned IPs fail2ban-client set ssh unbanip xxx.xxx.xxx.xxx # unbans one IP
Usually the log configured in fail2ban.conf is /var/log/fail2ban.log, so using grep you can view some info about how fail2ban has been working:
grep Ban /var/log/fail2ban.log grep Unban /var/log/fail2ban.log
Update: after being heavily attacked by hackers, I reconfigured my server more agressively like this:
[DEFAULT] bantime = 1 month findtime = 1 month maxretry = 2 ignoreip = 192.168.1.0/24 [ssh] enabled = true port = ssh filter = sshd logpath = %(sshd_log)s [ssh-ddos] enabled = true port = ssh filter = sshd-ddos logpath = %(sshd_log)s
Posted on 2019-05-23
__________________
Copyright © 2019-2024 Marcello Zaniboni