Skip to content

Commit 2bc9b42

Browse files
committed
Remove Secure Connection macro and add the config to wifimanager.
Secure connections will now automatically be used if the port for the MQTT broker in 443 or 8883. There is also an added checkbox in wifiManager to enable securing the connection with a non-standard port. Also added to wifiManager config is a text box to enter the brokers TLS certificate.
1 parent 18c8524 commit 2bc9b42

File tree

3 files changed

+96
-91
lines changed

3 files changed

+96
-91
lines changed

main/User_config.h

Lines changed: 6 additions & 24 deletions
Original file line numberDiff line numberDiff line change
@@ -80,6 +80,10 @@ const byte ip[] = {192, 168, 1, 99};
8080
const byte mac[] = {0xDE, 0xED, 0xBA, 0xFE, 0x54, 0x95}; //W5100 ethernet shield mac adress
8181
#endif
8282

83+
#ifndef NTP_SERVER
84+
# define NTP_SERVER "pool.ntp.org"
85+
#endif
86+
8387
#ifdef MQTT_HTTPS_FW_UPDATE
8488
# if defined(ESP8266) || defined(ESP32)
8589
//If used, this should be set to the root CA certificate of the server hosting the firmware.
@@ -89,7 +93,6 @@ const char* https_fw_server_cert PROGMEM = R"EOF("
8993
...
9094
-----END CERTIFICATE-----
9195
")EOF";
92-
# define NTP_SERVER "pool.ntp.org"
9396
# ifndef MQTT_HTTPS_FW_UPDATE_USE_PASSWORD
9497
# define MQTT_HTTPS_FW_UPDATE_USE_PASSWORD 1 // Set this to 0 if not using TLS connection to MQTT broker to prevent clear text passwords being sent.
9598
# endif
@@ -142,16 +145,6 @@ const char* https_fw_server_cert PROGMEM = R"EOF("
142145
# define mqtt_max_packet_size 128
143146
#endif
144147

145-
// activate the use of TLS for secure connection to the MQTT broker
146-
// MQTT_SERVER must be set to the Common Name (CN) of the broker's certificate
147-
//#define SECURE_CONNECTION
148-
149-
#ifdef SECURE_CONNECTION
150-
# define MQTT_DEFAULT_PORT "8883"
151-
#else
152-
# define MQTT_DEFAULT_PORT "1883"
153-
#endif
154-
155148
#ifndef MQTT_USER
156149
# define MQTT_USER "your_username"
157150
#endif
@@ -162,11 +155,10 @@ const char* https_fw_server_cert PROGMEM = R"EOF("
162155
# define MQTT_SERVER "192.168.1.17"
163156
#endif
164157
#ifndef MQTT_PORT
165-
# define MQTT_PORT MQTT_DEFAULT_PORT
158+
# define MQTT_PORT "1883"
166159
#endif
167160

168-
#ifdef SECURE_CONNECTION
169-
# if defined(ESP8266) || defined(ESP32)
161+
#if defined(ESP8266) || defined(ESP32)
170162
// The root ca certificate used for validating the MQTT broker
171163
// The certificate must be in PEM ascii format
172164
const char* certificate PROGMEM = R"EOF("
@@ -175,16 +167,6 @@ const char* certificate PROGMEM = R"EOF("
175167
-----END CERTIFICATE-----
176168
")EOF";
177169

178-
// specify a NTP server here or else the NTP server from DHCP is used
179-
# ifndef NTP_SERVER
180-
//# define NTP_SERVER "pool.ntp.org"
181-
# endif
182-
# else
183-
# error "only ESP8266 and ESP32 support SECURE_CONNECTION with TLS"
184-
# endif
185-
#endif
186-
187-
#if defined(ESP8266) || defined(ESP32)
188170
# define ATTEMPTS_BEFORE_BG 10 // Number of wifi connection attempts before going to BG protocol
189171
# define ATTEMPTS_BEFORE_B 20 // Number of wifi connection attempts before going to B protocol
190172
#endif

