Communicating devices

MQTT servers can be set up in a very permissive configuration, which makes the protocol easy to work with but leaves it vulnerable to mischief by anyone connected within the perimeter of the network.

This may not be a problem if you're just using MQTT for novelty and maybe to turn a lamp on and off. It's also not problematic if your network is perfectly secured from outsiders. However, if you are using MQTT for physical access control or important appliances such as heating and cooling, it is essential to set up a more secure system.

MQTT Brokers

Being a simple protocol, there are many message queue implementations, such as RabbitMQ or ActiveMQ, that can also serve as MQTT brokers. However the best choice is usually Mosquitto unless you have a compelling reason to use one of the others (such as their support for multiple protocols). We will focus on configuring Mosquitto. Many of these concepts apply to the other message queues, although the implementation details will be different.

Usernames and passwords

The most basic level of security is to require your devices to use a username and password to connect to the MQTT broker. You can set up one global identity to be shared by all clients (not recommended) or give each client its own unique credentials (better), possibly with different access levels.

TLS (SSL)

While usernames and passwords are a good first step in securing your MQTT network, there is one giant problem: network sniffing. Any malicious actor within your network can potentially intercept network traffic to read (and in many cases even modify) the communications between your various devices and computers.

TLS (also known as SSL) is the very same technology used on the Web to secure the connection between web sites and your browser, and you can also use it encrypt your MQTT connections.

Create a self-signed certificate using OpenSSL

A self-signed certificate can get your network encrypted without the hassle of requesting a certificate from one of the "trusted" certificate authorities. It's not as secure, but setting up a self-signed certificate will get you familiar with the technology.

First, generate a cryptographic key. Using OpenSSL (replacing "your-key-name" with some name you wish to use):

openssl genrsa -out your-key-name.key 2048

Next, create a certificate based on that key. You need to replace "your-key-name" with the same name used above, and also come up with something for "your-cert-name".

openssl req -new -x509 -days365 -key your-key-name.key -out your-cert-name.crt