Setting Up Fail2Ban for SSH Protection
After installing Fail2Ban, verify the service is running:
systemctl status fail2ban.service
Output should show the service as active and running.
Configuring the Jail
Edit /etc/fail2ban/jail.local to enable SSH protection with email notifications:
[sshd]
enabled = true
port = ssh
action = msmtp-whois-lines[name=SSHD, dest=your_email@example.com, sender=sender@example.com]
logpath = %(sshd_log)s
maxretry = 5
bantime = 600
This configuration bans IPs after 5 failed SSH attempts and sends email alerts.
Installing and Configuring MSMTP
Install the required packages for email functionality:
sudo apt-get install msmtp msmtp-mta
Configure /etc/msmtprc with your SMTP settings:
defaults
auth on
tls on
tls_trust_file /etc/ssl/certs/ca-certificates.crt
logfile /var/log/msmtp.log
account your_provider
host smtp.example.com
port 587
from sender@example.com
auth login
user your_username
password your_app_password
account default: your_provider
Create and set permissions for the log file:
sudo touch /var/log/msmtp.log
sudo chown $USER:mail /var/log/msmtp.log
sudo chmod 660 /var/log/msmtp.log
Configuring Fail2Ban Email Action
Ensure the msmtp action is configured in /etc/fail2ban/action.d/msmtp-whois-lines.conf:
[INCLUDES]
before = sendmail-common.conf
helpers-common.conf
[Definition]
actionban = ( printf %b "Subject: [Fail2Ban]: <name> banned <ip>
Date: `LC_ALL=C date +"%a, %d %h %Y %T %z"`
From: <sender>
To: <dest>
Hi,
The IP <ip> has just been banned by Fail2Ban after
<failures> attempts against <name>.
Here is more information about <ip>:
`/usr/bin/whois <ip> || echo missing whois program`
Lines containing failures of <name>:
"; %(_grep_logs)s; printf %b "
Regards,
Fail2Ban" ) | msmtp -t
[Init]
name = default
logpath = /dev/null</name></ip></ip></name></failures></ip></dest></sender></ip></name>
Testing and Monitoring
Start and enable Fail2Ban:
sudo systemctl start fail2ban
sudo systemctl enable fail2ban
fail2ban-client -t
Monitor the logs to verify IP banning:
sudo tail -f /var/log/fail2ban.log
Check jail status and banned IPs:
sudo fail2ban-client status sshd
To unban an IP:
sudo fail2ban-client set sshd unbanip IP_ADDRESS