The first step to securing your SSH configuration is to configure key-based authentication and not allow password authentication at all. That topic has already been discussed. Check out my post about that: https://www.ajni.it/2020/03/configure-ssh-key-based-authentication-on-a-linux-system/
The second step is to introduce an Intrusion Detection System (IDS or IPS). Fail2ban can achieve that specific goal. It analyses SSH authentication logs (it can be also set for other services) and blacklists IP addresses after n failed attempts with the help of iptables (firewall rules). Let’s check it out.
First of all make sure to update your system:
Now install fail2ban:
apt install fail2ban
Start and enable the fail2ban service:
systemctl start fail2ban
systemctl enable fail2ban
Now a “jail” can be configured for failed ssh login attempts. There is a default /etc/fail2ban/jail.conf file, but we are going to create a new config jail.local.
Paste following parameters in the file:
enabled = true
port = 22
filter = sshd
logpath = /var/log/auth.log
maxretry = 3
mode = aggressive
bantime = -1
findtime = 3600
Mode=aggressive includes failed attempts with public key authentication. Bantime = -1 is for persistent bans. Findtime indicates how far back logs are checked (now – 3600 minutes or 1 hour).
After saving the file, restart fail2ban:
service fail2ban restart
Blacklisted IPs can be viewed with
fail2ban-client status sshd
After some minutes one IP already showed up:
Or you can also view it with iptables.
iptables -L -n -v
Removing an IP from the blacklist is also easy (the command is self-explanatory)
fail2ban-client set sshd unbanip 10.10.10.1
Some other security considerations:
- Don’t log in as root and do not allow user root over SSH
- Use public-key authentication
- Change the SSH port
- Implement an IDS/IPS (fail2ban)