tobiasschuerg / InfluxDB-Client-for-Arduino

Simple library for sending measurements to an InfluxDB with a single network request. Supports ESP8266 and ESP32.
MIT License
379 stars 94 forks source link

v3.80 cannot connect to InfluxDB v2.0 OSS using TLS #146

Closed davidgs closed 3 years ago

davidgs commented 3 years ago

Steps to reproduce: List the minimal actions needed to reproduce the behavior.

  1. Deploy the simple Example SecureWrite.ino to an ESP-32 Device
  2. Set the host, token, etc
  3. Attempt to write data

Expected behavior: Should validate connection using if (client.validateConnection()) { Serial.print("Connected to InfluxDB: "); Serial.println(client.getServerUrl()); } else { Serial.print("InfluxDB connection failed: "); Serial.println(client.getLastErrorMessage()); }

Actual behavior: InfluxDB connection failed: connection refused

Specifications:

vlastahajek commented 3 years ago

@davidgs, I suppose, you are able to connect to the same server URL from a different host. When you referring to SecureWrite example, does it mean your InfluxDB OSS has TLS set up?

davidgs commented 3 years ago

The server is running TLS. I can send the exact same information via an http api client, like Postman, and it writes fine.

vlastahajek commented 3 years ago

So, you have to either set insecure connection or pass your server certificate instead cloud certificate.

davidgs commented 3 years ago

I am setting my server certificate, and sending it.

davidgs commented 3 years ago

It may very well be in the latest httpClient version, not in the InfluxDB Client. I tried using string httpClient code, and I get a -1 response.

vlastahajek commented 3 years ago

It seems WifiClientSecure for ESP32 doesn't allow direct validation of server certificate or self-signed certificate. Specifying the CA certificate works well. I always used a CA certificate until now, so I was not aware of this.

davidgs commented 3 years ago

So I have to use a Root CA cert?

Can you give me an example of code that seems to work?

vlastahajek commented 3 years ago

I'm not sure if you need exactly root CA or any CA cert in the chain above the server certificate.

SecureWrite uses, by default, InflluxDB2 Cloud CA certificate.
WiFiClientSecure example from ESP32 Arduino SDK also uses rootCA certificate..

davidgs commented 3 years ago

My cert is not a self-signed one.

That being said, I attempted to run the WiFiCLientSecure example above and, with no changes other than my SSID and PASSWORD and ... Connection Failed so something is not right. Are you able to run this?

vlastahajek commented 3 years ago

Sure, it works. I wouldn't recommend anything that doesn't work for me.

I've found you provided a lot more info in the InfluxData community slack. Using even the certificate of the 2nd CA (AplhaSSL CA), not the root CA, of your server certificate chain allows successful connection to the server.

If it doesn't work, try enabling debug in the board configuration. It should show, where is the problem.

davidgs commented 3 years ago

