TExcelTAD
Home › Wireless, IoT & Mobile Security › MQTT and CoAP Security

MQTT and CoAP Security

IoT devices rarely speak HTTP to their cloud. They use protocols designed for small devices and unreliable links: MQTT, a publish/subscribe protocol over TCP, and CoAP, a compact REST-style protocol over UDP. Both were designed with security as an add-on layer, and both are routinely found exposed on the Internet without it: brokers that accept anonymous clients, devices that send passwords in clear text, topic permissions that let one customer's device read every other customer's data. This lesson parses MQTT on the wire, builds a topic-permission check and reviews a broker configuration, then covers CoAP's equivalents.

MQTT in one paragraph

Clients connect to a broker (mqtt.lab.test) and publish messages to topics such as labhome/hub-01/state/power, or subscribe to topic filters, where + matches one level and # everything below. The broker delivers each message to every matching subscriber. Port 1883 is plain TCP, 8883 MQTT over TLS. Versions 3.1.1 (OASIS, 2014) and 5.0 (2019) are both common; 5.0 adds enhanced authentication and reason codes. The security of an MQTT system therefore rests on three things: transport (TLS), authentication (who is this client?) and authorisation (which topics may it use?).

What a plain-TCP CONNECT exposes

The hub connects with a username and password. The program builds the CONNECT packet exactly as the MQTT 3.1.1 specification defines it (fixed header 0x10, the protocol name, level 4, connect flags, keep-alive, then length-prefixed client ID, username and password) and parses it the way a sniffer or a broker does:

python · try it yourself
import struct

def s(b): return struct.pack(">H", len(b)) + b             # MQTT length-prefixed string
def connect(client_id, user, password, keepalive=60):     # MQTT 3.1.1 CONNECT, as the hub sends it
    flags = 0x80 | 0x40 | 0x02                             # username, password, clean session
    var = s(b"MQTT") + bytes([4, flags]) + struct.pack(">H", keepalive)
    body = var + s(client_id) + s(user) + s(password)
    assert len(body) < 128                                 # one-byte remaining length is enough here
    return bytes([0x10, len(body)]) + body

def parse_connect(pkt):
    assert pkt[0] >> 4 == 1, "not CONNECT"
    pos = 2
    def take():
        nonlocal pos
        n, = struct.unpack_from(">H", pkt, pos); v = pkt[pos + 2:pos + 2 + n]; pos += 2 + n; return v
    proto = take(); level, flags = pkt[pos], pkt[pos + 1]; keep, = struct.unpack_from(">H", pkt, pos + 2); pos += 4
    out = {"protocol": proto.decode(), "level": level, "keepalive": keep, "client_id": take().decode()}
    if flags & 0x80: out["username"] = take().decode()
    if flags & 0x40: out["password"] = take().decode()
    return out

pkt = connect(b"hub-01", b"hub", b"lab-only-Mqtt-2026")
print("CONNECT on TCP 1883:", pkt[:16].hex(" "), "...")
print("anyone on the path reads:", parse_connect(pkt))
CONNECT on TCP 1883: 10 2b 00 04 4d 51 54 54 04 c2 00 3c 00 06 68 75 ...
anyone on the path reads: {'protocol': 'MQTT', 'level': 4, 'keepalive': 60, 'client_id': 'hub-01', 'username': 'hub', 'password': 'lab-only-Mqtt-2026'}

On port 1883 that password crosses every network between the hub and the broker in clear text, the same weakness as HTTP logins and Telnet (cleartext protocols, HTTP in clear text). It is also the password the firmware lesson found in cloud.conf, shared by every hub.

Authorisation: topic ACLs

With one shared account, every device can read and write every topic. Per-device identities plus an ACL that confines each device to its own subtree contain a compromised device to itself. Note that checking a subscription means comparing two filters: a device granted labhome/hub-01/cmd/+ must not be allowed to subscribe to # or labhome/+/cmd/+.

python · try it yourself
def matches(filt, topic):                  # MQTT topic filters: + one level, # the rest
    f, t = filt.split("/"), topic.split("/")
    for i, part in enumerate(f):
        if part == "#": return True
        if i >= len(t) or (part != "+" and part != t[i]): return False
    return len(f) == len(t)

