Заметки сисадмина » How To Protect SSH with Fail2Ban on Debian 11

Заметки сисадмина о интересных вещах из мира IT, инструкции и рецензии. Настраиваем Компьютеры/Сервера/1С/SIP-телефонию в Москве

How To Protect SSH with Fail2Ban on Debian 11

2024-03-06 · Posted in Debian

SSH is the de facto method of connecting to a cloud server. It is durable, and it is extensible — as new encryption standards are developed, they can be used to generate new SSH keys, ensuring that the core protocol remains secure. However, no protocol or software stack is totally foolproof, and SSH being so widely deployed across the internet means that it represents a very predictable attack surface or attack vector through which people can try to gain access.

Any service that is exposed to the network is a potential target in this way. If you review the logs for your SSH service running on any widely trafficked server, you will often see repeated, systematic login attempts that represent brute force attacks by users and bots alike. Although you can make some optimizations to your SSH service to reduce the chance of these attacks succeeding to near-zero, such as disabling password authentication in favor of SSH keys, they can still pose a minor, ongoing liability.

Large-scale production deployments for whom this liability is completely unacceptable will usually implement a VPN such as WireGuard in front of their SSH service, so that it is impossible to connect directly to the default SSH port 22 from the outside internet without additional software abstraction or gateways. These VPN solutions are widely trusted, but will add complexity, and can break some automations or other small software hooks.

Prior to or in addition to committing to a full VPN setup, you can implement a tool called Fail2ban. Fail2ban can significantly mitigate brute force attacks by creating rules that automatically alter your firewall configuration to ban specific IPs after a certain number of unsuccessful login attempts. This will allow your server to harden itself against these access attempts without intervention from you.

In this guide, you’ll see how to install and use Fail2ban on a Debian 11 server.

1)Installing Fail2ban

Fail2ban is available in Debian’s software repositories. Begin by running the following commands as a non-root user to update your package listings and install Fail2ban:

Fail2ban will automatically set up a background service after being installed. You can check its status by using the systemctl command:


You can continue using Fail2ban with its default settings, but first, you’ll review some of its features.

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 that file using head -20:


As you’ll see, the first several 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’ll also see, these comments are directing you not to modify this file directly. Instead, you have two options: either create individual profiles for Fail2ban in multiple files within the jail.d/ directory, or create and collect all of your local settings in a jail.local file. The jail.conf file will be periodically updated as Fail2ban itself is updated, and will be used as a source of default settings for which you have not created any overrides.

In this tutorial, you’ll create jail.local. You can do that by copying jail.conf:

Now you can begin making configuration changes. Open the file in nano or your favorite text editor:

While you are scrolling through the file, this tutorial will review some options that you may want to update. The settings located under the [DEFAULT] section near the top of the file will be applied to all of the services supported by Fail2ban. Elsewhere in the file, there are headers for [sshd] and for other services, which contain service-specific settings that will apply over top of the defaults.

The bantime parameter sets the length of time that a client will be banned when they have failed to authenticate correctly. This is measured in seconds. By default, this is set to 10 minutes.

The next two parameters are findtime and 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 tries a client has 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.

If you need to receive email alerts when Fail2ban takes action, you should evaluate the destemail, sendername, and mta settings. The destemail parameter sets the email address that should receive ban messages. The sendername sets the value of the “From” field in the email. The mta parameter configures what mail service will be used to send mail. By default, this is sendmail, but you may want to use Postfix or another mail solution.

This parameter configures the action that 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 which you can replace $(action_) with above:

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, too.

Individual Jail Settings

Next is the portion 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, with their other settings.

By default, the SSH service is enabled and all others are disabled. . Some other settings that are set here are the filter that will be used to decide whether a line in a log indicates a failed authentication and the 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.d directory, 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 won’t be covering these files in-depth in this guide, because they are fairly complex and the predefined settings match appropriate lines well.

However, you can see what kind of filters are available by looking into that directory:

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 be able to at least 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 instance, imagine that you are serving a website using Nginx and realize that a password-protected portion of your site is getting slammed 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 enabled parameter:

When you are finished editing, save and close the file. If you’ve made any changes, you can restart the Fail2ban service using systemctl:

In the next step, you’ll demonstrate Fail2ban in action.

3)Testing the Banning Policies (Optional)

From another server, one that won’t need to log into your Fail2ban server in the future, you can test the rules by getting that second server banned. After logging into your second server, try to SSH into the Fail2ban server. You can try to connect using a nonexistent name:

Enter random characters into the password prompt. Repeat this a few times. At some point, the error you’re receiving should change from Permission denied to Connection refused. This signals that your second server has been banned from the Fail2ban server.

On your Fail2ban server, you can see the new rule by checking your iptables output. iptables is a command for interacting with low-level port and firewall rules on your server. If you followed DigitalOcean’s guide to initial server setup, you will be using ufw to manage firewall rules at a higher level. Running iptables -S will show you all of the firewall rules that ufw already created:


If you pipe the output of iptables -S to grep to search within those rules for the string f2b, you can see the rules that have been added by fail2ban:


The line containing REJECT –reject-with icmp-port-unreachable will have been added by Fail2ban and should reflect the IP address of your second server.

Leave a Reply