DEV Community

Cover image for Fail2Ban: The Essential Security Tool for Preventing Attacks on Linux Servers
M. K. Tanjin Sarker
M. K. Tanjin Sarker

Posted on • Edited on

Fail2Ban: The Essential Security Tool for Preventing Attacks on Linux Servers

πŸš€ 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
Enter fullscreen mode Exit fullscreen mode

Enable and start the service:

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

πŸ“Œ 2. Configure Fail2Ban

Copy default configuration:

sudo cp /etc/fail2ban/jail.conf /etc/fail2ban/jail.local
Enter fullscreen mode Exit fullscreen mode

Or open directly:

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

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
Enter fullscreen mode Exit fullscreen mode

πŸ“Œ 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
Enter fullscreen mode Exit fullscreen mode

Add the following:

[Definition]
failregex = ^<HOST> -.*"(GET|POST).*\.(php|asp|jsp|exe)(\?.*)? HTTP.*"
ignoreregex =
Enter fullscreen mode Exit fullscreen mode

πŸ“Œ 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
Enter fullscreen mode Exit fullscreen mode

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
Enter fullscreen mode Exit fullscreen mode

πŸ“Œ 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
Enter fullscreen mode Exit fullscreen mode

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
Enter fullscreen mode Exit fullscreen mode

Re-enable if needed:

sudo systemctl unmask firewalld
sudo systemctl unmask nftables
Enter fullscreen mode Exit fullscreen mode

πŸ“Œ 6. Install msmtp (Email Relay)

sudo apt install msmtp msmtp-mta mailutils
Enter fullscreen mode Exit fullscreen mode

πŸ“Œ 7. Configure msmtp

Edit config:

sudo nano /etc/msmtprc
Enter fullscreen mode Exit fullscreen mode

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
Enter fullscreen mode Exit fullscreen mode

Set permissions:

sudo chown root:root /etc/msmtprc
sudo chmod 600 /etc/msmtprc
Enter fullscreen mode Exit fullscreen mode

If running as non-root user:

sudo chown $USER:$USER ~/.msmtprc
sudo chmod 600 ~/.msmtprc
Enter fullscreen mode Exit fullscreen mode

Or make globally readable:

sudo chmod 644 /etc/msmtprc
sudo systemctl restart fail2ban
Enter fullscreen mode Exit fullscreen mode

Restart Fail2ban:

sudo systemctl restart fail2ban
Enter fullscreen mode Exit fullscreen mode

πŸ“Œ 8. Test Email Sending

echo -e "Subject: test\n\nThis is a test email" | msmtp --debug -a gmail tanjinsarker@gmail.com
Enter fullscreen mode Exit fullscreen mode

Check your inbox to verify delivery.


πŸ“Œ 9. Testing Fail2Ban Functionality

Test SSH protection:

  1. Attempt multiple failed SSH logins from a different IP (up to maxretry).
  2. Check if the IP gets banned:
sudo fail2ban-client status sshd
Enter fullscreen mode Exit fullscreen mode
  1. Verify email notification was sent.

Test Web filter (php-url-ban):

  1. Simulate a request to a forbidden URL (e.g., .php, .asp):
curl http://your-server-ip/test.php
Enter fullscreen mode Exit fullscreen mode
  1. Check if the IP appears in the banned list:
sudo fail2ban-client status php-url-ban
Enter fullscreen mode Exit fullscreen mode
  1. 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
Enter fullscreen mode Exit fullscreen mode

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
Enter fullscreen mode Exit fullscreen mode

At the end of the file, add the following line:

session optional pam_exec.so seteuid /usr/local/bin/ssh-login-alert.sh
Enter fullscreen mode Exit fullscreen mode

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
Enter fullscreen mode Exit fullscreen mode

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
Enter fullscreen mode Exit fullscreen mode

πŸ”§ 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
Enter fullscreen mode Exit fullscreen mode

Step 4: Restart SSH Service

Apply changes by restarting SSH:

sudo systemctl restart sshd
Enter fullscreen mode Exit fullscreen mode

Step 5: Test

  1. Log out of your server.
  2. Log back in via SSH.
  3. 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
Enter fullscreen mode Exit fullscreen mode

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)