To protect our server from brute-force passwords, you can use the sshguard or sshit utilities.

Work principles.

sshguard and sshit work the same way. They analyze system messages about incorrect authentication and, if a certain value is reached, enter the attacking ip into the blocking rule of the firewall. After a certain time, ip is removed from the rule.
Accordingly, a configured firewall is required for operation.

SSHGuard

sshguard can work with

  • AIX native firewall- for IBM AIX operating systems
  • netfilter / iptables- for Linux-based operating systems
  • Packet Filter (PF)- for BSD operating systems (Open, Free, Net, DragonFly -BSD)
  • IPFirewall (IPFW)- for FreeBSD and Mac OS X
  • IP Filter (IPFILTER)- for FreeBSD, NetBSD and Solaris
  • tcpd "s hosts_access (/etc/hosts.allow)- portable across UNIX
  • null- portable do-nothing backend for applying detection but not prevention

I use PF so in the note there are examples in PF.

Installing sshguard.

FreeBSD:

Install from ports

Cd / usr / ports / security / sshguard-pf / && make install clean

If for some reason you do not use ports, download the latest version from the sshguard website and compile manually

./configure --with-firewall = pf && make && make install

Debian:

apt-get install sshguard

Setting up the OS for sshguard to work.

Create a file for storing logs

# touch / var / log / sshguard

Debian (wheezy):

Edit the following line in // etc / default / sshguard

#mcedit / etc / default / sshguard #ARGS = "- a 40 -p 420 -s 1200" ARGS = "- a 5 -p 420 -s 2400 -b 5: / etc / sshguard / blacklist"

and restart sshguard
service sshguard restart

FreeBSD:

We need to add two lines to the PF configuration

Table persist

we declare a table where sshguard enters ip robots.

Block in quick on $ if0 proto tcp from

Actually the blocking rule itself, it should be marked at the very top of the rules block of the PF configuration file. $ if0 the interface on which connections will be blocked, to block on all interfaces, replace with any.
Re-read the config file

Auth.info; authpriv.info | exec / usr / local / sbin / sshguard

and restart syslog

# / etc / rc.d / syslogd restart

Actually, after these manipulations, sshguard will block attacks with default parameters.
When attacking in /var/log/auth.log we will see something like the following

Jun1611: 01: 40 www sshd: Invalid user test from61.172.251.183Jun1612: 29: 48 www sshd: Invalid user test from85.114.130.168Jun1612: 29: 49 www sshd: Invalid user test from85.114.130.168Jun1612: 29: 49 www sshd: Invalid user test from85.114.130.168Jun1612: 29: 50 www sshd: Invalid user test from85.114.130.168Jun1612: 29: 50 www sshguard: Blocking85.114.130.168: 4for> 420secs: 4 failures over 2 seconds.

Configuring sshguard options

sshguard has a number of parameters that we can override
-a the number of failed authentication attempts after which the ip will be blocked. The default is 4.
-p how many seconds the ip will be unlocked. The default is 420.
-s how many seconds sshguard remembers ip. The default is 1200. To make it clearer, if there is one attack from ip in 30 minutes, then it will never get banned with the default setting.
-w white ip, network, or path to a file of white addresses. The file format is one line - one entry, # defines comments.
-b determines after how many blocking ip will be added to the blacklist and the path to it. The blacklist is loaded when sshguard starts and is not automatically cleared.

sshguard does not have a configuration file, the parameters are set when sshguard starts. In our case, sshguard starts syslog, so let's edit syslog.conf so that sshguard will block ip after 3 unsuccessful attempts to authenticate for 30 minutes, and after 5 locks blacklist it.

Auth.info; authpriv.info | exec / usr / local / sbin / sshguard -a 3-p 1500-b 5: /usr/local/etc/sshguard.blacklist

the first time is blocked for 420 seconds and deleted after 7 minutes
the second time by 2 * 420 y is removed after 14 minutes
the third time for 2 * 2 * 420 and is deleted after 28 minutes and so on ...
2 ^ (N-1) * 420 Nth time.

Sshit

