F2B Fail2Ban Secure Mail

Ubuntu VPS security guide

Secure Email Notifications for Fail2Ban

Configure Fail2Ban with Gmail SMTP, Gmail API OAuth2, WHOIS enrichment, and real-time alert channels without installing a local mail transfer agent.

Gmail SMTP App Password based email alerts for bans and unbans.
OAuth2 Option Gmail API flow for stronger credential handling.
WHOIS Context Geolocation and source context for suspicious IPs.
Multi-Service SSH, NGINX, WordPress, Telegram, and Discord patterns.
Official update notice - Version 2

Secure E-mail Notifications for Fail2Ban (Version 2)

Last revision date:

Access the revised documentation

Official update notice - Fail2Ban Manager Script Version 3

Fail2Ban Manager Script (Version 3)

Last revision date:

Download manage_fail2ban_v3.tar.gz SHA256: ad2bff77eb9d46550bb46af4bfd92ddd5914c42600172a14b323100bef325f90
  • Interactive SSH port prompt with auto-detection and override.
  • Forced firewall action with iptables or nft backend auto-detection and guaranteed INPUT to f2b-sshd jump.
  • One-click unban for a single IP across all jails or all bans.
  • Optional Gmail notifications with sender, recipient, and App Password prompts.
  • Automatic HTML email reports for SSH connection attempts and bans, including WHOIS, reverse DNS, username, authentication method, and correlated log snippet.
  • Purge DB utility to wipe malformed bans and rebuild chains safely.
  • Built-in doctor for backend, port, rules, and logs diagnostics.
  • Hardened flow with best-effort installs, safe fallbacks, and resilience to missing tools.
Fail2Ban Manager Version 3 screenshot

Abstract

This document provides a comprehensive and structured guide to configuring Fail2Ban on Ubuntu-based Virtual Private Servers with secure email notification capabilities through Gmail SMTP, Gmail API (OAuth2), and improved configurations such as Telegram or Discord alerts, WHOIS geolocation, and multi-service protection.

The goal is proactive intrusion detection and immediate administrative awareness of unauthorized access attempts, using lightweight configurations without requiring additional mail transfer agents.

1. Introduction

Fail2Ban is a widely adopted intrusion prevention framework that monitors system logs for malicious authentication attempts. When it detects suspicious behavior, it dynamically updates firewall rules to temporarily ban the attacking IP address.

Secure notifications SMTP and OAuth2 Gmail API examples for alert delivery.
IP intelligence WHOIS and geolocation context for investigation workflows.
Service coverage Examples for SSH, NGINX, WordPress, Telegram, and Discord.
GitHub-ready structure Clean sections and reusable snippets for documentation.

2. Prerequisites

  • Operating System: Ubuntu 22.04.5 LTS or newer
  • Software: Fail2Ban installed via APT
  • Account: Gmail account with 2-Step Verification enabled
  • Optional: Google Cloud project with Gmail API enabled for OAuth2 authentication
  • No local MTA: A Mail Transfer Agent is not required

3. Fail2Ban Installation

Bash
sudo apt update
sudo apt install fail2ban -y
sudo systemctl enable fail2ban
sudo systemctl start fail2ban
sudo systemctl status fail2ban

4. Gmail SMTP Configuration

4.1 App Password Setup

  1. Enable 2-Step Verification in your Google account.
  2. Go to https://myaccount.google.com/apppasswords.
  3. Generate a password for "Mail".
  4. Copy and store it securely.

4.2 Fail2Ban Action File

Create the action file:

Bash
sudo nano /etc/fail2ban/action.d/sendmail-gmail.conf

Insert:

INI
[Definition]

actionstart =
actionstop =
actioncheck =

actionban = /etc/fail2ban/send_gmail.py <name> <ip> <fq-hostname> ban
actionunban = /etc/fail2ban/send_gmail.py <name> <ip> <fq-hostname> unban

[Init]

4.3 Integration with jail.local

INI
[DEFAULT]
bantime  = 10m
findtime = 10m
maxretry = 3

action = %(action_mwl)s
         sendmail-gmail[name=SSH, dest=youraddress@gmail.com, sender=youraddress@gmail.com]

[sshd]
enabled  = true
port     = ssh
logpath  = /var/log/auth.log
banaction = iptables-multiport

5. Gmail API (OAuth2)

This option secures email delivery without storing SMTP passwords directly in plain configuration files.

5.1 Setup

  1. Access Google Cloud Console.
  2. Enable Gmail API.
  3. Create an OAuth Client ID as a Desktop App.
  4. Download client_secret.json.

5.2 Python Script

Python
#!/usr/bin/env python3
import smtplib, ssl, sys
from email.mime.text import MIMEText
from email.mime.multipart import MIMEMultipart
from datetime import datetime

# Fail2Ban parameters
jail = sys.argv[1]
ip = sys.argv[2]
hostname = sys.argv[3]
action = sys.argv[4]  # "ban" or "unban"

# Email
subject = f"Fail2Ban: {jail} {action}ned {ip}"
body = f"""Host: {hostname}
Jail: {jail}
IP: {ip}
Date: {datetime.now().strftime('%Y-%m-%d %H:%M:%S')}"""

sender_email = "youraddress@gmail.com"
receiver_email = "youraddress@gmail.com"
password = "YOUR_APP_PASSWORD"

message = MIMEMultipart()
message["From"] = sender_email
message["To"] = receiver_email
message["Subject"] = subject
message.attach(MIMEText(body, "plain"))

context = ssl.create_default_context()
with smtplib.SMTP("smtp.gmail.com", 587) as server:
    server.starttls(context=context)
    server.login(sender_email, password)
    server.sendmail(sender_email, receiver_email, message.as_string())

6. Security Enhancements

  • Limit access to sensitive configuration files:
Bash
sudo chmod 600 /etc/fail2ban/action.d/sendmail-gmail.conf
  • Use encrypted credential storage such as systemd-credentials or GPG.
  • Avoid plaintext passwords wherever possible.

7. Example jail.local (SSH + Gmail)

INI
[DEFAULT]
bantime  = 10m
findtime = 10m
maxretry = 3

action = %(action_mwl)s
         sendmail-gmail[name=SSH, dest=youraddress@gmail.com, sender=youraddress@gmail.com]

[sshd]
enabled  = true
port     = ssh
logpath  = /var/log/auth.log
banaction = iptables-multiport

8. Advanced Examples

8.1 NGINX Protection

INI
[nginx-http-auth]
enabled  = true
port     = http,https
logpath  = /var/log/nginx/error.log
maxretry = 3

8.2 WordPress Brute-Force Mitigation

INI
[wordpress]
enabled = true
port = http,https
filter = wordpress
logpath = /var/www/*/logs/access.log

8.3 Telegram Notification

INI
[Definition]
actionban = curl -s -X POST https://api.telegram.org/bot<BOT_TOKEN>/sendMessage \
            -d chat_id=<CHAT_ID> \
            -d text="Fail2Ban Alert
Jail: <name>
IP: <ip>
Host: <fq-hostname>
Time: $(date '+%Y-%m-%d %H:%M:%S')"

9. Conclusion

Fail2Ban combined with Gmail, Telegram, or Discord delivers real-time security awareness and active intrusion prevention with minimal system overhead. This GitHub-ready guide provides both basic and advanced configurations suitable for professional and academic environments.