`Linking everything together... /Users/davidgs/Library/Arduino15/packages/esp32/tools/xtensa-esp32-elf-gcc/1.22.0-97-gc752ad5-5.2.0/bin/xtensa-esp32-elf-gcc -nostdlib -L/Users/davidgs/Library/Arduino15/packages/SparkFun/hardware/esp32/1.0.1/tools/sdk/lib -L/Users/davidgs/Library/Arduino15/packages/SparkFun/hardware/esp32/1.0.1/tools/sdk/ld -T esp32_out.ld -T esp32.common.ld -T esp32.rom.ld -T esp32.peripherals.ld -T esp32.rom.libgcc.ld -T esp32.rom.spiram_incompatible_fns.ld -u ld_include_panic_highint_hdl -u call_user_start_cpu0 -Wl,--gc-sections -Wl,-static -Wl,--undefined=uxTopUsedPriority -u cxa_guard_dummy -u cxx_fatal_exception -Wl,--start-group /var/folders/ns/44h75gxn0v95t1xj67pdfjqc0000gn/T/arduino-sketch-74FD4352355FAF34FC4BE558BC8593EB/sketch/MM_Weather_CB_Test.ino.cpp.o /var/folders/ns/44h75gxn0v95t1xj67pdfjqc0000gn/T/arduino-sketch-74FD4352355FAF34FC4BE558BC8593EB/libraries/Wire/Wire.cpp.o /var/folders/ns/44h75gxn0v95t1xj67pdfjqc0000gn/T/arduino-sketch-74FD4352355FAF34FC4BE558BC8593EB/libraries/SPI/SPI.cpp.o /var/folders/ns/44h75gxn0v95t1xj67pdfjqc0000gn/T/arduino-sketch-74FD4352355FAF34FC4BE558BC8593EB/libraries/SparkFun_BME280/SparkFunBME280.cpp.o /var/folders/ns/44h75gxn0v95t1xj67pdfjqc0000gn/T/arduino-sketch-74FD4352355FAF34FC4BE558BC8593EB/libraries/SparkFun_VEML6075_Arduino_Library/SparkFun_VEML6075_Arduino_Library.cpp.o /var/folders/ns/44h75gxn0v95t1xj67pdfjqc0000gn/T/arduino-sketch-74FD4352355FAF34FC4BE558BC8593EB/libraries/SparkFun_AS3935_Lightning_Detector_Arduino_Library/SparkFun_AS3935.cpp.o /var/folders/ns/44h75gxn0v95t1xj67pdfjqc0000gn/T/arduino-sketch-74FD4352355FAF34FC4BE558BC8593EB/libraries/SparkFun_SCD30_Arduino_Library/SparkFun_SCD30_Arduino_Library.cpp.o /var/folders/ns/44h75gxn0v95t1xj67pdfjqc0000gn/T/arduino-sketch-74FD4352355FAF34FC4BE558BC8593EB/libraries/Adafruit_PM25_AQI_Sensor/Adafruit_PM25AQI.cpp.o /var/folders/ns/44h75gxn0v95t1xj67pdfjqc0000gn/T/arduino-sketch-74FD4352355FAF34FC4BE558BC8593EB/libraries/Adafruit_BusIO/Adafruit_BusIO_Register.cpp.o /var/folders/ns/44h75gxn0v95t1xj67pdfjqc0000gn/T/arduino-sketch-74FD4352355FAF34FC4BE558BC8593EB/libraries/Adafruit_BusIO/Adafruit_I2CDevice.cpp.o /var/folders/ns/44h75gxn0v95t1xj67pdfjqc0000gn/T/arduino-sketch-74FD4352355FAF34FC4BE558BC8593EB/libraries/Adafruit_BusIO/Adafruit_SPIDevice.cpp.o /var/folders/ns/44h75gxn0v95t1xj67pdfjqc0000gn/T/arduino-sketch-74FD4352355FAF34FC4BE558BC8593EB/libraries/ESP8266_Influxdb/InfluxData.cpp.o /var/folders/ns/44h75gxn0v95t1xj67pdfjqc0000gn/T/arduino-sketch-74FD4352355FAF34FC4BE558BC8593EB/libraries/ESP8266_Influxdb/InfluxDb.cpp.o /var/folders/ns/44h75gxn0v95t1xj67pdfjqc0000gn/T/arduino-sketch-74FD4352355FAF34FC4BE558BC8593EB/libraries/ESP8266_Influxdb/InfluxDbClient.cpp.o /var/folders/ns/44h75gxn0v95t1xj67pdfjqc0000gn/T/arduino-sketch-74FD4352355FAF34FC4BE558BC8593EB/libraries/ESP8266_Influxdb/Options.cpp.o /var/folders/ns/44h75gxn0v95t1xj67pdfjqc0000gn/T/arduino-sketch-74FD4352355FAF34FC4BE558BC8593EB/libraries/ESP8266_Influxdb/Point.cpp.o /var/folders/ns/44h75gxn0v95t1xj67pdfjqc0000gn/T/arduino-sketch-74FD4352355FAF34FC4BE558BC8593EB/libraries/ESP8266_Influxdb/query/CsvReader.cpp.o /var/folders/ns/44h75gxn0v95t1xj67pdfjqc0000gn/T/arduino-sketch-74FD4352355FAF34FC4BE558BC8593EB/libraries/ESP8266_Influxdb/query/FluxParser.cpp.o /var/folders/ns/44h75gxn0v95t1xj67pdfjqc0000gn/T/arduino-sketch-74FD4352355FAF34FC4BE558BC8593EB/libraries/ESP8266_Influxdb/query/FluxTypes.cpp.o /var/folders/ns/44h75gxn0v95t1xj67pdfjqc0000gn/T/arduino-sketch--lgcc -lesp32 -lphy -lesp_http_client -lmbedtls -lrtc -lesp_http_server -lbtdm_app -lspiffs -lbootloader_support -lmdns -lnvs_flash -lfatfs -lpp -lnet80211 -ljsmn -lface_detection -llibsodium -lvfs -ldl_lib -llog -lfreertos -lcxx -lsmartconfig_ack -lxtensa-debug-module -lheap -ltcpip_adapter -lmqtt -lulp -lfd -lfb_gfx -lnghttp -lprotocomm -lsmartconfig -lm -lethernet -limage_util -lc_nano -lsoc -ltcp_transport -lc -lmicro-ecc -lface_recognition -ljson -lwpa_supplicant -lmesh -lesp_https_ota -lwpa2 -lexpat -llwip -lwear_levelling -lapp_update -ldriver -lbt -lespnow -lcoap -lasio -lnewlib -lconsole -lapp_trace -lesp32-camera -lhal -lprotobuf-c -lsdmmc -lcore -lpthread -lcoexist -lfreemodbus -lspi_flash -lesp-tls -lwpa -lwifi_provisioning -lwps -lesp_adc_cal -lesp_event -lopenssl -lesp_ringbuf -lfr -lstdc++ -Wl,--end-group -Wl,-EL -o /var/folders/ns/44h75gxn0v95t1xj67pdfjqc0000gn/T/arduino-sketch-74FD4352355FAF34FC4BE558BC8593EB/MM_Weather_CB_Test.ino.elf python /Users/davidgs/Library/Arduino15/packages/SparkFun/hardware/esp32/1.0.1/tools/gen_esp32part.py -q /Users/davidgs/Library/Arduino15/packages/SparkFun/hardware/esp32/1.0.1/tools/partitions/default.csv /var/folders/ns/44h75gxn0v95t1xj67pdfjqc0000gn/T/arduino-sketch-74FD4352355FAF34FC4BE558BC8593EB/MM_Weather_CB_Test.ino.partitions.bin /Users/davidgs/Library/Arduino15/packages/esp32/tools/esptool_py/3.0.0/esptool --chip esp32 elf2image --flash_mode dio --flash_freq 80m --flash_size 4MB -o /var/folders/ns/44h75gxn0v95t1xj67pdfjqc0000gn/T/arduino-sketch-74FD4352355FAF34FC4BE558BC8593EB/MM_Weather_CB_Test.ino.bin /var/folders/ns/44h75gxn0v95t1xj67pdfjqc0000gn/T/arduino-sketch-74FD4352355FAF34FC4BE558BC8593EB/MM_Weather_CB_Test.ino.elf esptool.py v3.0-dev Multiple libraries were found for "WiFiClient.h" Used: /Users/davidgs/Library/Arduino15/packages/SparkFun/hardware/esp32/1.0.1/libraries/WiFi Not used: /Users/davidgs/Documents/Arduino/libraries/WiFi101 Not used: /Applications/Arduino.app/Contents/Java/libraries/WiFi Using library Wire at version 1.0.1 in folder: /Users/davidgs/Library/Arduino15/packages/SparkFun/hardware/esp32/1.0.1/libraries/Wire Using library SPI at version 1.0 in folder: /Users/davidgs/Library/Arduino15/packages/SparkFun/hardware/esp32/1.0.1/libraries/SPI Using library SparkFun_BME280 at version 2.0.9 in folder: /Users/davidgs/Documents/Arduino/libraries/SparkFun_BME280 Using library SparkFun_VEML6075_Arduino_Library at version 1.1.4 in folder: /Users/davidgs/Documents/Arduino/libraries/SparkFun_VEML6075_Arduino_Library Using library SparkFun_AS3935_Lightning_Detector_Arduino_Library at version 1.4.3 in folder: /Users/davidgs/Documents/Arduino/libraries/SparkFun_AS3935_Lightning_Detector_Arduino_Library Using library SparkFun_SCD30_Arduino_Library at version 1.0.12 in folder: /Users/davidgs/Documents/Arduino/libraries/SparkFun_SCD30_Arduino_Library Using library Adafruit_PM25_AQI_Sensor at version 1.0.6 in folder: /Users/davidgs/Documents/Arduino/libraries/Adafruit_PM25_AQI_Sensor Using library Adafruit_BusIO at version 1.7.1 in folder: /Users/davidgs/Documents/Arduino/libraries/Adafruit_BusIO Using library ESP8266_Influxdb at version 3.8.0 in folder: /Users/davidgs/Documents/Arduino/libraries/ESP8266_Influxdb Using library HTTPClient at version 1.2 in folder: /Users/davidgs/Library/Arduino15/packages/SparkFun/hardware/esp32/1.0.1/libraries/HTTPClient Using library WiFi at version 1.0 in folder: /Users/davidgs/Library/Arduino15/packages/SparkFun/hardware/esp32/1.0.1/libraries/WiFi Using library WiFiClientSecure at version 1.0 in folder: /Users/davidgs/Library/Arduino15/packages/SparkFun/hardware/esp32/1.0.1/libraries/WiFiClientSecure Using library DNSServer at version 1.1.0 in folder: /Users/davidgs/Library/Arduino15/packages/SparkFun/hardware/esp32/1.0.1/libraries/DNSServer Using library ESPmDNS at version 1.0 in folder: /Users/davidgs/Library/Arduino15/packages/SparkFun/hardware/esp32/1.0.1/libraries/ESPmDNS /Users/davidgs/Library/Arduino15/packages/esp32/tools/xtensa-esp32-elf-gcc/1.22.0-97-gc752ad5-5.2.0/bin/xtensa-esp32-elf-size -A /var/folders/ns/44h75gxn0v95t1xj67pdfjqc0000gn/T/arduino-sketch-74FD4352355FAF34FC4BE558BC8593EB/MM_Weather_CB_Test.ino.elf Sketch uses 912570 bytes (69%) of program storage space. Maximum is 1310720 bytes. Global variables use 41304 bytes (12%) of dynamic memory, leaving 286376 bytes for local variables. Maximum is 327680 bytes.


Compilation complete. Waiting for upload port... "/Users/davidgs/Library/Arduino15/packages/esp32/tools/esptool_py/3.0.0/esptool" --chip esp32 --port "/dev/cu.SLAB_USBtoUART" --baud 921600 --before default_reset --after hard_reset write_flash -z --flash_mode dio --flash_freq 80m --flash_size detect 0xe000 "/Users/davidgs/Library/Arduino15/packages/SparkFun/hardware/esp32/1.0.1/tools/partitions/boot_app0.bin" 0x1000 "/Users/davidgs/Library/Arduino15/packages/SparkFun/hardware/esp32/1.0.1/tools/sdk/bin/bootloader_qio_80m.bin" 0x10000 "/var/folders/ns/44h75gxn0v95t1xj67pdfjqc0000gn/T/arduino-sketch-74FD4352355FAF34FC4BE558BC8593EB/MM_Weather_CB_Test.ino.bin" 0x8000 "/var/folders/ns/44h75gxn0v95t1xj67pdfjqc0000gn/T/arduino-sketch-74FD4352355FAF34FC4BE558BC8593EB/MM_Weather_CB_Test.ino.partitions.bin" `

