Set up and secure an MQTT broker on Ubuntu

I had some IoT devices that I wanted to integrate in my monitoring. For this I set up a MQTT broker as the MQTT protocol is a simple solution to send data from IoT devices to a server. This tutorial is focusing on setting up the server, but I also introduce a Python based MQTT client to test our installation.

On your server, first install mosquitto, our MQTT server/broker.

sudo apt-get install mosquitto

Allow standard mqtt port in firewall (if you have ufw installed)

sudo ufw allow 1883

Now on the client side connect to the server and publish some fake sensor values. First install the mqtt client

sudo pip install phao-mqtt

and then use the following python code on your client side to send fake values to your server. You only need to change mqtt.example.com to your servers IP/domain.

import time
import paho.mqtt.client as mqtt
import numpy
import numpy as np

def calc_temp():
    temp = np.sin(time.time()%(3600)*2*np.pi)*5+20
    return temp

def on_connect(client, userdata, flags, rc):
    print("Connected with result code " + str(rc))

client = mqtt.Client()
#client.username_pw_set(username="username",password="my_super_secret_pw")
client.on_connect = on_connect

client.connect("mqtt.example.com", 1883, 60)

client.loop_start()

while True:
    time.sleep(2)
    client.publish("test/temperature", calc_temp())

You can check if the broker accepts the values by subscribing to the topic:

#!/usr/bin/env python
import paho.mqtt.client as mqtt

def on_connect(client, userdata, flags, rc):
    print("Connected with result code " + str(rc))
    client.subscribe("test/#")

def on_message(client, userdata, msg):
    print(msg.topic + " " + str(msg.payload))

client = mqtt.Client()
#client.username_pw_set(username="username",password="my_super_secret_pw")
client.on_connect = on_connect
client.on_message = on_message

client.connect("mqtt.example.com", 1883, 60)

client.loop_forever()

Now secure your broker by creating a user with a password

sudo mosquitto_passwd -c /etc/mosquitto/passwd <username> 

and configure mosquitto to use it in /etc/mosquitto/conf.d/default.conf:

allow_anonymous false
password_file /etc/mosquitto/passwd

Now restart mosquitto to enable the protection

sudo systemctl restart mosquitto

Test the installation by uncommenting client.username_pw_set(username="username",password="my_super_secret_pw") and filling in your credentials. The result code 0 indicates a valid connection. 5 indicates a authentication error.

I hope this helps setting up a MQTT broker. Hopefully I will have the time to write how to connect such a broker to Grafana via Telegraf and Influx DB.

Student of Medical Engineering, He/Him