Skip to main content

Thanwer's Blog

Securing Your Linux Server with Fail2Ban for SSH Protection

Table of Contents

Fail2ban is a software which scans log files like /var/log/auth.log and bans IP addresses which have done too many failed login attempts.

This is just one layer of security and should be used together with other tools and techniques such as iptables and SSH hardening.

I always configure a simple SSH jail using fail2ban on my GNU/Linux servers.

Today, I am going to show you how to configure a simple SSH jail.

# Installing fail2ban

First you (obviously) need to install the fail2ban package.

apt install fail2ban   # For Ubuntu/Debian
yum install fail2ban   # For CentOS/RHEL

# Configuring Fail2Ban

The fail2ban configuration is very simple, the configuration files are located at: /etc/fail2ban

The fail2ban.conf contains the default configuration profile, it is a good practice to not edit this file, but instead create a separate file named fail2ban.local, which overrides fail2ban.conf:

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

The defaults should make a working setup for now, so let’s skip this for now.

Next, we have the jail.conf file, which is where we configure our “jails” as the name suggests.

Here we are going to make some changes, so first let’s create a jail.local file with the following content:

[DEFAULT]
bantime.multipliers = 5 15 30 60 300 720 1440 2880
bantime = 86400
findtime = 86400
maxretry = 2
ignoreip = 192.2.0.0/24, 2001:0DB8::/32

[sshd]
backend=systemd
enabled=true
mode=aggressive
action  = iptables[name=SSH, port=22, protocol=tcp]

Those settings are self explanatory, in the [DEFAULT] section we are setting some parameters, like for how long we should ban the attackers, and trusted IPs, remember to change those values as your needs, specially ignoreip.

Take your time to fine tune those parameters.

# Enabling and testing Fail2ban

Enable and start the fail2ban service

systemctl enable --now fail2ban

For SSH jails the test is very simple, you can test by simply failing to log on a couple times.

You can check the status with the command:

fail2ban-client status
fail2ban-client status sshd

Example of a SSH jail on a production server

As you can see, the SSH service on a cloud VPS is constantly being attacked, my server has almost 400 currently banned IPs.

# More jails!

Today I showed how to protect your GNU/Linux SSH service, but is is not over, you can use fail2ban to protect any service that you run!

You can even integrate fail2ban protection with Cloudflare if you use their services!

I suggest you to check the /etc/fail2ban/filter.d folder, which contains the default filters for popular services, like Apache, Asterisk, Mail server services, etc…

Be sure to take a look at the official documentation.