Continuing from my previous posts on Fail2ban notifications, which you can read about here: Adding ban/unban notifications from Fail2Ban to Discord! and Adding ban/unban notifications from Fail2Ban to Pushover!.
Adding the Action
Note: This guide uses the linuxserver swag
container.
- Navigate to your
/action.d
folder and copysendmail-whois.conf
, renaming it tosendmail-whois.local
. - Open the file and modify the
actionban
section, adding theactionunban
with the following code:
actionban = printf %%b "Subject:🕵️ [Fail2Ban] <name>: BANNED IP <ip>! 🔨
Date: `LC_ALL=C date +"%%a, %%d %%h %%Y %%T %%z"`
From: <sendername> <<sender>>
To: <destination>\n
Hi,\n
The jail <name> has banned IP <ip> after <failures> attempts against <name>.\n
Here is some info about the IP: https://db-ip.com/<ip> \n
Lines containing IP <ip>: \n
`grep '<ip>' <logpath>` \n
Regards,\n
Fail2Ban" | /usr/sbin/sendmail -t -v -H 'exec openssl s_client -quiet -tls1 -connect smtp.gmail.com:465' -au<from> -ap<password> <destination>
actionunban = printf %%b "Subject:đź”” [Fail2Ban] <name>: UNBANNED IP <ip> âś…
Date: `LC_ALL=C date +"%%a, %%d %%h %%Y %%T %%z"`
From: <sendername> <<sender>>
To: <destination>\n
Hi,\n
Fail2ban has unbanned IP https://db-ip.com/<ip> successfully. \n
Regards,\n
Fail2Ban" | /usr/sbin/sendmail -t -v -H 'exec openssl s_client -quiet -tls1 -connect smtp.gmail.com:465' -au<from> -ap<password> <destination>
Important: If you’re not using Gmail, update the SMTP address in the code accordingly.
- Save the file and copy
sendmail-common.conf
, renaming it tosendmail-common.local
. Edit this file to remove everything afteractionstart =
andactionstop =
. If you want email notifications for these events, you can add similar code as above, adjusting the subject and body as needed.
Updating jail.local
In your jail.local
file, add the following in the [DEFAULT]
section:
banaction = iptables-allports
action = %(action_mw)s[from=example@gmail.com, password=secretpassword, destination=example@gmail.com, sendername=Fail2Ban]
Breakdown of Mail Action Parameters:
- from: The email account used for sending.
- password: The password for the sender account.
- destination: The recipient of the notification.
- sendername: The name displayed as the sender.
The iptables-allports
action is necessary; if only the send mail action is present, it will override the action that updates iptables, preventing effective banning of IPs.
If you wish to apply email notifications to a specific jail only, add it directly within that jail’s configuration instead of under [DEFAULT]
.
Finally, restart Fail2ban and test by attempting to ban your own IP.