Which gets me:

Wi-Fi mode set to WIFI_STA .Mode: STA Channel: 1 SSID (7): XXXX Passphrase (9): XXXX BSSID set: 0 XXXX 3.164 [D] setUrls 3.164 [D] writeUrl: https://davidgs.com:8086/api/v2/write?org=influxdata&bucket=telegraf 3.170 [D] queryUrl: https://davidgs.com:8086/api/v2/query?org=influxdata 3.176 [D] writeUrl: https://davidgs.com:8086/api/v2/write?org=influxdata&bucket=telegraf&precision=ms 3.185 [D] setUrls 3.187 [D] writeUrl: https://davidgs.com:8086/api/v2/write?org=influxdata&bucket=telegraf 3.195 [D] queryUrl: https://davidgs.com:8086/api/v2/query?org=influxdata 3.201 [D] Reset buffer: writeBuffSize: 5 3.204 [D] Init 3.206 [D] Library version: 3.8.0 3.209 [D] Device : ESP32 3.211 [D] SDK version: 1.0.4 3.214 [D] Server url: https://davidgs.com:8086 3.218 [D] Org: influxdata 3.220 [D] Bucket: telegraf 3.222 [D] Token: XXXX 3.232 [D] DB version: 2 3.234 [D] Connection reuse: false 3.237 [D] setUrls 3.239 [D] writeUrl: https://davidgs.com:8086/api/v2/write?org=influxdata&bucket=telegraf 3.246 [D] queryUrl: https://davidgs.com:8086/api/v2/query?org=influxdata 3.253 [D] Validating connection to https://davidgs.com:8086/health 21.775 [E] Error - connection refused InfluxDB connection failed: connection refused

