Add certificates for the Mosquitto MQTT broker secure connections

The method below creates a self signed certificate that allow Mosquitto MQTT broker and it's clients to communicate over encrypted connections.

Create a CA (certificate authority) key pair

mkdir ~/certs
cd ~/certs
openssl genrsa -des3 -out ca.key 2048

Add a secret passphrase and store in a secure location.

Create a certificate for the CA key

openssl req -new -x509 -days 3650 -key ca.key -out ca.crt

Answer the questions at the prompt. Example:

Country Name (2 letter code) [AU]:SE
State or Province Name (full name) [Some-State]:.
Locality Name (eg, city) []:.
Organization Name (eg, company) [Internet Widgits Pty Ltd]:Pixilab
Organizational Unit Name (eg, section) []:.
Common Name (e.g. server FQDN or YOUR name) []:Pixilab CA
Email Address []:.

Create server key pair for the server

openssl genrsa -out server.key 2048

Adjust the -days parameter to suit you needs in the next command.(valid 10 years in the example)

Create a new certificate request

openssl req -new -out server.csr -key server.key

Answer the questions.

Example:

Country Name (2 letter code) [AU]:SE
State or Province Name (full name) [Some-State]:.
Locality Name (eg, city) []:.
Organization Name (eg, company) [Internet Widgits Pty Ltd]:Pixilab
Organizational Unit Name (eg, section) []:.
Common Name (e.g. server FQDN or YOUR name) []:MQTTServer
Email Address []:.

The two last questions can be ignored, just hit enter.

Please enter the following 'extra' attributes
to be sent with your certificate request
A challenge password []:
An optional company name []:

Verify and sign the request

openssl x509 -req -in server.csr -CA ca.crt -CAkey ca.key -CAcreateserial -out server.crt -days 3600

Copy the certificates to Mosquitto

We may have to change user to a super user. I.e

su pixi-admin
sudo cp ca.crt server.crt server.key /etc/mosquitto/certs/

Set correct permissions of certs so they can be read by mosquitto

sudo chmod 664 /etc/mosquitto/certs/*

Mosquitto config file

As sudoer user edit the mosquitto config file: sudo nano /etc/mosquitto/conf.d/pixi.conf

# Certificate listener
listener 8883
cafile /etc/mosquitto/ca_certificates/ca.crt
certfile /etc/mosquitto/certs/server.crt
keyfile /etc/mosquitto/certs/server.key
require_certificate false

password_file /etc/mosquitto/conf.d/pixi-pwd
allow_anonymous false

Restart mosquitto

systemctl restart mosquitto