main/main.ino

Lines changed: 84 additions & 59 deletions
Original file line numberDiff line numberDiff line change
@@ -173,6 +173,9 @@ int failure_number_mqtt = 0; // number of failure connecting to MQTT
173173
bool disc = true; // Auto discovery with Home Assistant convention
174174
#endif
175175
unsigned long timer_led_measures = 0;
176+
static void* eClient = nullptr;
177+
static bool mqtt_secure = false;
178+
static String mqtt_cert = "";
176179

177180
#ifdef ESP32
178181
# include <ArduinoOTA.h>
@@ -186,13 +189,8 @@ unsigned long timer_led_measures = 0;
186189
void WiFiEvent(WiFiEvent_t event);
187190
static bool esp32EthConnected = false;
188191
# endif
189-
# ifdef SECURE_CONNECTION
190-
# include <WiFiClientSecure.h>
191-
WiFiClientSecure eClient;
192-
# else
193-
# include <WiFi.h>
194-
WiFiClient eClient;
195-
# endif
192+
193+
# include <WiFiClientSecure.h>
196194
# include <WiFiMulti.h>
197195
WiFiMulti wifiMulti;
198196
# include <Preferences.h>
@@ -201,6 +199,7 @@ Preferences preferences;
201199
# ifdef MDNS_SD
202200
# include <ESPmDNS.h>
203201
# endif
202+
204203
#elif defined(ESP8266)
205204
# include <ArduinoOTA.h>
206205
# include <DNSServer.h>
@@ -209,26 +208,21 @@ Preferences preferences;
209208
# include <ESP8266WiFiMulti.h>
210209
# include <FS.h>
211210
# include <WiFiManager.h>
212-
# ifdef SECURE_CONNECTION
213-
WiFiClientSecure eClient;
214-
X509List caCert(certificate);
215-
# else
216-
WiFiClient eClient;
217-
# endif
211+
X509List caCert;
218212
ESP8266WiFiMulti wifiMulti;
219213
# ifdef MDNS_SD
220214
# include <ESP8266mDNS.h>
221215
# endif
216+
222217
#else
223218
# include <Ethernet.h>
224-
EthernetClient eClient;
225219
#endif
226220

227221
#define convertTemp_CtoF(c) ((c * 1.8) + 32)
228222
#define convertTemp_FtoC(f) ((f - 32) * 5 / 9)
229223

230224
// client link to pubsub mqtt
231-
PubSubClient client(eClient);
225+
PubSubClient client;
232226

