Chapters

MQTT Security Fundamentals: Reference

Start With The Command Nobody Else Should See

A device command has an intended audience. So does a private business message. Both need a check that keeps other clients from receiving them. The documented Bizbox Alpha exposure shows why that check matters.

MQTT sends messages through a broker, a service that routes them by topic, the name of a message route. Securing that route takes three separate checks. Transport layer security (TLS) protects the connection. Authentication checks the connecting client’s identity. An access control list (ACL) limits which topics that identity may read or write.

An encrypted connection can still deliver private data to the wrong recipient. Start with the audience: who should read this message, and who should be denied? Then test identity, topic permission, and the protected link on their own.

In research released on December 4, 2018, Trend Micro, EURECOM, and Politecnico di Milano investigated internet-exposed services. Researchers linked leaked traffic to Douzone’s Bizbox Alpha mobile groupware app. They reported 55,475 messages from one broker over more than four months, including about 18,000 emails. Conversation bodies and business contacts were exposed. These are reported message counts, not people. Source: groupware findings, printed page 30.

The report attributes the exposure to broker misconfiguration. It does not specify exact TLS, authentication, ACL, or anonymous settings, or an incident-specific remediation timeline.

Inference: confidentiality failed, but the disclosure does not identify the failed setting. Ask which independent check would stop an unintended recipient.

Learning Objectives

Use these goals to plan your checks. By the end of this chapter, you should be able to:

  • Set up TLS and check the broker’s identity. Explain why a port number alone does not prove encryption.
  • Compare passwords, client certificates, and verified tokens.
  • Write rules that limit each identity to the topics and actions it needs.
  • Tell disclosure, injection, impersonation, and denial of service apart.
  • Check secrets, certificate validation, and ACL scope on their own.
  • Use the setup-cost, token-lifetime, and ACL models. State what each model assumes.

These terms describe what the broker routes and keeps. Learn them before you set the access rules.

  • MQTT: Publish-subscribe messaging through a broker.
  • Broker: Routes permitted publications to matching subscribers.
  • Topic: A hierarchical message name, such as home/bedroom/temperature.
  • QoS Level: Quality of service: delivery behavior zero, one, or two.
  • Retained Message: The last retained value per topic for new matching subscriptions; not an archive.
  • Last Will and Testament: A client-registered message published after unexpected connection loss.
  • Persistent Session: Subscriptions and eligible pending messages kept across disconnection, subject to session policy and broker limits.

For Beginners: MQTT Security

A subscription requests messages; it does not establish a right to receive them. Check the client’s identity and topic permissions. TLS protects the connection, but does not choose the audience.

Imagine a repair to a broker with unintended recipients. Reject clients without a valid identity. Give accepted identities only their required topic permissions. Protect each connection with TLS and validate the broker certificate. These are proposed controls, not a reconstruction of the Bizbox settings.

Server-authenticated TLS alone does not authenticate the client. Mutual TLS can do that when the broker validates a client certificate. Even then, the authenticated identity still needs a restrictive ACL.

Prerequisites

First learn how topics route messages and how sessions keep state. These two pages cover the basics:

Why MQTT Security Matters

The reported outcome was message disclosure. Other possible MQTT risks need separate evidence:

  • Eavesdropping: Reading unprotected traffic.
  • Injection: Publishing fake commands when write permissions allow it.
  • Denial of service: Exhausting broker or client resources.
  • Impersonation: Passing identity checks as another sender.

These are counterfactual controls, not findings that particular settings were absent. The report leaves this broker’s settings unspecified.

BoundaryWhat the control would changeWhat remains to check
AuthenticationReject clients without accepted credentials.Valid logins can have excessive rights.
Topic ACLDeny forbidden reads and writes.Test each direction; reading does not prove writing.
TLSProtect client-to-broker bytes from network observers.The broker can still deliver data to an overprivileged recipient.
Listener and anonymous accessRestrict reachability and require identity for private topics.Reachability is not permission. Historical factory defaults are unknown.
Security Is Not Optional

Require all three for private messages:

  1. Encryption (TLS/SSL)
  2. Authentication (verify identity)
  3. Authorization (access control)

Review reachability and anonymous permission on each listener separately.

Worked example: what share of the exposed messages were emails?

Divide the approximate email subset, 18,000 messages, by the reported total, 55,475 messages. Multiply by one hundred: about 32.4 percent of the reported leaked messages were emails. Keep “about” because the numerator is approximate. Inputs: printed page 30.

Subtracting about 18,000 leaves roughly 37,475 messages outside that subset. They are not necessarily all chat. Neither result counts people or unique conversations. “More than four months” cannot supply an exact daily or monthly rate.

Protecting only emails would leave the rest outside the inventory. Write read-permission requirements for every private message family.

Common mistake: treating TLS as permission. Encrypting a connection does not narrow its read ACL. An overprivileged recipient can receive private messages through TLS. Test certificate validation, client identity, and topic authority independently.

Try a changed case: unknown clients are rejected, but a valid login receives another identity’s private messages. Which control needs investigation?

Check the control choice

Investigate read authorization. Keep TLS enabled and narrow the ACL. Confirm allowed messages arrive while forbidden messages do not. This is a hypothetical test, not another Bizbox finding.

Try It: Threat Impact Estimator

All inputs and fixed values in these calculators are made up for teaching. They are not measured data. This toy model gives scores on an arbitrary scale. The scores are not chances of harm or amounts of money lost. Use the reported message counts for the case arithmetic.

Transport Layer Security (TLS/SSL)

The case’s transport setting is unknown. For your own path, use TLS and validate the broker certificate. It protects transit, not topic permissions.

Registered ports are conventions; configuration enables encryption.

PortConventional useRequired check
1883MQTT without TLSReject exposed plaintext carrying private data.
8883MQTT over TLSVerify TLS settings and certificate rejection.

Python Example with TLS

This Paho MQTT two-or-later excerpt sets TLS before connecting. Replace the placeholder broker and certificate paths. Client certificates also need broker validation and authorization. Connection setup does not prove delivery.

# Requires paho-mqtt 2.0+
import paho.mqtt.client as mqtt
import ssl

client = mqtt.Client(mqtt.CallbackAPIVersion.VERSION2)

# Configure TLS
client.tls_set(
    ca_certs="/path/to/ca.crt",      # Certificate Authority
    certfile="/path/to/client.crt",  # Client certificate
    keyfile="/path/to/client.key",   # Client private key
    tls_version=ssl.PROTOCOL_TLS_CLIENT
)

# Connect to secure port
client.connect("broker.example.com", 8883)

This API-order exercise uses plaintext. Supply no real secrets; the credentials method does not enable TLS.

Knowledge check · self-test

Knowledge check

Test your understanding.

ESP32 Example with TLS

WiFiClientSecure supplies transport for PubSubClient. This excerpt omits Wi-Fi setup and the connection loop. Its CA certificate is truncated; supply a valid trusted certificate before use.

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

// Root CA certificate (from broker)
const char* ca_cert = R"(
-----BEGIN CERTIFICATE-----
MIIDxTCCAq2gAwIBAgIJAJC1...
-----END CERTIFICATE-----
)";

WiFiClientSecure espClient;
PubSubClient client(espClient);

void setup() {
    espClient.setCACert(ca_cert);
    client.setServer("broker.example.com", 8883);
}

Authentication Methods

Authentication checks who connected. It blocks a recipient without accepted credentials. Topic authorization must still constrain recipients with valid logins. Passwords, certificates, and verified tokens serve the identity check.

Username/Password Authentication

This snippet assumes TLS was configured before connect. The password is a placeholder; port 8883 does not enable encryption. Paho separates TLS and credential setup.

client.username_pw_set("device_001", "SecurePassword123!")
client.connect("broker.example.com", 8883)

Example credential policy:

  • Give each device unique credentials for separate replacement.
  • Protect secrets in storage, outside deployed source code.
  • Rotate credentials and test that retired secrets are rejected.
  • Generate random secrets; this example targets at least 16 characters. Length alone does not prove unpredictability.
Try It: Password Strength Analyzer

The analyzer assumes independent, uniform random characters and one billion guesses per second. Its time covers exhausting the search space, not a measured compromise. Human patterns, stolen credentials, and broker rate limits are outside this model.

Client Certificate Authentication

A unique certificate supports identity when the broker validates it and the handshake proves possession of its private key. Protect that key.

The password-free comment assumes broker support. For Mosquitto username ACLs, map the certificate to a username with require_certificate and use_identity_as_username, or use_subject_as_username. The broker configuration defines this mapping.

client.tls_set(
    certfile="/path/to/device.crt",
    keyfile="/path/to/device.key"
)
# No username/password needed - certificate proves identity

Benefits when enforced:

  • No device password in the MQTT credentials field.
  • Validated identity with proof of the private key.
  • Per-certificate revocation when the broker checks the revocation list.

Connection reuse reduces setup cost without changing who may read a message. The full-handshake model assumes a round-trip time of 100 milliseconds, excluding TCP setup, validation, processing, and retransmissions.

The equations retain E as their symbol, but milliampere seconds measure charge, not energy in joules. Energy requires voltage; the displayed fractions also describe energy only if voltage is constant.

TLS 1.2 handshake (2 RTTs):

TTLS1.2=2×RTT=2×100 ms=200 msT_{\text{TLS1.2}} = 2 \times \text{RTT} = 2 \times 100\text{ ms} = 200\text{ ms}

TLS 1.3 handshake (1 RTT, improved):

TTLS1.3=1×RTT=100 msT_{\text{TLS1.3}} = 1 \times \text{RTT} = 100\text{ ms}

Charge cost (assume 8 mA TX current, 6 handshake packets, 15 ms TX time per packet):

Ehandshake=6×(8 mA×15 ms)=0.72 mAsE_{\text{handshake}} = 6 \times (8\text{ mA} \times 15\text{ ms}) = 0.72\text{ mAs}

Amortized per message (connect once, send NN messages):

Eper_msg=0.72N+EMQTTE_{\text{per\_msg}} = \frac{0.72}{N} + E_{\text{MQTT}}

For N=1440N = 1440 (1 msg/min, 1 day session):

Eper_msg=0.721440+0.4=0.0005+0.4≈0.4 mAsE_{\text{per\_msg}} = \frac{0.72}{1440} + 0.4 = 0.0005 + 0.4 \approx 0.4\text{ mAs}

Illustrative bandwidth inputs, to measure for the deployed certificate chain: TLS 1.3 handshake: assume 3—5 kB TLS 1.2 handshake: assume 5—10 kB MQTT sensor message: assume 50 bytes

At one message per minute for a day, 1,440 messages share the setup. The 0.72 milliampere seconds add 0.0005 per message to the assumed 0.4. Setup contributes about 0.125 percent of modeled charge. Connection reuse does not remove validation or grant topic rights.

TLS Handshake Overhead Calculator

Vary timing, version, message count, and current. Charge is in milliampere seconds. Latency includes only the round-trip component; bandwidth inputs are assumptions. Measure the deployed chain and device before claiming total time or power.

Maths · guided foundations

Session Reuse in a Hypothetical TLS Charge Model

Check the quantities and assumptions.

Token-Based Authentication (JWT)

A JSON Web Token, or JWT, carries claims that a configured broker verifier or plugin must check. Putting a token in the password field alone enforces nothing.

Verify the signing algorithm, trusted signer, audience, and expiration. Map accepted scope claims into topic permissions; a signed string is not an ACL. The sample timestamps are one hour apart, unrelated to the case.

JWT Structure for MQTT:

Header.Payload.Signature

Header: {"alg": "RS256", "typ": "JWT"}
Payload: {
  "sub": "device_001",        # Device ID (subject)
  "iat": 1702834567,          # Issued at timestamp
  "exp": 1702838167,          # Expiration (1 hour later)
  "aud": "mqtt.example.com",  # Target broker
  "scope": ["publish:sensors/#", "subscribe:commands/#"]
}

Python implementation:

import jwt
import time
from cryptography.hazmat.primitives import serialization

# Load device private key
with open("device_private.pem", "rb") as key_file:
    private_key = serialization.load_pem_private_key(
        key_file.read(), password=None
    )

def generate_mqtt_token():
    payload = {
        "sub": "sensor_001",
        "iat": int(time.time()),
        "exp": int(time.time()) + 3600,  # 1 hour validity
        "aud": "mqtt.example.com",
        "scope": ["publish:sensors/temperature", "subscribe:commands/#"]
    }
    return jwt.encode(payload, private_key, algorithm="RS256")

# Connect with JWT
token = generate_mqtt_token()
client.username_pw_set("", token)  # Empty username, token as password