Sshit is a perl script, respectively, it is necessary for the system to have perl, as well as 2 modules

  • IPC :: Shareable
  • Proc :: PID :: File

Sshit can only work with pf and ipfw.

Installing sshit

cd / usr / ports / security / sshit / && make install clean

Sshit config.

Sshit has a configuration file /usr/local/etc/sshit.conf in which you can override the defaults.

FIREWALL_TYPE = "pf"; # What firewall we use MAX_COUNT = 3; # Number of failed authentication attempts after which ip is blocked WITHIN_TIME = 60; # Within how many seconds the specified number of unsuccessful authentications must occur RESET_IP = 300; # After how many seconds ip will be unlocked. PFCTL_CMD = "/ sbin / pfctl"; PF_TABLE = "badhosts" # name of the table where bad ip are entered

Configuring the OS for sshit.

By analogy with setting up for sshguard, edit the PF configuration file

Table persist block in quick on $ if0 proto tcp from to $ if0 port ssh label "ssh brute"

re-read the configuration file

#pfctl -f /etc/pf.conf

Editing syslog.conf

Auth.info; authpriv.info | exec / usr / local / sbin / sshit

and restart syslog

One of the common attacks on the SSH service is a brute-force attack, in which a remote attacker endlessly tries to log in with different passwords. Of course, there are arguments against password authentication for SSH, and there are alternative authentication mechanisms, existing options such as public key authentication or two-factor authentication will negate a brute-forcing attack. Without getting into a discussion about the advantages and disadvantages of different authentication methods, let's consider a situation where password authentication is required. How do you protect your SSH server against brute force attacks?

fail2ban is a well-known open source intrusion prevention framework for Linux, it monitors various system logs (e.g. /var/log/auth.log or / var / log / secure) and automatically enforces various defenses against detected suspicious actions. In fact, fail2ban can be very useful for protecting against brute-force attacks on an SSH server.

In this tutorial I will demonstrate how to install and configure fail2ban to protect SSH server against brute-forcing attacks from remote IP addresses.

Installing Fail2ban on Linux

To install fail2ban on CentOS or RHEL, first install the EPEL repository and then run the following command.

To install fail2ban on Fedora, simply run:

$ sudo yum install fail2ban

To install fail2ban on Ubuntu, Debian or Linux Mint:

$ sudo apt-get install fail2ban

Configuring Fail2ban for SSH Server

You are now ready to configure fail2ban to harden your SSH server. You need to edit the config file in /etc/fail2ban/jail.conf. The config file contains a “DEFAULT” section where you define default parameters for all services that are monitored and service-specific sections where you define any service-specific jails (eg SSH, Apache, etc.) to overwrite parameters default.

In the jail section of certain services (somewhere after the jail section) you need to define a section where you will configure specific settings for SSH jails. The current ban of IP addresses is done by iptables.

The following example is in /etc/fail2ban/jail.conf, which contains the "ssh-iptables" jail setting. Of course, there may be other jails for different applications, depending on your needs.

$ sudo vi /etc/fail2ban/jail.local # space-separated list of IP addresses, CIDR prefixes or DNS hostnames # to bypass security fail2ban ignoreip = 127.0.0.1 172.31.0.0/24 10.10.0.0/24 192.168.0.0/24 # the number of seconds for which the client is blocked bantime = 86400 # the number of unsuccessful attempts after which the blocking occurs maxretry = 5 # the number of seconds during which unsuccessful attempts are cumulatively recorded findtime = 600 mta = sendmail enabled = true filter = sshd action = iptables sendmail-whois # for Debian based distributions logpath = /var/log/auth.log # for Red Hat based distributions logpath = / var / log / secure # ssh specific maximum retry threshold maxretry = 3

In accordance with the given configuration, fail2ban will automatically ban any remote IP addresses from which at least 3 unsuccessful attempts were received in the last 10 minutes. Once banned, the offending IP will remain blocked for 24 hours. This event will be notified by mail.

After the configuration file is ready, restart the fail2ban service as shown below.

On Debian, Ubuntu or CentOS / RHEL 6:

$ sudo service fail2ban restart