So debug doesn't give much more info.

Browser gives: {"name":"influxdb", "message":"ready for queries and writes", "status":"pass", "checks":[], "version": "2.0.6", "commit": "4db98b4c9a"} from the /health URL.

vlastahajek commented 3 years ago

I meant the Debug option in the board configuration, not enabling debug for the library:

image

davidgs commented 3 years ago

BME 280 found ... VEML 6075 found ... PM 2.5 found! Schmow-ZoW, Lightning Detector Ready! [D][WiFiGeneric.cpp:337] _eventCallback(): Event: 0 - WIFI_READY [D][WiFiGeneric.cpp:337] _eventCallback(): Event: 2 - STA_START Wi-Fi mode set to WIFI_STA .[D][WiFiGeneric.cpp:337] _eventCallback(): Event: 4 - STA_CONNECTED .[D][WiFiGeneric.cpp:337] _eventCallback(): Event: 7 - STA_GOT_IP [D][WiFiGeneric.cpp:381] _eventCallback(): STA IP: 192.168.2.20, MASK: 255.255.255.0, GW: 192.168.2.1 Mode: STA Channel: 6 SSID (7): XXXX Passphrase (9): XXXX BSSID set: 0 InfluxIoT 3.664 [D] setUrls 3.664 [D] writeUrl: https://davidgs.com:8086/api/v2/write?org=influxdata&bucket=telegraf 3.670 [D] queryUrl: https://davidgs.com:8086/api/v2/query?org=influxdata 3.676 [D] writeUrl: https://davidgs.com:8086/api/v2/write?org=influxdata&bucket=telegraf&precision=ms 3.685 [D] setUrls 3.687 [D] writeUrl: https://davidgs.com:8086/api/v2/write?org=influxdata&bucket=telegraf 3.695 [D] queryUrl: https://davidgs.com:8086/api/v2/query?org=influxdata 3.701 [D] Reset buffer: writeBuffSize: 5 3.704 [D] Init 3.706 [D] Library version: 3.8.0 3.709 [D] Device : ESP32 3.711 [D] SDK version: 1.0.4 3.714 [D] Server url: https://davidgs.com:8086 3.718 [D] Org: influxdata 3.720 [D] Bucket: telegraf 3.722 [D] Token: XXXX 3.732 [D] DB version: 2 3.734 [D] Connection reuse: false 3.737 [D] setUrls 3.739 [D] writeUrl: https://davidgs.com:8086/api/v2/write?org=influxdata&bucket=telegraf 3.746 [D] queryUrl: https://davidgs.com:8086/api/v2/query?org=influxdata 3.753 [D] Validating connection to https://davidgs.com:8086/health [V][HTTPClient.cpp:235] beginInternal(): url: https://davidgs.com:8086/health [D][HTTPClient.cpp:276] beginInternal(): host: davidgs.com port: 8086 url: /health [V][ssl_client.cpp:56] start_ssl_client(): Free internal heap before TLS 257084 [V][ssl_client.cpp:58] start_ssl_client(): Starting socket [E][ssl_client.cpp:87] start_ssl_client(): Connect to Server failed! [E][WiFiClientSecure.cpp:132] connect(): start_ssl_client: -1 [V][ssl_client.cpp:248] stop_ssl_socket(): Cleaning SSL connection. [D][HTTPClient.cpp:1018] connect(): failed connect to davidgs.com:8086 [W][HTTPClient.cpp:1318] returnError(): error(-1): connection refused 22.382 [E] Error - connection refused [D][HTTPClient.cpp:383] disconnect(): tcp is closed So, no more information in this debug level, and it's on Verbose

