Modbus Server Port Number < 1024 causes a buffer overflow

20 views
Skip to first unread message

Emrah Ali PEKDEMİR

unread,
Apr 17, 2024, 12:13:21 PMApr 17
to libmodbus
Dear all,

I'm not a professional programmer, so I'll try to explain as best as I can.

My Modbus Server program crashes with *** buffer overflow detected ***: terminated Aborted (core dumped) , if I want to use 502 as the server port.

I tried both server examples coming with the library, and they both crash with any port number less than 1024. I believe there is a memory leak somewhere, since the crash happens when the program hits rc = modbus_receive(ctx, query).

And when I observe query in debug, it's full of garbage (memory is including OS related texts very close to this address). The program crashes before any client is connected, so how is query filled with more than its limit, making modbus_receive crash with an overflow? I have to use 502 as the port number, since it is hardwired into the device.

Best regards,

Emrah Pekdemir

Emrah Ali PEKDEMİR

unread,
Apr 17, 2024, 12:17:46 PMApr 17
to libmodbus
OS: Ubuntu 22.04
libmodbus 3.1.10

Bodo Meißner

unread,
Apr 17, 2024, 3:19:16 PMApr 17
to libm...@googlegroups.com
Are you running your server program as root? Does it work when you do so?
Does the code have sufficient error handling?

On UNIX or Linux, port numbers below 1024 are privileged ports that can only be bound with root privileges.

A function that tries to bind the port might return an error code. If your code ignores the error and continues, undefined behavior like buffer overflow may occur.

17.04.2024 18:17:52 Emrah Ali PEKDEMİR <shaman...@gmail.com>:

> OS: Ubuntu 22.04
> libmodbus 3.1.10
>
> On Wednesday, April 17, 2024 at 7:13:21 PM UTC+3 Emrah Ali PEKDEMİR wrote:

>> My Modbus Server program crashes with **** buffer overflow detected ***: terminated Aborted (core dumped)* , if I want to use 502 as the server port.
>>
>> I tried both server examples coming with the library, and they both crash with any port number less than *1024*. I believe there is a memory leak somewhere, since the crash happens when the program hits rc = modbus_receive(ctx, query).

If the function that initializes the modbus context ctx returns an error, ctx might be uninitialized leading to an error or undefined behavior.
What is the value of rc? If modbus_receive indicates an error, the variable query might be uninitialized.

Emrah Ali PEKDEMİR

unread,
Apr 18, 2024, 2:59:42 AMApr 18
to libmodbus
>On UNIX or Linux, port numbers below 1024 are privileged ports that can only be bound with root privileges.
Thank you so much! It works when I run with root privileges. I didn't know about this.

As a side note,  ctx was initialized fine, rc was 0, when modbus_receive failed.

Thank you again, and best regards,
Emrah
Reply all
Reply to author
Forward
0 new messages