• Get In Touch
September 26, 2016

How to Secure Your SSH Using Fail2Ban on CentOS 7

Want your very own server? Get our 1GB memory, Xeon V4, 25GB SSD VPS for £10.00 / month.
Get a Cloud Server

Connecting to your server using SSH is considered very secure as it uses an encrypted connection to send and receive the data. As the SSH service is exposed to internet, it is often attacked by the brute force method. Fail2Ban is a service which scans log files in real time and looks for brute force login attempts. If it finds multiple failed login attempts from a single IP, it blocks the attecker by modifying the iptables or firewalld rules. Fail2Ban is used for securing the SSH service but we can secure many services using Fail2Ban.

In this tutorial we will learn to install Fail2Ban on CentOS 7. We will also learn to secure SSH service.

Requirements

Installing Fail2Ban does not require any special hardware or software. You will need a CentOS Cloud or VPS server with root access on it. If you are logged in as non root user, you can login to root user using sudo -i command. Alternatively you can also use sudo command before all the commands.

Installing Fail2Ban

Before installing any package on your system it is recommended to update the system and the repositories. Run the following command to do so.

    yum -y update

Now you will need to install EPEL repository in your system, as the Fail2Ban package is not available on default YUM repository.

    yum -y install epel-release
    yum -y update
    yum clean all

Now install Fail2Ban using the following command.

    yum -y install fail2ban

Once installed you can start Fail2Ban using the folloing command.

    systemctl start fail2ban

To enable Fail2Ban to start automatically at boot time, run the following command.

    systemctl enable fail2ban

To check the status of Fail2Ban service, you can run the following command.

    systemctl status fail2ban

Now we have successfully installed Fail2Ban on our system, we can proceed to secure our SSH server.

Securing SSH Service

The configuration of Fail2Ban are saved in /etc/fail2ban/ directory. By default there is a default configuration file, jail.conf is available. But it is recommended that we create a local file jail.local, and set out custom configuration in there because the configuration in jail.local overrides jail.conf file.

Copy jail.conf file to jail.local using the following command.

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

Now we can edit the new configuration file jail.local using your favorite editor. In this tutorial we will be using nano if you don’t have nano installed, you can install it using yum -y install nano.

    nano /etc/fail2ban/jail.local

Scroll down to find the following lines.

    #
    # [DEFAULT]
    # bantime = 3600
    #
    # [sshd]
    # enabled = true
    #
    # See jail.conf(5) man page for more information

Remove the comment sign # from few lines to make it look like given below.

    #
    [DEFAULT]
    bantime = 3600
    #
    [sshd]
    enabled = true
    #
    # See jail.conf(5) man page for more information

You can also change the time of bantime in seconds. 3600 represents an hour.

You can now save the file and exit the editor. To enable the changes done in configuration file, you will need to restart Fail2Ban service using the following command.

    systemctl restart fail2ban

Now Fail2Ban is started with a few settings. Fail2Ban should block an IP address for specified seconds if anybody makes 5 failed login attempts.

You can check the status of the Fail2Ban status using the following command.

    fail2ban-client status

You will see following output.

    [root@ip-172-31-23-73 ~]# fail2ban-client status
    Status
    |- Number of jail:      1
    `- Jail list:   sshd

The output says that one Jail is configured and it is SSH.

Furthermore you can check the Fail2Ban status for SSH using the following command.

    fail2ban-client status sshd

You will see a similar output.

    [root@ip-172-31-23-73 ~]# fail2ban-client status sshd
    Status for the jail: sshd
    |- Filter
    |  |- Currently failed: 2
    |  |- Total failed:     86
    |  `- File list:        /var/log/secure
    `- Actions
       |- Currently banned: 1
       |- Total banned:     30
       `- Banned IP list:   64.188.212.170

Furthermore you can check the logs of failed login using the following command.

    cat /var/log/secure | grep 'Failed password'

You will see a similar output as shown below.

    Sep 25 19:36:50 localhost sshd[5866]: Failed password for root from 62.48.142.153 port 8723 ssh2
    Sep 25 19:36:52 localhost sshd[5866]: Failed password for root from 62.48.142.153 port 8723 ssh2
    Sep 25 20:10:52 localhost sshd[5965]: Failed password for root from 180.97.244.253 port 34062 ssh2
    Sep 25 20:10:55 localhost sshd[5965]: Failed password for root from 180.97.244.253 port 34062 ssh2
    Sep 25 20:12:03 localhost sshd[5973]: Failed password for root from 162.213.153.44 port 47352 ssh2
    Sep 25 20:13:17 localhost sshd[5980]: Failed password for invalid user a from 64.188.212.170 port 37530 ssh2
    Sep 25 20:24:07 localhost sshd[6024]: Failed password for invalid user liptan from 64.188.212.170 port 6962 ssh2

You can also check the IP address banned by iptables using the following command.

    iptables -L -n

You will see output similar to this.

    [root@ip-172-31-23-73 ~]# iptables -L -n
    Chain INPUT (policy ACCEPT)
    target     prot opt source               destination
    f2b-sshd   tcp  --  0.0.0.0/0            0.0.0.0/0            multiport dports 22

    Chain FORWARD (policy ACCEPT)
    target     prot opt source               destination

    Chain OUTPUT (policy ACCEPT)
    target     prot opt source               destination

    Chain f2b-sshd (1 references)
    target     prot opt source               destination
    REJECT     all  --  64.188.212.170       0.0.0.0/0            reject-with icmp-port-unreachable
    RETURN     all  --  0.0.0.0/0            0.0.0.0/0