vlastahajek commented 3 years ago

Thanks for debug output. You are correctly using preformatted tags, but the log is still hard to read because of missing line endings .

Are you setting a CA certificate for trust?

I have this simple test:

/**
   BasicHTTPSClient.ino

    Created on: 14.10.2018

*/

#include <Arduino.h>

#include <WiFi.h>

#include <HTTPClient.h>

#include <WiFiClientSecure.h>

const char AlphaSSLCA[] PROGMEM =  R"EOF( 
-----BEGIN CERTIFICATE-----
MIIETTCCAzWgAwIBAgILBAAAAAABRE7wNjEwDQYJKoZIhvcNAQELBQAwVzELMAkG
A1UEBhMCQkUxGTAXBgNVBAoTEEdsb2JhbFNpZ24gbnYtc2ExEDAOBgNVBAsTB1Jv
b3QgQ0ExGzAZBgNVBAMTEkdsb2JhbFNpZ24gUm9vdCBDQTAeFw0xNDAyMjAxMDAw
MDBaFw0yNDAyMjAxMDAwMDBaMEwxCzAJBgNVBAYTAkJFMRkwFwYDVQQKExBHbG9i
YWxTaWduIG52LXNhMSIwIAYDVQQDExlBbHBoYVNTTCBDQSAtIFNIQTI1NiAtIEcy
MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEA2gHs5OxzYPt+j2q3xhfj
kmQy1KwA2aIPue3ua4qGypJn2XTXXUcCPI9A1p5tFM3D2ik5pw8FCmiiZhoexLKL
dljlq10dj0CzOYvvHoN9ItDjqQAu7FPPYhmFRChMwCfLew7sEGQAEKQFzKByvkFs
MVtI5LHsuSPrVU3QfWJKpbSlpFmFxSWRpv6mCZ8GEG2PgQxkQF5zAJrgLmWYVBAA
cJjI4e00X9icxw3A1iNZRfz+VXqG7pRgIvGu0eZVRvaZxRsIdF+ssGSEj4k4HKGn
kCFPAm694GFn1PhChw8K98kEbSqpL+9Cpd/do1PbmB6B+Zpye1reTz5/olig4het
ZwIDAQABo4IBIzCCAR8wDgYDVR0PAQH/BAQDAgEGMBIGA1UdEwEB/wQIMAYBAf8C
AQAwHQYDVR0OBBYEFPXN1TwIUPlqTzq3l9pWg+Zp0mj3MEUGA1UdIAQ+MDwwOgYE
VR0gADAyMDAGCCsGAQUFBwIBFiRodHRwczovL3d3dy5hbHBoYXNzbC5jb20vcmVw
b3NpdG9yeS8wMwYDVR0fBCwwKjAooCagJIYiaHR0cDovL2NybC5nbG9iYWxzaWdu
Lm5ldC9yb290LmNybDA9BggrBgEFBQcBAQQxMC8wLQYIKwYBBQUHMAGGIWh0dHA6
Ly9vY3NwLmdsb2JhbHNpZ24uY29tL3Jvb3RyMTAfBgNVHSMEGDAWgBRge2YaRQ2X
yolQL30EzTSo//z9SzANBgkqhkiG9w0BAQsFAAOCAQEAYEBoFkfnFo3bXKFWKsv0
XJuwHqJL9csCP/gLofKnQtS3TOvjZoDzJUN4LhsXVgdSGMvRqOzm+3M+pGKMgLTS
xRJzo9P6Aji+Yz2EuJnB8br3n8NA0VgYU8Fi3a8YQn80TsVD1XGwMADH45CuP1eG
l87qDBKOInDjZqdUfy4oy9RU0LMeYmcI+Sfhy+NmuCQbiWqJRGXy2UzSWByMTsCV
odTvZy84IOgu/5ZR8LrYPZJwR2UcnnNytGAMXOLRc3bgr07i5TelRS+KIz6HxzDm
MTh89N1SyvNTBCVXVmaU6Avu5gMUTu79bZRknl7OedSyps9AsUSoPocZXun4IRZZ
Uw==
-----END CERTIFICATE-----
)EOF";

