Skip to content

Commit cbb0ab9

Browse files
committed
Fix insecure data handling
CID 416366: INTEGER_OVERFLOW found with Coverity Scan.
1 parent 957fa7b commit cbb0ab9

File tree

1 file changed

+14
-2
lines changed

1 file changed

+14
-2
lines changed

src/modbus-tcp.c

+14-2
Original file line numberDiff line numberDiff line change
@@ -16,6 +16,8 @@
1616

1717
#include <stdio.h>
1818
#include <stdlib.h>
19+
#include <stdint.h>
20+
#include <limits.h>
1921
#include <string.h>
2022
#include <errno.h>
2123
#ifndef _MSC_VER
@@ -478,7 +480,9 @@ static void _modbus_tcp_close(modbus_t *ctx)
478480
static int _modbus_tcp_flush(modbus_t *ctx)
479481
{
480482
int rc;
481-
int rc_sum = 0;
483+
// Use an unsigned 16-bit integer to reduce overflow risk. The flush function
484+
// is not expected to handle huge amounts of data (> 2GB).
485+
uint16_t rc_sum = 0;
482486

483487
do {
484488
/* Extract the garbage from the socket */
@@ -505,7 +509,15 @@ static int _modbus_tcp_flush(modbus_t *ctx)
505509
}
506510
#endif
507511
if (rc > 0) {
508-
rc_sum += rc;
512+
// Check for overflow before adding
513+
if (rc_sum <= UINT16_MAX - rc) {
514+
rc_sum += rc;
515+
} else {
516+
// Handle overflow
517+
ctx->error_recovery = MODBUS_ERROR_RECOVERY_PROTOCOL;
518+
errno = EOVERFLOW;
519+
return -1;
520+
}
509521
}
510522
} while (rc == MODBUS_TCP_MAX_ADU_LENGTH);
511523

0 commit comments

Comments
 (0)