On Fedora or CentOS / RHEL 7:

$ sudo systemctl restart fail2ban

To check if fail2ban started successfully, run the fail2ban-client command with the argument “ping”. If fail2ban is running normally, you should see a “pong” response.

$ sudo fail2ban-client ping Server replied: pong

Testing Fail2ban on SSH against brute-force attacks

To check if fail2ban is working, try logging into the SSH server using the wrong password to simulate a brute force attack. In the meantime, check /var/log/fail2ban.log, which records all the interesting events that happen in fail2ban.

$ sudo tail -f /var/log/fail2ban.log

According to the log above, fail2ban banned the IP address 192.168.1.8, as it detected multiple errors in an attempt to log into SSH from this IP address.

Check Fail2ban status and unblock blocked IP addresses

The “ssh-iptables” jail in fail2ban uses iptables to block the IP addresses of violators, you can easily check the ban by looking at the current iptables rules as shown below.

$ sudo iptables --list -n Chain INPUT (policy ACCEPT) target prot opt ​​source destination fail2ban-SSH tcp - 0.0.0.0/0 0.0.0.0/0 tcp dpt: 22 Chain FORWARD (policy ACCEPT) target prot opt ​​source destination Chain OUTPUT (policy ACCEPT) target prot opt ​​source destination Chain fail2ban-SSH (1 references) target prot opt ​​source destination DROP all - 192.168.1.8 0.0.0.0/0 RETURN all - 0.0.0.0/0 0.0.0.0/0

If you want to unblock IP addresses from fail2ban, you can also run the iptables command:

$ sudo iptables -D fail2ban-SSH -s 192.168.1.8 -j DROP

While you can manually check and manage the list of blocked IPs in fail2ban using iptables commands, the correct way is actually to use the tool command line ail2ban-client. This tool allows you to manage not only the “ssh-iptables” jail, but also any other type of fail2ban jail in a unified command line interface.

To check fail2ban status (which will show you a list of currently active jails):

$ sudo fail2ban-client status

To check the status of a specific jail (e.g. ssh-iptables):

$ sudo fail2ban-client status ssh-iptables

The above command will show a list of banned IP addresses.

To unblock a specific IP address:

$ sudo fail2ban-client set ssh-iptables unbanip 192.168.1.8

Note, if you stop fail2ban, all blocked IP addresses will be unblocked. When you restart fail2ban, it will find the list of offending IP addresses from / var / log / secure (or /var/log/auth.log) and re-ban those IP addresses if the ban time has not expired.

Setting Fail2ban to autoload and enable

After you have successfully tested fail2ban, the last step to enable fail2ban is to automatically start when the server is powered on. On Debian based distributions, fail2ban autostart is enabled by default. On Red Hat based distributions, enable autostart in the following way.

On CentOS / RHEL 6:

$ sudo chkconfig fail2ban on

On Fedora or CentOS / RHEL 7:

$ sudo systemctl enable fail2ban

Outcome

In this tutorial, I demonstrated how to install and configure fail2ban to secure an SSH server. While fail2ban can mitigate a brute-force attack, please remember, it cannot protect SSH servers against complex (distributed) brute-forcing campaigns where attackers bypass fail2ban using thousands of bot-controlled IP addresses.

As soon as a service "lights up" on the public network, it instantly becomes an object for attack. One of the problems is an attempt to gain access by brute-forcing passwords. And SSH is no exception.

Analysis of the authentication log file /var/log/auth.log or its analogues shows that attempts to guess a password are usually made from several IPs at once and are stretched in time.

SSH brute force protection

You can protect yourself from this in different ways:

  • Using SSH Daemon Configuration Capabilities
  • Packet filter
  • Special applications
  • Port knocking

The easiest and most effective way is to change the default port 22, for example, to 2002, if this does not interfere with other tasks. We make an entry in / etc / ssh / sshd_config:

After that, attempts to guess passwords practically stop. There are times when you cannot change the port. Alternatively, you can restrict SSH access to specific users (in particular, root) or a group. In sshd_config, a number of parameters are responsible for this: AllowUsers, AllowGroups, DenyUsers and DenyGroups. Conveniently, you can specify an IP or subnet with a login. For example, let's allow access to the user admin and user, the latter from only one IP:

