5 Best Practices to Prevent SSH Brute-Force Login Attacks in Linux

Servers running SSH are usually a soft target for brute-force attacks. Hackers are constantly coming up with innovative software tools and bots for automating brute-force attacks which further increase the risk of intrusion.

In this guide, we explore some of the tips that you can implement to safeguard your SSH servers from brute-force attacks on RHEL-based Linux distributions and Debian derivatives.

Disable SSH Password Authentication and Enable SSH-Key Authentication

The default authentication method for SSH is username/password authentication. But as we have seen, password authentication is prone to brute-force attacks. To be on the safe side, it is recommended to implement key-based SSH authentication where authentication is made possible by public and private SSH key pairs. The private key remains on the client’s PC while the public key is copied to the server.

During SSH key authentication, the server checks whether the client PC possesses the private key. If the check is successful, a shell session is created or the command sent to the remote server is executed successfully. We have a comprehensive guide on how to configure SSH key-based authentication.

Even after setting up Key-based authentication, your server is still susceptible to brute-force attacks for the simple reason that password authentication is still active. This needs to be disabled.

Therefore, edit the default SSH configuration file.

$ sudo vim /etc/ssh/sshd_config

Set the PasswordAuthentication parameter to no as shown.

PasswordAuthentication no
Disable SSH Password Authentication
Disable SSH Password Authentication

Then save the file and reload SSH to apply the changes.

$ sudo systemctl reload ssh

Implement Fail2ban Intrusion Prevention Tool

Written in Python, Fail2ban is an open-source intrusion prevention framework that scans log files of services for authentication failures and bans IPs that repeatedly fail password authentication checks for a specified amount of time.

Fail2ban constantly monitors server log files for intrusion attempts and other nefarious activity, After a predefined number of authentication failures – in most cases, 3 failed login attempts – Fail2ban automatically blocks the remote host from accessing the server, and the host is kept in a ‘Jail‘ for a specific duration of time.

In doing so, Fail2ban significantly reduces the rate of incorrect password authentication attempts. Check out our guide on how you can install and configure Fail2ban on Linux to secure your server from Bruteforce attacks.

Limit Maximum Number of SSH Authentication Attempts

Another simple way of safeguarding your server from brute-force attacks is by limiting the number of SSH login attempts. By default, this is set to 3, but if by any chance this is set to a higher value, set it to 3 connection attempts at most.

For example, to set the maximum connection attempts to 3 set the MaxAuthTries parameter to 3 as shown

MaxAuthTries = 3

Once again, save the changes and reload the SSH service.

$ sudo systemctl reload ssh

Implement TCP Wrappers to Limit SSH Access From Clients

TCP wrappers is a library that provides a host-based Access Control List (ACL) that restricts access to TCP services by remote clients based on their IP addresses

Remote hosts from accessing services on the system. TCP wrappers uses the /etc/hosts.allow and /etc/hosts.deny configuration files (in that order) to determine if the remote client is allowed to access a specific service or not.

Usually, these files are commented out and all hosts are allowed through the TCP wrappers layer. Rules for allowing access to a given service are placed in the /etc/hosts.allow file and take precedence over the rules in the /etc/hosts.deny file.

Best practice recommends blocking all incoming connections. Therefore, open the /etc/hosts.deny file.

$ sudo vim /etc/hosts.deny

Add the following line.

ALL: ALL

Save the changes and exit the file.

Then access the /etc/hosts.allow file.

$ sudo vim /etc/hosts.allow

Configure the hosts or domains that can connect to the server via SSH as shown. In this example, we are allowing only two remote hosts to connect to the server (173.82.227.89 and 173.82.255.55) and denying the rest.

sshd: 173.82.227.89 173.82.255.55
sshd: ALL: DENY
Limit SSH Access to Clients
Limit SSH Access to Clients

Save the changes and exit the configuration file.

To test it out, try to connect to the server from a host that is not among those you have allowed access to. You should get a permission error as shown.

$ ssh [email protected]

kex_exchange_identification: read: Connection reset by peer
Connection reset by 173.82.235.7 port 22
lost connection

Implement SSH Two Factor Authentication

Two Factor Authentication provides an added security layer to password authentication, thereby making your server more secure from brute-force attacks. A widely-used Two Factor Authentication solution is Google Authenticator App and we have a well-documented guide on how you can set up Two Factor Authentication.