Configuring Fail2Ban

You can further configure Fail2Ban for additional settings. Reopen the Fail2Ban configuration file using the following command.

    nano /etc/fail2ban/jail.local

Scroll down to find the miscellaneous options you can configure with Fail2Ban, few of the options are.

ignoreip – You can specify a single IP address or multiple IP address by separating them with space. You can also put the range of IP address in CIDR notation. Fail2Ban will not ban any IP address or hosts which matches the list provided here. A typical example would be like

    ignoreip = 127.0.0.1/8 69.164.365.134

findtime – This parameter specifies the time interval in which it will look for subsequent failed login attempt. It is specified in seconds, default value is 600 seconds.

    findtime = 600

maxretry – Number of retries from an IP before it gets banned by Fail2Ban. Default value in 5, but you can change it according to your choice.

    maxretry = 5

Setting up Mail Notifications

If you wish to receive email alerts when Fail2Ban bans an IP address, you can change the mail notifications configuration. Fail2Ban uses sendmail to send email notifications. To enable email notifications you will need to install sendmail in to your machine. Use the following command to do so.

    yum -y install sendmail

Once done you can check if sendmail is working using the following command. Replace my@email.com with your email address.

    echo "Subject: sendmail test" | sendmail -v my@email.com

You should see output similar to this.

    [root@ip-172-31-23-73 ~]# echo "Subject: sendmail test" | sendmail -v my@email.com
    my@email.com... Connecting to [127.0.0.1] via relay...
    220 ip-172-31-23-73.localdomain ESMTP Postfix
    >>> EHLO ip-172-31-23-73.ap-south-1.compute.internal
    250-ip-172-31-23-73.localdomain
    250-PIPELINING
    250-SIZE 10240000
    250-VRFY
    250-ETRN
    250-ENHANCEDSTATUSCODES
    250-8BITMIME
    250 DSN
    >>> MAIL From: SIZE=23
    250 2.1.0 Ok
    >>> RCPT To:
    >>> DATA
    250 2.1.5 Ok
    354 End data with .
    >>> .
    250 2.0.0 Ok: queued as 6AE251010ACE
    my@email.com... Sent (Ok: queued as 6AE251010ACE)
    Closing connection to [127.0.0.1]
    >>> QUIT
    221 2.0.0 Bye

Now edit your jail.local file again the following command.

    nano /etc/fail2ban/jail.local

Scroll down to find the following lines.

    #
    # ACTIONS
    #

    # Some options used for actions

    # Destination email address used solely for the interpolations in
    # jail.{conf,local,d/*} configuration files.
    destemail = root@localhost

    # Sender email address used solely for some actions
    sender = root@localhost

    # E-mail action. Since 0.8.1 Fail2Ban uses sendmail MTA for the
    # mailing. Change mta configuration parameter to mail if you want to
    # revert to conventional 'mail'.
    mta = sendmail

Change destemail with the email address on which you want to receive the email alerts. change sender with the email address of the sender. You can also change the default MTA from sendmail to conventional mail.

Conclusion

In this tutorial we learnt to secure our SSH server from brute force attacks using Fail2Ban service. You can now easily deploy Fail2Ban on your CentOS 7.x servers. Deploying Fail2Ban on your server will harden the security of your machine.

Want your very own server? Get our 1GB memory, Xeon V4, 25GB SSD VPS for £10.00 / month.
Get a Cloud Server

Share this Article!

Related Posts

Node.js Authentication – A Complete Guide with Passport and JWT

Node.js Authentication – A Complete Guide with Passport and JWT

Truth be told, it’s difficult for a web application that doesn’t have some kind of identification, even if you don’t see it as a security measure in and of itself. The Internet is a kind of lawless land, and even on free services like Google’s, authentication ensures that abuses will be avoided or at least […]

Node.js and MongoDB: How to Connect MongoDB With Node

Node.js and MongoDB: How to Connect MongoDB With Node

MongoDB is a document-oriented NoSQL database, which was born in 2007 in California as a service to be used within a larger project, but which soon became an independent and open-source product. It stores documents in JSON, a format based on JavaScript and simpler than XML, but still with good expressiveness. It is the dominant […]

Using MySQL with Node.js: A Complete Tutorial

Using MySQL with Node.js: A Complete Tutorial

Although data persistence is almost always a fundamental element of applications, Node.js has no native integration with databases. Everything is delegated to third-party libraries to be included manually, in addition to the standard APIs. Although MongoDB and other non-relational databases are the most common choice with Node because if you need to scale an application, […]

Node.Js Vs Django: Which Is the Best for Your Project

Node.Js Vs Django: Which Is the Best for Your Project

Django and NodeJs are two powerful technologies for web development, both have great functionality, versatile applications, and a great user interface. Both are open source and can be used for free. But which one fits your project best? NodeJs is based on JavaScript, while Django is written in Python. These are two equally popular technologies […]

Nodejs Vs PHP:  Which Works Best?

Nodejs Vs PHP: Which Works Best?

Before getting into the “battle” between Node.js and PHP we need to understand why the issue is still ongoing. It all started with the increased demand for smartphone applications, their success forcing developers to adapt to new back-end technologies that could handle a multitude of simultaneous requests. JavaScript has always been identified as a client-side […]