/*
Secure connection example for ESP32 <----> Mosquitto broker (used for MQTT) communcation
with possible client authentication
Prerequisite:
PubSubClient library for Arduino - https://github.com/knolleary/pubsubclient/
OpenSSL - https://www.openssl.org/
Mosquitto broker - https://mosquitto.org/
1. step - Generate the certificates
For generating self-signed certificates please run the following commands:
openssl req -new -x509 -days 365 -extensions v3_ca -keyout ca.key -out ca.crt -subj '/CN=TrustedCA.net' #If you generate self-signed certificates the CN can be anything
openssl genrsa -out mosquitto.key 2048
openssl req -out mosquitto.csr -key mosquitto.key -new -subj '/CN=Mosquitto_borker_adress' #Its necessary to set the CN to the adress of which the client calls your Mosquitto server (eg. yourserver.com)!!!
openssl x509 -req -in mosquitto.csr -CA ca.crt -CAkey ca.key -CAcreateserial -out mosquitto.crt -days 365
#This is only needed if the mosquitto broker requires a client autentithication (require_certificate is set to true in mosquitto config)
openssl genrsa -out esp.key 2048
openssl req -out esp.csr -key esp.key -new -subj '/CN=localhost'
openssl x509 -req -in esp.csr -CA ca.crt -CAkey ca.key -CAcreateserial -out esp.crt -days 365
2. Open ca.crt, esp.crt and esp.key with text viewer and copy the values to this WiFiClientSecureClientAuthentication.ino source file into
corresponding const char CA_cert[], const char ESP_CA_cert[] and const char ESP_RSA_key[] with escape characters.
(1-2.) Alternatively you can use the certificates/certificate_generator.sh script
for generating and formatting the certificates. Befor you run it, please modify the CN value for your adress, or modify any other settings based on yout requierments.
3. step - Install and setup your Mosquitto broker
Follow the instructions from https://mosquitto.org/ and check the manual for the configuration.
For the Mosquito broker you need ca.crt, mosquitto.key and mosquitto.crt files generated in previous step.
Recommended to put they in /etc/mosquitto/ca_certificates/ and /etc/mosquitto/certs/
You need to config Mosquitto broker to use these files (usually /etc/mosquitto/conf.d/default.conf):
listener 8883
cafile path/to/ca.crt
keyfile path/to/mosquitto.key
certfile path/to/mosquitto.crt
require_certificate true or false #If you need client authentication set it to true
log_type all #for logging in /var/log/mosquitto/
4.Restart the Mosquitto service or start the broker:
sudo service mosquitto restart
or
mosquitto -c /etc/mosquitto/conf.d/default.conf
2021 - Norbert Gal - Apache 2.0 License.
*/
#include <WiFi.h>
#include <WiFiClient.h>
#include <PubSubClient.h>
#include "WiFiClientSecure.h"
const char* CA_cert = \
"-----BEGIN CERTIFICATE-----\n" \
"MIIBvzCCAWWgAwIBAgIQBGsfdx20tQFzRBuWuYcm4jAKBggqhkjOPQQDAjA+MRkw\n" \
"FwYDVQQKExBNcXR0QXBwU2FtcGxlc0NBMSEwHwYDVQQDExhNcXR0QXBwU2FtcGxl\n" \
"c0NBIFJvb3QgQ0EwHhcNMjQxMDExMDQwNTAxWhcNMzQxMDA5MDQwNTAxWjA+MRkw\n" \
"FwYDVQQKExBNcXR0QXBwU2FtcGxlc0NBMSEwHwYDVQQDExhNcXR0QXBwU2FtcGxl\n" \
"c0NBIFJvb3QgQ0EwWTATBgcqhkjOPQIBBggqhkjOPQMBBwNCAAT0Om4Jq6TajZOG\n" \
"tUu3+dUwmq05ZGVmJezg50hU4/g8YHfkvEwgy3Rjqku5qkvLJmHsmYe+NceCFHP5\n" \
"07U8O3Syo0UwQzAOBgNVHQ8BAf8EBAMCAQYwEgYDVR0TAQH/BAgwBgEB/wIBATAd\n" \
"BgNVHQ4EFgQUY62W+NJdpee9hKyjYJXQHcUZvg4wCgYIKoZIzj0EAwIDSAAwRQIh\n" \
"ALmywPSpmC8259P1Qo6e9xtKj3bQJX6a3psb0YDIFBZgAiAc0r6k3cCt7jQBX6wT\n" \
"oYjpLQC0gaLA/MPIF0lBxc6Wsw==\n" \
"-----END CERTIFICATE-----";
const char* ESP_CA_cert = \
"-----BEGIN CERTIFICATE-----\n" \
"MIIB3zCCAYagAwIBAgIRALBCRjf5swF8eOJNA336XmUwCgYIKoZIzj0EAwIwRjEZ\n" \
"MBcGA1UEChMQTXF0dEFwcFNhbXBsZXNDQTEpMCcGA1UEAxMgTXF0dEFwcFNhbXBs\n" \
"ZXNDQSBJbnRlcm1lZGlhdGUgQ0EwHhcNMjQxMDExMDQyNDAyWhcNMjUwMTE5MDQy\n" \
"MzU2WjATMREwDwYDVQQDEwhjbGllbnRlMjBZMBMGByqGSM49AgEGCCqGSM49AwEH\n" \
"A0IABFmbYFsGClFutrlJnefu5DnqxVXDcc0qls9SqbZZePuK3bP0lWlb6cqnlbwm\n" \
"C7pn9GMTqld2p53azEidnf0X0ByjgYcwgYQwDgYDVR0PAQH/BAQDAgeAMB0GA1Ud\n" \
"JQQWMBQGCCsGAQUFBwMBBggrBgEFBQcDAjAdBgNVHQ4EFgQUy6YjeO2ShogV6HBC\n" \
"6YK2ZvztWAEwHwYDVR0jBBgwFoAUPVzb1//NouCCDzysZnUyXHAQs2gwEwYDVR0R\n" \
"BAwwCoIIY2xpZW50ZTIwCgYIKoZIzj0EAwIDRwAwRAIgEMQXd31kW5048YI3MgqS\n" \
"CsuOa+4m2h2rebPwn/g28JACIAGIQBeR8GzaVbkUB1makDKQwH6nFmkiDeZAojeB\n" \
"ZyTF\n" \
"-----END CERTIFICATE-----";
const char* ESP_RSA_key= \
"-----BEGIN EC PRIVATE KEY-----\n" \
"MHcCAQEEIDwFdhBHt6Ed/Z/5M76JacG55mOgwdo/W7QqON03kQ5JoAoGCCqGSM49\n" \
"AwEHoUQDQgAEWZtgWwYKUW62uUmd5+7kOerFVcNxzSqWz1Kptll4+4rds/SVaVvp\n" \
"yqeVvCYLumf0YxOqV3anndrMSJ2d/RfQHA==\n" \
"-----END EC PRIVATE KEY-----";
const char* ssid = "Wokwi-GUEST"; // your network SSID (name of wifi network)
const char* password = ""; // your network password
const char* mqtt_server = "mqttbrokereventgrid.eastus2-1.ts.eventgrid.azure.net"; //Adress for your Mosquitto broker server, it must be the same adress that you set in Mosquitto.csr CN field
int port = 8883; //Port to your Mosquitto broker server. Dont forget to forward it in your router for remote access
const char* mqtt_user = "cliente2"; //Depends on Mosquitto configuration, if it is not set, you do not need it
const char* mqtt_pass = "123"; //Depends on Mosquitto configuration, if it is not set, you do not need it
WiFiClientSecure client;
PubSubClient mqtt_client(client);
void setup() {
Serial.begin(115200);
delay(100);
Serial.print("Attempting to connect to SSID: ");
Serial.println(ssid);
WiFi.begin(ssid, password);
// attempt to connect to Wifi network:
while (WiFi.status() != WL_CONNECTED) {
Serial.print(".");
// wait 1 second for re-trying
delay(1000);
}
Serial.print("Connected to ");
Serial.println(ssid);
//Set up the certificates and keys
client.setCACert(CA_cert); //Root CA certificate
client.setCertificate(ESP_CA_cert); //for client verification if the require_certificate is set to true in the mosquitto broker config
client.setPrivateKey(ESP_RSA_key); //for client verification if the require_certificate is set to true in the mosquitto broker config
mqtt_client.setServer(mqtt_server, port);
}
void loop() {
Serial.println("\nStarting connection to server...");
//if you use password for Mosquitto broker
//if (mqtt_client.connect("ESP32", mqtt_user , mqtt_pass)) {
//if you dont use password for Mosquitto broker
if (mqtt_client.connect("ESP32")) {
Serial.print("Connected, mqtt_client state: ");
Serial.println(mqtt_client.state());
//Publsih a demo message to topic LivingRoom/TEMPERATURE with a value of 25
mqtt_client.publish("telemetry/TEMPERATURE", "25");
}
else {
Serial.println("Connected failed! mqtt_client state:");
Serial.print(mqtt_client.state());
Serial.println("WiFiClientSecure client state:");
char lastError[100];
client.lastError(lastError,100); //Get the last error for WiFiClientSecure
Serial.print(lastError);
}
delay(10000);
}Loading
esp32-s3-devkitc-1
esp32-s3-devkitc-1