From 0cc06b27ec040645917b3d112677b1532963d881 Mon Sep 17 00:00:00 2001 From: Steven Hartland Date: Fri, 18 Jun 2021 23:35:17 +0100 Subject: [PATCH] fix(utils): protect against errors in str_replace Protect against misuse of str_replace if the replace string is larger than the find string by forcing an exit with error. --- utils.c | 15 +++++++++++++-- utils.h | 6 ++++++ 2 files changed, 19 insertions(+), 2 deletions(-) diff --git a/utils.c b/utils.c index 77a86c08..59d1d78c 100644 --- a/utils.c +++ b/utils.c @@ -5,6 +5,11 @@ #include "utils.h" +#ifndef _WIN32 + #include + #include +#endif + #if !HAVE_STRNSTR /* @@ -138,9 +143,15 @@ str_replace(char *source, char *find, char *replace) int rlen = strlen(replace); int flen = strlen(find); + if (rlen > flen) { + err(EX_SOFTWARE, "str_replace: replace is larger than find"); + } + while (NULL != s) { - strncpy(s, replace, rlen); - strcpy(s + rlen, s + flen); + strncpy(s, replace, rlen); // -Wstringop-truncation warning here is a false positive. + if (rlen < flen) { + strcpy(s + rlen, s + flen); + } s += rlen; s = strstr(s, find); } diff --git a/utils.h b/utils.h index 6f0b1fc2..ec1d0ecd 100644 --- a/utils.h +++ b/utils.h @@ -8,6 +8,8 @@ #define QSTAT_UTILS_H #ifndef _WIN32 + #include + #include #ifdef HAVE_CONFIG_H #include "gnuconfig.h" #endif @@ -43,6 +45,10 @@ #define EX_OSERR 71 /* system error (e.g., can't fork) */ #endif +#ifndef EX_SOFTWARE + #define EX_SOFTWARE 70 /* An internal software error has been detected */ +#endif + #if !HAVE_ERR_H void err(int eval, const char *fmt, ...); void warn(const char *fmt, ...);