def covers(granted, requested):            # does a granted filter allow subscribing to the requested filter?
    g, r = granted.split("/"), requested.split("/")
    for i, part in enumerate(g):
        if part == "#": return True
        if i >= len(r) or r[i] == "#" or (part != "+" and (r[i] == "+" or part != r[i])): return False
    return len(g) == len(r)

ACL = {  # per-client rules on the broker mqtt.lab.test (synthetic)
    "hub-01": {"pub": ["labhome/hub-01/state/#"], "sub": ["labhome/hub-01/cmd/+"]},
    "hub-02": {"pub": ["labhome/hub-02/state/#"], "sub": ["labhome/hub-02/cmd/+"]},
    "app-svc": {"pub": ["labhome/+/cmd/+"], "sub": ["labhome/+/state/#"]},
}
requests = [("hub-01", "pub", "labhome/hub-01/state/power"), ("hub-01", "sub", "labhome/hub-01/cmd/relay"),
            ("hub-01", "sub", "labhome/hub-02/cmd/relay"), ("hub-01", "sub", "#"),
            ("hub-01", "pub", "labhome/hub-02/cmd/relay"), ("app-svc", "pub", "labhome/hub-02/cmd/relay")]
for client, op, topic in requests:
    rules = ACL[client][op]
    ok = any((covers if op == "sub" else matches)(r, topic) for r in rules)
    print(f"{client:7} {op} {topic:28} -> {'allowed' if ok else 'DENIED'}")
hub-01  pub labhome/hub-01/state/power   -> allowed
hub-01  sub labhome/hub-01/cmd/relay     -> allowed
hub-01  sub labhome/hub-02/cmd/relay     -> DENIED
hub-01  sub #                            -> DENIED
hub-01  pub labhome/hub-02/cmd/relay     -> DENIED
app-svc pub labhome/hub-02/cmd/relay     -> allowed

The hub may talk only about itself; the cloud service app-svc may command any hub, which is why its credentials deserve the most protection. Real brokers express the same idea with patterns such as %c (client ID) or %u (username) in ACL files, or with plugins that ask an authorisation service.

Reviewing a broker configuration

The lab broker runs Mosquitto. The checker reads its configuration listener by listener (simplified: in Mosquitto, settings apply per listener only with per_listener_settings true, otherwise globally):

python · try it yourself
CONF = """# mosquitto.conf of mqtt.lab.test (synthetic)
listener 1883 0.0.0.0
allow_anonymous true
listener 8883
certfile /etc/mosquitto/certs/mqtt.lab.test.crt
keyfile /etc/mosquitto/certs/mqtt.lab.test.key
require_certificate false
password_file /etc/mosquitto/passwd
"""
listeners, cur = [], None
for line in CONF.splitlines():
    if not line.strip() or line.startswith("#"): continue
    key, *val = line.split()
    if key == "listener":
        cur = {"port": int(val[0]), "bind": val[1] if len(val) > 1 else "all"}; listeners.append(cur)
    else:
        cur[key] = " ".join(val)
global_acl = "acl_file" in CONF
for l in listeners:
    f = []
    if "certfile" not in l: f.append("no TLS: credentials and data in clear text")
    if l.get("allow_anonymous") == "true": f.append("anonymous clients allowed")
    if l["bind"] in ("0.0.0.0", "all") and "certfile" not in l: f.append("plain listener on all interfaces")
    if "certfile" in l and l.get("require_certificate") != "true": f.append("no client certificates: passwords only")
    if not global_acl: f.append("no acl_file: every client may use every topic")
    print(f"listener {l['port']}: " + ("; ".join(f) if f else "ok"))
listener 1883: no TLS: credentials and data in clear text; anonymous clients allowed; plain listener on all interfaces; no acl_file: every client may use every topic
listener 8883: no client certificates: passwords only; no acl_file: every client may use every topic

