Skip to content

[BUG] TLS handshake is always attempted even when TLS is disabled, causing connection reset on plain MQTT ports #2056

@maghibus

Description

@maghibus

Description
When using TBClient from thingsboard-gateway, the MQTT client always attempts a TLS handshake, even if TLS is not enabled in the configuration and the connection is made to a plain MQTT port (e.g. 1883).

In _create_mqtt_client() the code unconditionally calls:

self.client._client.tls_set(...)

This happens even when self.__tls is False. As a result, the client sends TLS handshake bytes to a non-TLS MQTT listener. Brokers like VerneMQ then log errors such as:

cant_parse_connect_fixed_header

and immediately close the connection. On the client side this appears as:

Connection reset by peer (Errno 104)

How to reproduce

  1. Configure ThingsBoard Gateway to connect to a plain MQTT broker (no TLS) on port 1883.
  2. Do not enable TLS or provide any CA/cert in the configuration.
  3. Start the gateway.
  4. The connection fails with Connection reset by peer, while the broker logs show TLS handshake data on a non-TLS port.

Expected behavior
TLS should only be initialized if TLS is explicitly enabled (tls or caCert present).
On plain MQTT connections, no TLS handshake should be attempted.

Proposed fix
Replace

cert_required = CERT_REQUIRED if (self.__ca_cert and
                                  self.__cert) else ssl.CERT_OPTIONAL if self.__cert else ssl.CERT_NONE

self.client._client.tls_set(...)
if credentials.get("insecure", False):
    self.client._client.tls_insecure_set(True)

with

if self.__tls:
    cert_required = CERT_REQUIRED if (self.__ca_cert and self.__cert) else \
        (ssl.CERT_OPTIONAL if self.__cert else ssl.CERT_NONE)

    self.client._client.tls_set(
        ca_certs=self.__ca_cert,
        certfile=self.__cert,
        keyfile=self.__private_key,
        tls_version=ssl.PROTOCOL_TLSv1_2,
        cert_reqs=cert_required,
        ciphers=None
    )

    if credentials.get("insecure", False):
        self.client._client.tls_insecure_set(True)

Versions:

  • Thingsboard IoT Gateway version 3.8.x

Metadata

Metadata

Assignees

Labels

Type

No type

Projects

No projects

Relationships

None yet

Development

No branches or pull requests

Issue actions