Another effective option for brute-force protection is the use of certificates for authentication. Moreover, using the special parameter match, you can create a conditional block in which you can override the parameters of the global section. For example, we will deny SSH login with a password for the root user, allowing everyone else:

# allow everyone access by password
PasswordAuthentication yes
# root will only use the certificate
match user root
PasswordAuthentication no
KbdInteractiveAuthentication no

Using TCP Wrapper, we can also restrict access to any service only from certain IPs, for this you just need to write the necessary rule in the /etc/hosts.allow or /etc/hosts.deny file. Allow in /etc/hosts.allow access only from the required subnet:

sshd: 192.168.1.0/24: allow

Or in /etc/hosts.deny:

sshd: ALL: deny
sshd: ALL EXCEPT 192.168.1.0/24: allow

The packet filter allows you to very precisely set the connection parameters by discarding unnecessary packets. With its help it is easy to restrict access to the 22nd port only certain addresses... Simple example:

iptables -A INPUT -s! 192.168.0.1 -p tcp -m tcp --dport 22 ↵
-j REJECT -reject-with icmp-port-unreachable

Filtering packets by ports and IP addresses is not very effective if the Administrator is not tied to the workplace. In this case, special utilities will help: Fail2ban, Sshguard. Fail2ban was originally designed to secure SSH. Although today it is already a framework that can be easily customized for any application. The principle of operation is very simple. The daemon periodically checks the logs for any suspicious activity records. The suspicious IP address is then blocked by iptables or TCP Wrapper. After the time specified in the settings, the blocking is usually removed so as not to accidentally block a legal site. When the rule is triggered, an event is logged in the /var/log/fail2ban.log and an email can be sent.

One process can control several services at once, and the package contains ready-made settings for popular Linux applications. In the default settings, only SSH is protected.

On Ubuntu and Debian, it is installed with the command:

$ sudo apt-get install fail2ban

All settings are made in several files located in the / etc / fail2ban directory. The fail2ban.conf contains the parameters for starting the daemon itself, the jail.conf describes the monitored services (inside the SSH section).

Enabled = true
port = 22
filter = sshd
logpath = /var/log/auth.log
maxretry = 3

Filters and actions are written in files located in the filter.d and action.d subdirectories. By default, all files have the .conf extension, it is better not to touch them (including jail.conf). All changes should be entered into a file with the .local extension (for example, jail.local), the parameters of which replace the settings from the first one, and will not be lost during the update. You can use the fail2ban-regex utility to check if the filter is working.

Secure Shell can be found everywhere. Since its release in 1995, SSH has been widely adopted as a powerful remote access protocol for Linux.

However, as you know, great strength is great responsibility. A misconfigured SSH daemon can be more of a threat than a help. In this article, we'll walk through five steps to harden SSH security.

1. Disable root login.

The easiest step. Obviously, there are few reasons to allow root login over SSH. Disabling such access is quite simple and will improve security.

Let's find / etc / ssh / sshd_config (it may be in a different directory, it depends on the distribution). In it we define the place of PermitRootLogin and replace the value with "no":

PermitRootLogin no

Of course, this will not prevent anyone from breaking into the system under a regular user, but it will still serve as an extra obstacle on the way to the prevalence of the system.

After reading everything written above and implementing it in practice, we will receive the keys for authorization on the server as a result. After making sure everything works, you can disable interactive input:

PasswordAuthentication no
ChallengeResponseAuthentication no

Using this Python script, the administrator can automatically blacklist hosts upon unsuccessful login, banning them forever. The simplest way installation:

Europa ~ # emerge -pv denyhosts
These are the packages that would be merged, in order:
Calculating dependencies ... done!
app-admin / denyhosts-2.5 0 kB
Total size of downloads: 0 kB
europa ~ # emerge denyhosts

There is not a lot of documentation on the program (if there is anything, for example), however, all configuration options are normally described in the configuration file.

