DEV Community

Cover image for Protect your Virtual Machine with Fail2ban
Codearmo
Codearmo

Posted on • Originally published at codearmo.com

Protect your Virtual Machine with Fail2ban

Intro

OK so after a long time playing around with Linux servers, and now at the stage I have to spin them up pretty frequently with dozens done this year alone, I made a 10 Things to do on New Linux Server Checklist to try reduce the pain process of setting them up.

I had always known web security stuff was a real deep rabbit hole :( but my experience with automated login attempts to my servers really made me realize how scary a place the internet can be.

On Step 4 of the checklist , inspired by watching videos at the excellent LearnLinuxTV I decided to install Fail2ban.

Internet is a Scary Place

SO anyway, I install fail2ban on the test server and the results totally shocked me.

In just 3–4 hours since spinning up the test server for the checklist post, there were already 18 unauthorized login attempts to my virtual machine.

And now about a week later, the ssh jail is getting overcrowded as you can see below.

Fail2ban sshd Jailed IP addresses

Check Login Attempts on your Virtual Machine

Below I list some handy commands to check your machine for login attempts

Check Failed Password Attempts

sudo grep "Failed password" /var/log/auth.log 
Enter fullscreen mode Exit fullscreen mode

Check Invalid User Attempts

sudo grep "Invalid user" /var/log/auth.log 
Enter fullscreen mode Exit fullscreen mode

Count the Number of Attempts in Latest Log file

sudo grep "Failed password" /var/log/auth.log | wc -l 
Enter fullscreen mode Exit fullscreen mode

Since the logs rotate pretty quick, you might need to change that to log.1 etc for old attempts.

🛡️Protect your Virtual Machine with Fail2ban.

So if you found some bots trying to brute force in to your server, you might want to install fail2ban

Install ✅

sudo apt update && sudo apt install fail2ban 
Enter fullscreen mode Exit fullscreen mode

Enable & start it ✅

sudo systemctl enable fail2ban sudo systemctl start fail2ban 
Enter fullscreen mode Exit fullscreen mode

Create a Jail for the bots ✅

sudo nano /etc/fail2ban/jail.d/sshd.local 
Enter fullscreen mode Exit fullscreen mode

Configure your jail file full guide here

[sshd] enabled = true port = ssh logpath = %(sshd_log)s backend = %(sshd_backend)s maxretry = 5 bantime = 24h findtime = 1h 
Enter fullscreen mode Exit fullscreen mode

Restart the service ✅

sudo systemctl restart fail2ban 
Enter fullscreen mode Exit fullscreen mode

Check How many IPs are Blocked

sudo fail2ban-client status sshd 
Enter fullscreen mode Exit fullscreen mode

Top comments (0)