// Not sure if WiFiClientSecure checks the validity date of the certificate. 
// Setting clock just to be sure...
void setClock() {
  configTime(0, 0, "pool.ntp.org", "time.nist.gov");

  Serial.print(F("Waiting for NTP time sync: "));
  time_t nowSecs = time(nullptr);
  while (nowSecs < 8 * 3600 * 2) {
    delay(500);
    Serial.print(F("."));
    yield();
    nowSecs = time(nullptr);
  }

  Serial.println();
  struct tm timeinfo;
  gmtime_r(&nowSecs, &timeinfo);
  Serial.print(F("Current time: "));
  Serial.print(asctime(&timeinfo));
}

void setup() {

  Serial.begin(115200);
   Serial.setDebugOutput(true);

  Serial.println();

  WiFi.mode(WIFI_STA);
  WiFi.begin("SSID", "pass");

  // wait for WiFi connection
  Serial.print("Waiting for WiFi to connect...");
  int i=0;
  while (WiFi.status() != WL_CONNECTED && i<30) {
    Serial.print(".");
    delay(500);
    i++;
  }
  Serial.println();
  if(WiFi.status() != WL_CONNECTED) {
    Serial.println("WiFi failed");
    ESP.restart();  
  }

  setClock();  
}

void loop() {
  WiFiClientSecure *client = new WiFiClientSecure;
  if(client) {
    client -> setCACert(AlphaSSLCA);
    {
      // Add a scoping block for HTTPClient https to make sure it is destroyed before WiFiClientSecure *client is 
      HTTPClient https;

      Serial.print("[HTTPS] begin...\n");
      if (https.begin(*client, "https://davidgs.com:8086/health")) {
        Serial.print("[HTTPS] GET...\n");
        // start connection and send HTTP header
        int httpCode = https.GET();

        // httpCode will be negative on error
        if (httpCode > 0) {
          // HTTP header has been send and Server response header has been handled
          Serial.printf("[HTTPS] GET... code: %d\n", httpCode);

          // file found at server
          if (httpCode == HTTP_CODE_OK || httpCode == HTTP_CODE_MOVED_PERMANENTLY) {
            String payload = https.getString();
            Serial.println(payload);
          }
        } else {
          Serial.printf("[HTTPS] GET... failed, error: %s\n", https.errorToString(httpCode).c_str());
        }

        https.end();
      } else {
        Serial.printf("[HTTPS] Unable to connect\n");
      }

      // End extra scoping block
    }

    delete client;
  } else {
    Serial.println("Unable to create client");
  }

  Serial.println();
  Serial.println("Waiting 10s before the next round...");
  delay(10000);
}

I'm using ESP32 Arduino SDK 1.0.6.

With CA certificate set for trust is the output:

[HTTPS] begin...
[V][HTTPClient.cpp:245] beginInternal(): url: https://davidgs.com:8086/health
[D][HTTPClient.cpp:293] beginInternal(): protocol: https, host: davidgs.com port: 8086 url: /health
[D][HTTPClient.cpp:579] sendRequest(): request type: 'GET' redirCount: 0

[V][ssl_client.cpp:59] start_ssl_client(): Free internal heap before TLS 278152
[V][ssl_client.cpp:65] start_ssl_client(): Starting socket
[V][ssl_client.cpp:104] start_ssl_client(): Seeding the random number generator
[V][ssl_client.cpp:113] start_ssl_client(): Setting up the SSL/TLS structure...
[V][ssl_client.cpp:129] start_ssl_client(): Loading CA cert
[V][ssl_client.cpp:197] start_ssl_client(): Setting hostname for TLS session...
[V][ssl_client.cpp:212] start_ssl_client(): Performing the SSL/TLS handshake...
[V][ssl_client.cpp:233] start_ssl_client(): Verifying peer X.509 certificate...
[V][ssl_client.cpp:242] start_ssl_client(): Certificate verified.
[V][ssl_client.cpp:257] start_ssl_client(): Free internal heap after TLS 237320
[D][HTTPClient.cpp:1125] connect():  connected to davidgs.com:8086
[V][ssl_client.cpp:295] send_ssl_data(): Writing HTTP request with 152 bytes...
[V][HTTPClient.cpp:1216] handleHeaderResponse(): RX: 'HTTP/1.1 200 OK'
[V][HTTPClient.cpp:1216] handleHeaderResponse(): RX: 'Content-Type: application/json; charset=utf-8'
[V][HTTPClient.cpp:1216] handleHeaderResponse(): RX: 'Date: Fri, 21 May 2021 13:44:29 GMT'
[V][HTTPClient.cpp:1216] handleHeaderResponse(): RX: 'Content-Length: 136'
[V][HTTPClient.cpp:1216] handleHeaderResponse(): RX: ''
[D][HTTPClient.cpp:1257] handleHeaderResponse(): code: 200
[D][HTTPClient.cpp:1260] handleHeaderResponse(): size: 136
[D][HTTPClient.cpp:603] sendRequest(): sendRequest code=200