Europa $ nano -w /etc/denyhosts.conf

I do not think that configuring DenyHosts will cause any special problems - it is enough to read the config carefully.

After configuration, you can run the program with a daemon or through the scheduler. In Gentoo daemon:

Rc-update add denyhosts default

Via cron, let's say every 10 minutes:

Python / usr / bin / denyhosts -c /etc/denyhosts.conf

All the joy of DenyHost is not only in blocking hosts trying to get to your SSH server, but also in the fact that you can synchronize your "blacklist" with DenyHost servers. This creates a collective host list containing all attackers. It will prevent an attack at its root.

4. Change the port number.

Most of the hacking attempts come from automated scripts that scan the network for SSH daemons. In the overwhelming majority of cases, they try to break into port 22, which only plays into our hands. By changing the port, we will automatically cut off most unauthorized access attempts.

It is worth changing in the config.

SSH allows you to create a secure connection to the server, however, to work properly, the SSH service itself must have access to the Internet. This creates an attack vector for potential attackers, hence SSH needs additional protection.

In general, any service with network access is a potential target. In the logs of these services, you may notice repeated, systematic login attempts - these are brute force attacks by users and bots.

The fail2ban service can mitigate attacks with rules that automatically re-configure the iptables firewall based on a predefined number of failed login attempts. This will allow the server to respond in a timely manner to unauthorized access without administrator intervention.

This guide will help you install and configure fail2ban on an Ubuntu 14.04 server.

Install fail2ban

The Ubuntu repository provides the fail2ban package, so it can be installed using the standard package manager.

Update package index and install fail2ban using these commands:

sudo apt-get update
sudo apt-get install fail2ban

Now you can start configuring the utility.

Fail2ban configurations

The fail2ban configuration files are stored in the / etc / fail2ban directory. The default parameters can be found in the jail.conf file.

Since this file can be changed during the package upgrade, you do not need to edit it. It is better to copy its contents to another file and adjust the parameters there. For these two files to work correctly, it is best to leave only the settings in the new file that need to be overridden in the jail.local file. All parameters by default will be read from jail.conf file.

Copy jail.conf and use it as base for jail.local file. To do this, enter:

awk "(printf" # "; print;)" /etc/fail2ban/jail.conf | sudo tee /etc/fail2ban/jail.local

After that, look at jail.conf:

sudo nano /etc/fail2ban/jail.conf

Some parameters can be updated in this file. The section parameters will be applied to all services that fail2ban supports (unless these values ​​are overridden in the configuration files of these services).


. . .
ignoreip = 127.0.0.1/8
. . .

The ignoreip parameter configures the source addresses that fail2ban will ignore. By default, it allows any traffic coming from the local machine to pass through. You can add other addresses to ignore by placing them at the end of the ignoreip directive, separated by a space.


. . .
bantime = 600
. . .

The bantime parameter sets the time during which the client will be blocked if it failed to authenticate. Its value is measured in seconds. The default is 600 seconds (10 minutes).


. . .
findtime = 600
maxretry = 3
. . .

The next two parameters to watch out for are findtime and maxretry. Together they define the conditions under which illegal users will be blocked.

The maxretry variable specifies the number of login attempts and findtime the time interval within which the user must authenticate. If the client has exceeded any of these indicators, he will be blocked. By default, fail2ban service blocks clients who failed to provide credentials 3 times within 10 minutes.


. . .
destemail = [email protected]
sendername = Fail2Ban
mta = sendmail
. . .

The destemail, sendername, and mta parameters allow you to configure email alerts. The destemail parameter specifies the address Email that should receive messages about blocked users. The sendername parameter specifies the sender of the message. The mta parameter determines which mail service will be used to send mail. Add these parameters to jail.local in the section and set the appropriate values.


. . .
action = $ (action_) s
. . .

This parameter configures the fail2ban action in case of blocking. The action_ value is defined in the file a little before this parameter. The default action will block attacker traffic until the ban time expires by reconfiguring the firewall.

