# mqtt — Port 1883 IoT Broker Publishes, QoS & Subscriptions (`mqtt`)

> **FrameAssembly v3.2.2** · Protocol 73 of 81 · Canonical URL: https://frameassembly-lang.dev/docs/protocols/mqtt

- **Full Protocol Name:** Message Queuing Telemetry Transport (IoT & IIoT)
- **Keyword:** `mqtt`
- **OSI Layer & Transport:** Layer 7 · TCP 1883
- **Host Endpoint Rule:** Dual-Stack IPv4/IPv6
- **Standards:** OASIS MQTT v3.1.1, OASIS MQTT v5.0
- **Wireshark Display Filter:** `mqtt`
- **Wire Encapsulation:** `Ethernet II -> [802.1Q / QinQ / MPLS] -> IPv4 / IPv6 -> TCP 1883 -> MQTT`

## Overview

Test whether a compromised smart thermostat can subscribe to `"factory/#"` on TCP `1883` — `mqtt` computes the variable-byte Remaining Length encoding automatically.

Message Queuing Telemetry Transport (`mqtt`, OASIS MQTT v3.1.1) connects IoT sensors, smart-grid meters, and Industrial IoT (Sparkplug B / IIoT) gateways to brokers (Mosquitto, EMQX, HiveMQ, AWS IoT) over **TCP port `1883`** (or `8883` over TLS).

FrameAssembly encodes the MQTT Fixed Header (4-bit Control Packet Type + QoS/Retain flags + variable-byte Remaining Length) and Variable Header for `connect`, `connack`, `publish`, `puback`, `subscribe`, `suback`, `pingreq`, `pingresp`, and `disconnect`.

## Minimal Quickstart (`mqtt_quickstart.frasm`)

```frameassembly
host edge_gw { ip 10.60.10.25 }
host broker  { ip 10.60.10.10 }

compile {
    edge_gw -> broker tcp syn srcport 51883 dstport 1883 wait 1ms
    edge_gw <- broker tcp syn ack wait 1ms
    edge_gw -> broker tcp ack wait 1ms
    edge_gw -> broker mqtt connect clientid "gw-rack04" keepalive 60 wait 2ms
    edge_gw <- broker mqtt connack returncode 0 wait 2ms
    edge_gw -> broker mqtt publish topic "dc1/rack04/kw" qos 0 retain payload "4.85"
}
```

### Automatic Wire Calculations

- Defaults to TCP destination port `1883` (`psh ack`) and encodes the multi-byte variable-length `Remaining Length` field per OASIS MQTT §2.2.3.
- Encodes the `"MQTT"` Protocol Level `4` header inside `connect`, and includes the 2-byte Packet Identifier (`pktid`) automatically on `qos 1` / `qos 2` `publish`, `puback`, `subscribe`, and `suback` packets.
- Appends `payload "<text>"` directly as the UTF-8 topic message payload on `publish` frames.

## Practical Lab Example: IIoT Gateway Connect, Wildcard Topic Subscribe, QoS 1 Publish & Keepalive Ping (`mqtt_iiot_telemetry.frasm`)

Connects an industrial gateway to TCP 1883, subscribes to control commands, publishes a `qos 1` retained sensor reading acknowledged via `puback`, and exchanges `pingreq`/`pingresp`.

