From a5ed043d07ca51299819170f989122a2b349f7bc Mon Sep 17 00:00:00 2001 From: Ed Sabol <22986767+esabol@users.noreply.github.com> Date: Tue, 6 Aug 2024 14:37:35 -0400 Subject: [PATCH] Addressed CodeQL gripe about uncontrolled format string in handling of the GEARMAND_PORT environment variable. --- .../plugins/protocol/gear/protocol.cc | 22 +++++++++++++++++-- 1 file changed, 20 insertions(+), 2 deletions(-) diff --git a/libgearman-server/plugins/protocol/gear/protocol.cc b/libgearman-server/plugins/protocol/gear/protocol.cc index 8a718f5f0..b19f12f76 100644 --- a/libgearman-server/plugins/protocol/gear/protocol.cc +++ b/libgearman-server/plugins/protocol/gear/protocol.cc @@ -52,6 +52,9 @@ #include #include #include +#include +#include +#include #include "libgearman/ssl.h" @@ -452,8 +455,23 @@ gearmand_error_t Gear::start(gearmand_st *gearmand) char* service; if ((service= getenv("GEARMAND_PORT")) and service[0]) { - _port.clear(); - _port.append(service); + const size_t max_port_str_len= 5; /* TCP port numbers are unsigned 16-bit integers, so the maximum value is 65535, which is 5 characters long. */ + std::string port_str(service, std::min(strlen(service), max_port_str_len)); + /* Truncate at first non-digit character, if present, to address CodeQL gripe about uncontrolled format string. */ + bool done= false; + for (size_t loop= 0; !done && (loop < port_str.length()); loop++) + { + if (!std::isdigit(port_str[loop])) + { + port_str.resize(loop); + done= true; + } + } + if (!port_str.empty()) + { + _port.clear(); + _port.append(port_str); + } } }