Skip to content

Frame Modbus TCP messages by their MBAP length - #881

Open
StalderT wants to merge 3 commits into
stephane:masterfrom
StalderT:fix/reply-no-sleep-over-tcp
Open

StalderT wants to merge 3 commits into
stephane:masterfrom
StalderT:fix/reply-no-sleep-over-tcp

Conversation

@StalderT

@StalderT StalderT commented Sep 29, 2026 •

Copy link
Copy Markdown
Contributor

Over TCP, libmodbus delimited a message by its function code and never by the length field of the MBAP header. Three commits:

Frame Modbus TCP requests by their MBAP length (server). An unknown function code left the rest of its ADU in the socket, a request whose MBAP length didn't match its function code was read too short or into the next request, and a write followed by octets its byte count doesn't cover was executed, the extra octets being parsed as the next request (#867). response_exception() slept for the response timeout, 500 ms by default, then flushed the socket to discard such leftovers: any malformed request held the server for that long, which an unauthenticated peer can repeat at will (#874), and the flush also discarded pipelined requests. A request is now read exactly up to its MBAP length, a protocol identifier other than 0 or an invalid length gives EMBBADDATA (documented as a reason to close the connection), modbus_reply() rejects one whose length differs from what its function code requires, longer included, and nothing is left to sleep on or flush over TCP. RTU keeps its sleep and flush.

Don't read the octets a server adds after its TCP response as the next one (client). Octets announced and sent beyond a response were read as the next response, which a faulty or compromised device can use to forge it, possibly for another device behind a shared gateway. A response of known layout is still read by its content, since some gateways announce a longer MBAP length than they send, or a meaningless one; when the MBAP length is valid, the announced octets beyond are discarded as far as they have already arrived, without waiting, and an invalid one is ignored as before. The response of a function code unknown to libmodbus, which was cut after one octet, is read up to its MBAP length.

Skip the late response to a TCP request that timed out (client). A response arriving after its timeout was taken for the response to the next request, and every following exchange stayed shifted by one. After a timeout, the first response with another transaction ID is now skipped, one per timeout, so the wait stays bounded.

Each commit comes with its tests in unit-test-client / unit-test-server.

Fixes #874, fixes #867.

@cla-bot

cla-bot Bot commented Sep 29, 2026

Copy link
Copy Markdown

We require contributors to sign our Contributor License Agreement. In order for us to review and merge your code, please fill https://forms.gle/5635zjphDo5JEJQSA to get added. Your document will be manually checked by the maintainer. Be patient...

@sotomayorlucas

Copy link
Copy Markdown

Thanks for the fix for #874. I tested this PR (fix/reply-no-sleep-over-tcp) against v3.2.0. It does remove the 500 ms delay, but the remaining modbus_flush() on TCP still discards valid requests, and in one case it now desynchronizes the stream.

1. Pipelined requests are still discarded. If a valid request arrives in the same TCP segment as (or right behind) a request that hits a to_flush = TRUE branch, _modbus_tcp_flush removes it from the socket. The client gets no response and no error. Same result with and without this PR:

input (one connection) v3.2.0 PR #881
fc 0x7f + valid fc 3 read, one send() only the exception; valid read flushed only the exception; valid read flushed
fc 3 qty 0 + valid fc 3 read, one send() only the exception; valid read flushed only the exception; valid read flushed
fc 0x7f, valid read 300 ms later valid read flushed (inside the 500 ms window) both answered ✔

Pipelining is allowed by the Modbus Messaging Implementation Guide (section 4.2) and is common behind gateways that share one connection between masters.

2. The comment "the whole request has already been read" does not hold for unknown function codes. For an unknown function, compute_meta_length_after_function returns 0, so _modbus_receive_msg reads only 8 octets and leaves the rest of the ADU (as given by the MBAP length) in the socket. In v3.2.0 the 500 ms sleep happens to let that tail arrive before the flush removes it. With the PR, the flush runs immediately. If the tail is still in flight, the flush misses it, and the tail is then parsed as the start of the next request:

fc 0x7f request 000900000006017f00000002 sent as 8 octets + 4 octets (50 ms apart),
then a valid read 000200000006010300000001:

v3.2.0 :  REQ tid 9 fc 0x7f   -> exception;  valid read flushed
PR #881:  REQ tid 9 fc 0x7f   -> exception;
          REQ tid 0 unit 0 fc 0 (built from the 4-octet tail + the valid read's MBAP)  -> exception 0x80/01
          valid read (tid 2) lost

So the server answers a request the client never sent and drops the one it did send.

Suggestion. On TCP, neither the sleep nor the flush is needed if the receive path always consumes exactly the MBAP length. Concretely, in _modbus_receive_msg on the TCP backend, after the 7-octet header, read LENGTH − 1 more octets regardless of the function code (rejecting or closing on a LENGTH above the maximum ADU size). Then response_exception can skip the flush for TCP entirely. Pipelined requests survive, and no tail is ever left to resynchronize on. A server that wants to drop a connection after a malformed request can still do so explicitly.

Reproducer (Python against any modbus_receive/modbus_reply TCP server, e.g. tests/unit-test-server tcp on port 1502; restart the server between the two runs if it serves a single connection):

import socket, time
def run(chunks):
    s = socket.create_connection(("127.0.0.1", 1502))
    s.setsockopt(socket.IPPROTO_TCP, socket.TCP_NODELAY, 1)
    for hexdata, delay in chunks:
        s.sendall(bytes.fromhex(hexdata)); time.sleep(delay)
    s.settimeout(1.5); got = b""
    try:
        while (c := s.recv(200)): got += c
    except socket.timeout: pass
    print(got.hex()); s.close()

run([("000900000006017f00000002" "000200000006010300000001", 0)])                        # pipelined
run([("000900000006017f", 0.05), ("00000002", 0.05), ("000200000006010300000001", 0)])  # split tail

@cla-bot

cla-bot Bot commented Oct 12, 2026

Copy link
Copy Markdown

We require contributors to sign our Contributor License Agreement. In order for us to review and merge your code, please fill https://forms.gle/5635zjphDo5JEJQSA to get added. Your document will be manually checked by the maintainer. Be patient...

@StalderT

Copy link
Copy Markdown
Contributor Author

@sotomayorlucas Thanks for the careful analysis and the reproducer, both points are right. The root cause is that the TCP receive path frames a request by its function code and never reads the MBAP length: an unknown function code is read as 8 octets whatever the header announces, and the sleep followed by the flush was what cleaned up behind it, pipelined requests included.

5cbf9e0 now frames TCP requests by their MBAP length once the function code is known, and rejects a length below 2 or beyond the maximum ADU size. Nothing is left to discard after that, so response_exception() no longer flushes over TCP. A MBAP length shorter than the function code requires is answered by the existing truncated request check in modbus_reply(). I left the client side (confirmations) framed as before, to keep this PR on #874.

Both of your scenarios are in unit-test-client: an unknown function code followed by a valid read in one segment, and the same cut after the function code, each expecting the two answers in order with their TIDs.

@cla-bot

cla-bot Bot commented Oct 12, 2026

Copy link
Copy Markdown

We require contributors to sign our Contributor License Agreement. In order for us to review and merge your code, please fill https://forms.gle/5635zjphDo5JEJQSA to get added. Your document will be manually checked by the maintainer. Be patient...

1 similar comment
@cla-bot

cla-bot Bot commented Oct 12, 2026

Copy link
Copy Markdown

We require contributors to sign our Contributor License Agreement. In order for us to review and merge your code, please fill https://forms.gle/5635zjphDo5JEJQSA to get added. Your document will be manually checked by the maintainer. Be patient...

@StalderT
StalderT force-pushed the fix/reply-no-sleep-over-tcp branch from 27af7a4 to 1ff1c96 Compare October 12, 2026 10:24
@cla-bot

cla-bot Bot commented Oct 12, 2026

Copy link
Copy Markdown

We require contributors to sign our Contributor License Agreement. In order for us to review and merge your code, please fill https://forms.gle/5635zjphDo5JEJQSA to get added. Your document will be manually checked by the maintainer. Be patient...

@StalderT StalderT changed the title modbus_reply: don't sleep before sending an exception over TCP Frame Modbus TCP messages by their MBAP length Oct 12, 2026
@sotomayorlucas

Copy link
Copy Markdown

Thanks, that was fast. I built the branch at 1ff1c96 (and at 27af7a4 before the force-push, with identical results) and re-ran both scenarios plus two more: the pipelined unknown function code, the split tail, a delayed valid request (300 ms) and fc 3 with quantity 0 followed by a valid read. All four now give both responses in order, with their TIDs.

I also replayed our 243 request streams (defects in the protocol id, LENGTH, function code, quantity, truncation, garbage and trailing octets, each under four segmentations) against v3.2.0 and the branch, and compared the requests the server executes with a receiver that frames strictly by the MBAP LENGTH (and stops at a protocol id other than 0 or a LENGTH outside 2..254). Agreement goes from 67 of 243 on v3.2.0 to 179 of 243 on the branch. The 64 that still differ fall into two groups that look like decisions rather than bugs:

  1. The protocol id is not checked (16 streams). Requests with protocol id 1 or 0xffff are executed.
  2. What follows a malformed header (48 streams). This covers an invalid MBAP length (0, 1, 255, 65535), 1,100 octets of garbage, and the leftover octets of an under-declared LENGTH 2. The server reports Invalid data: invalid MBAP length or answers a truncated request, then keeps reading where it stopped, so the next octets are parsed as a new request. With a debug build, <00><00><00><02><00><02><00><00> becomes REQ tid 0, unit 0, fc 0, answered with exception 80 03, and the valid request behind it is lost. Checking pid == 0 would reject most of these misaligned headers. When the length itself is invalid the boundary is unknowable, so closing the connection, or documenting that the caller must close on EMBBADDATA, may be safer than resuming.

Happy to share the 243 streams as pcaps if useful for the test suite.

@StalderT

Copy link
Copy Markdown
Contributor Author

I regrouped the branch into three commits (server framing, client framing, late responses) and updated the description.

Two changes since my last comment. On the server side, a request longer than its function code requires is now rejected instead of executed, as asked in #867, which this PR now also fixes. On the client side, a response of known layout is read by its content again, because some gateways announce a longer MBAP length than they send and would have been broken by waiting for those octets; the extra octets that do arrive are discarded without waiting, so they can't be read as the next response.

On the server side, _modbus_receive_msg() computed the length of a TCP request from its function code and never looked at the MBAP header. An unknown function code was read as 8 octets and the rest of its ADU stayed in the socket, a request whose MBAP length did not match its function code was read too short or into the next request, and a write followed by octets its byte count doesn't cover was executed, the extra octets being parsed as the next request (stephane#867). The protocol identifier wasn't checked either. response_exception() slept for the response timeout, 500 ms by default, then flushed the socket to discard such leftovers: any malformed request held the server for that long, which an unauthenticated peer can repeat at will (stephane#874), and the flush also discarded any pipelined request behind it.

Over TCP, a request is now read exactly up to its MBAP length, whatever its function code, and a protocol identifier other than 0 or a length below 2 or beyond the maximum ADU size is rejected with EMBBADDATA. Where the next request starts can't be known after such a header, so the modbus_receive() documentation advises closing the connection on that error. modbus_reply() answers a request whose length differs from what its function code requires with an illegal data value exception, a longer one included, so nothing of a malformed request is executed. Nothing is left to discard over TCP, so response_exception() neither sleeps nor flushes there; over RTU it still does, the delay letting the rest of a corrupted frame arrive.

The unknown function code test uses a response timeout shorter than the server's over TCP. An unknown function code followed by a valid read, in one segment and cut after the function code, must get both answers in order. A write with two octets more than its byte count must be rejected and leave the register unchanged. A read with protocol identifier 1 must not be answered, and the test server closes the connection.

Refs stephane#874, stephane#867
@StalderT
StalderT force-pushed the fix/reply-no-sleep-over-tcp branch from 1ff1c96 to ffaddf3 Compare October 12, 2026 11:23
@cla-bot

cla-bot Bot commented Oct 12, 2026

Copy link
Copy Markdown

We require contributors to sign our Contributor License Agreement. In order for us to review and merge your code, please fill https://forms.gle/5635zjphDo5JEJQSA to get added. Your document will be manually checked by the maintainer. Be patient...

@StalderT

Copy link
Copy Markdown
Contributor Author

@sotomayorlucas Thanks for replaying your 243 streams, that's a very useful measure.

Both groups are addressed in cbbbd74, folded into the server commit. A request whose protocol identifier isn't 0 is now rejected with EMBBADDATA, like an MBAP length below 2 or above 254. For what follows a malformed header, I agree the boundary can't be known; rather than have libmodbus close the socket behind the application, the modbus_receive() documentation now says to close the connection on EMBBADDATA over TCP, which is what the test server does. An under-declared LENGTH still gets its truncated request answered, and the octets it leaves behind usually fail the protocol identifier check, as in your <00><00><00><02>… example, which ends the connection there. A new test checks that a read with protocol identifier 1 is not executed.

The pcaps would be welcome. Whether they belong in the test suite is the maintainer's call, but I'd gladly replay them against the branch.

…t one

A client read a TCP response by its function code and ignored the MBAP length. Octets a server announced and sent beyond its response stayed in the socket and were read as the start of the next response, so a faulty or compromised device could forge the response to the next request: the transaction ID is predictable, and behind a gateway shared by several devices, the next request can target another one. The response of a function code unknown to libmodbus, sent with modbus_send_raw_request(), was cut after one octet, and its remaining octets desynchronized the connection.

A response whose layout libmodbus knows is still read by its content, since some gateways announce a longer MBAP length than they send, or even a meaningless one, and refusing them or waiting for octets that never come would break them. When the MBAP length is valid, the octets it announces beyond the response are discarded, as far as they have already been received, without waiting; an invalid one is ignored, as before. The response of another function code is read up to its MBAP length. modbus_proxy() with a TCP backend gets the same.

The test server answers a read at three new special addresses with an MBAP length two octets too long, followed by them or not, or with an MBAP length of 0. The test client expects the response in each case, then a valid response to its next request.
When a response timed out over TCP, it could still arrive later, ahead of the response to the next request. The client took it for that response and failed on its transaction ID, and every following exchange read the response to the previous request: the connection stayed shifted until the application closed it, or flushed it at the right time. A faulty or compromised device can cause this at will by answering just after the response timeout.

After a timeout, the first response whose transaction ID doesn't match the request is now read whole and skipped, and the client goes on waiting for the response it expects. A server answers the requests of a connection in order, so only that first response can be a late one, and only one response is skipped per timeout: a peer can't make the client wait longer than one more response timeout by sending responses with other transaction IDs. Connecting or closing forgets the timeout. modbus_receive_confirmation(), which doesn't know the request, is unchanged.

The test client lets a request time out against the delayed reply of the server, then expects a valid response to its next request.
@StalderT
StalderT force-pushed the fix/reply-no-sleep-over-tcp branch from ffaddf3 to 21cecc7 Compare October 12, 2026 12:56
@cla-bot

cla-bot Bot commented Oct 12, 2026

Copy link
Copy Markdown

We require contributors to sign our Contributor License Agreement. In order for us to review and merge your code, please fill https://forms.gle/5635zjphDo5JEJQSA to get added. Your document will be manually checked by the maintainer. Be patient...

@sotomayorlucas

Copy link
Copy Markdown

Thanks, I replayed the 243 streams against 21cecc7 (cbbbd74 plus the two client commits). Both of my earlier scenarios and the two extra ones still give both responses in order. Against a receiver that frames strictly by MBAP LENGTH (and stops at a protocol id other than 0 or a LENGTH outside 2..254), the branch now agrees on all 243 streams: 235 identically, and the 8 under-declared LENGTH 5 streams differ only in how my harness logs the truncated request that gets answered (the same requests are executed). The result is the same whether the server closes or continues on EMBBADDATA. v3.2.0 agreed on 67.

The pcaps are attached: one per stream, client to server, named <defect>--<position>--<segmentation>.pcap, each ending with a valid read request (the sentinel); there is a README inside. Use them however is useful.

modbus-tcp-243-request-streams.zip

@StalderT

Copy link
Copy Markdown
Contributor Author

@sotomayorlucas Thanks a lot for replaying everything against the final branch and for sharing the streams, that’s a very convincing result.

@stephane This PR is ready for review. It fixes #874 and #867, and it has been checked independently: 243 malformed request streams replayed against a strict MBAP receiver now agree on all of them, against 67 for v3.2.0. Each commit comes with its unit tests, make check passes, and the CLA is signed. Happy to rebase or split it differently if that makes the review easier.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

2 participants