Securing Network Services with Fail2Ban (CentOS, Debian, Ubuntu)

Installing Fail2ban

To install the Fail2ban program, run the following commands:

  • To install on Ubuntu, Debian:
    sudo apt-get update
    sudo apt-get install fail2ban
  • To install on CentOS:
    yum update
    rpm -Uvh http://dl.fedoraproject.org/pub/epel/6/x86_64/epel-release-6-8.noarch.rpm
    yum install fail2ban

Definitions

Before you begin, it is important to clarify some of the terms used in the following sections:

  • filter - filter defines a regular expression that should match a pattern matching a login error or any other expression
  • action - action defines several commands that are executed at different points in time
  • jail - jail (lit. English "prison") is a combination of one filter and one or more actions. Fail2ban can handle multiple filters at the same time
  • client - refers to the fail2ban-client script
  • server - refers to the fail2ban-server script

Server

Fail2ban consists of two parts: a client and a server. The server is multi-threaded and listens on a Unix socket for commands. The server itself knows nothing about configuration files. Thus, at startup, the server is in a "default" state where no jails are defined. The following options are available for the fail2ban server:

**-b** Start in the background
**-f** Start in front
**-s ** Socket path
**-x** Force the server to run
**-h, —help** Display this help message
**-V, —version** Print version

Fail2ban-server should not be used directly except for debugging purposes. The -s option is probably the most important and is used to set the socket path. Thus, it is possible to run multiple instances of Fail2ban on different sockets. However, this is not necessary as Fail2ban can run multiple jails at the same time.
Fail2ban-client is an interface to Fail2ban. It connects to the server's socket file and sends commands to configure and control the server. The client can read configuration files or simply be used to send a single command to the server using the command line or interactive mode (which is activated with the -i option). fail2ban-client can also start the server. The following options are available for the fail2ban client:

**-c** Configuration directory
**-s** Socket path
**-d** Dump configuration. For debugging
**-i** Interactive mode
**-v** Increase verbosity
**—q** Decrease verbosity
**-x** Force the server to run
**-h, —help** Display this help message
**-V**, —version Print version

All settings in the configuration files can be configured manually. Configuration is a simple and effective way to set up a server. fail2ban-client translates the configuration into a set of commands. However, fail2ban-client has two more commands for internal use. The first is the start. When you enter the command $ fail2ban-client start - the client will first try to deploy a server instance. The client then waits for the server to start by sending it ping requests. Once the server responds to these requests, the fail2ban client parses the configuration and sends the appropriate commands to the server.

The second command is reboot. It is done by entering the command: $fail2ban-client reload

General settings

The fail2ban.conf file contains general settings for the fail2ban server daemon, such as logging level and target. Here you can also specify the socket path used for communication between the client and the server.

Jails

The most important file is jail.conf which contains the declaration of your jails. By default, some sections are inserted as templates. You should include the sections you are interested in and adapt to your local configuration. The following is an example of an ssh-iptables section:
[ssh-iptables]
#enabled = false
enabled = true
filter = sshd
action = iptables[name=SSH, port=ssh, protocol=tcp]
# mail-whois[name=SSH, dest=yourmail@mail.com]
#logpath = /var/log/sshd.log
logpath = /var/log/auth.log
maxretry = 5

With these settings, the following will happen:

* the ssh-iptables section is enabled;
* use the **sshd.conf** filter from the **filter.d** subdirectory;
* the action(s) described in iptables.conf (subdirectory action.d) will be executed if the filter result is true. In this example, the optional mail-whois.conf action is commented out.
* **auth.log** – this log file will be scanned by the filter.

The filter and actions are combined to create jails. Only one filter is allowed per jail, but multiple actions can be specified on separate lines. For example, you can respond to an SSH hack attempt by first adding a new firewall rule, then extracting some information about the offending host using whois, and finally sending an email notification. Or maybe you just want to be notified about your Jabber account when someone accesses the /donotaccess.html page on your web server.

Fail2ban is not limited to the SSH filter. It contains filters and default actions for many daemons and services. You can easily modify them or create new ones. If you look at the filter.d file, you'll notice a few default filters that don't appear in the standard jail.conf that come with the sources. In this example, we take "sshd-ddos.conf". To integrate the filter into fail2ban, edit your jail.conf:
[ssh-ddos]
enabled = true
port = ssh,sftp
filter = sshd-ddos
logpath = /var/log/messages
maxretry = 2
Always remember to adjust $logpath to your log file as above.

Jail Options

Each jail can be customized by configuring the following options:

Name Default setting Description
filter The name of the filter that the jail will use to find matches. Each new filter match increments the counter in the jail
logpath /var/log/messages Path to the log file that is provided to the filter
maxretry 3 Number of matches (i.e. counter value) that triggers the ban action on an IP address
findtime 600 sec Counter is set to zero if no match is found in search seconds
bantime 600 sec Duration (in seconds) for banning an IP address. A negative number for "permanent" ban

