A DISCONNECT carrying a reserved Reason Code is treated as a normal disconnection, so the Will Message is discarded
Summary
Hello, our team @AIS2Lab found that a DISCONNECT carrying a Reason Code that is not in the
specification's table is treated as a normal disconnection, so the Will Message is silently
discarded.
A client connects with a Will Message, then sends a DISCONNECT whose Reason Code is 0xFF, which
is not in the table of section 3.14.2.1. Mosquitto closes the connection without answering, and the
Will Message is never published. The broker therefore treated a malformed packet as a normal
disconnection.
Specification
Two independent clauses are involved, and the Will must survive under either reading.
Section 3.14.2.1 lists the Reason Codes a DISCONNECT may carry. 0xFF is not one of them, so by
section 4.13 the packet is a Malformed Packet and:
the receiving endpoint ... MUST close the Network Connection ... sending a DISCONNECT packet with Reason Code 0x81 (Malformed Packet)
Section 3.1.2.5 permits the Will to be discarded in exactly one case:
unless the Will Message has been deleted by the Server on receipt of a DISCONNECT packet with Reason Code 0x00 (Normal disconnection)
0xFF is not 0x00. So either the packet is malformed, in which case it is not a normal
disconnection and the Will must be published, or it is somehow accepted as a valid DISCONNECT with a
non-zero Reason Code, in which case section 3.1.2.5 still requires the Will to be published.
Steps to reproduce
CONNECTwith a Will Message on some topic, Will Delay Interval 0, Session Expiry Interval 0.- Send
DISCONNECTwith Reason Code0xFF: the four bytese0 02 ff 00. - Close the TCP connection.
- Watch the Will topic with a second client.
Expected
The Will Message is published. Additionally, section 4.13 expects the server to answer with
DISCONNECT 0x81 before closing.
Actual
Nothing is published on the Will topic, and the server sends no DISCONNECT at all.
Wire trace, Mosquitto 2.1.2:
control arm, same Will shape, abrupt TCP close and NO DISCONNECT:
<-- watcher: PUBLISH 'xcv/.../will' qos=1 payload=b'control-will'
322a00197863762f623265393161333930646263343336342f77696c6c000100636f6e74726f6c2d77696c6c
the Will IS published for an ordinary abnormal close
test arm, same Will shape:
--> DISCONNECT rc=0xff e002ff00
<-- (nothing: no DISCONNECT 0x81, the server just closes)
... 10 seconds of silence on the Will topic ...Control
The control is in the same run and is what makes the silence evidence rather than a blind spot: an identical Will, on the same watcher and the same topic, cut abruptly with no DISCONNECT at all, is published within 0.0 s. Only the malformed DISCONNECT suppresses it.
Environment
- Mosquitto 2.1.2, image
eclipse-mosquitto:2.1.2-alpine, digestsha256:6dba0f1b2795ddcbe0d41bdfb8b8d56a423acca23ccde4342a4652be54639b11 - Configuration:
listener 1883,allow_anonymous true,persistence false - MQTT v5.0 over plain TCP
- Reproduced 3 out of 3 runs, each with a fresh random Client Identifier and topic namespace
Reproducer
Standard library only, no dependencies. Exit code 1 means the behaviour was reproduced; the script prints every frame it sends and receives, so its output can be pasted back here as-is.
python3 h54_disc_validation.py <host> <port>#!/usr/bin/env python3
"""Self-contained MQTT v5 reproducer. Standard library only, no dependencies.
Usage: python3 <script>.py [host] [port]
"""
import socket, struct, sys, time, uuid
CONNECT, CONNACK, PUBLISH, PUBACK, PUBREC, PUBREL, PUBCOMP = 1, 2, 3, 4, 5, 6, 7
SUBSCRIBE, SUBACK, UNSUBSCRIBE, UNSUBACK, PINGREQ, PINGRESP, DISCONNECT = 8, 9, 10, 11, 12, 13, 14
NAMES = {1:"CONNECT",2:"CONNACK",3:"PUBLISH",4:"PUBACK",5:"PUBREC",6:"PUBREL",7:"PUBCOMP",
8:"SUBSCRIBE",9:"SUBACK",10:"UNSUBSCRIBE",11:"UNSUBACK",12:"PINGREQ",13:"PINGRESP",14:"DISCONNECT"}
P_MSG_EXPIRY, P_SESSION_EXPIRY, P_WILL_DELAY, P_RECV_MAX, P_MAX_PKT = 0x02, 0x11, 0x18, 0x21, 0x27
P_SUB_ID, P_TOPIC_ALIAS_MAX, P_TOPIC_ALIAS, P_USER = 0x0B, 0x22, 0x23, 0x26
_U8 = {0x01,0x17,0x19,0x24,0x25,0x28,0x29,0x2A}
_U16 = {0x13,0x21,0x22,0x23}
_U32 = {0x02,0x11,0x18,0x27}
_STR = {0x03,0x08,0x12,0x15,0x1A,0x1C,0x1F}
_BIN = {0x09,0x16}
_VAR = {0x0B}
def vbi(n):
out = bytearray()
while True:
b = n % 128; n //= 128
if n: b |= 0x80
out.append(b)
if not n: return bytes(out)
def rvbi(buf, i):
mult, val = 1, 0
for _ in range(4):
b = buf[i]; i += 1
val += (b & 0x7F) * mult
if not b & 0x80: return val, i
mult *= 128
raise ValueError("bad varint")
def s(t):
r = t.encode(); return len(r).to_bytes(2, "big") + r
def rs(buf, i):
n = int.from_bytes(buf[i:i+2], "big"); i += 2
return buf[i:i+n].decode("utf-8", "replace"), i + n
def props(items):
b = bytearray()
for k, v in items:
b.append(k)
if k in _U8: b.append(int(v) & 0xFF)
elif k in _U16: b += int(v).to_bytes(2, "big")
elif k in _U32: b += int(v).to_bytes(4, "big")
elif k in _STR: b += s(str(v))
elif k in _BIN: b += len(v).to_bytes(2, "big") + v
elif k in _VAR: b += vbi(int(v))
elif k == P_USER: b += s(v[0]) + s(v[1])
else: raise ValueError("prop 0x%02x" % k)
return vbi(len(b)) + bytes(b)
def rprops(buf, i):
n, i = rvbi(buf, i); end = i + n; out = {}; users = []
while i < end:
k = buf[i]; i += 1
if k in _U8: v = buf[i]; i += 1
elif k in _U16: v = int.from_bytes(buf[i:i+2], "big"); i += 2
elif k in _U32: v = int.from_bytes(buf[i:i+4], "big"); i += 4
elif k in _STR: v, i = rs(buf, i)
elif k in _BIN:
m = int.from_bytes(buf[i:i+2], "big"); i += 2; v = buf[i:i+m]; i += m
elif k in _VAR: v, i = rvbi(buf, i)
elif k == P_USER:
a, i = rs(buf, i); b2, i = rs(buf, i); v = (a, b2); users.append(v)
else: raise ValueError("unknown prop 0x%02x" % k)
out[k] = v
out["users"] = users
return out, i
class C:
"""One MQTT v5 connection. Every frame is printed so the log IS the evidence."""
def __init__(self, host, port, tag, verbose=True):
self.sk = socket.create_connection((host, port), timeout=15)
self.sk.setsockopt(socket.IPPROTO_TCP, socket.TCP_NODELAY, 1)
self.buf = bytearray(); self.tag = tag; self.v = verbose; self.closed = False
self.log("tcp connect %s:%d" % (host, port))
def log(self, m):
if self.v: print(" [%s] %s" % (self.tag, m))
def send(self, raw, what):
self.log("--> %-46s %s" % (what, raw[:40].hex()))
self.sk.sendall(raw)
def _fill(self, n, deadline):
while len(self.buf) < n:
left = deadline - time.monotonic()
if left <= 0: raise TimeoutError
self.sk.settimeout(max(0.01, left))
try: c = self.sk.recv(65536)
except socket.timeout: raise TimeoutError
except ConnectionResetError: self.closed = True; raise EOFError
if not c: self.closed = True; raise EOFError
self.buf += c
def read(self, timeout):
d = time.monotonic() + timeout
self._fill(1, d); first = self.buf[0]
n, mult, i = 0, 1, 1
while True:
self._fill(i + 1, d); b = self.buf[i]; n += (b & 0x7F) * mult; i += 1
if not b & 0x80: break
mult *= 128
self._fill(i + n, d)
raw = bytes(self.buf[:i+n]); del self.buf[:i+n]
p = parse(first, raw[i:]); p["raw"] = raw
self.log("<-- %-46s %s" % (p["desc"], raw[:40].hex()))
return p
def drain(self, seconds):
d = time.monotonic() + seconds; out = []
while True:
left = d - time.monotonic()
if left <= 0: return out
try: out.append(self.read(left))
except (TimeoutError, EOFError, ValueError): return out
def connect(self, cid, clean=True, se=None, will=None, keepalive=60, extra=None, timeout=20):
pr = []
if se is not None: pr.append((P_SESSION_EXPIRY, se))
pr += (extra or [])
flags = 0x02 if clean else 0x00
payload = s(cid)
if will:
flags |= 0x04 | ((will.get("qos", 1) & 3) << 3)
if will.get("retain"): flags |= 0x20
payload += props(will.get("props", [])) + s(will["topic"])
payload += len(will["payload"]).to_bytes(2, "big") + will["payload"]
vh = s("MQTT") + bytes([5, flags]) + keepalive.to_bytes(2, "big") + props(pr)
body = vh + payload
self.send(bytes([CONNECT << 4]) + vbi(len(body)) + body,
"CONNECT id=%s clean=%d" % (cid, clean))
p = self.read(timeout)
assert p["t"] == CONNACK, "expected CONNACK, got %s" % p["desc"]
return p
def subscribe(self, filt, opts=1, pid=1, subid=None, timeout=20):
pr = [(P_SUB_ID, subid)] if subid else []
body = pid.to_bytes(2, "big") + props(pr) + s(filt) + bytes([opts])
self.send(bytes([(SUBSCRIBE << 4) | 2]) + vbi(len(body)) + body, "SUBSCRIBE %s" % filt)
d = time.monotonic() + timeout
while True:
p = self.read(d - time.monotonic())
if p["t"] == SUBACK: return p
def publish(self, topic, payload, qos=0, pid=None, retain=False, dup=False, pr=None):
f = (qos & 3) << 1
if retain: f |= 1
if dup: f |= 8
body = s(topic) + (pid.to_bytes(2, "big") if qos else b"") + props(pr or []) + payload
self.send(bytes([(PUBLISH << 4) | f]) + vbi(len(body)) + body,
"PUBLISH %s qos=%d retain=%d dup=%d" % (topic, qos, retain, dup))
def ack(self, t, pid, reason=0):
f = 2 if t == PUBREL else 0
body = pid.to_bytes(2, "big") + (bytes([reason]) + props([]) if reason else b"")
self.send(bytes([(t << 4) | f]) + vbi(len(body)) + body,
"%s pid=%d rc=0x%02x" % (NAMES[t], pid, reason))
def pub_qos1(self, topic, payload, pid=1, timeout=20, **kw):
self.publish(topic, payload, qos=1, pid=pid, **kw)
d = time.monotonic() + timeout
while True:
try: p = self.read(d - time.monotonic())
except (TimeoutError, EOFError): return None
if p["t"] == PUBACK and p["pid"] == pid: return p
def pub_qos2(self, topic, payload, pid=1, timeout=20, **kw):
self.publish(topic, payload, qos=2, pid=pid, **kw)
d = time.monotonic() + timeout
rec = None
while rec is None:
try: p = self.read(d - time.monotonic())
except (TimeoutError, EOFError): return None
if p["t"] == PUBREC and p["pid"] == pid: rec = p
self.ack(PUBREL, pid)
while True:
try: p = self.read(d - time.monotonic())
except (TimeoutError, EOFError): return rec
if p["t"] == PUBCOMP and p["pid"] == pid: return p
def disconnect(self, reason=0):
body = bytes([reason]) + props([])
try: self.send(bytes([DISCONNECT << 4]) + vbi(len(body)) + body, "DISCONNECT rc=0x%02x" % reason)
except OSError: pass
self.close()
def kill(self):
"""Abnormal close: TCP RST, which section 3.1.2.5 treats as not a normal disconnection."""
try: self.sk.setsockopt(socket.SOL_SOCKET, socket.SO_LINGER, struct.pack("ii", 1, 0))
except OSError: pass
self.log("--- abrupt close (TCP RST)")
self.close()
def close(self):
self.closed = True
try: self.sk.close()
except OSError: pass
def parse(first, body):
t = first >> 4; f = first & 0x0F
o = {"t": t, "flags": f, "pid": None, "rc": None, "props": {}, "desc": NAMES.get(t, str(t))}
if t == CONNACK:
o["sp"] = bool(body[0] & 1); o["rc"] = body[1]
o["props"], _ = rprops(body, 2)
o["desc"] = "CONNACK session_present=%d rc=0x%02x" % (o["sp"], o["rc"])
elif t == PUBLISH:
o["dup"] = bool(f & 8); o["qos"] = (f & 6) >> 1; o["retain"] = bool(f & 1)
o["topic"], i = rs(body, 0)
if o["qos"]: o["pid"] = int.from_bytes(body[i:i+2], "big"); i += 2
o["props"], i = rprops(body, i); o["payload"] = body[i:]
o["desc"] = "PUBLISH %r qos=%d dup=%d retain=%d pid=%s payload=%r" % (
o["topic"], o["qos"], o["dup"], o["retain"], o["pid"], o["payload"][:24])
elif t in (PUBACK, PUBREC, PUBREL, PUBCOMP):
o["pid"] = int.from_bytes(body[0:2], "big"); o["rc"] = body[2] if len(body) > 2 else 0
o["desc"] = "%s pid=%d rc=0x%02x" % (NAMES[t], o["pid"], o["rc"])
elif t in (SUBACK, UNSUBACK):
o["pid"] = int.from_bytes(body[0:2], "big")
o["props"], i = rprops(body, 2); o["codes"] = list(body[i:])
o["desc"] = "%s pid=%d codes=%s" % (NAMES[t], o["pid"], [hex(c) for c in o["codes"]])
elif t == DISCONNECT:
o["rc"] = body[0] if body else 0
o["desc"] = "DISCONNECT rc=0x%02x" % o["rc"]
return o
def endpoint(default_port):
host = sys.argv[1] if len(sys.argv) > 1 else "127.0.0.1"
port = int(sys.argv[2]) if len(sys.argv) > 2 else default_port
return host, port
def nid(p): return "%s-%s" % (p, uuid.uuid4().hex[:10])
def ns(): return "repro/%s" % uuid.uuid4().hex[:12]
def verdict(name, failed, detail):
print("\n" + "=" * 72)
print("%s: %s" % (name, "REPRODUCED (spec violation observed)" if failed else "not reproduced"))
print(detail)
print("=" * 72)
return 1 if failed else 0
def will_watcher(host, port, topic):
w = C(host, port, "watcher")
w.connect(nid("w"), clean=True)
sub = w.subscribe(topic, opts=1)
assert all(c < 0x80 for c in sub["codes"]), "watcher could not subscribe: %s" % sub["desc"]
return w
def saw(w, payload, seconds):
"""Wait for one Will payload and report how long it actually took to arrive."""
t0 = time.monotonic(); deadline = t0 + seconds
while True:
left = deadline - time.monotonic()
if left <= 0: return False, time.monotonic() - t0
try: m = w.read(left)
except (TimeoutError, EOFError, ValueError): return False, time.monotonic() - t0
if m["t"] == PUBLISH and m["payload"] == payload:
if m["qos"]: w.ack(PUBACK, m["pid"])
return True, time.monotonic() - t0
# ---------------------------------------------------------------------------
# H-54: a malformed DISCONNECT is treated as a normal disconnection,
# so the Will Message is discarded
# ---------------------------------------------------------------------------
# Section 3.14.2.1 lists the Reason Codes a DISCONNECT may carry. 0xFF is not
# among them, so by section 4.13 the packet is Malformed and the Server MUST
# close the Network Connection with Reason Code 0x81 (Malformed Packet).
# Section 3.1.2.5 permits the Will to be discarded ONLY on "a DISCONNECT packet
# with Reason Code 0x00 (Normal disconnection)". 0xFF is not 0x00, so whichever
# way the Server reads the packet, the Will must still be published.
#
# ARM connect with a Will, send DISCONNECT with Reason Code 0xFF, then cut
# the TCP connection. The Will MUST be published.
# CONTROL an identical Will cut abruptly with NO DISCONNECT at all. Its Will
# must be published, which proves the watcher sees Wills here and that
# silence in the arm is evidence rather than a blind spot.
def main():
host, port = endpoint(1883)
wt = ns() + "/will"
print("target %s:%d will topic %s\n" % (host, port, wt))
w = will_watcher(host, port, wt)
print("-- CONTROL: same Will, abrupt close, no DISCONNECT (Will must be published)")
c = C(host, port, "control")
c.connect(nid("ctl"), clean=True, se=0,
will={"topic": wt, "payload": b"control-will", "qos": 1,
"props": [(P_WILL_DELAY, 0)]})
c.kill()
ok, dt = saw(w, b"control-will", 10)
if not ok:
w.disconnect(0)
return verdict("H-54", False,
"Control failed: this broker published no Will even for a plain abrupt "
"close, so the arm below cannot be interpreted.")
print(" control OK: Will published after %.1fs\n" % dt)
print("-- ARM: same Will, then DISCONNECT with the reserved Reason Code 0xFF")
a = C(host, port, "arm")
a.connect(nid("arm"), clean=True, se=0,
will={"topic": wt, "payload": b"malformed-will", "qos": 1,
"props": [(P_WILL_DELAY, 0)]})
body = bytes([0xFF]) + props([])
a.send(bytes([DISCONNECT << 4]) + vbi(len(body)) + body,
"DISCONNECT rc=0xff <-- not in the section 3.14.2.1 table")
reaction = a.drain(4)
server_rc = next((p["rc"] for p in reaction if p["t"] == DISCONNECT), None)
a.kill()
seen, dt2 = saw(w, b"malformed-will", 10)
w.disconnect(0)
return verdict("H-54", not seen,
"After DISCONNECT 0xFF the Will was %s.\n"
"The server answered %s; section 4.13 requires DISCONNECT 0x81 for a Malformed Packet.\n"
"The control Will (abrupt close, no DISCONNECT) WAS published %.1fs after the cut." % (
("published after %.1fs -- correct" % dt2) if seen
else "NOT published, so the malformed packet was treated as a normal disconnection",
("DISCONNECT 0x%02x" % server_rc) if server_rc is not None else "nothing",
dt))
if __name__ == "__main__":
sys.exit(main())Source: eclipse-mosquitto/mosquitto