From d1ecfc3eb4d8ea8afad74e19732cd416a4c9c8c0 Mon Sep 17 00:00:00 2001 From: Peter Lebbing Date: Thu, 15 Apr 2021 12:33:39 +0200 Subject: [PATCH] Add MQTT encryption and authentication Authentication is only allowed on encrypted connections to prevent sending the password in plaintext. --- arduino_secrets.h.example | 9 +++++++++ config.h.example | 7 +++++++ pe32me162ir_pub.ino | 25 ++++++++++++++++++++++++- 3 files changed, 40 insertions(+), 1 deletion(-) diff --git a/arduino_secrets.h.example b/arduino_secrets.h.example index 4f2ab6e..dc17916 100644 --- a/arduino_secrets.h.example +++ b/arduino_secrets.h.example @@ -3,3 +3,12 @@ #define SECRET_MQTT_BROKER "192.168.1.2" #define SECRET_MQTT_PORT 1883 #define SECRET_MQTT_TOPIC "some/topic" +/* If you enabled MQTT_TLS, fill in your server certificate fingerprint. + * If the SHA1 fingerprint of your certificate is 01:02:FA:FB:..., fill in all + * 20 bytes as: { 0x01, 0x02, 0xFA, 0xFB, ... } + */ +#define SECRET_MQTT_FINGERPRINT \ + { 0x.., 0x.., ... } +/* If you enabled MQTT_AUTH, fill these in as well */ +#define SECRET_MQTT_USER "" +#define SECRET_MQTT_PASS "" diff --git a/config.h.example b/config.h.example index 304298d..73f15a9 100644 --- a/config.h.example +++ b/config.h.example @@ -1,3 +1,10 @@ +/* Define MQTT_TLS to use TLS with pinned certificate for secure MQTT. Put the + * SHA1 fingerprint of the server certificate in arduino_secrets.h. */ +//#define MQTT_TLS +/* Define MQTT_AUTH to use password authentication (only valid when + * MQTT_TLS is set). */ +//#define MQTT_AUTH + /* Optionally, if you define OPTIONAL_LIGHT_SENSOR, you may attach a light * sensor diode (or photo transistor or whatever) to analog pin A0 and have it * monitor the red watt hour pulse LED. This improves the current Watt diff --git a/pe32me162ir_pub.ino b/pe32me162ir_pub.ino index 9a61c25..ca2806a 100644 --- a/pe32me162ir_pub.ino +++ b/pe32me162ir_pub.ino @@ -214,10 +214,27 @@ const char C_ENDL = '\n'; static char guid[24] = ""; // "EUI48:11:22:33:44:55:66" #ifdef HAVE_WIFI +# ifdef MQTT_TLS +WiFiClientSecure wifiClient; +# else WiFiClient wifiClient; -#ifdef HAVE_MQTT +# endif +# ifdef HAVE_MQTT MqttClient mqttClient(wifiClient); +# endif +#endif + +#ifdef MQTT_TLS +static const uint8_t mqtt_fingerprint[20] PROGMEM = SECRET_MQTT_FINGERPRINT; #endif + +#ifdef MQTT_AUTH +# ifndef MQTT_TLS +# error MQTT_AUTH requires MQTT_TLS +# else +DECLARE_PGM_CHAR_P(mqtt_user, SECRET_MQTT_USER); +DECLARE_PGM_CHAR_P(mqtt_pass, SECRET_MQTT_PASS); +# endif #endif /* We need a (Custom)SoftwareSerial because the Arduino Uno does not do @@ -271,6 +288,12 @@ void setup() #ifdef HAVE_WIFI strncpy(guid, "EUI48:", 6); strncpy(guid + 6, WiFi.macAddress().c_str(), sizeof(guid) - (6 + 1)); +# ifdef MQTT_TLS + wifiClient.setFingerprint(mqtt_fingerprint); +# endif +# ifdef MQTT_AUTH + mqttClient.setUsernamePassword(mqtt_user, mqtt_pass); +# endif #endif pinMode(PIN_IR_RX, INPUT);