Some hopefully helpful information on how to generate keys, configure Mosquitto and configure clients with mutual certificate authentication.
Includes a Python and Arduino example of MQTT clients with mutual certificate authentication enabled.
We are going to self sign our certificates (we are the certificate authority).
- Install openssl
sudo apt-get update
sudo apt-get install openssl
- Generate CA key and certificate. Set password for ca.key.
openssl genrsa -des3 -out ca.key 2048
openssl req -new -x509 -days 1826 -key ca.key -out ca.crt
- Generate server key and certificate signing request.Ensure the common name is the broker hostname.
openssl genrsa -out server.key 2048
openssl req -new -out server.csr -key server.key
- Sign the server certificate as the CA.
openssl x509 -req -in server.csr -CA ca.crt -CAkey ca.key -CAcreateserial -out server.crt -days 360
- Generate the client key and certificate signing request. Ensure the common name is something unique to the client. This will be its username.
openssl genrsa -out client.key 2048
openssl req -new -out client.csr -key client.key
- Sign the client certificate as the CA.
openssl x509 -req -in client.csr -CA ca.crt -CAkey ca.key -CAcreateserial -out client.crt -days 360
Ensure you already have mosquitto installed on your server, exposed to the internet and has a domain.
- Place the server.crt, server.key & ca.crt inside /etc/mosquitto/certs
- Create custom mosquitto configuration file:
sudo nano /etc/mosquitto/conf.d/custom.conf
- Set the following configurations
allow_anonymous false
listener 8883
log_type error
log_type notice
log_type information
log_type debug
use_identity_as_username true
cafile /etc/mosquitto/certs/ca.crt
keyfile /etc/mosquitto/certs/server.key
certfile /etc/mosquitto/certs/server.crt
tls_version tlsv1.2
require_certificate true
- Restart the mosquitto service:
sudo service mosquitto restart
See mosquittoConfig for example configuration files.
- Install requirements (you should create venv first):
pip3 install -r requirements.txt
- Modify values for your configuration.
- Run script:
python3 mqtt_client.py
- Setup VS Code.
- Install platformIO plugin for VS Code.
- Modify values to match your configuration.
- Build project with platformIO.
- Upload and Monitor to your ESP32.