From 3b839c9fb33a26738ced12b080040d306e3df7c7 Mon Sep 17 00:00:00 2001 From: TaikiAkita <8894805+TaikiAkita@users.noreply.github.com> Date: Sun, 19 Jun 2022 14:07:59 +0800 Subject: [PATCH 1/2] Compute PDU length from MBAP Length field directly. For Modbus TCP, the PDU length can be computed directly from the Length field of the header (MBAP). --- src/modbus.c | 11 +++++++++++ 1 file changed, 11 insertions(+) diff --git a/src/modbus.c b/src/modbus.c index 4c7a33a76..8bc74d7d3 100644 --- a/src/modbus.c +++ b/src/modbus.c @@ -436,6 +436,17 @@ int _modbus_receive_msg(modbus_t *ctx, uint8_t *msg, msg_type_t msg_type) if (length_to_read == 0) { switch (step) { case _STEP_FUNCTION: + /* HACK: derive the length from the Length field of the MBAP. */ + if (ctx->backend->backend_type == _MODBUS_BACKEND_TYPE_TCP) { + int mbap_length_field = ( + (((int)(msg[4])) << 8) | + ((int)(msg[5])) + ); + length_to_read = mbap_length_field - 2 /* the unit identifier and function code. */; + step = _STEP_DATA; + break; + } + /* Function code position */ length_to_read = compute_meta_length_after_function( msg[ctx->backend->header_length], From cb5aa3892af1ec78445e2dcd8a9b9952b5453d83 Mon Sep 17 00:00:00 2001 From: TaikiAkita <8894805+TaikiAkita@users.noreply.github.com> Date: Wed, 22 Jun 2022 00:27:47 +0800 Subject: [PATCH 2/2] Validate the PDU length computes from MBAP Length field. The PDU length computes from MBAP Length field shall be validated to ensure that PDU is not too short to be read. --- src/modbus.c | 5 +++++ 1 file changed, 5 insertions(+) diff --git a/src/modbus.c b/src/modbus.c index 8bc74d7d3..31e302c89 100644 --- a/src/modbus.c +++ b/src/modbus.c @@ -442,6 +442,11 @@ int _modbus_receive_msg(modbus_t *ctx, uint8_t *msg, msg_type_t msg_type) (((int)(msg[4])) << 8) | ((int)(msg[5])) ); + if (mbap_length_field < 2) { + errno = EMBBADDATA; + _error_print(ctx, "need more data"); + return -1; + } length_to_read = mbap_length_field - 2 /* the unit identifier and function code. */; step = _STEP_DATA; break;