From 824a1448b9cbe685664f94c25aa00c37e3e3c058 Mon Sep 17 00:00:00 2001 From: Mai Bui Date: Mon, 26 Jun 2023 20:20:00 -0400 Subject: [PATCH] replace atoi with strtol (#6) From Semgrep: https://semgrep.dev/r?q=c.lang.correctness.incorrect-use-ato-fn.incorrect-use-ato-fn > Avoid the 'ato*()' family of functions. Their use can lead to undefined behavior, integer overflows, and lack of appropriate error handling. Instead prefer the 'strtol*()' family of functions. From atoi() man page: https://www.man7.org/linux/man-pages/man3/atoi.3.html > The atoi() function converts the initial portion of the string pointed to by nptr to int. The behavior is the same as > strtol(nptr, NULL, 10); > except that atoi() does not detect errors. Therefore, replace atoi() with strtol() Verified by kill dhcpmon process, installing new .deb change to dhcp_relay docker, execute dhcpmon process, check if counters is printing in syslog, compare counters before and after this change. logs: [before.txt](https://github.com/sonic-net/sonic-dhcpmon/files/11377335/before.txt) [after.txt](https://github.com/sonic-net/sonic-dhcpmon/files/11377336/after.txt) example commands: [command.txt](https://github.com/sonic-net/sonic-dhcpmon/files/11423945/command.txt) --- src/main.cpp | 20 +++++++++++++++++--- 1 file changed, 17 insertions(+), 3 deletions(-) diff --git a/src/main.cpp b/src/main.cpp index e660bbd90..bb9e94836 100644 --- a/src/main.cpp +++ b/src/main.cpp @@ -114,11 +114,13 @@ int main(int argc, char **argv) { int rv = EXIT_FAILURE; int i; + char *endptr; int window_interval = dhcpmon_default_health_check_window; int max_unhealthy_count = dhcpmon_default_unhealthy_max_count; size_t snaplen = dhcpmon_default_snaplen; int make_daemon = 0; bool debug_mode = false; + errno = 0; setlogmask(LOG_UPTO(LOG_INFO)); openlog(basename(argv[0]), LOG_CONS | LOG_PID | LOG_NDELAY, LOG_DAEMON); @@ -150,15 +152,27 @@ int main(int argc, char **argv) i++; break; case 's': - snaplen = atoi(argv[i + 1]); + snaplen = strtol(argv[i + 1], &endptr, 10); + if (errno != 0 || *endptr != '\0') { + fprintf(stderr, "%s: %s: Invalid snap length\n", basename(argv[0]), argv[i + 1]); + usage(basename(argv[0])); + } i += 2; break; case 'w': - window_interval = atoi(argv[i + 1]); + window_interval = strtol(argv[i + 1], &endptr, 10); + if (errno != 0 || *endptr != '\0') { + fprintf(stderr, "%s: %s: Invalid window interval\n", basename(argv[0]), argv[i + 1]); + usage(basename(argv[0])); + } i += 2; break; case 'c': - max_unhealthy_count = atoi(argv[i + 1]); + max_unhealthy_count = strtol(argv[i + 1], &endptr, 10); + if (errno != 0 || *endptr != '\0') { + fprintf(stderr, "%s: %s: Invalid max unhealthy count\n", basename(argv[0]), argv[i + 1]); + usage(basename(argv[0])); + } i += 2; break; case 'D':