If you want to customize email alerts, add or uncomment the action element in the jail.local file and change its value from action_ to action_mw. If you want the email to include the corresponding lines from the logs, you can specify the value of action_mwl. If you choose to use email alerts, make sure your mail settings support them.

Individual parameters

Support for individual services is included in special sections of the same name. For example, ssh service parameters can be specified in the section.

Each of these sections can be enabled by uncommenting the section header in jail.local and changing the enabled line to "true":


. . .
enabled = true
. . .

By default, only SSH service is supported, and all other services are disabled.

These sections use the values ​​set in the section as a basis and adjust them as necessary. To override any values, add a section for the corresponding service to jail.local and change its values.

Also some other parameters are set here. The filter parameter helps determine if a line in the log indicates a failed authentication attempt; the logpath parameter tells fail2ban where the logs for that particular service are located.

The value of the filter parameter is a link to a file with the .conf extension located in the /etc/fail2ban/filter.d directory. These files contain regular expressions that determine if a line in the log represents a failed authentication attempt. These files are beyond the scope of this tutorial because they are quite complex, and the default options are fine in most cases.

You can view the filters in this catalog:

ls /etc/fail2ban/filter.d

Find the file associated with the required service and open it with text editor... Most of the files are well commented out, and you can familiarize yourself with the service protection scenario. Most of these filters have corresponding sections in the jail.conf file (they are disabled by default). They can be included in the jail.local file if needed.

Let's say you have a site that is served from using nginx... The web server logs are constantly updated with unsuccessful login attempts. The fail2ban utility can use the nginx-http-auth.conf file to constantly check /var/log/nginx/error.log.

Almost all the necessary parameters for this are already in the section in the /etc/fail2ban/jail.conf file. You just need to uncomment this section in the jail.local file and set the enabled parameter to true.

. . .
enabled = true
. . .

After that, you need to restart fail2ban.

Configuring fail2ban

Now you know the basics of fail2ban. Try configuring auto blocking policy for SSH and Nginx service. You also want the fail2ban tool to send email messages in case of IP blocking.

First, install the required software.

You will need nginx as fail2ban will track its logs and sendmail to send notifications. We also need the iptables-persistent package so that the server will save and automatically load the firewall rules when the server boots. All of these packages can be downloaded from the standard Ubuntu repositories:

sudo apt-get update
sudo apt-get install nginx sendmail iptables-persistent

Stop the fail2ban service to set up a basic firewall.

Configuring the firewall

The underlying firewall must support established connections as well as traffic generated by the server itself and traffic destined for SSH and web server ports. All other traffic will be blocked. The rules look like this:

sudo iptables -A INPUT -i lo -j ACCEPT
sudo iptables -A INPUT -m conntrack --ctstate ESTABLISHED, RELATED -j ACCEPT
sudo iptables -A INPUT -p tcp --dport 22 -j ACCEPT
sudo iptables -A INPUT -p tcp -m multiport --dports 80,443 -j ACCEPT
sudo iptables -A INPUT -j DROP

These commands implement the above policy. To view the current firewall rules, type:

sudo iptables -S
-P INPUT ACCEPT
-P FORWARD ACCEPT
-P OUTPUT ACCEPT
-A INPUT -i lo -j ACCEPT




-A INPUT -j DROP

Save your firewall rules so they are not lost after a reboot.

sudo dpkg-reconfigure iptables-persistent

Restart fail2ban:

sudo service fail2ban start

Request firewall rules:

sudo iptables -S
-P INPUT ACCEPT
-P FORWARD ACCEPT
-P OUTPUT ACCEPT
-N fail2ban-ssh

-A INPUT -i lo -j ACCEPT
-A INPUT -m conntrack --ctstate RELATED, ESTABLISHED -j ACCEPT
-A INPUT -p tcp -m tcp --dport 22 -j ACCEPT
-A INPUT -p tcp -m tcp --dport 80 -j ACCEPT
-A INPUT -j DROP
-A fail2ban-ssh -j RETURN

Each chain now has its own default policy. There are also five basic rules in the firewall. The fail2ban structure is highlighted in red: this tool already enforces SSH blocking rules. Sometimes this structure is not displayed at first, as fail2ban may not add the structure until the first block.

