To block IP addresses with several failed SSH login attempts, you can use several methods, with fail2ban
being one of the most popular and effective solutions.
Using Fail2Ban
Step 1: Install Fail2Ban
On Ubuntu/Debian:
sudo apt update
sudo apt install fail2ban
Step 2: Configure Fail2Ban
-
Create a local configuration:
It's a good practice to create a local fail2ban configuration file instead of editing the default. Run:sudo cp /etc/fail2ban/jail.conf /etc/fail2ban/jail.local
-
Edit the
jail.local
file:
Open thejail.local
file with a text editor:sudo nano /etc/fail2ban/jail.local
-
Configure the settings:
Look for the[sshd]
section and modify (or add) the following parameters if they're not present:[sshd] port = ssh logpath = %(sshd_log)s backend = %(sshd_backend)s bantime=3600 findtime=120 maxretry=5
"bantime" is the number of seconds that a host is banned.
A host is banned if it has generated "maxretry" during the last "findtime" # seconds.
"maxretry" is the number of failures before a host get banned.
Step 3: Start and Enable Fail2Ban
Start the Fail2Ban service:
sudo systemctl start fail2ban
Enable it to start on boot:
sudo systemctl enable fail2ban
Step 4: Check Fail2Ban Status
To check the status of Fail2Ban and see if any IPs have been banned:
sudo fail2ban-client status sshd
Step 5: Check rules add in iptables
sudo iptables -S
Step 6: Unban an IP (if needed)
If you accidentally ban a legitimate IP, you can unban it with:
sudo fail2ban-client set sshd unbanip