</>EmbeddedInterview

What is MQTT, and how do you make an MQTT client secure?

MediumCommunication Protocols

Short answer: MQTT is a lightweight publish/subscribe messaging protocol over TCP, widely used in IoT. Devices connect to a broker, publish messages to hierarchical topics (e.g. factory/line1/temp) and subscribe to topics they are interested in; the broker forwards messages, so senders and receivers never talk directly. It offers three QoS levels, retained messages, a "last will" message for unexpected disconnects, and keep-alive. Security comes from TLS (encryption and server authentication), client authentication (X.509 client certificates or username/password/tokens), and authorisation (each client can only publish/subscribe to its own topics).

QoS levels

QoS Guarantee Mechanism Use
0 at most once fire and forget frequent telemetry where loss is fine
1 at least once PUBACK; duplicates possible most commands and events (make handlers idempotent)
2 exactly once 4-step handshake rarely needed; expensive

Useful features

  • Retained message: the broker keeps the last message on a topic and sends it to new subscribers (current state).
  • Last Will and Testament: the broker publishes it if the client disappears without disconnecting (device offline detection).
  • Keep-alive pings detect dead connections; persistent sessions queue QoS 1/2 messages while a client is offline.
  • MQTT 5 adds reason codes, message expiry, user properties, shared subscriptions and request/response.

Securing an embedded MQTT client

  1. TLS 1.2/1.3 on port 8883, with the broker's CA certificate pinned in the device; verify the server certificate and hostname.
  2. Mutual TLS: a unique client certificate and private key per device, ideally generated and stored in a secure element or TrustZone/secure storage (never the same key in every device).
  3. Least-privilege topics: broker ACLs so device 123 can only publish to devices/123/# and subscribe to its own command topic.
  4. Validate payloads from command topics (sizes, ranges); treat the broker as untrusted input.
  5. Time: certificate validation needs a correct clock (SNTP or RTC), and plan for certificate rotation before expiry.
  6. Resilience: reconnect with exponential back-off and jitter, buffer messages while offline, and secure OTA for updates.

Embedded clients: Eclipse Paho Embedded C, coreMQTT (FreeRTOS), Zephyr's MQTT library, lwIP's MQTT app; with mbedTLS or wolfSSL for TLS.