There are a lot of tutorials online that will tell you how to secure your SSH server. Most of them will tell you not to allow the
root account to login, to use only keys for authentication and possibly to change the port on which your server listens from 22 to any other. Although this is valid advice, there are times when due to zealous system administrators you have to use port 22 (because along with 21 and 80 it’s not blocked and you do like to check your server from time to time). Also, you might still want to use password authentication together with public and private keys just because there are chances that you might lose your keys (it happens to the best of us). Combine these two and you are exposing your server to a lot of brute-force attacks from various script kiddies.
If your SSH server (generally OpenSSH) is compiled to use TCP Wrapper you can use DenyHosts to protect yourself against the annoying attempts to hack the server. However, if you don’t have the option to use a TCP Wrapper aware SSH server (which happens to be the case on almost all Linux distributions made to operate home-class routers), you’re pretty much on your own. Unless you’d like to use another script I wrote while I was bored.
The script analyses your SSH daemon’s log, identifies IPs from which there are unauthorized access attempts (the attackers usually try to login using a multitude of user/password combinations - brute-force attacks) and then denies all traffic from those IPs. Also it keeps a list of all those pesky “hackers” for times when you reboot (the part where you re-add those IPs to your
iptables configuration is left as an exercise to you). The cherry on top of the cake is that for every bad IP the script tries to mail the ISP with the relevant parts from your log (in case you have configured
sendmail or another MTA with a
As usual, you can find the script in one of my GitHUB repos with a nice README file giving you all the juicy configuration details.
If you can improve the script to do even more, please fork the repo. Also, if you find any bugs please let me know.
TIP: if your kernel can use the recent module, you can add some rules like these:
1 2 3
This would assure that a user cannot open more than 8 connections in 60 seconds to your server on port 22. Of course, if the user tries to open a ninth connection,
iptables will block the access for 60 seconds. This is just an extra measure to protect your server in addition to the script.
Don’t let the “hackers” win!