sshguard is a nice, smaller alternative to fail2ban that serves the same purpose: stop people and bots from brute-forcing their way into your server. The biggest difference is that sshguard uses significantly less resources than fail2ban, which I believe is due to the fact that it’s written in C, and is compiled rather than interpreted.
While you can just install with a simple:
sudo apt install sshguard
I found that this does not give the flexibility I want. I cannot configure sshguard to send emails upon blocking an IP, and the version in the repositories did not seem to actually block IP addresses. So, I decided to build it from the source, which wasn’t hard at all. To do so, just run the following:
cd /tmp wget https://goo.gl/DfBv9M -O sshguard.tar.gz tar xzvf sshguard.tar.gz cd sshguard-2.1.0/ ./configure --prefix=/usr/local make sudo make install
Now, go to
cd command), and edit the
sshg-fw-iptables file to your liking. I added:
printf "Dear $(hostname) admin,\nThe ip address $1 has tried to hack into your VPS. sshguard has blocked it, and here is some IP info:\n\n$(/usr/local/bin/iplookup $1 silent)\n\nIf you would like to report this IP, click on the following link: https://www.abuseipdb.com/report?ip=$1\n\nRegards,\nYour Linux VPS" | mail -s "$1 blocked by sshguard" -a "From: VPS<sshguard@$(hostname)>" firstname.lastname@example.org
fw_block function. This script utilizes my iplookup script, and sends an email containing a link to report the IP.
Next, copy the sample config file:
sudo cp /tmp/sshguard-2.1.0/examples/sshguard.conf.sample /usr/local/etc/sshguard.conf
and edit it to your liking. Be sure to at least set the following:
and everything else can stay the default. Now, to add this as a service, run:
sudo cp /tmp/sshguard-2.1.0/examples/sshguard.service /lib/systemd/system/sshguard.service
and comment out the following line:
ExecStartPre=-/usr/sbin/iptables -N sshguard
sudo systemctl daemon-reload
and restart the service:
sudo service sshguard restart
To get sshguard to start on boot, just run:
sudo systemctl enable sshguard
To check up on how sshguard is doing, just run:
sudo service sshguard status
This will show you some IP addresses that are attacking your server, and those that have been blocked by sshguard.
Update: I have disabled email notifications because sshguard will send multiple notifications for the same IP(each time it is blocked after being unblocked). This is not sshguard’s fault, but it got really annoying.
Now, you need to configure the iptables rules. This is fairly simple; all you need is to run the following:
sudo iptables -N sshguard sudo iptables -I INPUT -j sshguard sudo ip6tables -N sshguard sudo ip6tables -I INPUT -j sshguard
Basically, this just sends everything through the sshguard rules to ensure offending IPs are blocked.