233227
void revert_hex_data(const char* in, char* out, int l) {
234228
//reverting array 2 by 2 to get the data in good order
@@ -517,10 +511,10 @@ void connectMQTT() {
517511
failure_number_mqtt++; // we count the failure
518512
Log.warning(F("failure_number_mqtt: %d" CR), failure_number_mqtt);
519513
Log.warning(F("failed, rc=%d" CR), client.state());
520-
#if defined(SECURE_CONNECTION) && defined(ESP32)
521-
Log.warning(F("failed, ssl error code=%d" CR), eClient.lastError(nullptr, 0));
522-
#elif defined(SECURE_CONNECTION) && defined(ESP8266)
523-
Log.warning(F("failed, ssl error code=%d" CR), eClient.getLastSSLError());
514+
#if defined(ESP32)
515+
Log.warning(F("failed, ssl error code=%d" CR), ((WiFiClientSecure*)eClient)->lastError(nullptr, 0));
516+
#elif defined(ESP8266)
517+
Log.warning(F("failed, ssl error code=%d" CR), ((WiFiClientSecure*)eClient)->getLastSSLError());
524518
#endif
525519
digitalWrite(LED_INFO, LED_INFO_ON);
526520
delay(1000);
@@ -590,9 +584,6 @@ void setup() {
590584
# endif
591585

592586
setOTA();
593-
# ifdef SECURE_CONNECTION
594-
setupTLS();
595-
# endif
596587
#else // In case of arduino platform
597588

598589
//Launch serial for debugging purposes
@@ -617,6 +608,19 @@ void setup() {
617608
port = strtol(mqtt_port, NULL, 10);
618609
Log.trace(F("Port: %l" CR), port);
619610
Log.trace(F("Mqtt server: %s" CR), mqtt_server);
611+
# if defined(ESP8266) || defined(ESP32)
612+
if (port == 8883 || port == 443 || mqtt_secure) {
613+
eClient = new WiFiClientSecure;
614+
mqtt_secure = true;
615+
setupTLS();
616+
} else {
617+
eClient = new WiFiClient;
618+
}
619+
# else
620+
eClient = new EthernetClient;
621+
# endif
622+
623+
client.setClient(*(Client*)eClient);
620624
client.setServer(mqtt_server, port);
621625
#endif
622626

@@ -848,19 +852,24 @@ void setOTA() {
848852
ArduinoOTA.begin();
849853
}
850854

851-
# ifdef SECURE_CONNECTION
852855
void setupTLS() {
853-
# if defined(NTP_SERVER)
854856
configTime(0, 0, NTP_SERVER);
855-
# endif
856-
# if defined(ESP32)
857-
eClient.setCACert(certificate);
858-
# elif defined(ESP8266)
859-
eClient.setTrustAnchors(&caCert);
860-
eClient.setBufferSizes(512, 512);
861-
# endif
862-
}
857+
WiFiClientSecure* sClient = (WiFiClientSecure*)eClient;
858+
if (mqtt_cert.length() > 0) {
859+
# if defined(ESP32)
860+
sClient->setCACert(mqtt_cert.c_str());
861+
} else {
862+
sClient->setCACert(certificate);
863+
}
864+
# elif defined(ESP8266)
865+
caCert.append(mqtt_cert.c_str());
866+
} else {
867+
caCert.append(certificate);
868+
}
869+
sClient->setTrustAnchors(&caCert);
870+
sClient->setBufferSizes(512, 512);
863871
# endif
872+
}
864873
#endif
865874

866875
#if defined(ESPWifiManualSetup)
@@ -999,6 +1008,10 @@ void setup_wifimanager(bool reset_settings) {
9991008
strcpy(mqtt_pass, json["mqtt_pass"]);
10001009
if (json.containsKey("mqtt_topic"))
10011010
strcpy(mqtt_topic, json["mqtt_topic"]);
1011+
if (json.containsKey("mqtt_broker_secure"))
1012+
mqtt_secure = json.get<bool>("mqtt_broker_secure");
1013+
if (json.containsKey("mqtt_broker_cert"))
1014+
mqtt_cert = json.get<const char*>("mqtt_broker_cert");
10021015
if (json.containsKey("gateway_name"))
10031016
strcpy(gateway_name, json["gateway_name"]);
10041017
} else {
@@ -1015,6 +1028,8 @@ void setup_wifimanager(bool reset_settings) {
10151028
WiFiManagerParameter custom_mqtt_user("user", "mqtt user", mqtt_user, parameters_size);
10161029
WiFiManagerParameter custom_mqtt_pass("pass", "mqtt pass", mqtt_pass, parameters_size * 2);
10171030
WiFiManagerParameter custom_mqtt_topic("topic", "mqtt base topic", mqtt_topic, mqtt_topic_max_size);
1031+
WiFiManagerParameter custom_mqtt_secure("secure", "mqtt secure", "1", 1, "type=\"checkbox\"");
1032+
WiFiManagerParameter custom_mqtt_cert("cert", "mqtt broker cert", mqtt_cert.c_str(), 1500);
10181033
WiFiManagerParameter custom_gateway_name("name", "gateway name", gateway_name, parameters_size * 2);
10191034

10201035
//WiFiManager
@@ -1041,6 +1056,8 @@ void setup_wifimanager(bool reset_settings) {
10411056
wifiManager.addParameter(&custom_mqtt_port);
10421057
wifiManager.addParameter(&custom_mqtt_user);
10431058
wifiManager.addParameter(&custom_mqtt_pass);
1059+
wifiManager.addParameter(&custom_mqtt_secure);
1060+
wifiManager.addParameter(&custom_mqtt_cert);
10441061
wifiManager.addParameter(&custom_gateway_name);
10451062
wifiManager.addParameter(&custom_mqtt_topic);
10461063

@@ -1090,6 +1107,8 @@ void setup_wifimanager(bool reset_settings) {
10901107
strcpy(mqtt_pass, custom_mqtt_pass.getValue());
10911108
strcpy(mqtt_topic, custom_mqtt_topic.getValue());
10921109
strcpy(gateway_name, custom_gateway_name.getValue());
1110+
mqtt_secure = *custom_mqtt_secure.getValue();
1111+
mqtt_cert = custom_mqtt_cert.getValue();
10931112

10941113
//save the custom parameters to FS
10951114
if (shouldSaveConfig) {
@@ -1102,6 +1121,8 @@ void setup_wifimanager(bool reset_settings) {
11021121
json["mqtt_pass"] = mqtt_pass;
11031122
json["mqtt_topic"] = mqtt_topic;
11041123
json["gateway_name"] = gateway_name;
1124+
json["mqtt_broker_secure"] = mqtt_secure;
1125+
json["mqtt_broker_cert"] = mqtt_cert;
11051126

11061127
File configFile = SPIFFS.open("/config.json", "w");
11071128
if (!configFile) {
@@ -1623,12 +1644,11 @@ void receivingMQTT(char* topicOri, char* datacallback) {
16231644
}
16241645

16251646
#ifdef MQTT_HTTPS_FW_UPDATE
1626-
# ifndef NTP_SERVER
1627-
# error no NTP_SERVER defined
1628-
# endif
16291647
# include <WiFiClientSecure.h>
1648+
1649+
# include "Ota_github.h"
1650+
16301651
# ifdef ESP32
1631-
# include "Ota_github.h"
16321652
# include "zzHTTPUpdate.h"
16331653
# elif ESP8266
16341654
# include <ESP8266httpUpdate.h>
@@ -1649,9 +1669,6 @@ void MQTTHttpsFWUpdate(char* topicOri, JsonObject& HttpsFwUpdateData) {
16491669
}
16501670

16511671
# if MQTT_HTTPS_FW_UPDATE_USE_PASSWORD > 0
1652-
# ifndef SECURE_CONNECTION
1653-
# warning using a password with an unsecure MQTT connection will send it as clear text!!!
1654-
# endif
16551672
const char* pwd = HttpsFwUpdateData["password"];
16561673
if (pwd) {
16571674
if (strcmp(pwd, ota_password) != 0) {
@@ -1683,38 +1700,46 @@ void MQTTHttpsFWUpdate(char* topicOri, JsonObject& HttpsFwUpdateData) {
16831700

16841701
} else {
16851702
WiFiClientSecure update_client;
1686-
# ifdef SECURE_CONNECTION
1687-
client.disconnect();
1688-
update_client = eClient;
1689-
# else
1690-
configTime(0, 0, NTP_SERVER);
1691-
time_t now = time(nullptr);
1692-
uint8_t count = 0;
1693-
Log.trace(F("Waiting for NTP time sync" CR));
1694-
while ((now < 8 * 3600 * 2) && count++ < 60) {
1695-
vTaskDelay(500);
1696-
now = time(nullptr);
1703+
if (mqtt_secure) {
1704+
client.disconnect();
1705+
update_client = *(WiFiClientSecure*)eClient;
1706+
} else {
1707+
configTime(0, 0, NTP_SERVER);
1708+
time_t now = time(nullptr);
1709+
uint8_t count = 0;
1710+
Log.trace(F("Waiting for NTP time sync" CR));
1711+
while ((now < 8 * 3600 * 2) && count++ < 60) {
1712+
delay(500);
1713+
now = time(nullptr);
1714+
}
1715+
1716+
if (count >= 60) {
1717+
Log.error(F("Unable to update - invalid time" CR));
1718+
# if defined(ZgatewayBT) && defined(ESP32)
1719+
startProcessing();
1720+
# endif
1721+
return;
1722+
}
16971723
}
16981724

1699-
if (count >= 60) {
1700-
Log.error(F("Unable to update - invalid time" CR));
1701-
# if defined(ZgatewayBT) && defined(ESP32)
1702-
startProcessing();
1703-
# endif
1704-
return;
1705-
}
1706-
# endif
17071725
# ifdef ESP32
17081726
if (strstr(url, "github") != 0) {
17091727
update_client.setCACert(_github_cert);
17101728
} else {
17111729
update_client.setCACert(https_fw_server_cert);
17121730
}
1731+
17131732
update_client.setTimeout(12);
17141733
httpUpdate.setFollowRedirects(HTTPC_STRICT_FOLLOW_REDIRECTS);
17151734
result = httpUpdate.update(update_client, url);
17161735
# elif ESP8266
1717-
update_client.setInsecure(); // TODO: replace with cert checking
1736+
if (strstr(url, "github") != 0) {
1737+
caCert.append(_github_cert);
1738+
} else {
1739+
caCert.append(https_fw_server_cert);
1740+
}
1741+
1742+
update_client.setTrustAnchors(&caCert);
17181743
update_client.setTimeout(12000);
17191744
ESPhttpUpdate.setFollowRedirects(HTTPC_STRICT_FOLLOW_REDIRECTS);
17201745
result = ESPhttpUpdate.update(update_client, url);

platformio.ini

Lines changed: 6 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -71,8 +71,8 @@ extra_configs =
7171
;default_envs = uno-fastled
7272
;default_envs = atmega-all-test
7373
;default_envs = manual-wifi-test
74-
;default_envs = esp32dev-tls-test
75-
;default_envs = nodemcuv2-tls-test
74+
;default_envs = esp32dev-mqtt-fw-test
75+
;default_envs = nodemcuv2-mqtt-fw-test
7676
;default_envs = nodemcuv2-rs232
7777
;default_envs = sonoff-rfbridge-direct
7878

@@ -822,29 +822,27 @@ build_flags =
822822
'-DGateway_Name="OpenMQTTGateway_TEST_MANUAL_WIFI"'
823823
board_build.flash_mode = dout
824824

825-
[env:esp32dev-tls-test]
825+
[env:esp32dev-mqtt-fw-test]
826826
platform = ${com.esp32_platform}
827827
board = esp32dev
828828
lib_deps =
829829
${com-esp.lib_deps}
830830
build_flags =
831831
${com-esp.build_flags}
832-
'-DSECURE_CONNECTION'
833832
'-DMQTT_HTTPS_FW_UPDATE'
834-
'-DGateway_Name="OpenMQTTGateway_TEST_TLS"'
833+
'-DGateway_Name="OpenMQTTGateway_TEST_MQTT_FW"'
835834
board_build.flash_mode = dout
836835

837836

838-
[env:nodemcuv2-tls-test]
837+
[env:nodemcuv2-mqtt-fw-test]
839838
platform = ${com.esp8266_platform}
840839
board = nodemcuv2
841840
lib_deps =
842841
${com-esp.lib_deps}
843842
build_flags =
844843
${com-esp.build_flags}
845-
'-DSECURE_CONNECTION'
846844
'-DMQTT_HTTPS_FW_UPDATE'
847-
'-DGateway_Name="OpenMQTTGateway_TEST_TLS"'
845+
'-DGateway_Name="OpenMQTTGateway_TEST_MQTT_FW"'
848846
board_build.flash_mode = dout
849847

850848
[env:rf-wifi-gateway]

0 commit comments

Comments
 (0)