Contents
Step 1 — Installing Fail2ban
Fail2ban is available in Ubuntu's software repositories. Begin by running the following commands as a non-root user to update your package lists and install Fail2ban:
sudo apt update
sudo apt install fail2ban
Once installed, Fail2ban will automatically set up a background service. However, it is disabled by default, because some of its default settings can cause undesirable effects. You can verify this using the systemctl command:
systemctl status fail2ban.service
Output○ fail2ban.service - Fail2Ban Service
Loaded: loaded (/lib/systemd/system/fail2ban.service; disabled; vendor preset: enabled
Active: inactive (dead)
Docs: man:fail2ban(1)
You could enable Fail2ban right away, but first you will review some of its features.
Step 2 – Configuring Fail2ban
The fail2ban service keeps its configuration files in the /etc/fail2ban directory. There is a file with defaults called jail.conf. Go to that directory and print the first 20 lines of this file using head -20:
cd /etc/fail2ban
head -20 jail.conf
Output#
# WARNING: heavily refactored in 0.9.0 release. Please review and
# customize settings for your setup.
#
# Changes: in most of the cases you should not modify this
# file, but provide customizations in jail.local file,
# or separate .conf files under jail.d/ directory, e.g.:
#
# HOW TO ACTIVATE JAILS:
#
# YOU SHOULD NOT MODIFY THIS FILE.
#
# It will probably be overwritten or improved in a distribution update.
#
# Provide customizations in a jail.local file or a jail.d/customisation.local.
# For example to change the default bantime for all jails and to enable the
# ssh-iptables jail the following (uncommented) would appear in the .local file.
# See man 5 jail.conf for details.
#
# [DEFAULT]
As you can see, the first few lines of this file are commented out – they begin with #characters, indicating that they are to be read as documentation rather than as settings. As you can also see, these comments direct you not to modify this file directly. Instead, you have two options: either create individual profiles for Fail2ban in multiple files in the jail.d/ directory, or create and collect all of your local settings in a jail.local file. The jail.conf file will be updated periodically as Fail2ban itself is updated, and will be used as a source of default settings for which you have not created any override.
In this tutorial, you will create jail.local. You can do this by copying jail.conf:
sudo cp jail.conf jail.local
You can now start making configuration changes. Open the file in nanoor your favorite text editor:
sudo nano jail.local
As you scroll through the file, this tutorial will review some options you may want to update. The settings located under the [DEFAULT] section near the top of the file will be applied to all services supported by Fail2ban. Elsewhere in the file, there are headers for [sshd] and for other services, containing service-specific settings that will be applied on top of the defaults ./etc/fail2ban/jail.local
[DEFAULT]
. . .
bantime = 10m
. . .
The bantime parameter sets the length of time a client will be banned when it fails to authenticate correctly. This is measured in seconds. By default, this is set to 10 minutes. /etc/fail2ban/jail.local
[DEFAULT]
. . .
findtime = 10m
maxretry = 5
. . .
The next two parameters are findtimeand maxretry. These work together to establish the conditions under which a client is found to be an illegitimate user that should be banned.
The maxretry variable sets the number of attempts a client must make to authenticate within a window of time defined by findtime, before being banned. With the default settings, the fail2ban service will ban a client that unsuccessfully attempts to log in 5 times within a 10-minute window. /etc/fail2ban/jail.local
[DEFAULT]
. . .
destemail = root@localhost
sender = root@<fq-hostname>
mta = sendmail
. . .
If you need to receive email alerts when Fail2ban takes action, you should evaluate the destemail, sendername, and mtasettings. The destemail parameter sets the email address that should receive ban messages. The sendernamesets the value of the “From” field in the email. The mta parameter configures which mail service will be used to send mail. By default this is sendmail, but you may want to use Postfix or another mail solution. /etc/fail2ban/jail.local
[DEFAULT]
. . .
action = $(action_)s
. . .
This parameter configures the action Fail2ban takes when it wants to institute a ban. The value action_ is defined in the file shortly before this parameter. The default action is to update your firewall configuration to reject traffic from the offending host until the ban time elapses.
There are other action_scripts provided by default that you can substitute for $(action_)above: /etc/fail2ban/jail.local
…
# ban & send an e-mail with whois report to the destemail.
action_mw = %(action_)s
%(mta)s-whois[sender="%(sender)s", dest="%(destemail)s", protocol="%(protocol)s", chain="%(chain)s"]
# ban & send an e-mail with whois report and relevant log lines
# to the destemail.
action_mwl = %(action_)s
%(mta)s-whois-lines[sender="%(sender)s", dest="%(destemail)s", logpath="%(logpath)s", chain="%(chain)s"]
# See the IMPORTANT note in action.d/xarf-login-attack for when to use this action
#
# ban & send a xarf e-mail to abuse contact of IP address and include relevant log lines
# to the destemail.
action_xarf = %(action_)s
xarf-login-attack[service=%(__name__)s, sender="%(sender)s", logpath="%(logpath)s", port="%(port)s"]
# ban IP on CloudFlare & send an e-mail with whois report and relevant log lines
# to the destemail.
action_cf_mwl = cloudflare[cfuser="%(cfemail)s", cftoken="%(cfapikey)s"]
%(mta)s-whois-lines[sender="%(sender)s", dest="%(destemail)s", logpath="%(logpath)s", chain="%(chain)s"]
…
For example, action_mw takes action and sends an email, action_mwl takes action, sends an email, and includes logging, and action_cf_mwl does all of the above in addition to sending an update to the Cloudflare API associated with your account to ban the offender there.
Individual Jail Settings
Next comes the part of the configuration file that deals with individual services. These are specified by section headers, like [sshd].
Each of these sections needs to be enabled individually by adding an enabled = true line under the header, along with its other settings. /etc/fail2ban/jail.local
[jail_to_enable]
. . .
enabled = true
. . .
By default, the SSH service is enabled and the others are disabled. Some other settings configured here are filter, which will be used to decide whether a line in a log indicates a failed authentication, and logpath, which tells fail2ban where the logs for that particular service are located.
The filter value is actually a reference to a file located in the /etc/fail2ban/filter.ddirectory, with its .conf extension removed. These files contain regular expressions (a common shorthand for text parsing) that determine whether a line in the log is a failed authentication attempt. We will not cover these files in depth in this guide, because they are fairly complex and the predefined settings match the appropriate lines well.
However, you can see what kinds of filters are available by looking in that directory:
ls /etc/fail2ban/filter.d
If you see a file that looks related to a service you are using, you should open it with a text editor. Most of the files are fairly well commented, and you should at least be able to tell what type of condition the script was designed to guard against. Most of these filters have appropriate (disabled) sections in the jail.conf file that we can enable in the jail.local file if desired.
For example, imagine that you are serving a website using Nginx and notice that a password-protected portion of your site is being hammered with login attempts. You can tell fail2ban to use the nginx-http-auth.conf file to check for this condition within the /var/log/nginx/error.log file.
This is actually already set up in a section called [nginx-http-auth]in your /etc/fail2ban/jail.conf file. You would just need to add the enabledparameter: etc/fail2ban/jail.local
. . .
[nginx-http-auth]
enabled = true . . .
When you are finished editing, save and close the file. At this point, you can enable your Fail2ban service so that it will run automatically from now on. First run systemctl enable:
sudo systemctl enable fail2ban
Then, start it manually for the first time with systemctl start:
sudo systemctl start fail2ban
You can verify that it is running with systemctl status:
sudo systemctl status fail2ban
Output● fail2ban.service - Fail2Ban Service
Loaded: loaded (/lib/systemd/system/fail2ban.service; enabled; vendor preset: enab>
Active: active (running) since Mon 2022-06-27 19:25:15 UTC; 3s ago
Docs: man:fail2ban(1)
Main PID: 39396 (fail2ban-server)
Tasks: 5 (limit: 1119)
Memory: 12.9M
CPU: 278ms
CGroup: /system.slice/fail2ban.service
└─39396 /usr/bin/python3 /usr/bin/fail2ban-server -xf start
Jun 27 19:25:15 fail2ban22 systemd[1]: Started Fail2Ban Service.
Jun 27 19:25:15 fail2ban22 fail2ban-server[39396]: Server ready
In the next step, you will see Fail2ban in action.
Step 3 — Testing the Banning Policies (Optional)
From another server, one that will not need to log in to your Fail2ban server in the future, you can test the rules by getting that second server banned. After logging in to your second server, try to SSH into the Fail2ban server. You can try to connect using a nonexistent name:
ssh blah@your_server
Enter random characters at the password prompt. Repeat this a few times. At some point, the error you receive should change from Permission denied to Connection refused. This indicates that your second server has been banned from the Fail2ban server.
On your Fail2ban server, you can see the new rule by checking the output of iptables. iptables is a command for interacting with low-level port and firewall rules on your server. If you followed DigitalOcean's initial server setup guide, you will be using ufw to manage firewall rules at a higher level. Running iptables -S will show you all of the firewall rules, including those previously created by ufw:
sudo iptables -S
Output-P INPUT DROP
-P FORWARD DROP
-P OUTPUT ACCEPT
-N f2b-sshd
-N ufw-after-forward
-N ufw-after-input
-N ufw-after-logging-forward
-N ufw-after-logging-input
-N ufw-after-logging-output
-N ufw-after-output
-N ufw-before-forward
-N ufw-before-input
-N ufw-before-logging-forward
-N ufw-before-logging-input
-N ufw-before-logging-output
…
If you pipe the output of iptables -Sto grepto search within those rules for the string f2b, you can see the rules added by fail2ban:
sudo iptables -S | grep f2b
Output-N f2b-sshd
-A INPUT -p tcp -m multiport --dports 22 -j f2b-sshd
-A f2b-sshd -s 134.209.165.184/32 -j REJECT --reject-with icmp-port-unreachable
-A f2b-sshd -j RETURN
The line containing REJECT --reject-with icmp-port-unreachablewill have been added by Fail2ban and should reflect your second server's IP address.