π Fail2Ban Setup with Email Alerts (msmtp + Gmail)
This guide explains how to install, configure, and use Fail2Ban to protect your server from brute-force attacks, block malicious requests, and send email alerts via msmtp + Gmail.
π 1. Install Fail2Ban
sudo apt update
sudo apt install fail2ban -y
Enable and start the service:
sudo systemctl enable fail2ban
sudo systemctl start fail2ban
sudo systemctl status fail2ban
π 2. Configure Fail2Ban
Copy default configuration:
sudo cp /etc/fail2ban/jail.conf /etc/fail2ban/jail.local
Or open directly:
sudo nano /etc/fail2ban/jail.local
Example jail.local
configuration:
[DEFAULT]
# Ban settings
bantime = 1m
findtime = 10m
maxretry = 2
backend = auto
banaction = ufw
action = %(action_mwl)s
# Email notification
destemail = tanjinsarker@gmail.com
sender = tanjinfail2ban@gmail.com
mta = sendmail
# Ignore trusted IPs
ignoreip = 127.0.0.1/8 ::1
# Logging
loglevel = INFO
logtarget = /var/log/fail2ban.log
# π Protect SSH
[sshd]
enabled = true
# π Block malicious file requests (.php, .asp, .jsp, .exe)
[php-url-ban]
enabled = true
filter = php-url
port = http,https
logpath = /var/www/html/access.log
π 3. Create Custom Fail2Ban Filter
Create a new filter for suspicious .php
, .asp
, .jsp
, .exe
requests:
sudo nano /etc/fail2ban/filter.d/php-url.conf
Add the following:
[Definition]
failregex = ^<HOST> -.*"(GET|POST).*\.(php|asp|jsp|exe)(\?.*)? HTTP.*"
ignoreregex =
π 4. Manage Fail2Ban
Check active jails:
sudo fail2ban-client status | grep "Jail list" | cut -d: -f2 | tr ',' '\n' | while read jail; do
echo "Jail: $jail"
sudo fail2ban-client status "$jail" | grep "Banned IP list"
done
Ban / Unban IPs manually:
# Ban IP
sudo fail2ban-client set sshd banip 192.168.68.129
# Unban IP
sudo fail2ban-client set sshd unbanip 192.168.68.129
# Check if an IP is banned
sudo fail2ban-client get sshd banip 192.168.68.129
π 5. Firewall Configuration
Ensure only one firewall backend is active.
Check status:
sudo systemctl is-active ufw
sudo systemctl is-active firewalld
sudo systemctl is-active nftables
Disable unused backends:
# Disable firewalld
sudo systemctl stop firewalld
sudo systemctl disable firewalld
sudo systemctl mask firewalld
# Disable nftables
sudo systemctl stop nftables
sudo systemctl disable nftables
sudo systemctl mask nftables
Re-enable if needed:
sudo systemctl unmask firewalld
sudo systemctl unmask nftables
π 6. Install msmtp (Email Relay)
sudo apt install msmtp msmtp-mta mailutils
π 7. Configure msmtp
Edit config:
sudo nano /etc/msmtprc
Example msmtprc
:
defaults
auth on
tls on
tls_trust_file /etc/ssl/certs/ca-certificates.crt
logfile ~/.msmtp.log
account gmail
host smtp.gmail.com
port 587
from tanjinfail2ban@gmail.com
user tanjinfail2ban@gmail.com
password *********
account default : gmail
Set permissions:
sudo chown root:root /etc/msmtprc
sudo chmod 600 /etc/msmtprc
If running as non-root user:
sudo chown $USER:$USER ~/.msmtprc
sudo chmod 600 ~/.msmtprc
Or make globally readable:
sudo chmod 644 /etc/msmtprc
sudo systemctl restart fail2ban
Restart Fail2ban:
sudo systemctl restart fail2ban
π 8. Test Email Sending
echo -e "Subject: test\n\nThis is a test email" | msmtp --debug -a gmail tanjinsarker@gmail.com
Check your inbox to verify delivery.
π 9. Testing Fail2Ban Functionality
Test SSH protection:
- Attempt multiple failed SSH logins from a different IP (up to
maxretry
). - Check if the IP gets banned:
sudo fail2ban-client status sshd
- Verify email notification was sent.
Test Web filter (php-url-ban
):
- Simulate a request to a forbidden URL (e.g.,
.php
,.asp
):
curl http://your-server-ip/test.php
- Check if the IP appears in the banned list:
sudo fail2ban-client status php-url-ban
- Check your email for the ban alert.
Test Filter Regex Manually
Before banning, you can test the filter regex against your access log:
sudo fail2ban-regex /var/www/html/access.log /etc/fail2ban/filter.d/php-url.conf
This will:
- Show which lines match the filter.
- Confirm your
php-url
filter works correctly. - Help troubleshoot if IPs are not being banned.
π 10. SSH Successful Login Email Alerts
This guide explains how to configure your server so that every successful SSH login triggers an email alert. This method uses PAM (Pluggable Authentication Modules), which integrates directly with the SSH login process.
Requirements
- A working mail service on your server (e.g.,
postfix
,sendmail
, or an SMTP relay) - Root or sudo access
Step 1: Edit PAM SSH Configuration
Open the PAM configuration for SSH:
sudo nano /etc/pam.d/sshd
At the end of the file, add the following line:
session optional pam_exec.so seteuid /usr/local/bin/ssh-login-alert.sh
This tells PAM to run our custom script on every successful SSH login.
Step 2: Create the Alert Script
Create a new script at /usr/local/bin/ssh-login-alert.sh
:
sudo nano /usr/local/bin/ssh-login-alert.sh
Paste the following content:
#!/bin/bash
USERNAME=$(whoami)
IP=$(echo $PAM_RHOST)
HOST=$(hostname)
DATE=$(date '+%Y-%m-%d %H:%M:%S')
MESSAGE="SSH Login on $HOST
User: $USERNAME
From: $IP
Date: $DATE"
echo "$MESSAGE" | mail -s "SSH Login Alert on $HOST" you@example.com
π§ Replace
you@example.com
with your actual email address.
Step 3: Make Script Executable
Run:
sudo chmod +x /usr/local/bin/ssh-login-alert.sh
Step 4: Restart SSH Service
Apply changes by restarting SSH:
sudo systemctl restart sshd
Step 5: Test
- Log out of your server.
- Log back in via SSH.
- Check your email inbox.
You should receive an alert similar to:
SSH Login on myserver
User: root
From: 192.168.1.100
Date: 2025-08-27 12:34:56
Notes
- Ensure your mail system is properly configured; otherwise, emails will not be delivered.
- For added reliability, consider also logging alerts to a file.
- This method works for all SSH users system-wide.
β Done! You now receive an email on every successful SSH login.
β Final Notes
- Fail2Ban is now protecting SSH and web access logs from malicious requests.
- Emails will be sent using msmtp (Gmail SMTP relay).
- Always secure your Gmail account with an App Password (never your real Gmail password).
Top comments (0)