Preventing brute force SSH attacks with fail2ban
If you run any type of service on your Raspberry Pi, it's inevitable that bots will attempt to gain access to your system by brute force attacs. Without some kind of protection, these bots can continuously try to gain root access via SSH with millions of password combinations, non stop. Luckily, there is a simple way to prevent this by using fail2ban. This page will show you how to set it up on a Raspberry Pi / Debian system.
First, as always, get things up to date:
sudo apt-get updateand
sudo apt-get upgradeand if you want to upgrade the firmware, do this and reboot:
OK, now lets install fail2ban:
sudo apt-get install fail2ban
By default, fail2ban works on SSH only, but it can be set up on other services such as FTP, apache2 etc. The default setup bans the bad IP on the SSH port after 6 unsuccessful attempts for 600 seconds. You can take a look at the configuration file at:
sudo nano /etc/fail2ban/jail.conf
Custom settings should not be set in this file, instead do your configuration in jail.local
Settings placed in here will override those in jail.conf
sudo nano /etc/fail2ban/jail.local
I set mine to ban the bad IP for 31 days (2678400 seconds) on ALL ports after 3 unsuccessful attempts like so:
[ssh] enabled = true port = ssh filter = sshd logpath = /var/log/auth.log bantime = 2678400 banaction = iptables-allports findtime = 604800 maxretry = 3
Bantime is in seconds. For example, 7 days is 604800. 31 days is 2678400. For permament bans, change bantime to -1. Findtime I have set to 7 days (604800 seconds). This is the time that the max retries applies to.
Note, all bans will be cleared upon restarting fail2ban or rebooting the server. So if you get banned yourself, you can just reboot. Once you have edited the configuration file, restart fail2ban:
sudo service fail2ban restart
After a few days, you will probably have a number of banned IP's. You can check your iptables list with the following command:
sudo iptables -L -n --line
If you wish to unban an IP, use this command, changing the number to the line you want to remove:
sudo iptables -D fail2ban-ssh 1
I hope that helps you prevent any brute force attacks!