In this tutorial we will cover the steps needed to install and configure fail2ban in order to secure our server. The software works by scanning through log files and reacting to offending actions such as repeated failed login attempts.

Requirements

* Server with installed Linux Distribution (CentOS, Ubuntu, Debian)

* Python version 2.6 or higher

Installing fail2ban

1) Installation:

- For Ubuntu/Debian users, fail2ban can be installed using apt-get:

sudo apt-get install fail2ban

- CentOS users will need to download the EPEL repository first, because fail2ban is not available from CentOS:

rpm -Uvh http://dl.fedoraproject.org/pub/epel/6/x86_64/epel-release-6-8.noarch.rpm

and after that proceed with the installation using yum:

yum install fail2ban

2) Copy the configuration file:

For all supported distributions, fail2ban is installed in /etc/fail2ban. The configuration jail.conf file is located in this folder. However, if we need to make any changes to the configuration, we should not edit jail.conf file directly. We need to make a local copy of it instead:

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

Configuring fail2ban

Once we have copied the configuration file, we can make the needed changes in jail.local.

The Default section contains the general information about the bans and the functions are the same for all distributions:

Configuring fail2ban to protect the SSH

The ssh-iptables section is the part of the configuration file which is responsible for monitoring the SSH connections and blocking the SSH login failures. The values are set up and configured to work by default, but you can modify them if you want.

The structure of this section on CentOS is shown below:

For Ubuntu/Debian users the ssh-iptables section is similar:

enabled = true – The value indicates that the monitoring for SSH login attempts is enabled.

filter = sshd – Refers to the configuration file containing the rules that fail2ban uses to find matches. For example, sshd refers to:

/etc/fail2ban/filter.d/sshd.conf

action - describes the steps that fail2ban will take to ban a matching IP address. Each action refers to a file within the action.d directory. The default ban action, "iptables" can be found at:

/etc/fail2ban/action.d/iptables.conf

logpath – this is the log location that fail2ban will track.

maxretry - is the number of failures before a host gets banned. It is defined in the Default section. However, if you want to set a different number of failures for every service, you can change that here.

Starting fail2ban

Once you have installed and configured fail2ban the way you want, you just need to start it:

1) On Ubuntu/Debian, you need to run:

sudo service fail2ban start

1) On CentOS, you need to run:

service fail2ban start