I am having a problem connecting to a mqtt server using self signed certificate. I want to connect my mkr1000 securely to my mosquitto MQTT server on ubuntu. I am generating a CSR on mkr1000 using ARDUINOECCX08CSR example and creating a certificate(.crt),using CA file of ubuntu. Below I am mentioning the process of generating CA,CSR and CRT files for my project.
PROCEDURE I
Ubuntu Machine Steps
Generate a certificate authority certificate and key in ubuntu
openssl req -new -x509 -days 3650 -extensions v3_ca -keyout ca.key -out ca.crt
#### passphrase: abcd
here i get ca.key and ca.crt, where i used “Ubuntu IP” in common name
Server: Generate a server key.
openssl genrsa -des3 -out server.key 2048
#passphrase :abcd
#I tried both ways with and without -des3
Generate a server key without encryption.
openssl genrsa -out server.key 2048
Generate a certificate signing request to send to the CA.
openssl req -out server.csr -key server.key -new
Here I again used “Ubuntu IP” in common Name and I used my subscriber IP( reason, I have no domain name)
Send the CSR to the CA, or sign it with your CA key:
openssl x509 -req -in server.csr -CA ca.crt -CAkey ca.key -CAcreateserial -out server.crt -days 365
Client/Device/MKR1000/ Generating csr
: CSR generated by mkr1000(procedure given below)
We are using mkr1000 device for sending sensor data to mosquitto broker as stated above. Libraries which i am using are:
#include <PubSubClient.h>
#include <WiFi101.h>
#include <ArduinoBearSSL.h>
#include <ArduinoECCX08.h>
#include <ArduinoJson.h>
#include <OneWire.h>
#include <DallasTemperature.h>
#include "arduino_secrets.h"
#define ONE_WIRE_BUS 2
#For connecting to secure mqtt broker at port no 8883, we are generating ECCX08CSR example from #ArduinoECCX08 library for ECC508 & ECC608 crypto chips, examples in Arduino IDE.##
#Burned code example ECCX08CSR in mkr1000 board
#On serial monitor we filled the attributes
#“”””’Serial Monitor”””””””’
ECCX08 Serial Number = 012322619525B27AAF
#Hi there, in order to generate a new CSR for your board, we'll need the following information ...
Country Name (2 letter code) []:
State or Province Name (full name) []:
Locality Name (eg, city) []:
Organization Name (eg, company) []:
Organizational Unit Name (eg, section) []:
Common Name (e.g. server FQDN or YOUR name) [012322619525B27AAF]: 54.196.102.5########
#########54.196.102.5 is used as a common name
What slot would you like to use? (0 - 4) [0]: 0
Would you like to generate a new private key? (Y/n) [Y]: y
Here's your CSR, enjoy!
-----BEGIN CERTIFICATE REQUEST-----
MIHKMHICAQAwEDEOMAwGA1UEAxMFbXlta3IwWTATBgcqhkjOPQIBBggqhkjOPQMBBwNCAARo6lo/
SW6XJ3vWTptpq+xRfiGtVXlfx0H7PRfZqrQCEA6NCkD+DZUQA5hNekMPzveohJscta5PYqAwCQet
TxxhoAAwCgYIKoZIzj0EAwIDSAAwRQIgQbwP9SF10O1dVyXsrNhr/HIEP/o2YzRyN7aqeSYaSvQC
IQCaH6+svv9/oV9bfqePi67PrcDLX+PGkAXlTlZlwJD5ZA==
-----END CERTIFICATE REQUEST-----
“””””””“
After this, Copy the CSR and store it in a file in .txt format. This file is given to CA for generating a certificate for mkr1000.
And I used again ubuntu IP in Common Name, copy the client.csr content and paste it in new file in UBUNTU with same name client.csr where I run below command to get client.crt
Send the CSR to the CA, or sign it with your CA key:
openssl x509 -req -in client.csr -CA ca.crt -CAkey ca.key -CAcreateserial -out client.crt -days 365
IF I compare this UBUNTU generated client.crt file with AWS IoT generated CRT file I found X509 content is missing. To add X509 content I followed another procedure that one I also tried but still I could not understand why MKR1000 is not connected with Ubuntu while using self signed ssl. Even When I was not using SSL concept It work properly following are the mosquitto sub commands which I ran in Ubuntu Terminal
mosquitto_sub -h “UBUNTU IP” -t “Home” --cafile /home/ubuntu/client.crt -p 8333
After getting .crt file generated and signed by CA , We copy the content of the file and paste it in const char SECRET_CERTIFICATE[] variable such as given below
//////////////////////
const char SECRET_CERTIFICATE[] = R"(-----BEGIN CERTIFICATE-----
MIICZTCCAU0CCQDPGXh/GuZk5zANBgkqhkiG9w0BAQsFADB7MQswCQYDVQQGEwJV
UzENMAsGA1UECAwET2hpbzENMAsGA1UEBwwEb2hpbzEMMAoGA1UECgwDaW90MQsw
CQYDVQQLDAJDQTEzMDEGA1UEAwwqSXAtMTcyLTMxLTM0LTQzLnVzLWVhc3QtMi5j
b21wdXRlLmludGVybmFsMB4XDTIwMDEwNTE3MjkwOFoXDTMwMDEwMjE3MjkwOFow
OTE3MDUGA1UEAxMuZWMyLTMtMTQtMy0xMTIudXMtZWFzdC0yLmNvbXB1dGUuYW1h
em9uYXdzLmNvbTBZMBMGByqGSM49AgEGCCqGSM49AwEHA0IABDDoEdFWMR6ELTDC
R/8O1kle/6hVEmUA5q+OlSXeUID76FQ5aFG5PkdQcOOI1TfAwBDTTj3Ga+SIKey2
tXtdkGwwDQYJKoZIhvcNAQELBQADggEBAGNaTcYI2hnUXufV5LWtQPXxBwciPy7/
apRhd3e2T5j1HuxO9F1uJ5pT5pv+31Cn/d1Aqu/ZmXPMPHRVOl1845cGrm8cYWcj
ZY1puYQk91t3g9pLHmZbphvL5QeAXPgtZ/saqr3Jch36FvSJrMMy3w+1UXesYFFX
/lDpwSjSF0F6SqfcezRjp+JFZgl4CHUdXVA1j5K0hwZAm3p8dCdSZABn8SIVdNEc
jFq4lBxjCoivlTHpQSEeUu30pxyM/CEq0sdxjhIUeq2/74NbKVpGrZJpTRWOxkMG
lzW+H3txpiuCTedk5FluO4cqUsjlRrlqeC4cZAREVwz11SVhB5Hj8fE=
-----END CERTIFICATE-----
)"
////////////////////////
After this We upload the code in the MKR1000, the code is given below:
'''
#include <PubSubClient.h>
#include <WiFi101.h>
#include <ArduinoBearSSL.h>
#include <ArduinoECCX08.h>
#include <ArduinoJson.h>
#include <OneWire.h>
#include <DallasTemperature.h>
#include "arduino_secrets.h"
#define ONE_WIRE_BUS 2
OneWire oneWire(ONE_WIRE_BUS);
DallasTemperature sensors(&oneWire);
String temp;
''' const char* ssid = "XXXXXX";
const char* password = "XXXX";
const char* certificate = SECRET_CERTIFICATE;
const char* mqtt_server = "";
'''
WiFiClient espClient;
'''BearSSLClient espClient1(espClient);
PubSubClient client(espClient1);
long lastMsg = 0;
char msg[100];
long long int Node_ID = 44;
int value = 0;
int i= 0;
long int tempint;
void setup_wifi()
{ delay(10);
// We start by connecting to a WiFi network
'''
while (!Serial);
if (!ECCX08.begin())
{
Serial.println("No ECCX08 present!");
while (1);
}'''
'''ArduinoBearSSL.onGetTime(getTime);
espClient1.setEccSlot(0, certificate);
Serial.print("Connecting to ");
Serial.println(ssid);
''' WiFi.begin(ssid, password);
while (WiFi.status() != WL_CONNECTED)
{
delay(500);
Serial.print(".");
}
randomSeed(micros());
Serial.println("");
Serial.println("WiFi connected");
Serial.println("IP address: ");
Serial.println(WiFi.localIP());
}
void callback(char* topic, byte* payload, unsigned int length)
{
Serial.print("Message arrived [");
Serial.print(topic);
Serial.print("] ");
for (int i = 0; i < length; i++)
{
Serial.print((char)payload[i]);
}
Serial.println();
// Switch on the LED if an 1 was received as first character
if ((char)payload[0] == '1')
{
// digitalWrite(BUILTIN_LED, LOW); // Turn the LED on (Note that LOW is the voltage level
// but actually the LED is on; this is because
// it is active low on the ESP-01)
}
else
{
// digitalWrite(BUILTIN_LED, HIGH); // Turn the LED off by making the voltage HIGH
}
}
'''
void reconnect()
{
// Loop until we're reconnected
while (!client.connected()) {
Serial.print("Attempting MQTT connection...");
// Create a random client ID
String clientId = "Client-";
clientId += String(random(0xffff), HEX);
// Attempt to connect
if (client.connect(clientId.c_str())) {
Serial.println("connected");
// Once connected, publish an announcement...
client.publish("accelout", "hello vinit");
// ... and resubscribe
client.subscribe("inTopic");
} else {
Serial.print("failed, rc=");
Serial.print(client.state());
Serial.println(" try again in 5 seconds");
// Wait 5 seconds before retrying
delay(5000);
}
}
}
void setup()
{
Serial.begin(115200);
setup_wifi();
Serial.println("Dallas temp started");
sensors.begin();
client.setServer(mqtt_server, 8883);
client.setCallback(callback);
// Start the serial terminal
}
void loop()
{
i=++i;
if (!client.connected())
{
reconnect();
}
client.loop();
sensors.requestTemperatures();
long now = millis();
StaticJsonDocument<400> doc;
doc["ID"] = Node_ID;
doc["RN"] = i;
doc["Temp"] = sensors.getTempCByIndex(0);
Serial.println();
serializeJsonPretty(doc,msg);
Serial.println("Sending message to MQTT topic..");
Serial.println(msg);
client.publish("Home",msg);
unsigned long getTime()
{
// get the current time from the WiFi module
return WiFi.getTime();
}
#
After burning this code I am getting connected to wifi message on my serial monitor but mkr1000 remains unable to connect to the mqtt server, the code retry to connect to server in every 5 mins.