Fernando Tschopp
Posted on September 18, 2022
Authentication
Mosquitto 2.x is now more secure by default and requires users to make an active decision about how to configure security on their broker, rather than possibly relying on the previous very permissive behavior, as well as remove privileged access more quickly.
When Mosquitto is run without a configuration file, or without configuring any listeners, it will now bind to the 127.0.0.1 and/or ::1 loopback interfaces. This means that only connections from the local host will be possible.
Running the broker with a listener defined will by default bind to 0.0.0.0/:: and thus be accessible from any interface.
All listeners now default to allow_anonymous false unless explicitly set to true in the configuration file. This means that when configuring a listener, the user must configure an authentication and access control method, or set allow_anonymous to true.
Edit the configuration file
sudo nano /etc/mosquitto/mosquitto.conf
Edit the file adding the following content
# Setup listener port
listener 1883
# Set log type
log_type all
log_timestamp true
# Set the usser password file
password_file /etc/mosquitto/passwd
Restart the service
sudo systemctl restart mosquitto
Create MQTT users setting the password file defined before and replace mqtt-user1 for your desire username
sudo mosquitto_passwd -c /etc/mosquitto/passwd mqtt-user1
Restart the service again
sudo systemctl restart mosquitto
At this point you're ready to test the publish and subscribe commands.
In one terminal session run the following command:
mosquitto_sub -h <BROKER_IP> -t "mqtt/mytopic" -u mqtt-user1 -P password
In other terminal session run the following command:
mosquitto_pub -h <BROKER_IP> -u mqtt-user1 -P password -t mqtt/mytopic -m "Hello World!"
Authorization on Mosquitto Broker
The created users have access to all the topics, to limit the access permissions you have to configure the ACLs (Access Lists).
Create the ACLs file
sudo nano /etc/mosquitto/aclfile
and put the following content
# This only affects clients with username
user mqtt-user1
topic readwrite #
topic read $SYS/#
user mqtt-user2
topic readwrite mytopic/#
topic read readponly/#
# This affects all clients.
pattern write $SYS/broker/connection/%c/state
Edit the mosquitto configuration file
sudo nano /etc/mosquitto/mosquitto.conf
and add the following line
acl_file /etc/mosquitto/aclfile
Restart the service
Posted on September 18, 2022
Join Our Newsletter. No Spam, Only the good stuff.
Sign up to receive the latest update from our blog.
Related
October 18, 2023