[HTTPS] GET... code: 200
[D][HTTPClient.cpp:1394] writeToStreamDataBlock(): connection closed or file end (written: 136).
[D][HTTPClient.cpp:385] disconnect(): tcp keep open for reuse
 "status":"pass", "checks":[], "version": "2.0.6", "commit": "4db98b4c9a"}

[D][HTTPClient.cpp:385] disconnect(): tcp keep open for reuse
[V][ssl_client.cpp:265] stop_ssl_socket(): Cleaning SSL connection.
[V][ssl_client.cpp:265] stop_ssl_socket(): Cleaning SSL connection.

With disabled line with setting CA certificate, I get output similar to yours.

[HTTPS] begin...
[V][HTTPClient.cpp:245] beginInternal(): url: https://davidgs.com:8086/health
[D][HTTPClient.cpp:293] beginInternal(): protocol: https, host: davidgs.com port: 8086 url: /health
[D][HTTPClient.cpp:579] sendRequest(): request type: 'GET' redirCount: 0
[V][ssl_client.cpp:59] start_ssl_client(): Free internal heap before TLS 279308
[E][WiFiClientSecure.cpp:133] connect(): start_ssl_client: -1
[V][ssl_client.cpp:265] stop_ssl_socket(): Cleaning SSL connection.
[D][HTTPClient.cpp:1118] connect(): failed connect to davidgs.com:8086
[W][HTTPClient.cpp:1417] returnError(): error(-1): connection refused
[HTTPS] GET... failed, error: connection refused
[D][HTTPClient.cpp:400] disconnect(): tcp is closed
[V][ssl_client.cpp:265] stop_ssl_socket(): Cleaning SSL connection.
[V][ssl_client.cpp:265] stop_ssl_socket(): Cleaning SSL connection.
davidgs commented 3 years ago

So using your AlphaSSL Cert, it now works. So weird. The cert I was using is the exact same one that I use with the --tls-cert= at InfluxDB startup.

¯_(ツ)_/¯

vlastahajek commented 3 years ago

This not my cert. It's part of the chain of your server cert: image

However, I wrote this already two days ago: a server certificate doesn't work, only a CA certificate. The name of the function for setting trusted certificate hints this: setCACert.

davidgs commented 3 years ago

Something odd is afoot. This was working last week. Today? Back to the -1

/**
   BasicHTTPSClient.ino
    Created on: 14.10.2018
**/

#include <Arduino.h>
#include <WiFi.h>
#include <HTTPClient.h>
#include <WiFiClientSecure.h>

const char AlphaSSLCA[] PROGMEM =  R"EOF( 
-----BEGIN CERTIFICATE-----
MIIETTCCAzWgAwIBAgILBAAAAAABRE7wNjEwDQYJKoZIhvcNAQELBQAwVzELMAkG
A1UEBhMCQkUxGTAXBgNVBAoTEEdsb2JhbFNpZ24gbnYtc2ExEDAOBgNVBAsTB1Jv
b3QgQ0ExGzAZBgNVBAMTEkdsb2JhbFNpZ24gUm9vdCBDQTAeFw0xNDAyMjAxMDAw
MDBaFw0yNDAyMjAxMDAwMDBaMEwxCzAJBgNVBAYTAkJFMRkwFwYDVQQKExBHbG9i
YWxTaWduIG52LXNhMSIwIAYDVQQDExlBbHBoYVNTTCBDQSAtIFNIQTI1NiAtIEcy
MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEA2gHs5OxzYPt+j2q3xhfj
kmQy1KwA2aIPue3ua4qGypJn2XTXXUcCPI9A1p5tFM3D2ik5pw8FCmiiZhoexLKL
dljlq10dj0CzOYvvHoN9ItDjqQAu7FPPYhmFRChMwCfLew7sEGQAEKQFzKByvkFs
MVtI5LHsuSPrVU3QfWJKpbSlpFmFxSWRpv6mCZ8GEG2PgQxkQF5zAJrgLmWYVBAA
cJjI4e00X9icxw3A1iNZRfz+VXqG7pRgIvGu0eZVRvaZxRsIdF+ssGSEj4k4HKGn
kCFPAm694GFn1PhChw8K98kEbSqpL+9Cpd/do1PbmB6B+Zpye1reTz5/olig4het
ZwIDAQABo4IBIzCCAR8wDgYDVR0PAQH/BAQDAgEGMBIGA1UdEwEB/wQIMAYBAf8C
AQAwHQYDVR0OBBYEFPXN1TwIUPlqTzq3l9pWg+Zp0mj3MEUGA1UdIAQ+MDwwOgYE
VR0gADAyMDAGCCsGAQUFBwIBFiRodHRwczovL3d3dy5hbHBoYXNzbC5jb20vcmVw
b3NpdG9yeS8wMwYDVR0fBCwwKjAooCagJIYiaHR0cDovL2NybC5nbG9iYWxzaWdu
Lm5ldC9yb290LmNybDA9BggrBgEFBQcBAQQxMC8wLQYIKwYBBQUHMAGGIWh0dHA6
Ly9vY3NwLmdsb2JhbHNpZ24uY29tL3Jvb3RyMTAfBgNVHSMEGDAWgBRge2YaRQ2X
yolQL30EzTSo//z9SzANBgkqhkiG9w0BAQsFAAOCAQEAYEBoFkfnFo3bXKFWKsv0
XJuwHqJL9csCP/gLofKnQtS3TOvjZoDzJUN4LhsXVgdSGMvRqOzm+3M+pGKMgLTS
xRJzo9P6Aji+Yz2EuJnB8br3n8NA0VgYU8Fi3a8YQn80TsVD1XGwMADH45CuP1eG
l87qDBKOInDjZqdUfy4oy9RU0LMeYmcI+Sfhy+NmuCQbiWqJRGXy2UzSWByMTsCV
odTvZy84IOgu/5ZR8LrYPZJwR2UcnnNytGAMXOLRc3bgr07i5TelRS+KIz6HxzDm
MTh89N1SyvNTBCVXVmaU6Avu5gMUTu79bZRknl7OedSyps9AsUSoPocZXun4IRZZ
Uw==
-----END CERTIFICATE-----
)EOF";

