Skip to content

Instantly share code, notes, and snippets.

@francescor93
Created September 12, 2020 15:50
Show Gist options
  • Save francescor93/a3cbe8f2be43275aa4d1999ef0e501e6 to your computer and use it in GitHub Desktop.
Save francescor93/a3cbe8f2be43275aa4d1999ef0e501e6 to your computer and use it in GitHub Desktop.
Simple fail2ban jail for Mosquitto authentication
Following is a simple fail2ban jail for Mosquitto authentication.
When an authentication attempt fails, Mosquitto writes three lines like these to his log file:
---
<TIMESTAMP>: New connection from <HOST> on port <PORT>.
<TIMESTAMP>: Sending CONNACK to <HOST>
<TIMESTAMP>: Socket error on client <unknown>, disconnecting.
---
This filter looks for these three lines to get the host and allow you to ban it.
Instructions:
1. Paste the jail.local content at the bottom of your /etc/fail2ban/jail.local file
2. Save the mosquitto-auth.conf file to the /etc/fail2ban/filter.d folder
3. Restart the fail2ban server and check if it works. Fit it according to your needs.
[mosquitto-auth]
port = 1883,8883
enabled = true
filter = mosquitto-auth
logpath = /var/log/mosquitto/mosquitto.log
# Fail2Ban filter for unsuccesful Mosquitto authentication attempts
[INCLUDES]
# Read common prefixes. If any customizations available -- read them from
# common.local
before = common.conf
[Init]
maxlines = 3
[Definition]
failregex = .+ New connection from <HOST> on port \d+\.\n.+\n.+ Socket error on client <unknown>, disconnecting.
ignoreregex =
# Author: Francesco Rega
@DarrenBeck
Copy link

Great. Thanks very much for taking the time to post this.

@RiaanAspeling
Copy link

Thanks man, this works great!

@rogersguedes
Copy link

Thank You so much!
I needed to update failregex to to get it properly working with mosquitto 2.0.20:

failregex = .+New\s+connection\s+from\s+<HOST>:\d+\s+on\s+port\s+\d+\.
            .+Client.+disconnected,\s+not\s+authorised\.

@Toastyyy3
Copy link

For me your approach didn't work and it stated "No failure id group in Client disconnected, not authorised."
Maybe someone has the same problem.
The following did the trick for me:
[Init]
maxlines = 2

[Definition]
failregex = .+New\s+connection\s+from\s+:\d+\s+on\s+port\s+\d+..+Client.+disconnected,\s+not\s+authorised.
ignoreregex =

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment