Maker tech hub - AI · 3D print · Pi · ESP32 · plus the classic tech archive.

Free ESP32 kit · AI tools directory · Books · Archive

Project · Advanced · ESP32

ESP32 MQTT with TLS Basics (Home Lab)

Certs, device identities, and why open MQTT on WAN is a bad idea.

Written by

Avery J. Parker

IT veteran, maker educator, and author of Network Ninja, 3D Printing Mastery, and AI Workflow Mastery. Business IT: Diversified Tech Solutions.

In this guide

  • Goal & materials
  • Steps / firmware
  • Troubleshooting
  • AI assist notes
  • Related gear & books

MQTT is the easiest way to get ESP32 sensors talking to Home Assistant, Node-RED, or your own scripts. Out of the box, though, it sends everything in plain text, and a broker without authentication accepts commands from anyone who can reach it. This guide sets up TLS on a Mosquitto broker, gives each ESP32 its own identity, and explains why the broker should never be exposed directly to the internet.

The threat model in plain terms

  • Plain MQTT on port 1883 can be read and spoofed by anything on the same network path.
  • An open broker on the internet will be found by scanners. Strangers can read your topics and publish commands to your relays.
  • Shared credentials mean one compromised device exposes all of them.

The fixes: encrypt with TLS, authenticate every client, limit what each client can publish and subscribe to, and keep the broker on your LAN or behind a VPN.

Step 1: create a small certificate authority

For a home lab, your own CA is simpler than public certificates, because devices connect to a local hostname. On a Linux machine with OpenSSL:

# CA (keep ca.key offline and safe)
openssl req -x509 -new -nodes -newkey rsa:2048 -keyout ca.key \
  -out ca.crt -days 3650 -subj "/CN=Home Lab MQTT CA"

# Broker certificate; the name must match how devices reach the broker
openssl req -new -nodes -newkey rsa:2048 -keyout server.key \
  -out server.csr -subj "/CN=broker.lan"
openssl x509 -req -in server.csr -CA ca.crt -CAkey ca.key -CAcreateserial \
  -out server.crt -days 825 \
  -extfile <(printf "subjectAltName=DNS:broker.lan")

Replace broker.lan with your broker's real hostname. If devices connect by IP address, use IP:192.168.x.x in the subjectAltName instead. The <( ) syntax needs bash; in other shells, write the extension to a file.

Step 2: give each device its own certificate

openssl req -new -nodes -newkey rsa:2048 -keyout sensor-01.key \
  -out sensor-01.csr -subj "/CN=sensor-01"
openssl x509 -req -in sensor-01.csr -CA ca.crt -CAkey ca.key \
  -CAcreateserial -out sensor-01.crt -days 825

The common name becomes the device's identity. Per-device certificates let you revoke or replace one board without touching the rest. If certificates per device feel like too much at first, TLS plus a unique username and password per device is still a big step up from plain MQTT.

Step 3: configure Mosquitto

Since Mosquitto 2.0, a broker with no listener configured only accepts local connections, which is a safe default. Add a TLS listener in a file under /etc/mosquitto/conf.d/:

listener 8883
cafile /etc/mosquitto/certs/ca.crt
certfile /etc/mosquitto/certs/server.crt
keyfile /etc/mosquitto/certs/server.key
require_certificate true
use_identity_as_username true
allow_anonymous false
acl_file /etc/mosquitto/acl

Make sure the key files are readable by the mosquitto user and no one else. An ACL file limits each device to its own topics:

# each client may only use topics under its own name
pattern readwrite lab/%u/#

# Home Assistant or your automation user can read everything
user homeassistant
topic read lab/#

With use_identity_as_username, %u is the certificate's common name. Restart Mosquitto and watch its log for errors.

Step 4: connect from the ESP32

#include <WiFi.h>
#include <WiFiClientSecure.h>
#include <PubSubClient.h>

extern const char CA_CERT[];      // contents of ca.crt
extern const char DEVICE_CERT[];  // sensor-01.crt
extern const char DEVICE_KEY[];   // sensor-01.key

WiFiClientSecure net;
PubSubClient mqtt(net);

void setup() {
  WiFi.begin("your-ssid", "your-password");
  while (WiFi.status() != WL_CONNECTED) delay(250);
  configTime(0, 0, "pool.ntp.org");   // correct clock for certificate dates
  net.setCACert(CA_CERT);
  net.setCertificate(DEVICE_CERT);
  net.setPrivateKey(DEVICE_KEY);
  mqtt.setServer("broker.lan", 8883);
  if (mqtt.connect("sensor-01")) {
    mqtt.publish("lab/sensor-01/status", "online", true);
  }
}

void loop() {
  mqtt.loop();
}

Notes:

  • Never use setInsecure() outside a quick test. It turns off server verification, which defeats the point.
  • PubSubClient's default maximum packet size is small. Call mqtt.setBufferSize() if you publish larger JSON payloads.
  • Add reconnect logic in loop() for real deployments.

Step 5: remote access without exposing the broker

Do not forward 1883 or 8883 on your router. If you need to reach devices or dashboards from outside, use a VPN such as WireGuard into your home network. Your phone or laptop joins the LAN securely, and the broker stays invisible to the internet.

Limits to know about

  • A device's private key lives in its flash. Anyone with physical access can read it unless flash encryption is enabled. Treat each device key as replaceable.
  • Certificates expire. Note expiry dates and plan a way to update device certificates, for example during an OTA update.
  • TLS adds memory use and connection time on the ESP32. Keep connections open rather than reconnecting for every message.

Common mistakes

SymptomLikely causeFix
TLS handshake failsHostname does not match the server certificateConnect using the name in subjectAltName
Connection refused, not authorizedACL or identity mismatchCheck the CN, the ACL pattern, and the broker log
Fails after a reboot, works laterClock not set yetWait for NTP time before connecting
Large messages silently droppedPubSubClient buffer too smallIncrease with setBufferSize()

Summary

Run Mosquitto with a TLS listener, your own small CA, per-device certificates or credentials, and an ACL that keeps each device in its own topic space. Verify the server on the ESP32 instead of skipping checks, and use a VPN rather than port forwarding for remote access.

Related