Configuring fail2ban

Now you need to add the fail2ban settings to the jail.local file:

sudo nano /etc/fail2ban/jail.local

Here you can set a stricter blocking time interval. Find and uncomment the title. In this section, change the bantime parameter so that the service blocks the client for half an hour:


. . .
bantime = 1800
. . .

You also need to set up notifications. First, find the destemail parameter, which should also be in the section. Enter the email address you want to use to collect these messages:


. . .
destemail = [email protected]
. . .

In sendername, specify any convenient value. We recommend that you use a descriptive value here that the postal service can easily filter out.

Then you need to fix the value of action. You can set the value to action_mw, which blocks the client and then sends the "whois" report. The action_mwl value does the same, but also sends the appropriate log lines in the message.


. . .
action =% (action_mwl) s
. . .

In the SSH section in the maxretry directive, you can change the number of failed authentication attempts. If you are using a non-standard port (not 22), specify it in the port parameter. As stated earlier, this server is already on.

Then find the nginx-http-auth section. Uncomment the header and change the enabled parameter to "true".

. . .

enabled = true
. . .

That's all you need to do in this section if the web server uses standard ports and its logs are stored in the standard directory.

Restart fail2ban

Save and close the file.

Then restart the fail2ban service. Sometimes it is even better to stop it and then start it again.

sudo service fail2ban stop
sudo service fail2ban start

It can take several minutes for all firewall rules to load. Sometimes rules are not added until the first client is blocked. After a while, you will be able to check the new rules:

sudo iptables -S
-P INPUT ACCEPT
-P FORWARD ACCEPT
-P OUTPUT ACCEPT
-N fail2ban-nginx-http-auth

-N fail2ban-ssh

-A INPUT -p tcp -m multiport --dports 80,443 -j fail2ban-nginx-http-auth


-A INPUT -p tcp -m multiport --dports 22 -j fail2ban-ssh

-A INPUT -i lo -j ACCEPT
-A INPUT -m conntrack --ctstate RELATED, ESTABLISHED -j ACCEPT
-A INPUT -p tcp -m tcp --dport 22 -j ACCEPT
-A INPUT -p tcp -m tcp --dport 80 -j ACCEPT
-A INPUT -j DROP
-A fail2ban-nginx-http-auth -j RETURN

-A fail2ban-ssh -j RETURN

Lines created by fail2ban policy are highlighted in red. Now they simply route traffic to new, almost empty chains, and then pass the traffic flow back to the INPUT chain.

Blocking rules will be added to these chains.

Testing the blocking policy

Now you can test the rules by connecting from another server that does not have credentials on the fail2ban server.

Try to create an SSH connection to the server using non-existent credentials:

ssh [email protected] _server_IP

Enter a random set of characters for the password. Repeat several times. At some point fail2ban will deny access and display the message "Permission denied".

Go back to the first server and view the new iptables rules:

sudo iptables -S
-P INPUT ACCEPT
-P FORWARD ACCEPT
-P OUTPUT ACCEPT
-N fail2ban-nginx-http-auth
-N fail2ban-ssh
-A INPUT -p tcp -m multiport --dports 80,443 -j fail2ban-nginx-http-auth
-A INPUT -p tcp -m multiport --dports 22 -j fail2ban-ssh
-A INPUT -i lo -j ACCEPT
-A INPUT -m conntrack --ctstate RELATED, ESTABLISHED -j ACCEPT
-A INPUT -p tcp -m tcp --dport 22 -j ACCEPT
-A INPUT -p tcp -m tcp --dport 80 -j ACCEPT
-A INPUT -j DROP
-A fail2ban-nginx-http-auth -j RETURN
-A fail2ban-ssh -s 203.0.113.14/32 -j REJECT --reject-with icmp-port-unreachable
-A fail2ban-ssh -j RETURN

The new rule is highlighted in red. It blocks traffic from the second server's IP address to the SSH port. You will receive a notification about the client being blocked shortly.

Conclusion

You are now familiar with the basics of fail2ban and can create a basic configuration for this tool.