From ee954dcc794e939ca7574322874d0c45b9766499 Mon Sep 17 00:00:00 2001 From: jmestwa-coder Date: Fri, 22 May 2026 11:04:09 +0530 Subject: [PATCH] SN_Decode_PublishResp: reject total_len not matching fixed packet layout The MQTT-SN PUBACK frame is fixed at 7 octets (Length + MsgType + TopicID + MsgID + ReturnCode) and PUBREC/PUBREL/PUBCOMP are fixed at 4 octets (Length + MsgType + MsgID). SN_Decode_PublishResp only checked total_len <= rx_buf_len before reading the message-type byte at offset 1, so a frame whose declared total_len is smaller than the relevant fixed layout passed validation and the subsequent *rx_payload++ for rec_type walked past the caller-supplied bound. A page-guard reproducer (mmap of one RW page followed by an adjacent PROT_NONE page, with rx_buf placed at the last byte of the readable page and rx_buf[0] = 0x00 so total_len=0) crashes with SIGBUS at the rec_type read on master and returns MQTT_CODE_ERROR_MALFORMED_DATA cleanly after the patch. Existing well-formed PUBACK (total_len=7) and PUBREC/PUBREL/PUBCOMP (total_len=4) frames continue to decode unchanged. --- src/mqtt_sn_packet.c | 15 +++++++++++++++ 1 file changed, 15 insertions(+) diff --git a/src/mqtt_sn_packet.c b/src/mqtt_sn_packet.c index 80e5a88e..cdb5c8f0 100644 --- a/src/mqtt_sn_packet.c +++ b/src/mqtt_sn_packet.c @@ -1313,6 +1313,21 @@ int SN_Decode_PublishResp(byte* rx_buf, int rx_buf_len, byte type, return MQTT_TRACE_ERROR(MQTT_CODE_ERROR_OUT_OF_BUFFER); } + /* MQTT-SN: PUBACK is fixed at 7 octets (Length + MsgType + TopicID(2) + + * MsgID(2) + ReturnCode); PUBREC, PUBREL and PUBCOMP are fixed at 4 + * octets (Length + MsgType + MsgID(2)). Any other total_len cannot + * cover the bytes the function still has to read - notably the + * *rx_payload++ message-type read below - so reject the frame before + * that read walks past the caller-supplied bound. */ + if (type == SN_MSG_TYPE_PUBACK) { + if (total_len != 7) { + return MQTT_TRACE_ERROR(MQTT_CODE_ERROR_MALFORMED_DATA); + } + } + else if (total_len != 4) { + return MQTT_TRACE_ERROR(MQTT_CODE_ERROR_MALFORMED_DATA); + } + /* Validate packet type */ rec_type = *rx_payload++; if (rec_type != type) {