Receive messages on Telegram from Fail2ban

To continue my serie of articles about receiving notifications on Telegram, today I want to receive Fail2ban alerts. Sending an e-mail requires several prerequisites (having a domain name with an e-mail server, set up a relay host with Postfix to make sure that our e-mails are well delivered), in short a lot of things, for not much.

On the contrary, it is much easier to send notifications on a Telegram bot, you just have to create a bot as I did in this article, and that’s almost done!

Information and requirement

These elements are to be taken into consideration to follow this article:

Update the system

sudo dnf -y update

Install the required utilities

sudo dnf -y install fail2ban-server fail2ban-firewalld

Copy the following content into /etc/fail2ban/jail.d/sshd.local.

[DEFAULT]
maxretry   = 3
bantime    = 86400
findtime   = 3600
ignoreip   = <IP address>
action     = telegram[name=SSH]

[sshd]
enabled = true

Directives’ explanation:

Configure the Fail2ban action

Copy the following content into /etc/fail2ban/action.d/telegram.conf.

[Definition]
actionstart = /usr/bin/curl -sSf -X POST https://api.telegram.org/bot1390824186:AAE-a336pYNwMqH41PjxJR-UP0xk_stWtWU/sendMessage --data chat_id=939838712 --data text="[F2B] - jail <name> has been started on your server successfully."
actionstop  = /usr/bin/curl -sSf -X POST https://api.telegram.org/bot1390824186:AAE-a336pYNwMqH41PjxJR-UP0xk_stWtWU/sendMessage --data chat_id=939838712 --data text="[F2B] - jail <name> has been stopped on your server"
actioncheck =
actionban   = /usr/bin/curl -sSf -X POST https://api.telegram.org/bot1390824186:AAE-a336pYNwMqH41PjxJR-UP0xk_stWtWU/sendMessage --data chat_id=939838712 --data text="[F2B] - <ip> has just been banned by Fail2ban after <failures> attempts against <name> from your server."
actionunban = /usr/bin/curl -sSf -X POST https://api.telegram.org/bot1390824186:AAE-a336pYNwMqH41PjxJR-UP0xk_stWtWU/sendMessage --data chat_id=939838712 --data text="[F2B] - <ip> has just been unbanned from your server."

[Init]
init = "Fail2ban Telegram plugin activated"

Directives’ explanation:

Thanks to the magic of Fail2ban, the variables <name>, <ip>, <failures> will be replaced by the information provided by the Fail2ban server and the message will be correctly formatted.

SELinux

You must allow the system to work with Network Information Service (NIS). To do this, you must enable the nis_enabled boolean. This one is disabled by default.

sudo setsebool -P nis_enabled on

Enable and start the service

sudo systemctl enable --now fail2ban

Once the Fail2ban service has started, you should have received a message telling you that the SSH jail has started. You can of course change the content of the received messages by customizing the cURL request in the --data text="" part.