From 96c176e0bc8c32a1fe1afcc92096e900c2f4b865 Mon Sep 17 00:00:00 2001 From: dxbjavid Date: Fri, 22 May 2026 00:52:45 +0530 Subject: [PATCH] SN_Decode_Header: reject extended-length frame whose total_len leaves no room for the message type The extended-length header form ([0x01][len_hi][len_lo]) decodes total_len from the second and third bytes and then reads the message-type byte that follows. The only bound check is `total_len > rx_buf_len`, which is met by total_len == rx_buf_len even though the three header bytes alone have already consumed the entire buffer. The subsequent `*rx_buf++` read of the type byte then crosses one byte past the caller-supplied rx_buf/rx_buf_len bound. Reject the malformed frame before that read. --- src/mqtt_sn_packet.c | 10 ++++++++++ 1 file changed, 10 insertions(+) diff --git a/src/mqtt_sn_packet.c b/src/mqtt_sn_packet.c index 80e5a88e..0aecd9ae 100644 --- a/src/mqtt_sn_packet.c +++ b/src/mqtt_sn_packet.c @@ -101,6 +101,7 @@ int SN_Decode_Header(byte *rx_buf, int rx_buf_len, int rc; SN_MsgType packet_type; word16 total_len; + byte *rx_buf_orig = rx_buf; if (rx_buf == NULL || rx_buf_len < MQTT_PACKET_HEADER_MIN_SIZE) { return MQTT_TRACE_ERROR(MQTT_CODE_ERROR_BAD_ARG); @@ -120,6 +121,15 @@ int SN_Decode_Header(byte *rx_buf, int rx_buf_len, if (total_len > rx_buf_len) { return MQTT_TRACE_ERROR(MQTT_CODE_ERROR_OUT_OF_BUFFER); } + /* Reject a declared total_len that does not cover the bytes already + * consumed plus the upcoming message-type read. Without this, a peer + * crafted SN_PACKET_LEN_IND packet whose 2-byte length field decodes + * to a value equal to rx_buf_len (e.g., rx_buf_len == 3 with + * total_len == 3) slips past the > rx_buf_len check above and the + * *rx_buf++ below reads one byte past the caller-supplied buffer. */ + if (total_len < (word16)(rx_buf - rx_buf_orig) + 1) { + return MQTT_TRACE_ERROR(MQTT_CODE_ERROR_MALFORMED_DATA); + } /* Message Type */ packet_type = (SN_MsgType)*rx_buf++;