// Not sure if WiFiClientSecure checks the validity date of the certificate. 
// Setting clock just to be sure...
void setClock() {
  configTime(0, 0, "pool.ntp.org", "time.nist.gov");

  Serial.print(F("Waiting for NTP time sync: "));
  time_t nowSecs = time(nullptr);
  while (nowSecs < 8 * 3600 * 2) {
    delay(500);
    Serial.print(F("."));
    yield();
    nowSecs = time(nullptr);
  }

  Serial.println();
  struct tm timeinfo;
  gmtime_r(&nowSecs, &timeinfo);
  Serial.print(F("Current time: "));
  Serial.print(asctime(&timeinfo));
}

void setup() {

  Serial.begin(115200);
   Serial.setDebugOutput(true);

  Serial.println();

  WiFi.mode(WIFI_STA);
  WiFi.begin("SSID", "PW");

  // wait for WiFi connection
  Serial.print("Waiting for WiFi to connect...");
  int i=0;
  while (WiFi.status() != WL_CONNECTED && i<30) {
    Serial.print(".");
    delay(500);
    i++;
  }
  Serial.println();
  if(WiFi.status() != WL_CONNECTED) {
    Serial.println("WiFi failed");
    ESP.restart();  
  }
  setClock();  
}

void loop() {
  WiFiClientSecure *client = new WiFiClientSecure;
  if(client) {
    client -> setCACert(AlphaSSLCA);
    {
      // Add a scoping block for HTTPClient https to make sure it is destroyed before WiFiClientSecure *client is 
      HTTPClient https;

      Serial.print("[HTTPS] begin...\n");
      if (https.begin(*client, "https://davidgs.com:8086/health")) {
        Serial.print("[HTTPS] GET...\n");
        // start connection and send HTTP header
        int httpCode = https.GET();

        // httpCode will be negative on error
        if (httpCode > 0) {
          // HTTP header has been send and Server response header has been handled
          Serial.printf("[HTTPS] GET... code: %d\n", httpCode);

          // file found at server
          if (httpCode == HTTP_CODE_OK || httpCode == HTTP_CODE_MOVED_PERMANENTLY) {
            String payload = https.getString();
            Serial.println(payload);
          }
        } else {
          Serial.printf("[HTTPS] GET... failed, error: %s\n", https.errorToString(httpCode).c_str());
        }

        https.end();
      } else {
        Serial.printf("[HTTPS] Unable to connect\n");
      }

      // End extra scoping block
    }

    delete client;
  } else {
    Serial.println("Unable to create client");
  }

  Serial.println();
  Serial.println("Waiting 10s before the next round...");
  delay(10000);
}
> [HTTPS] begin...
> [V][HTTPClient.cpp:235] beginInternal(): url: https://davidgs.com:8086/health
> [D][HTTPClient.cpp:276] beginInternal(): host: davidgs.com port: 8086 url: /health
> [V][ssl_client.cpp:56] start_ssl_client(): Free internal heap before TLS 253516
> [V][ssl_client.cpp:58] start_ssl_client(): Starting socket
> [E][ssl_client.cpp:87] start_ssl_client(): Connect to Server failed!
> [E][WiFiClientSecure.cpp:132] connect(): start_ssl_client: -1
> [V][ssl_client.cpp:248] stop_ssl_socket(): Cleaning SSL connection.
> [D][HTTPClient.cpp:1018] connect(): failed connect to davidgs.com:8086
> [W][HTTPClient.cpp:1318] returnError(): error(-1): connection refused
> [D][HTTPClient.cpp:383] disconnect(): tcp is closed
vlastahajek commented 3 years ago

Wierd. It works for me.

Are you on 1.0.6 SDK? Previous debug log shown 1.0.4... Are you able to connect to a different server using TLS? E.g., with the original BasicHttpsClient example from SDK or to InfluxDB Cloud (SecureWrite from this lib)? Or using a different device? From a different place/network (mitigate routing problem)?

If nothing above will help, I would suggest asking on the ESP forum. I don't know what else could be a problem.