Unauthenticated Stack Buffer Overflow in modbus_slave via Modbus-TCP Write Requests (Hex-Expansion Overflow)

Author Details

Field Value
Name n0tduck1e
Org Reverser Space
Email duckie@reverser.space

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 slave service, runs as root, init script S99modbus_slave)
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")
Discovery date 2026-10-26

Firmware details

Field Value
Vendor Milesight
Firmware version 60.0.0.50
Sha256 010b6f8699b7074d4c3526efdd0451b8becd611501d76d50bbcbad765d9d98b7
Product UG65 and UG67 LoRaWAN gateways
Component /usr/sbin/modbus_slave (PIE, stripped of neither symbols nor DWARF; links the Milesight-forked libmodbus.so.5.1.0)

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 every listener on the LAN 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 bounds this field at 1..121 -- client-side only (www/view/protocol/modbus/object.js, minvalue: 1, maxvalue: 121). The daemon parses it with util_json_get_int() and performs no validation of its own: any integer is accepted, 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 smashes everything 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) deterministically kills the root daemon when any writable object with register_num >= 128 exists. The binary has no stack canary.

Trigger (the value bytes are irrelevant):

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 hex-expands register_num*2 source bytes into char buf[512]; then strcmp/snprintf dereference the object pointer reloaded from the smashed slot
util_data_to_hex_string 0x13588 sprintf loop with no destination bound and no NUL discipline beyond the final byte
convert_data 0x4170 secondary sink: numeric branches hex-expand register_num*2 bytes into the 256-byte heap field obj+0x2f8 (overflows the field at register_num > 64; escapes 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

poc_modbus_tcp_hexoverflow.py (pwntools, ships with this report). It probes liveness with an FC 3 read, sends the 12-byte FC 6 frame, receives the normal echo reply (emitted by modbus_reply_with_address() before the write handler corrupts the stack), then probes again -- connection refused / listener gone means the daemon died.

$ 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 -- shipped binary under qemu-aarch64-static

Threshold sweep (fresh instance per value, one FC 6 frame each):

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, which cleanly separates "UI-legal" from "daemon-accepted".

Core-dump forensics (qemu_modbus_slave_*.core, DWARF intact): bt reports "corrupt stack"; saved return-address slots contain their original libc/text bytes with single jammed bytes; the faulting PC sits at the ret of a libc syscall trampoline (libc+0x8932c, x30 at libc+0x7d138, a sem/futex call site) -- i.e. the overflow smashed a frame that was blocked in a syscall, and the process died returning through it.

Observed result -- full AArch64 service VM (native execution)

The firmware service VM was rebooted with a host-forward to guest TCP 502 and the service configured as above (configuration persists in the VM overlay). Running the PoC from the host:

$ 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)

Guest evidence: pidof modbus_slave changed 939 -> 1542 (crash + respawn), and /etc/urlog/modbus.log captured the exact 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 pattern established in MS-03..MS-07, where lora_gateway_ubus applies no field validation) the ubus backend accept arbitrary values. With the factory web default credentials (admin/password) -- the project's accepted "effectively unauthenticated" bar -- the attacker configures the object themselves in one request and then any unauthenticated LAN host can trigger the crash at will.

Exploitability analysis (why this is DoS, not RCE)

The write primitive is unusually constrained. Three independent walls block control-flow hijacking; each was verified against the actual disassembly, and every bypass route enumerated below was tested or code-audited:

  1. Charset. 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 non-canonical by construction.
  2. 4-character granularity. Output length is exactly register_num*4, so the write can only stop at offsets \u2261 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 smashes 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.

Escape routes examined and closed:

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 anything useful persists
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 killed 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) a genuine OOB read, but the same convert_data() call hex-smashes the object's list head and the 30-second cache walk crash-races the read; leak-at-best, no write upgrade
Milesight-forked libmodbus.so.5.1.0 modbus_reply_with_address() (full attacker byte control, no charset -- the only place classic ROP could hide on this surface) 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

Conclusion: from this primitive the bug yields a reliable unauthenticated remote crash (and would yield a stack-content write of hex characters into a target's stack), but not instruction-pointer control. A separate byte-granular write primitive would be required to weaponize it further.

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 charset constraint. It has zero call sites in 60.0.0.50 (dead code, documented in poc_modbus_string_overflow.py). If any future firmware wires this function to a network path, it becomes a textbook ROP-ready overflow on the same service. Recommend fixing both together and adding a regression test.

Collateral findings from the investigation (for the record)

Security impact

Unauthenticated remote denial of service against a root system service with a 12-byte packet, repeatable at will (crash loop via procd respawn). 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). With the one-request object configuration via factory default web credentials included in the chain, the availability impact is unconditional for a LAN attacker on any feature-enabled gateway.

  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 remediation for MS-03..MS-07.
  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