Unauthenticated Modbus-TCP Stack Overflow in modbus_slave

Tags

unauthenticated, denial_of_service, stack_buffer_overflow, configuration_dependent, tested

Disclosure information

Field Value
Vendor Milesight
Product UG65 and UG67 LoRaWAN gateways
Tested firmware 60.0.0.50
Component /usr/sbin/modbus_slave (Modbus-TCP/RTU-over-TCP; root; init S99modbus_slave; PIE with symbols/DWARF; Milesight-forked libmodbus.so.5.1.0)
Vulnerability class CWE-787, Out-of-bounds Write (unauthenticated remote stack buffer overflow; stack OOB read as a secondary effect)
Suggested severity High (7.5) - unauthenticated remote crash of a root daemon; code execution assessed as not achievable from this primitive (see "Exploitability analysis")
Validation status Tested; overflow threshold, daemon crash, and respawn recorded
Discovery date 2026-10-26

Summary

modbus_slave implements the gateway's Modbus slave feature: when a Modbus server is configured (Packet Forwarder -> Protocol -> Modbus), it accepts unauthenticated Modbus-TCP connections on the configured port (default 502) and maps device "objects" (configurable register blocks) into Modbus address space. Modbus has no authentication mechanism, so any LAN host with access to the listener can reach the parsing path described below.

Each object definition carries a register_num field (register block size, "Register Quantity" in the web UI). The web UI limits this field to 1..121, enforced only on the client side (www/view/protocol/modbus/object.js, minvalue: 1, maxvalue: 121). The daemon parses it with util_json_get_int() and does not validate the value. It accepts any integer, including values far above the UI maximum.

On every Modbus write request (function codes 5, 6, 15, 16), handle_modbus_write_req() passes a pointer into the 260-byte stack receive buffer of modbus_server_thread() to write_one_register(), which converts the value to a hexadecimal string for the object cache:

/* write_one_register @ file offset 0x6018 (Ghidra decompile, verified
   against disassembly) */
char buf[512];                                            /* sp+0x38  */
...
obj = find_modbud_object_by_addr(server, addr, type, slave, 1);
util_data_to_hex_string(value_ptr,                        /* sp+0x10  */
                        obj->register_num * 2,            /* config   */
                        buf);                             /* 512 B    */
strcmp(buf, obj + 0x2f8);                                 /* obj slot sp+0x238 */

/* util_data_to_hex_string @ 0x13588 */
for (i = 0; i < len; i++)
    sprintf(buf + 2*i, "%02x", src[i]);                   /* unbounded */

register_num == N makes this loop write N*4 + 1 bytes (2 ASCII hex characters per input byte, plus the final sprintf NUL) into the 512-byte stack buffer. register_num >= 128 overflows the buffer and corrupts stack memory above it: the object-pointer slot at sp+0x238, the caller frames of handle_modbus_write_req() and modbus_server_thread(), and the receive buffer itself. The read side is equally unbounded: for FC 5/6 the source pointer addresses only 2 valid frame bytes, so the loop also reads up to ~750 bytes past the received frame up the thread stack.

A single 12-byte unauthenticated Modbus-TCP frame (FC 6, Write Single Register) reliably crashes the root daemon when any writable object with register_num >= 128 exists. The binary has no stack canary.

Triggering frame (the value bytes do not affect the result):

00 01 00 00 00 06   MBAP (txn 1, proto 0, len 6)
01                  unit id
06                  function code 6 (write single register)
00 00               address of the object
11 22               value

Root cause and code paths

Function File offset Role
parse_single_modbus_object 0x6f0c reads register_num from /etc/protocol/modbus/<server>.conf with util_json_get_int() - no range check (stored at object +0x1a4)
modbus_server_thread 0x9200 recv(fd, stack_buf, 0x104, 0); for FC > 4 calls handle_modbus_write_req(server, pdu, slave) where pdu points into that stack buffer
handle_modbus_write_req 0x6498 FC 5/6 -> write_one_register(server, addr, type, pdu+3, slave); FC 15/16 -> write_registers(...)
write_one_register 0x6018 converts register_num*2 source bytes to hexadecimal in char buf[512]; then strcmp/snprintf dereference the object pointer reloaded from the corrupted slot
util_data_to_hex_string 0x13588 Unbounded sprintf loop with no additional NUL-termination handling beyond the final byte
convert_data 0x4170 secondary sink: numeric branches convert register_num*2 bytes to hexadecimal in the 256-byte heap field obj+0x2f8 (overflows the field at register_num > 64; extends beyond the 0x518 chunk at > 136)

