From 6110a7cb637058a9d750870f3cf71130b3e0b89a Mon Sep 17 00:00:00 2001 From: Robert Lubos Date: Thu, 26 Mar 2020 13:36:39 +0100 Subject: [PATCH] net: mqtt: Improve buffer bounds validation in mqtt_read_message_chunk Verify more strictly that data read from the transport fits into RX buffer. Switch to unsigned integers, where possible, to prevent unnecessary signed/unsigned operations. Signed-off-by: Robert Lubos --- subsys/net/lib/mqtt/mqtt_rx.c | 15 +++++++++------ 1 file changed, 9 insertions(+), 6 deletions(-) diff --git a/subsys/net/lib/mqtt/mqtt_rx.c b/subsys/net/lib/mqtt/mqtt_rx.c index b7e7219f905..d124d7ae19e 100644 --- a/subsys/net/lib/mqtt/mqtt_rx.c +++ b/subsys/net/lib/mqtt/mqtt_rx.c @@ -146,20 +146,23 @@ static int mqtt_handle_packet(struct mqtt_client *client, static int mqtt_read_message_chunk(struct mqtt_client *client, struct buf_ctx *buf, u32_t length) { - int remaining; + u32_t remaining; int len; + /* In case all data requested has already been buffered, return. */ + if (length <= (buf->end - buf->cur)) { + return 0; + } + /* Calculate how much data we need to read from the transport, * given the already buffered data. */ remaining = length - (buf->end - buf->cur); - if (remaining <= 0) { - return 0; - } /* Check if read does not exceed the buffer. */ - if (buf->end + remaining > client->rx_buf + client->rx_buf_size) { - MQTT_ERR("[CID %p]: Buffer too small to receive the message", + if ((buf->end + remaining > client->rx_buf + client->rx_buf_size) || + (buf->end + remaining < client->rx_buf)) { + MQTT_ERR("[CID %p]: Read would exceed RX buffer bounds.", client); return -ENOMEM; }