Set up MQTT broker on raspberry pi

Mosquitto is popular MQTT broker, its available through the raspberry pi main repository. So installing it is very simple.

sudo apt-get update
sudo apt-get install mosquitto
sudo apt-get install mosquitto-clients
sudo systemctl status mosquitto
checking mosquitto service status

The default installation will not allow remote connections. We need to enable it explicitly. create mosquitto.conf file in /etc/mosquitto/conf.d and copy the following contents into the file. Please note that we are allowing anonymous users (client doesn’t need to provide any username/password), this is not recommend outside of the small local (trusted) networks. Please see the documentation for available authentication methods.

listener 1883 0.0.0.0
allow_anonymous true

We need to restart the mosquitto service for the new configuration to take effect.

sudo systemctl restart mosquitto

You can test the installation using the python publisher and consumer.

Mosquitto add password authentication

in the above method, we allowed remote connections without any password. It’s not secure, lets add password based authentication. We can use the password utility provided by mosquitto-clients for adding users. First create a file then run the command to create a new user.

sudo mosquitto_passwd <file path> <user name>
sudo touch /etc/mosquitto/pwfile
sudo mosquitto_passwd /etc/mosquitto/pwfile icircuit
creating password file for mosquitto broker

It’s also possible to remove a user from password file

mosquitto_passwd -D <password file path> <user name>

Now we need to add this password file the configuration file we created above. We will also remove the anonymous access. Update the contents of the configuration file to the following.

listener 1883 0.0.0.0
password_file /etc/mosquitto/pwfile

once restarted, broker will not allow connections without credentials. please note that without TLS, its is password will be sent in plain text on wire, so its possible to sniff the credentials.

Add a Comment

Your email address will not be published. Required fields are marked *