Conclusion

This was a summary of 5 best practices that you can implement to prevent SSH Brute Force login attacks and ensure your server’s safety. You can also read How to secure and harden OpenSSH Server.

Hey TecMint readers,

Exciting news! Every month, our top blog commenters will have the chance to win fantastic rewards, like free Linux eBooks such as RHCE, RHCSA, LFCS, Learn Linux, and Awk, each worth $20!

Learn more about the contest and stand a chance to win by sharing your thoughts below!

James Kiarie
This is James, a certified Linux administrator and a tech enthusiast who loves keeping in touch with emerging trends in the tech world. When I'm not running commands on the terminal, I'm taking listening to some cool music. taking a casual stroll or watching a nice movie.

Each tutorial at TecMint is created by a team of experienced Linux system administrators so that it meets our high-quality standards.

Join the TecMint Weekly Newsletter (More Than 156,129 Linux Enthusiasts Have Subscribed)
Was this article helpful? Please add a comment or buy me a coffee to show your appreciation.

21 Comments

Leave a Reply
  1. # cat /etc/redhat-release
    CentOS Linux release 8.5.2111

    # rpm -qa | grep epel-release
    epel-release-8-13.el8.noarch

    # yum install denyhosts
    No match for argument: denyhosts

    Reply
  2. This is good. I took it one step further too. I took all the blocklists maintained by http://www.wizcrafts.net/iptables-blocklists.html and saved them into a single file, then wrote this shell script to filter the comments out of the list and use iptables to block entire ranges:

    #/bin/bash
    file="wiznets.txt"
    
    while read line; do
        echo " "
        echo "Current Line: $line"
        if [[ ${line:0:1} == [0-9]* ]]; then        
            iptables -I INPUT -s $line -j DROP
            echo "$line is a valid IP range. Added to iptables block list."
        else
            echo "$line was skipped. Not a valid IP."
        fi
    done <"$file"
    
    Reply
  3. Thanks for the info! What happens if you log in from an ISP that changes your IP once in a while? You’d be locked out of the whitelist unbeknown to you. Any way around this apart from console access?

    Reply
  4. Hi All

    Can we block multiple services on denyhosts like BLOCK_SERVICE = sshd,proftpd and also can these block public IP’s as well.

    Thanks
    chacko

    Reply
    • @Chacko,
      Using DenyHosts, you can only block SSH attacks, but if you want to block other services such as ftp, mail, etc, you can use xinetd functionality called hosts.deny.

      Reply
  5. Password crackers are using automated scripts to target websites to hack the passwords and Brute Force Attacks have become a common thing, but many don’t know the concept behind it and how these attacks are so successful at cracking the passwords of the websites.

    The easiest method to block such attacks is by blacklisting the IPs that carry out such abuses, many hosting providers have added Brute Force Attacks protection in their added security features.

    For more information about these attacks read: http://www.cloudways.com/blog/what-is-brute-force-attack/

    Reply
  6. HI All,

    Every day morning iptables rules would be automatically flushed. I dont know how,,,

    Please help me to resolve this issue.

    Reply
  7. Very Nice article. I have one suggestion. This article work just fine for Ubuntu 12.04 Server, except installation which can be done with

    sudo apt-get install denyhosts

    So i recomment just add Ubuntu to the list. And add the installation method.

    Reply
  8. Hi, am using CentOS release 5.7 (Final), i can’t install denyhosts with yum, provided i have enabled epel repo and logged in as root.

    when i run #yum install denyhosts

    it gives,
    “Setting up Install Process
    No package denyhosts available.
    Nothing to do”

    what is the problem here. pls advice.

    Reply
  9. I do trust all of the concepts you’ve offered to your post. They’re really convincing and will certainly work. Still, the posts are too brief for newbies. May you please prolong them a bit from next time? Thanks for the post.

    Reply

Got Something to Say? Join the Discussion...

Thank you for taking the time to share your thoughts with us. We appreciate your decision to leave a comment and value your contribution to the discussion. It's important to note that we moderate all comments in accordance with our comment policy to ensure a respectful and constructive conversation.

Rest assured that your email address will remain private and will not be published or shared with anyone. We prioritize the privacy and security of our users.