Skip to content

Instantly share code, notes, and snippets.

@codefionn
Last active December 4, 2021 03:44
Show Gist options
  • Save codefionn/0d9ccfa4b216c003a0ba2a8dc65b27be to your computer and use it in GitHub Desktop.
Save codefionn/0d9ccfa4b216c003a0ba2a8dc65b27be to your computer and use it in GitHub Desktop.

Setup mosquitto for TLS

Below, certificates and keys will be created for TLS. Then the misquitto configuration will be edited. Your server will run on localhost:8883 afterwards not localhost:1883.

Create directory for certificates

mkdir /etc/mosquitto/certs
cd /etc/mosquitto/certs

Create CA Key

Using password protection and 4096-bit RSA.

openssl genrsa -des3 -out m2mqtt_ca.key 4096

Create CA Certificate

openssl req -new -x509 -days 9000 -key m2mqtt_ca.key -out m2mqtt_ca.crt

Create Server Key

Using no password and 4096-bit RSA.

openssl genrsa -out m2mqtt_srv.key 4096

Create Server Sign Request

openssl req -new -out m2mqtt_srv.csr -key m2mqtt_srv.key -subj '/CN=localhost'

Create domain configuration

This is important, so the domain and certificate can be validated.

authorityKeyIdentifier=keyid,issuer
basicConstraints=CA:FALSE
subjectAltName = @alt_names
[alt_names]
DNS.1 = localhost
IP.1 = 127.0.0.1
IP.2 = ::1

Create Server Certificate

openssl x509 -req -CA m2mqtt_ca.crt -CAkey m2mqtt_ca.key -in m2mqtt_srv.csr -out m2mqtt_srv.crt -days 9000 -CAcreateserial -extfile domain.ext

Edit /etc/mosquitto/mosquitto.conf

Uncomment line with setting listener and add the following at the end of the line:

8883

Uncomment line with setting cafile and add the following at the end of the line:

/etc/mosquitto/certs/m2mqtt_ca.crt

Uncomment line with setting certfile and add the following at the end of the line:

/etc/mosquitto/certs/m2mqtt_srv.crt

Uncomment line with setting keyfile and add the following at the end of the line:

/etc/mosquitto/certs/m2mqtt_srv.key

These should be all changes you made just now:

listener 8883
cafile /etc/mosquitto/certs/m2mqtt_ca.crt
certfile /etc/mosquitto/certs/m2mqtt_srv.crt
keyfile /etc/mosquitto/certs/m2mqtt_srv.key

Don't forget to add the CAfile m2mqtt_ca.crt to your MQTT client!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment