26  MQTT Security

In 60 Seconds

MQTT security requires three layers: TLS encryption (port 8883) to prevent eavesdropping, authentication (username/password or client certificates) to verify device identity, and Access Control Lists (ACLs) to restrict which topics each client can publish or subscribe to. Never deploy MQTT on unencrypted port 1883 in production – without TLS, credentials and sensor data travel in plaintext, making the entire IoT system vulnerable to interception and unauthorized control.

Key Concepts

  • MQTT: Message Queuing Telemetry Transport — pub/sub protocol optimized for constrained IoT devices over unreliable networks
  • Broker: Central server routing messages from publishers to all matching subscribers by topic pattern
  • Topic: Hierarchical string (e.g., home/bedroom/temperature) used to route messages to interested subscribers
  • QoS Level: Quality of Service 0/1/2 trading delivery guarantee for message overhead
  • Retained Message: Last message on a topic stored by broker for immediate delivery to new subscribers
  • Last Will and Testament: Pre-configured message published by broker when a client disconnects ungracefully
  • Persistent Session: Broker stores subscriptions and pending messages allowing clients to resume after disconnection

26.1 Introduction

Securing MQTT communications is essential for production IoT deployments. This chapter covers Transport Layer Security (TLS), authentication mechanisms, and Access Control Lists (ACLs) for robust MQTT security.

Simple Explanation: Imagine sending a postcard through the mail - anyone who handles it can read your message. That’s how unprotected MQTT works! MQTT security is like putting your message in a locked box that only the recipient can open.

Three Protections You Need:

  1. Encryption (TLS): Scrambles your message so eavesdroppers see gibberish
  2. Authentication: Proves you are who you say you are (like showing ID)
  3. Authorization (ACLs): Controls what each user can access (like VIP areas)

Real-World Analogy: Think of a secure office building: - TLS = The building’s walls and locked doors (keeps outsiders out) - Authentication = Your employee badge (proves your identity) - ACLs = Your badge only opens certain floors (limits access)

Key Ports to Remember:

  • Port 1883 = Insecure (like an unlocked door - development only!)
  • Port 8883 = Secure with TLS (production use)

26.2 Learning Objectives

By the end of this chapter, you will be able to:

  • Implement TLS Encryption: Configure secure MQTT connections on port 8883 using self-signed or CA-issued certificates
  • Configure Authentication: Set up username/password and certificate-based authentication on a Mosquitto broker
  • Design Access Control: Create topic-level ACL policies for multi-tenant systems following the principle of least privilege
  • Diagnose Common Security Mistakes: Identify and remediate production security pitfalls such as plaintext credentials and overly broad ACLs
  • Compare Authentication Methods: Evaluate username/password versus client certificate authentication and select the appropriate approach for a given deployment scale
  • Assess Security Posture: Evaluate an MQTT deployment against the three-layer defense model and justify configuration choices
Minimum Viable Understanding: MQTT Security

Core Concept: MQTT security requires three layers working together: transport encryption (TLS on port 8883), authentication (username/password or certificates), and authorization (topic-level ACLs). Missing any layer leaves your IoT system vulnerable.

Why It Matters: An unprotected MQTT broker on port 1883 exposes all device communications in plaintext - attackers can read sensor data, inject malicious commands, and impersonate devices. A 2023 study found over 8,000 exposed MQTT brokers on the internet with no authentication.

Key Insight: Always use TLS (port 8883) + authentication + ACLs together. Like a bank vault needs a locked door (TLS), ID check (authentication), AND restricted access to specific boxes (ACLs) - one layer alone isn’t enough.

Critical Security Warning

NEVER use public MQTT brokers (test.mosquitto.org) for production systems! These are unencrypted, unauthenticated, and anyone can subscribe to your topics. Always use: - TLS encryption (port 8883) - Username/password OR client certificates - Topic-level ACLs - A private broker (self-hosted or managed cloud service)

Sammy the Temperature Sensor says: “MQTT security is like having a super-secret club with special rules!”

26.2.1 The Sensor Squad Adventure: Protecting the Clubhouse

The Sensor Squad wanted to share secret messages about the weather, but they discovered that anyone could listen in! “This won’t do,” said Bella the Button. “We need three special protections!”

Protection 1: The Secret Language (TLS Encryption) “First,” said Lila the Light Sensor, “let’s speak in a secret code! Even if someone overhears us, they won’t understand what we’re saying.” This is like TLS - it scrambles messages so only the right receiver can unscramble them.

Protection 2: The Password (Authentication) “Second,” said Max the Motion Detector, “everyone needs a secret password to join our club!” Just like how your favorite app needs a password, MQTT devices need usernames and passwords too.

Protection 3: The Room Rules (ACLs) “Third,” said Sammy, “different members can only go into certain rooms! I can talk about temperature, but I can’t sneak into the motion detector room.” These are ACL rules - they decide who can send and receive which messages.

26.2.2 Key Words for Kids

Word What It Means
TLS A secret code language that scrambles messages so bad guys can’t read them
Authentication Proving who you are with a password, like showing your library card
ACL Access Control List - rules about who can go where and do what
Port 8883 The special secure door for MQTT messages (like a VIP entrance!)

26.2.3 Fun Fact

Did you know that MQTT was invented to help oil pipelines talk to each other in the desert? Even back then, they knew security was important!

26.3 Security Layers

MQTT security consists of three layers that work together to protect your IoT communications. Think of these as concentric walls of defense - an attacker must breach all three to compromise your system.

MQTT three-layer security

MQTT Security Layers: Defense in Depth Architecture
Figure 26.1: MQTT Security Layers: Defense in Depth Architecture
Layer Purpose Implementation
Transport Encrypt data in transit TLS/SSL on port 8883
Authentication Verify client identity Username/password, certificates
Authorization Control topic access Access Control Lists (ACLs)

The following diagram shows what happens when security layers are missing:

MQTT attack vectors when security layers are missing showing unencrypted traffic vulnerable to eavesdropping, unauthenticated connections allowing unauthorized device access, and missing authorization enabling topic hijacking and data exfiltration

Attack Vectors When Security Layers Are Missing
Figure 26.2: Attack Vectors When Security Layers Are Missing
Quick Check: Security Layers

26.4 TLS Encryption

TLS vs SSL

TLS (Transport Layer Security) is the successor to SSL. Modern MQTT implementations use TLS 1.2 or 1.3. Always use TLS, not the deprecated SSL.

Standard Ports:

  • 1883: Unencrypted MQTT (development only!)
  • 8883: Encrypted MQTT over TLS (production)
  • 443: MQTT over WebSocket with TLS (browser-based clients)

How much does TLS encryption actually cost in terms of packet size and processing? Let’s quantify the overhead of securing MQTT communications.

Unencrypted MQTT packet (port 1883): \[\text{Total} = 2\text{ (fixed header)} + 5\text{ (topic length)} + 10\text{ (payload)} = 17\text{ bytes}\]

Encrypted MQTT packet (port 8883) adds:

  • TLS record header: 5 bytes
  • Authentication tag (GCM mode): 16 bytes
  • IV (initialization vector): 8 bytes
  • Padding: ~0-15 bytes (average 8)

\[\text{TLS overhead} = 5 + 16 + 8 + 8 = 37\text{ bytes}\] \[\text{Total encrypted} = 17 + 37 = 54\text{ bytes}\]

Overhead ratio: \(\frac{37}{17} \times 100\% = 217\%\) overhead for this small payload.

CPU impact: TLS 1.3 with AES-128-GCM on ESP32 (240 MHz): - Handshake: ~150-200 ms once per connection - Per-message encryption: ~0.5 ms for 17-byte payload - Energy cost: ~2 mAh for 1000 encrypted messages vs ~1.8 mAh unencrypted (~11% increase)

Key insight: TLS overhead is significant for tiny payloads but essential for production. The security benefit vastly outweighs the modest energy increase.

Interactive Calculator: TLS Overhead Analysis

Adjust the payload size and message frequency to see how TLS overhead scales with your use case.

The TLS handshake establishes a secure, encrypted channel before any MQTT messages are exchanged:

TLS handshake sequence

TLS Handshake for Secure MQTT Connection
Figure 26.3: TLS Handshake for Secure MQTT Connection

26.4.1 Step 1: Generate SSL/TLS Certificates

# Create certificate directory
sudo mkdir -p /etc/mosquitto/certs
cd /etc/mosquitto/certs

# Generate CA certificate
sudo openssl req -new -x509 -days 365 -extensions v3_ca \
  -keyout ca.key -out ca.crt \
  -subj "/C=US/ST=State/L=City/O=IoTClass/CN=CA"

# Generate server key and certificate
sudo openssl genrsa -out server.key 2048
sudo openssl req -new -out server.csr -key server.key \
  -subj "/C=US/ST=State/L=City/O=IoTClass/CN=mqtt.local"
sudo openssl x509 -req -in server.csr -CA ca.crt -CAkey ca.key \
  -CAcreateserial -out server.crt -days 365

# Set permissions
sudo chmod 644 /etc/mosquitto/certs/*.crt
sudo chmod 600 /etc/mosquitto/certs/*.key

26.4.2 Step 2: Configure Mosquitto with Security

Edit /etc/mosquitto/mosquitto.conf:

# Default listener (disabled for production)
listener 1883
allow_anonymous false

# TLS listener
listener 8883
cafile /etc/mosquitto/certs/ca.crt
certfile /etc/mosquitto/certs/server.crt
keyfile /etc/mosquitto/certs/server.key
require_certificate false

# Password file
password_file /etc/mosquitto/passwd

# Logging
log_dest file /var/log/mosquitto/mosquitto.log
log_type all

26.4.3 Step 3: Create User Accounts

# Create password file with first user
sudo mosquitto_passwd -c /etc/mosquitto/passwd iotuser

# Add more users (without -c flag)
sudo mosquitto_passwd /etc/mosquitto/passwd admin

26.4.4 Step 4: Restart Mosquitto

sudo systemctl restart mosquitto
sudo systemctl status mosquitto

26.5 Python Client with TLS and Authentication

import paho.mqtt.client as mqtt
import ssl

# paho-mqtt 2.0+ requires CallbackAPIVersion
client = mqtt.Client(mqtt.CallbackAPIVersion.VERSION2)
client.username_pw_set("iotuser", "your_password")

client.tls_set(
    ca_certs="/path/to/ca.crt",
    tls_version=ssl.PROTOCOL_TLS_CLIENT
)

def on_connect(client, userdata, flags, reason_code, properties):
    if reason_code == 0:
        print("Securely connected!")
        client.subscribe("secure/test/#")
    else:
        print(f"Connection failed: {reason_code}")

def on_message(client, userdata, msg):
    print(f"[{msg.topic}] {msg.payload.decode()}")

client.on_connect = on_connect
client.on_message = on_message

client.connect("mqtt.local", 8883, 60)
client.loop_forever()

Expected Output:

Securely connected!
[secure/test/data] Hello from secure MQTT!
Try It: MQTT Connection Parameter Explorer

26.6 Access Control Lists (ACLs)

ACLs control which clients can publish/subscribe to which topics. This is the authorization layer - even authenticated users should only access topics they need (principle of least privilege).

MQTT ACL architecture

Topic-Level Access Control: Different Users, Different Permissions
Figure 26.4: Topic-Level Access Control: Different Users, Different Permissions

26.6.1 Mosquitto ACL Configuration

Create /etc/mosquitto/acl:

# Admin can access everything
user admin
topic readwrite #

# Sensor devices can only publish to their topics
user sensor_001
topic write sensors/001/#
topic read commands/001

# Dashboard can read everything, write nothing
user dashboard
topic read sensors/#
topic read devices/#

# Default: deny everything
topic deny #

Update mosquitto.conf:

acl_file /etc/mosquitto/acl
Interactive Calculator: ACL Permission Matrix

This calculator helps you design ACL policies following the principle of least privilege.

26.7 Knowledge Checks

Concept Matching: MQTT Security Terms

Match each MQTT security concept to its correct definition or role.

26.8 Summary

This chapter covered the three essential layers of MQTT security that every production IoT deployment must implement:

26.8.1 Key Takeaways

MQTT security summary

MQTT Security Summary: Three Layers of Defense
Figure 26.5: MQTT Security Summary: Three Layers of Defense
Security Layer Key Points Implementation
Transport (TLS) Encrypts all data in transit; prevents eavesdropping Port 8883, tls_set() in Python, certificates
Authentication Verifies client identity; prevents impersonation Username/password or client certificates
Authorization (ACLs) Controls topic access; prevents unauthorized data access acl_file in Mosquitto, topic patterns

26.8.2 Critical Rules to Remember

  1. Never use port 1883 in production - always use TLS on port 8883
  2. Never hardcode credentials - use environment variables or secure vaults
  3. Never use overly broad ACLs - grant minimum necessary permissions
  4. Always implement all three layers - one layer alone is insufficient
  5. Always monitor and rotate - track certificate expiry, rotate credentials regularly

26.8.3 Security Checklist Summary

26.9 What’s Next

Chapter Focus Why Read It
MQTT Labs Hands-on broker setup and ESP32 TLS experiments Apply every security configuration from this chapter in a working lab environment
MQTT QoS Levels At-most-once, at-least-once, exactly-once delivery Understand how QoS interacts with persistent sessions and offline message queuing
MQTT Advanced Topics Clustering, bridging, and high availability Extend your secure broker to production-scale multi-broker architectures
Encryption Principles Symmetric and asymmetric cryptography, PKI fundamentals Deepen your understanding of TLS, certificate authorities, and key exchange mechanisms
Authentication and Access Control OAuth 2.0, JWT, and identity management Explore token-based authentication patterns used in cloud MQTT services (AWS IoT, Azure IoT Hub)
IoT Security Threats Attack taxonomy: eavesdropping, MITM, replay, device hijacking Understand the full threat landscape that MQTT security layers are designed to counter