By Adrian | September 8, 2019
Fail2Ban is a great piece of software to keep those who would try (and fail) to access your services. It’s easy to setup as well, and can be as complicated as you want.
Firstly perform the install by using this command. This will perform the install and create a service so that when you reboot, fail2ban will automatically start.
sudo apt install fail2ban
The configuration I am going to be performing will be for sshd, however there are stacks of pre-configured jails that can be used, and if it doesn’t have a pre-canned option, if your app has a log file file, then it can be customised accordingly.
Firstly we need to create a
jail.local file, so that if fail2ban gets updated, we will keep our configuration and not lose it during the update.
cd /etc/fail2ban sudo cp jail.conf jail.local
Now to modify this configuration file. There are lots of settings in here from the default ban time, to how many tries before a ban gets put into place. Its important to remember to not ban yourself if you are testing, or not to accidentally ban your internal IP address.
sudo nano /etc/fail2ban/jail.local # Modify these lines bantime = 600 findtime = 600 maxretry = 3 # This part appears under Jails [sshd] enabled = true port = ssh logpath = %(sshd_log)s
Restart the service afterwards
sudo service fail2ban restart
And you can check the current status of fail2ban with this command….. oh yeah, locked myself out. LOL
$ sudo fail2ban-client status sshd test@test:~$ sudo fail2ban-client status sshd Status for the jail: sshd |- Filter | |- Currently failed: 0 | |- Total failed: 3 | `- File list: /var/log/auth.log `- Actions |- Currently banned: 1 |- Total banned: 1 `- Banned IP list: 10.10.1.200
This is all well and great, and will stop people trying to brute force your ssh server, however when they are unbanned, they can simply try again. From here we can ratchet up the settings and create a file that contains all the IP/hosts who have attempted and create a more permanent list.
First we need to create the
iptables-multiport.local file so it doesn’t get blown away on upgrades.
cd /etc/fail2ban/action.d cp iptables-multiport.conf iptables-multiport-local
and modify the following in this file
sudo nano iptables-multiport-local # Action Start actionstart = <iptables> -N f2b-<name> <iptables> -A f2b-<name> -j <returntype> <iptables> -I <chain> -p <protocol> -m multiport --dports <port> -j f2b-<name> cat /etc/fail2ban/ip.blocklist | while read IP; do iptables -I f2b-<name> 1 -s $IP -j DROP; done # Action ban actionban = <iptables> -I f2b-<name> 1 -s <ip> -j <blocktype> echo <ip> >> /etc/fail2ban/ip.blocklist
What this is doing is when fail2ban starts, it reads in the
/etc/fail2ban/ip.blocklist file and for each line runs an iptables insert the ip and drop anything from it.
The actionban part simply starts appending the offenders to the