Frame layout of write_one_register (from disassembly):

0x6018: sub  sp, sp, #0x240
0x601c: stp  x29, x30, [sp]        ; own saved FP/LR BELOW the buffer
0x6118: add  x1, sp, #0x38         ; 512-byte hex buffer
0x612c: ldr  x0, [sp, #0x238]      ; object pointer slot immediately after
0x6130: add  x1, x0, #0x2f8
0x6138: bl   strcmp                ; <- first victim of the overflow

With register_num >= 129 the object-pointer slot is overwritten with 8 ASCII hex characters, and the subsequent strcmp(buf, obj'+0x2f8) dereferences a wild pointer - this is the observed crash. With register_num == 128 the final NUL lands on the first byte of the slot (obj' = obj & ~0xff), which keeps the pointer inside the heap and leads to a later crash in new_send_downlink_data() (misaligned reference-array dereference) instead.

Proof of concept

The accompanying PoC, poc_modbus_tcp_hexoverflow.py, uses pwntools. It checks whether the service is running with an FC 3 read, sends the 12-byte FC 6 frame, and receives the normal echo reply, which modbus_reply_with_address() emits before the write handler corrupts the stack. It then probes again. A refused connection or missing listener indicates that the daemon has terminated.

$ python3 poc_modbus_tcp_hexoverflow.py --host <ip> --port 502
[*] pre-fire probe : alive
[*] firing FC6 write to unit 1 addr 0 ...
[*] echo reply: 000100000006010600001122
[+] daemon crashed (listener gone / connection refused)

Verification object configuration used throughout (written to /etc/protocol/modbus/srv1.conf; server stanza in server.conf with "connect_type":"modbus_tcp", "slave_id_type":1, "enable":1):

[{"id":"1","lora_name":"str1","dev_eui":"525400FFFE123456",
  "register_type":"holding_register","register_addr":0,
  "register_num":400,"data_type":"string",
  "payload_codec_object_id":0,"work_mode":"rw"}]

Observed result - binary-level test

Threshold sweep, using a fresh instance and one FC 6 frame for each value:

register_num 8 121 127 128 129 136 160 400
result alive alive alive SIGSEGV SIGSEGV SIGSEGV SIGSEGV SIGSEGV

The boundary matches the decompiled buffer exactly (128*4 + 1 = 513 > 512). Values 121 (the UI maximum) and below are safe for this overflow, distinguishing values permitted by the UI from those accepted by the daemon.

Core-dump forensics (DWARF intact): bt reports "corrupt stack"; saved return-address slots retain their original libc/text bytes with individual bytes overwritten; the faulting PC sits at the ret of a libc syscall trampoline (libc+0x8932c, x30 at libc+0x7d138, a sem/futex call site) - the overflow corrupted a frame that was blocked in a syscall, and the process crashed while returning through that frame.

Observed result - service integration test

The test system was rebooted with the persistent service configuration shown above. The lab forwarded TCP 15002 to service port 502. Running the PoC against that endpoint produced:

$ python3 poc_modbus_tcp_hexoverflow.py --host 127.0.0.1 --port 15002
[*] pre-fire probe : alive
[*] firing FC6 write to unit 1 addr 0 ...
[*] echo reply: 000100000006010600001122
[+] daemon crashed (listener gone / connection refused)

On the test system, pidof modbus_slave showed a PID change (939 -> 1542), indicating a crash and respawn. /etc/urlog/modbus.log recorded the execution path:

17:03:54 New connection from 10.0.2.2:63183 on socket 9
17:03:54 receive modbus write request for slave 1
17:03:54 write_one_register addr:0 reg_type:holding_register data:... slave_id:1
17:03:59 <respawned instance startup lines>

Affected assets

Attack prerequisites

  1. Network reachability of the Modbus-TCP port (LAN-side by default; firewall posture for WAN interfaces was not assessed here).
  2. A writable object with register_num >= 128 in the server configuration. The web UI enforces 121 client-side only; the daemon and (per the related handler findings, where lora_gateway_ubus applies no field validation) the ubus backend accept arbitrary values. If the factory web credentials (admin/password) remain valid, an attacker can use that authenticated configuration step to create the object in one request. Subsequent Modbus requests require no login. Default-credential login is not an authentication bypass; see the shared tag definitions.

Exploitability analysis (why this is DoS, not RCE)

The write primitive has three independent constraints that prevent control-flow hijacking. Each was verified against the disassembly, and every potential bypass listed below was tested or reviewed in code:

  1. Character set. Every overflow byte is one of 0123456789abcdef (0x30-0x66). Canonical AArch64 user pointers require the top two bytes to be 0x00; the writer emits exactly one NUL, at the very end. Any fully overwritten pointer slot is therefore non-canonical.
  2. 4-character granularity. Output length is exactly register_num*4, so the write can only stop at offsets congruent to 512 (mod 4) above the buffer. The partial overwrites that would preserve a pointer's high bytes never align with the 8-byte slots (obj @+512, caller FP @+520, caller LR @+528). Enumerated stops k = 0..8 all land in non-executable or unmapped windows.
  3. Dereference ordering. Any stop that reaches a return address first corrupts the object-pointer slot at +512; the subsequent strcmp(buf, obj'+0x2f8) faults before the corrupted return address is used. Observed crashes are wild reads, with RIP intact.

Potential bypasses examined and ruled out:

Route Outcome
register_num = 128 object-pointer pivot (obj' = obj & ~0xff) keeps a valid heap pointer; writes 255 hex chars confined to [obj+0x208, obj+0x4f8]; the intrusive list head at +0x500 is 8 bytes out of reach by struct design; crashes in new_send_downlink_data() (misaligned reference-array pointer) before useful changes persist
Partial overwrite of the caller's saved LR k=1 lands on the page start of a r--p segment; k=2/3 land unmapped (byte math in the session log)
Read-side info leak via FC 16 source offset blocked by is_last_addr_out_of_range() - a write may not span past a single object's virtual span (observed: last_addr:122 is out of range)
Leak via the stored hex value snprintf(obj+0x2f8, 0x100, ...) truncates the string while it still contains only the attacker's own request bytes
Rollback-path stack->mapping copy (modbus_server_update_register memcpy of register_num*2 bytes from the 516-byte stack buffer, readable via FC 3 at register_num > 258) an OOB read, but the same convert_data() call corrupts the object's list head with hexadecimal output, and a crash during the 30-second cache walk races the read; at most an information leak, with no stronger write primitive
Milesight-forked libmodbus.so.5.1.0 modbus_reply_with_address() (full attacker control over byte values, without a character-set constraint; the only location on this surface considered capable of supporting classic ROP) full branch audit performed (5.4 KB of code, all 12 function-code paths): FC 5/6 echo memcpy capped at the 260-byte recv limit into a 264-byte buffer; FC 3/4 responses <= 254 bytes; FC 17 <= 250 with explicit MAX_ADU check; FC 16/15 quantity and mapping bounds enforced - no overflow found

This primitive produces a reliable unauthenticated remote crash and can write hexadecimal characters derived from stack contents into the target stack. It does not provide instruction-pointer control. Achieving that would require a separate write primitive with byte-level control.

modbus_slave_handle_uplink() (file offset 0xbb40) passes a raw json_object_get_string() pointer to modbus_server_update_register() whose convert_data() string branch performs an unbounded memcpy of strlen(value) bytes into the same 516-byte stack buffer - no character-set constraint. It has zero call sites in 60.0.0.50 (dead code, documented in poc_modbus_string_overflow.py). If future firmware connects this function to a network path, the overflow would support ROP against the same service. Both issues should be fixed together, with a regression test.

Additional observations from the investigation

Security impact

A 12-byte packet causes unauthenticated remote denial of service against a root system service. Repeated requests can maintain a crash loop as procd respawns the service. CVSS 3.1 base (assuming the feature is enabled and an over-wide object exists): AV:N/AC:L/PR:N/UI:N/S:U/C:N/I:N/A:H = 7.5 (High). Where factory web credentials remain valid, a LAN attacker can first configure the required object and then trigger the crash. The feature and configuration prerequisites still apply.

  1. Validate register_num server-side in parse_single_modbus_object() (accept 1..121, reject others) - the authoritative fix; the web UI's client-side cap is not a control.
  2. Bound the hex expansion: pass the destination capacity to util_data_to_hex_string() (e.g. min(len*2, dest_size-1) plus explicit NUL termination), and clamp the read length to the received frame length in write_one_register()/write_registers().
  3. Apply the same capacity clamp in convert_data() for the obj+0x2f8 cache field, and bound the rollback-path memcpy in modbus_server_update_register() to the 516-byte staging buffer.
  4. Re-validate object fields in the ubus handler that writes /etc/protocol/modbus/*.conf (backend-side), consistent with the related handler remediation.
  5. Remove or harden the dead modbus_slave_handle_uplink() caller.
  6. Build with stack canaries (-fstack-protector-strong) as defense-in-depth for this service.

Notes on scope

See the shared testing scope.