Skip to content

Commit 3c7961e

Browse files
committed
docs: add notes on mosquitto mbedtls bug fix
1 parent b08bc6f commit 3c7961e

1 file changed

Lines changed: 53 additions & 0 deletions

File tree

docs/ai/MOSQUITTO_TLS_FIX_NOTES.md

Lines changed: 53 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,53 @@
1+
# TLS Initialization Fix for mbedTLS Backend
2+
3+
## Problem
4+
The mbedTLS implementation was unconditionally calling `mosquitto__mbedtls_connect()` for **every** connection in `net__socket_connect_step3()`, even when connecting to non-SSL hosts. This caused TLS handshake attempts on plain MQTT connections, leading to connection failures.
5+
6+
## Root Cause
7+
In `lib/net_mosq.c`, the mbedTLS code path (added as a modification to support mbedTLS alongside OpenSSL) was missing a conditional check that exists in the OpenSSL implementation.
8+
9+
**OpenSSL implementation** (line 872):
10+
```c
11+
if(mosq->ssl_ctx){
12+
// Only setup TLS if ssl_ctx exists
13+
mosq->ssl = SSL_new(mosq->ssl_ctx);
14+
// ... TLS setup code ...
15+
}
16+
```
17+
18+
**Original mbedTLS implementation** (line 917-922, BROKEN):
19+
```c
20+
#elif defined(WITH_TLS_MBEDTLS)
21+
int rc = mosquitto__mbedtls_connect(mosq, host); // ← ALWAYS called!
22+
if(rc){
23+
net__socket_close(mosq);
24+
return rc;
25+
}
26+
```
27+
28+
## Solution
29+
Added the same conditional check used in `net__init_ssl_ctx()` (line 678) to only initialize TLS when it's actually configured:
30+
31+
**Fixed mbedTLS implementation** (line 917-924):
32+
```c
33+
#elif defined(WITH_TLS_MBEDTLS)
34+
if(mosq->tls_cafile || mosq->tls_capath || mosq->tls_psk || mosq->tls_use_os_certs){
35+
int rc = mosquitto__mbedtls_connect(mosq, host);
36+
if(rc){
37+
net__socket_close(mosq);
38+
return rc;
39+
}
40+
}
41+
```
42+
43+
## Verification
44+
TLS should now only be initialized when one of these is configured:
45+
- `mosq->tls_cafile` - CA certificate file path
46+
- `mosq->tls_capath` - CA certificate directory path
47+
- `mosq->tls_psk` - Pre-shared key for PSK authentication
48+
- `mosq->tls_use_os_certs` - Use OS certificate store
49+
50+
When connecting to a non-SSL MQTT broker (e.g., `mqtt://broker:1883`), TLS initialization will be skipped entirely, allowing plain MQTT connections to work correctly.
51+
52+
## Files Modified
53+
- `lib/net_mosq.c` - Added conditional check before `mosquitto__mbedtls_connect()`

0 commit comments

Comments
 (0)