```frameassembly
host plc_gw      { ip 192.168.80.21 }
host mqtt_broker { ip 192.168.80.10 }

compile {
    plc_gw -> mqtt_broker tcp syn srcport 52883 dstport 1883 win 65535 mss 1460 wait 1ms
    plc_gw <- mqtt_broker tcp syn ack win 65535 mss 1460 wait 1ms
    plc_gw -> mqtt_broker tcp ack wait 1ms
    plc_gw -> mqtt_broker mqtt connect clientid "line2-plc-gw" keepalive 30 wait 2ms
    plc_gw <- mqtt_broker mqtt connack returncode 0 wait 2ms
    // 1. Subscribe to actuator commands (pktid 1)
    plc_gw -> mqtt_broker mqtt subscribe pktid 1 topic "plant1/line2/cmd" qos 1 wait 2ms
    plc_gw <- mqtt_broker mqtt suback pktid 1 wait 3ms
    // 2. Publish QoS 1 retained telemetry (pktid 2 -> puback)
    plc_gw -> mqtt_broker mqtt publish topic "plant1/line2/pressure_bar" qos 1 retain pktid 2 payload "{\"bar\":6.42}" wait 2ms
    plc_gw <- mqtt_broker mqtt puback pktid 2 wait 10ms
    // 3. Keepalive heartbeat + clean disconnect
    plc_gw -> mqtt_broker mqtt pingreq wait 1ms
    plc_gw <- mqtt_broker mqtt pingresp wait 2ms
    plc_gw -> mqtt_broker mqtt disconnect
}
```

```bash
# 1. Eyeball relative timestamps, ports & wire lengths in your terminal
frameassembly show mqtt_iiot_telemetry.frasm

# 2. Compile .frasm -> classic .pcap (tcpdump/tcpreplay/Suricata) or nanosecond .pcapng
frameassembly mqtt_iiot_telemetry.frasm mqtt_iiot_telemetry.pcap
frameassembly mqtt_iiot_telemetry.frasm mqtt_iiot_telemetry.pcapng

# 3. Round-trip .pcap <-> .frasm whenever you want to scrub or tweak an existing capture
frameassembly reverse mqtt_iiot_telemetry.pcap mqtt_iiot_telemetry_edited.frasm

# 4. Verify dissected protocol fields in tshark
tshark -r mqtt_iiot_telemetry.pcap
```

## All `mqtt` Keywords & Header Options

Packet line pattern: `src_host -> dst_host mqtt [connect | connack | publish | puback | subscribe | suback | pingreq | pingresp | disconnect | pkttype "<text>"] [clientid "<text>"] [topic "<text>"] [qos <0..2>] [retain] [pktid <0..65535>] [keepalive <0..65535>] [returncode <0..255>]`

| Keyword / Option | Accepted Value | Default | Effect on Packet |
| --- | --- | --- | --- |
| `connect \| connack \| publish \| puback \| subscribe \| suback \| pingreq \| pingresp \| disconnect` | MQTT Control Packet type (or `pkttype "<text>"`) | `publish` | Sets the upper 4-bit Control Packet Type (`1`..`14`) in byte 0 of the MQTT header. |
| `clientid "<text>" \| keepalive <0..65535>` | Quoted Client ID + keepalive seconds on `connect` | `clientid "frameassembly", keepalive 60` | Populates the `CONNECT` payload Client Identifier and Keep Alive timer. |
| `topic "<text>"` | Quoted slash-delimited MQTT topic (`"sensors/temp"`) | `"sensors/temp"` | Encodes the 2-byte length-prefixed Topic Name in `publish` or Topic Filter in `subscribe`. |
| `qos <0..2> \| retain` | QoS delivery level (`0`, `1`, or `2`) + `retain` flag | `qos 0, retain off` | Sets QoS bits `1..2` and Retain bit `0` in the Fixed Header. |
| `pktid <0..65535>` | 16-bit Packet Identifier | `1 (when qos > 0 or subscribe/puback)` | Matches `publish` <-> `puback` and `subscribe` <-> `suback`. |
| `returncode <0..255>` | CONNACK return code (`0` Accepted, `4` Bad user/pass, `5` Not authorized) | `0 (Connection Accepted)` | Sets byte 3 (`Connect Return Code`) of `connack`. |

## Cross-Layer Options Valid with `mqtt`