Verifier and lifecycle decisions:

PracticeRecommendation
AlgorithmExplicitly allow the intended algorithm. Use RS256/ES256 when verifiers must not sign; HS256 requires a strong shared secret.
ExpirationEnforce a deployment-specific lifetime; the sample uses one hour.
Scope claimsMap verified claims into topic permissions.
Key rotationDefine replacement and rejection of old keys.

Follow JWT verification guidance; no generic lifetime or quarterly rule replaces policy.

JWT Token Lifetime Calculator

The model assumes a reconnect at every renewal. Availability counts only those modeled interruptions. Actual expiry and continued-session behavior depend on broker policy.

The lifetime index uses an arbitrary formula, not a security assessment. Load is the mean for spread-out renewals, not a synchronized burst. Bandwidth counts only token bytes, in mebibytes. These outputs do not establish an optimum.

Access Control Lists (ACLs)

Read ACLs limit disclosure; write ACLs limit publication. Test both. This compact Mosquitto teaching example is not the unpublished Bizbox policy.

# Compact Mosquitto ACL example
user sensor_01
topic write bldg/sensor_01/temp

user act_01
topic read bldg/cmd/act_01
topic write bldg/status/act_01

user dashboard
topic read bldg/#

The sensor writes its temperature topic; the actuator reads commands and writes status. The dashboard’s broader building read needs a policy reason. Neither direction grants the other.

A client ID names a session, not an authenticated identity. Accepting a second connection with the same ID disconnects the earlier client, so collisions can resemble network faults.

ACL Patterns

Read a rule as a grant for one action on a named path. Check whether it uses a fixed name, a wildcard, or a name drawn from the login. Those choices change whose data the client can reach.

topic read sensors/temp grants one topic. topic write sensors/+/data accepts any one device level, not just the writer’s. topic read sensors/# includes the branch’s parent and descendants.

pattern write sensors/%u/data substitutes the authenticated username for a whole level. %u is literal on a topic line. %c uses the client ID, whose trust depends on broker policy. Mosquitto defines pattern substitution.

A root hash excludes leading-dollar topics. Broad quiz descriptions refer to ordinary topic branches; system namespaces need separately authorized filters. MQTT defines this exception.

ACL Rule Complexity Estimator

Fewer rules can mean broader permissions. Check authorization before comparing file sizes. Username patterns also require a tested login-to-topic mapping.

The estimator limits distinct deployed types to the device count and assumes grouping by type and a fixed review rate. Its audit hours are not measured, and its reduction percentage does not prove policy equivalence.

Knowledge Check: Concept Matching and Protocol Sequencing

Match controls, then order the simplified TLS 1.2 exchange. Its ChangeCipherSpec terminology does not describe TLS 1.3 wire order. Token and certificate answers assume verification and private-key proof.

Knowledge check · self-test

Knowledge check

Test your understanding.

Label the Diagram

Place each control in its own region: the link, the client identity, or topic access. A pass in one region does not prove a pass in the others.

Knowledge check · self-test

Knowledge check

Test your understanding.

Deep-Dive Note: Broker-Enforced Security Boundaries

Use synthetic messages on your own isolated broker. Encrypted connection success proves neither topic permission nor application validity.

Locate transport, identity, and topic policy in the house figure as a guide for your own design.

Follow the house figure from transport through identity to policy. Keep identity, topic, operation, and result together. The house figure tests the concrete publication topic plant/boiler7/valve/set: the boiler sensor may not publish valve commands, and the operations screen may not read them without permission. A literal PUBLISH cannot contain a wildcard. TLS protects the client-to-broker path, while authentication proves the client identity. Authorization limits which topics that identity may publish or subscribe to. The checks are independent: an encrypted connection alone proves neither topic permission nor application validity. Read each denial example as a failed permission for a topic and action, then compare the result with the intended access. This is a design guide, not the historical broker.

  • Recovery safety: Test link loss and restart. Define the safe state in advance, verify that the device enters it, and retain evidence alongside the rejection tests.
  • Transport: Confirm rejection of an invalid broker certificate or hostname.
  • Identity: Confirm refusal of unknown or expired credentials, then recovery with a valid replacement.
  • Read authority: Publish a unique synthetic marker. Confirm intended delivery and forbidden non-delivery with broker and subscriber traces.
  • Write authority: Confirm a forbidden publication is not delivered while a permitted control succeeds.