Listener 1883 is the classic exposed broker: no TLS, anonymous access, bound to every interface, no ACL. Internet scans regularly find tens of thousands of such brokers, many leaking sensor data, location tracks and commands. Listener 8883 has TLS but relies on passwords; client certificates (mutual TLS) give every device an identity that can't be phished or shared and can be revoked individually.

CoAP

CoAP (RFC 7252) is REST for constrained devices: GET, PUT, POST, DELETE on URIs such as coap://hub-01.lab.test/sensors/temp, carried in a 4-byte binary header over UDP 5683. Security options:

Layer Mechanism Notes
transport DTLS on UDP 5684 (CoAPS), with pre-shared keys, raw public keys or certificates protects each hop
object OSCORE (RFC 8613) protects the CoAP message end to end, even through proxies
authorisation ACE framework (OAuth-style tokens for constrained devices) per-resource permissions

CoAP over plain UDP has a second problem besides confidentiality: amplification. A small spoofed request (GET /.well-known/core, the resource-discovery listing) can produce a large response sent to the spoofed victim, so open CoAP endpoints on the Internet are abused for reflection DDoS, like open DNS resolvers (UDP amplification).

How MQTT and CoAP weaknesses are detected

  • Configuration review of brokers: plain listeners, anonymous access, missing ACLs, wildcard grants, shared accounts, TLS versions.
  • External exposure checks of your own address ranges: ports 1883, 8883, 5683, 5684 open to the Internet (exposed services); a lab connection to your own broker without credentials must fail.
  • Broker logs: connections from unexpected networks, clients subscribing to #, failed authentications, client IDs used from two places at once (cloned credentials).
  • Traffic analysis on your network: MQTT CONNECT packets on 1883 carry visible credentials; IDS rules can alert on them.

How they are fixed

  • TLS everywhere (8883, CoAPS/OSCORE), certificate validation on the device (pinning for the broker's CA), no plain listener outside a lab.
  • Per-device identities, preferably client certificates provisioned at manufacturing; no shared accounts in firmware.
  • Least-privilege ACLs per client, using the client identity in the rule; review wildcard grants.
  • No anonymous access; brokers not exposed to the Internet unless that is their purpose, and then behind rate limits.
  • CoAP: no open endpoints on the Internet, DTLS or OSCORE, response-size limits.

Pitfalls

  • TLS on the broker but devices that don't validate its certificate.
  • One account for the whole fleet "because provisioning is hard": one extraction gives access to everything.
  • Granting # to a monitoring tool and then putting its credentials in a dashboard config.

Practice

1. In the ACL program, add the request ("hub-01", "sub", "labhome/+/cmd/relay"). What should the result be, and does the code give it?

DENIED: the filter would match other hubs' command topics. The covers function compares level by level and refuses a + in the request where the grant has a fixed hub-01, so it reports DENIED.

2. Fix the broker configuration so that the checker reports only "ok". What do you add or remove?

Remove the 1883 listener (or bind it to 127.0.0.1 for local tools only), remove allow_anonymous true, set require_certificate true on 8883 (with a cafile for client certificates) and add an acl_file with per-client rules.

3. Why is OSCORE useful when CoAP messages pass through a proxy?

DTLS protects only each hop, so the proxy sees the plaintext. OSCORE protects the message itself end to end, so a proxy can forward it without reading or changing it.

Test yourself

What does a plain-TCP MQTT CONNECT on port 1883 expose?

  1. Nothing; MQTT is encrypted
  2. The client ID, username and password in clear text
  3. Only the topic
  4. The broker's private key

A device is granted labhome/hub-01/cmd/+. Which subscription must the broker refuse?

  1. labhome/hub-01/cmd/relay
  2. labhome/hub-01/cmd/led
  3. #
  4. None

Which mechanism gives every MQTT device its own revocable identity?

  1. A shared password
  2. Client certificates (mutual TLS)
  3. Anonymous access
  4. Topic names

Why are open CoAP endpoints abused in DDoS attacks?

  1. They use TCP
  2. Small spoofed UDP requests produce large responses sent to the victim (amplification)
  3. They run Telnet
  4. They have no URIs