Krzysztow / modbus-utils

Modbus client and server command line tools based on libmodbus.
MIT License
35 stars 21 forks source link

There is a memory leak in modbus_client. #17

Open balckgu1 opened 3 months ago

balckgu1 commented 3 months ago

Vulnerability details

In line 142 of modbus_client.c, the createTcpBackend() function does not free the TcpBackend structure after allocating it. This resulted in the first memory leak, which was 88 bytes in size.

There is also a memory leak in the createTcpBackend() function on line 234 of mbu-common.h. Although the memory of the TcpBackend structure is not allocated directly in this function, it does allocate a memory block with the size of the TcpBackend structure. Therefore, a memory leak of size 88 bytes is created here as well.

At line 272 of modbus_client.c, the data.data16 array allocated by malloc() is not freed. Although there is only a 6-byte memory leak here, if there are similar memory allocation operations elsewhere in the program, it may cause larger problems.

AddressSanitizer report

`================================================================= ==15573==ERROR: LeakSanitizer: detected memory leaks

Direct leak of 88 byte(s) in 1 object(s) allocated from:

0 0x7f408390fb40 in __interceptor_malloc (/usr/lib/x86_64-linux-gnu/libasan.so.4+0xdeb40)

#1 0x5598445b8051 in main /home/zyl/modbus-utils/modbus_client/modbus_client.c:142
#2 0x7f4082534c86 in __libc_start_main (/lib/x86_64-linux-gnu/libc.so.6+0x21c86)

Direct leak of 88 byte(s) in 1 object(s) allocated from:

0 0x7f408390fb40 in __interceptor_malloc (/usr/lib/x86_64-linux-gnu/libasan.so.4+0xdeb40)

#1 0x5598445b75e6 in createTcpBackend /home/zyl/modbus-utils/common/mbu-common.h:234
#2 0x5598445b805e in main /home/zyl/modbus-utils/modbus_client/modbus_client.c:142
#3 0x7f4082534c86 in __libc_start_main (/lib/x86_64-linux-gnu/libc.so.6+0x21c86)

Direct leak of 6 byte(s) in 1 object(s) allocated from:

0 0x7f408390fb40 in __interceptor_malloc (/usr/lib/x86_64-linux-gnu/libasan.so.4+0xdeb40)

#1 0x5598445b8914 in main /home/zyl/modbus-utils/modbus_client/modbus_client.c:272
#2 0x7f4082534c86 in __libc_start_main (/lib/x86_64-linux-gnu/libc.so.6+0x21c86)

SUMMARY: AddressSanitizer: 182 byte(s) leaked in 3 allocation(s).`

How to reproduce

  1. Enable ASan when compiling: -fsanitize=address -fsanitize-recover=address -O1 -fno-omit-frame-pointer
  2. Start modbus_server: ./modbus_server -m tcp -p 1502 127.0.0.1
  3. Start modbus_client in another terminal and send the following message: ./modbus_client --debug -mtcp -t0x10 -r0 -p1502 127.0.0.1 0x01 0x02 0x03
  4. Then, quit modbus_client and you will be able to find this. 1713353398345