How to Protect Your Linux Server from Brute Force SSH Attacks

How to Protect Your Linux Server from Brute Force SSH Attacks

Posted By

kamlesh paul

on

Dec 13, 2024

Brute Force SSH Attacks are among the most common threats to Linux servers. Cybercriminals use automated tools to guess passwords and gain unauthorized access. In this article, we’ll explore effective strategies to safeguard your Linux server from these attacks.

Table of contents

1. Disable Root Login

Why Disable Root Login?

  • Allowing root login via SSH can make it easier for attackers to gain full access. Instead, use a regular user account with sudo privileges.

How to Disable Root Login

  • To disable root login, edit the SSH configuration file:
sudo nano /etc/ssh/sshd_config
  • Find the line:
PermitRootLogin yes
  • Change it to:
PermitRootLogin no
  • Then, restart the SSH service to apply the changes:
sudo systemctl restart sshd

2. Implement Public Key Authentication

Why Use Public Key Authentication?

  • Public key authentication is more secure than password-based logins. It relies on a pair of cryptographic keys, making it much harder for attackers to compromise

How to Set Up Public Key Authentication

  • Generate SSH Keys (Local PC):
cd ~/.ssh && ssh-keygen -t rsa -b 4096
  • Copy the Public Key to the Server (Local PC):
 ssh-copy-id user@your_server_ip

Disable Password Authentication (Server) : Edit the SSH configuration file:

sudo nano /etc/ssh/sshd_config
  • Find and change:
PasswordAuthentication yes

to

PasswordAuthentication no

Finally, restart SSH to apply the changes:

sudo systemctl restart sshd

3. Use Fail2Ban

What is Fail2Ban?

  • Fail2Ban is a security tool that scans log files and bans IP addresses with too many failed login attempts, significantly reducing the risk of brute force attacks.

How to Install and Configure Fail2Ban

  1. Install Fail2Ban:
sudo apt install fail2ban
  1. Configure Fail2Ban for SSH: Open the configuration file:
sudo nano /etc/fail2ban/jail.local

Add the following lines:

[sshd]
enabled  = true
port     = ssh
filter   = sshd
logpath  = /var/log/auth.log
maxretry = 3
bantime  = 15d 
  1. Start and Enable Fail2Ban:
sudo systemctl start fail2ban
sudo systemctl enable fail2ban
  1. Check Banned IP List:
sudo fail2ban-client status sshd
  1. Add an IP to the Ban List:
sudo fail2ban-client set sshd banip <IP>

Replace <IP> with the actual IP address you want to ban.

  1. Remove an IP from the Ban List:
sudo fail2ban-client set sshd unbanip <IP>

Replace <IP> with the IP address you wish to unban.

4. Monitor Login Attempts

Why Monitor Login Attempts?

Regularly reviewing login attempts can help you identify and respond to potential threats quickly.

Tools for Monitoring

  • SSH Logs: Check logs at /var/log/auth.log for unauthorized access attempts:
sudo tail -f /var/log/auth.log

You can also view recent activity with the following command:

sudo journalctl --since "5 minute ago"

Share this article

41 views