The positive control distinguishes denial from a broken test path. SUBACK or PUBACK alone may not establish authorization; version and broker policy affect responses. Observe effective delivery and the broker decision.

MQTT 5 adds AUTH for methods such as SCRAM. Packet-specific codes include Not authorized, hexadecimal 87. Pre-CONNECT TLS failures suggest trust or negotiation. For refused CONNECT, inspect CONNACK for credential, protocol, client-ID, availability, or capacity errors. Topic denials suggest authorization. Check packet-specific responses.

TLS ends at its endpoints. It does not encrypt stored queues or hide data from authorized recipients. If the broker must not read payloads, define end-to-end application protection and key ownership.

The Secure MQTT research proposal uses SMQTT for payload protection with key-policy or ciphertext-policy attribute-based encryption, KP-ABE or CP-ABE. One encrypted publication can serve multiple authorized subscribers. This differs from MQTT over TLS. Check which subscriber attributes allow decryption and how keys are issued and revoked; retain TLS, identity, and broker ACL checks.

Keep one security acceptance record: TLS-only listener on 8883, plaintext listener disabled or fenced, certificate validation failure test, per-device identity inventory, ACL negative publish and subscribe tests, MQTT 5 reason-code evidence, and logs tied to client IDs, certificate subjects, or token claims.

Implementation-Level Attack Surface: String Validation and Message Stages

The disclosure case does not establish an implementation exploit. Keep these additional failure paths separate when reviewing the broker and its clients.

MQTT 3.1.1 section 1.5.3 requires connection closure for malformed UTF-8 or a null character in an MQTT UTF-8 protocol string, such as a topic name. For some other control characters and Unicode non-characters, closure is permitted rather than required. A PUBLISH payload is different: section 3.3.3 leaves its content to the application. Arbitrary payload bytes are not automatically a protocol error. An application expecting JSON or UTF-8 must validate that format before storing, acting on, or displaying the data. Protocol string and payload rules.

Retained and queued messages can carry malformed application data to later clients. Retention gives a stored value for a topic, not an unlimited history. Separately, a noncompliant implementation that accepts a malformed protocol string and repeatedly redelivers a retained quality-of-service-two message can create a denial-of-service loop. Test rejection and recovery on an isolated setup; this is not an outcome documented for Bizbox.

Regular expression denial of service, or ReDoS, is another implementation risk. A custom topic matcher built with an inefficient regular expression can spend excessive time backtracking on a crafted topic. Review custom middleware as well as the broker’s own matcher. This is a conditional code-path risk, not a claim that every broker uses such a matcher.

Carry the same review into four application stages. Data collection needs source, channel, and payload checks. Device configuration must not let untrusted connection details direct a device to a rogue broker. Command delivery needs an authorized sender and permitted action before a physical output changes. Over-the-air updates need firmware authenticity and an authenticated delivery path so an intermediary cannot substitute code. Keep a separate acceptance row for each stage; a protected MQTT connection does not establish all four.

Summary

The reported disclosure establishes a confidentiality failure while leaving detailed settings unknown. Test your own boundaries separately. Case outcome.

LayerImplementation
TransportTLS and broker certificate validation
AuthenticationUnique, revocable device credentials
AuthorizationLeast-privilege read and write ACLs
MonitoringActor, topic, action, and outcome logs

Keep these release checks:

  • Reject exposed plaintext carrying private data.
  • Test broker certificate rejection.
  • Test allowed and forbidden topic operations.
  • Rotate credentials and reject retired secrets.

Key Takeaway

Protect the connection, identify the client, and restrict the audience. Encrypted delivery to the wrong recipient is still disclosure. Name each topic’s readers and writers, then prove a neighboring identity is denied.

Hi, I’m Broker Bex. What do you need?

Find help

Let’s find what you need

Find a lesson or return to your module guide.

Give feedback

Help improve this chapter

Tell us what helped or what needs fixing.

Tips

Try a small next step

A few ways to get more from this chapter.

Ask AI

Continue the conversation

Take the conversation further with your preferred assistant.

AI help is available in supported modules when enabled in Settings.

No live person answers on independent study. Feedback does not promise a personal reply.

For welfare or safety concerns, follow your school’s procedures outside IoTClass.