| Option | Range / Format | Default | Effect |
| --- | --- | --- | --- |
| `wait <number><ns\|us\|ms\|s\|m>` | Time gap (ns, us, ms, s, m) | `10ms` | Advances the packet timestamp clock after sending this packet and before the next packet (`wait 0ns` sends back-to-back). |
| `payload "<text>" \| hexpayload "<hex>"` | Quoted text or hex bytes (choose one) | `Omitted` | Appends or overrides raw payload bytes (`"deadbeef"` or `"de:ad:be:ef"`) and updates packet lengths and checksums. |
| `srcmac <mac> \| dstmac <mac> \| ethertype <0..65535>` | Colon/hyphen/Cisco MAC · EtherType u16 (e.g. 0x0800) | `Host MAC / RFC multicast MAC / auto EtherType` | Overrides the 14-byte Ethernet II source MAC, destination MAC, or 16-bit EtherType for this single packet. |
| `vlan <0..4095> [pcp <0..7>] [dei <0\|1>]` | VLAN ID 0..4095, PCP 0..7, DEI 0..1 | `Untagged` | Wraps the packet in an IEEE 802.1Q VLAN tag (`0x8100`) with optional 802.1p QoS priority. |
| `qinq <0..4095> [innervlan <0..4095>]` | Outer S-VLAN 0..4095, Inner C-VLAN 0..4095 | `Untagged (innervlan 1 when qinq is set)` | Double-tags the packet with outer IEEE 802.1ad S-Tag (`0x88a8`) plus inner IEEE 802.1Q C-Tag (`0x8100`). |
| `mpls <0..1048575> [label <0..1048575>] [exp\|tc <0..7>] [bos <0\|1>] [mplsttl <0..255>]` | Label 0..1048575, exp/tc 0..7, bos 0..1, ttl 0..255 | `Unlabeled (at most 1 mpls tag per packet)` | Inserts a 32-bit MPLS label header (`0x8847`) ahead of the Layer 3 header. |
| `ttl <0..255> [dscp <0..63>] [ecn <0..3>]` | TTL/Hop Limit 0..255, DSCP 0..63, ECN 0..3 | `ttl 64, dscp 0, ecn 0` | Sets IPv4 TTL or IPv6 Hop Limit plus DiffServ (DSCP) and ECN QoS markings. |
| `ipid <0..65535> [df] [mf] [fragoffset <0..8191>]` | IPv4 ID, DF/MF flags, fragment offset 0..8191 | `ipid 1, flags 0, fragoffset 0` | Sets IPv4 Identification, Do-Not-Fragment (`df`), More-Fragments (`mf`), and fragment offset (ignored over IPv6). |
| `flowlabel <0..1048575>` | 20-bit IPv6 Flow Label (0..1048575) | `0` | Sets the 20-bit IPv6 Flow Label for ECMP routing tests (ignored when running over IPv4 hosts). |
| `srcport <0..65535> \| dstport <0..65535>` | Port number 0..65535 | `srcport 49152 (remembered), TCP 1883` | Overrides source or destination port and remembers the port pair automatically on `<-` replies. |
| `seq <number> \| acknum <number> \| win\|window <0..65535> \| urgent <0..65535> \| syn \| ack \| psh \| fin \| rst \| urg \| ece \| cwr` | TCP sequence/ack numbers, window size, flags & RFC 7323 options | `psh ack, win 65535, automatic TCP seq/acknum` | Overrides automatic TCP sequence tracking, flags, or RFC 7323 options (`mss`, `wscale`, `sackperm`, `tsval`, `tsecr`). |

## Common Mistakes & Quick Fixes

### QoS Maximum Value Is 2 (0, 1, or 2)

- **Avoid:** `edge_gw -> broker mqtt publish topic "a/b" qos 3`
- **Valid v3.2.2 Syntax:** `edge_gw -> broker mqtt publish topic "a/b" qos 1 pktid 10`

MQTT reserves `QoS 3` (`0b11`) as a protocol violation (` Malformed Packet`); valid levels are `0`, `1`, and `2`.
