Secure your SSH using fail2ban Ubuntu 20.04

Sujit Patel
2 min readMar 26, 2022
Secure SSH using fail2ban

Fail2Ban is a Python-based intrusion prevention framework that defends Linux systems and servers against brute-force attacks.
You can use Fail2Ban to safeguard SSH on your server from brute-force attacks.
It also allows you to keep track of the attack’s strength in terms of the number of authentication tries attempted.

Fail2Ban monitors server access logs and automatically bans IP addresses of bots and attacking users in iptables.

Links:

  1. fail2ban official git repo
  2. fail2ban sample conf file
  3. fail2ban conf location: /etc/fail2ban
  4. fal2ban log location: /var/log/fail2ban.log
  5. fail2ban database file: /var/lib/fail2ban/fail2ban.sqlite3(you can change location by editing fail2ban.conf file.)

Overview

  1. Update and upgrade OS
  2. Install fail2ban
  3. Enable fail2ban on startup
  4. Configure fail2ban
  5. Restart fail2ban
  6. Test fail2ban

Steps

  1. Update your operating system
sudo apt-get update && sudo apt-get upgrade -y

2. Install fail2ban

sudo apt-get install fail2ban

3. Enable fail2ban on startup

sudo systemctl enable fail2ban.service

4. Configuration files are located at /etc/fail2ban. Default file is jail.conf.

It is not recommended to edit default file. It is best to create a new file and write your configuration there. By doing this we will guarantee that your settings will get not override while running package upgrades.

create new file.

sudo vi /etc/fail2ban/jail.d/jail.local

and use below configuration.

Note: You can disable fail2ban jail by setting the enabled configuration to false.

5. Restart fail2ban service to load your new configuration.

sudo systemctl restart fail2ban

To check status

sudo systemctl status fail2ban

6. Now its time to verify fail2ban is working or not.

let’s try to login using wrong username.

ssh using wrong username

Now check logs.

fail2ban logs

As you can see in logs my ip get banned after using wrong username in last 5 min.

To unban use below command.

fail2ban-client set sshd unbanip <your-ip-address>

by using above command you can unban users.

--

--

Sujit Patel

DevOps Engineer, Linux lover, Technology and Automation enthusiast. A strong believer in continuous learning.