Filters

The filter.d directory contains mostly regular expressions that are used to detect hack attempts, password failures, etc. Below is an example filter.d / sshd.conf file with three possible regular expressions corresponding to log file lines:
failregex = Authentication failure for . from
Failed [-/\w]+ for .
from
ROOT LOGIN REFUSED . FROM
iI user .
from
If you are creating your own failregex expressions, the information below will be especially helpful to you.

A failregex can have multiple lines, any of which can match a line in the log file.

In each failregex line, the part corresponding to the hostname or IP address must be wrapped in a (?P ...) sandwich. This is a special regular expression extension associated with Python that assigns the content of the match to the name. The tag is how you tell fail2ban which host connected to, so it must be present on every failregex line. If this is not the case, fail2ban will issue a "No 'host' group" error message.

For convenience, you can use the predefined object in your regular expressions. is an alias for (?:::f{4,6}:)? (?P\S+) which matches either a hostname or an IPv4 address (perhaps embedded in an IPv6 address).

In action scripts, the tag is replaced with the IP address of the host that was matched in the tag.

For a log line to match your failregex, it must match in two parts: the start of the line must match the time pattern or regular expression, and the rest of the line must match your failregex. If the failregex is anchored with a leading ^, then the anchor refers to the beginning of the remainder of the line after the timestamp and intervening white space.

The pattern or regular expression to match the timestamp is not currently documented and is not available for users to read or set (see Debian bug #491253). This is a problem if your log has a label format that fail2ban does not expect, as it will not match any strings. Because of this, you should test any new failregex in the sample log line like in the examples below to make sure it will match. If fail2ban doesn't recognize your log timestamp, you have two options: either reconfigure your daemon to log with a timestamp in a more common format, such as the log line above; or file a bug report asking for your timestamp format.

As an example of the above points, run the following commands on the console and compare the results:
fail2ban-regex 'Jul 18 12:13:01 [1.2.3.4] authentication failed' 'authentication failed'
fail2ban-regex 'Jul 18 12:13:01 [1.2.3.4] authentication failed' '[] authentication failed'
fail2ban-regex '18-07-2008 12:13:01 [1.2.3.4] authentication failed' '[] authentication failed'
fail2ban-regex '18-7-2008 12:13:01 [1.2.3.4] authentication failed' '[] authentication failed'

The first command failed with a "No" host group error message. The second command succeeds and finds the host address 1.2.3.4. The third command will succeed and find the host address 1.2.3.4. Error in the 4th command. She tells us - she says "... no valid date/time found for..." - .

Actions

The action.d directory contains various scripts that define actions. Actions are executed at well-defined points during the execution of Fail2ban: when starting/stopping a jail, when a host is banned/disabled, etc.

Testing/Verification

The following commands will help you check your settings: # fail2ban-client -d Check current configuration. # fail2ban-regex "line" "failregex" The main points on installing and configuring the program are considered. If an IP address is blocked by Fail2ban by mistake, you can remove it from the "black list" with the command: sudo fail2ban-client se t JAIL unbanip IP Where JAIL is the name of the section of the jail.local configuration file, by the rules of which the blocking was activated, IP is the address to be unblocked. Example of the unblock command: sudo fail2ban-client se t ssh-iptables unbanip 78.47.10.113 Will test a single failregex (such as the one defined in sshd.conf) with one line of the log file. Don't forget the double quotes around your line and the failgegex definition. Fail2ban-regex also accepts files for verification. This way it's easier to test and debug your own regular expressions. # fail2ban-regex /var/log/auth.log /etc/fail2ban/filter.d/sshd.conf You can use a combination: # fail2ban-regex /var/log/auth.log "Failed [-/\w]+ for .* from "

Restrictions

Reaction time
First of all, remember that Fail2ban is a log analyzer. It can't do anything until something is written to the log files. Many syslog daemons buffer their output. This may affect the performance of Fail2ban. Thus, it would be a good idea to disable buffering of your syslog daemon.

Estimating the reaction time is quite difficult. Fail2ban waits 1 second before starting new logs to check. In most cases, this should be fine. However, it is possible to get more login errors than maxretry specified.

Was this article helpful?

Tags:

#server

Did you like the article?

Cookie consent

By clicking «I agree», you consent to our website's use of cookies to give you the most relevant experience by remembering your preferences and repeat visits. However, you may visit «Manage сookies» to provide controlled consent. Learn more

Cookies settings

functional

Necessary cookies are crucial for the basic functions of the website and the website will not work in its intended way without them.

Analytics

Analytical cookies are used to understand how visitors interact with the website.

Advertisement

Advertisement cookies are used to provide visitors with relevant ads and marketing campaigns.