In a previous article I described how to install an MQTT broker in a Docker container on a Raspberry Pi; today we will add mandatory authentication for clients connecting to the MQTT server.
The first step (as well as having Docker already installed) is to create a folder on the Raspberry Pi that will contain the configuration files for the MQTT broker.
So connect to your device via SSH and run the following commands:
sudo mkdir docker-mosquitto
sudo mkdir docker-mosquitto/configsudo mkdir docker-mosquitto/datasudo mkdir docker-mosquitto/log
Once these folders have been created, create an initial configuration file using the nano text editor with the following command:
sudo nano docker-mosquitto/config/mosquitto.conf
In the screen that appears, enter the following configuration:
pid_file /var/run/mosquitto.pid
persistence true
persistence_location /mosquitto/data/
log_dest file /mosquitto/log/mosquitto.log
log_dest stdout
Then close the file and save it (control/command+x, yes, enter).
Now create the MQTT container with the following command:
sudo docker run --init -d -it -p 1883:1883 --name mosquitto --restart=always -v ~/docker-mosquitto/config:/mosquitto/config -v ~/docker-mosquitto/log:/mosquitto/log -v ~/docker-mosquitto/data/:/mosquitto/data eclipse-mosquitto
When it has finished, Mosquitto will be running as a Docker container.
To set up authentication on the MQTT broker, you now need to create one or more user accounts to be granted access to the broker. At the moment access is open and anonymous — which can obviously be a vulnerability.
Access the container with the command:
sudo docker exec -it mosquitto sh
and run the following command to create the users/passwords file:
mosquitto_passwd -c /mosquitto/config/mosquitto.passwd mqtt_user
you will then be asked twice for the password for the specified user (in the example, mqtt_user); then exit with the following command:
exit
This defines a first username/password, which you can then use to configure your MQTT clients on your network.
Now we need to tell Mosquitto to use the username/password list we just created. To do this, edit the file created at the beginning with the command:
sudo nano docker-mosquitto/config/mosquitto.conf
and add the following configuration at the end:
password_file /mosquitto/config/mosquitto.passwdallow_anonymous false
Exit and save (control/command+x, yes, enter).
Finally, restart the container to apply the changes:
sudo docker container restart mosquitto
Enjoy!
Enjoy!
