]> git.ipfire.org Git - thirdparty/systemd.git/commitdiff
string-util: check for overflow in strrep() 41661/head
authorFrantisek Sumsal <frantisek@sumsal.cz>
Thu, 16 Apr 2026 09:59:36 +0000 (11:59 +0200)
committerFrantisek Sumsal <frantisek@sumsal.cz>
Thu, 16 Apr 2026 15:46:31 +0000 (17:46 +0200)
This simply mirrors the same overflow check we already have in
strrepa(), in case someone passed us a sufficiently long string.

strrep() is currently used only in tests, so this is just hardening.

src/basic/string-util.c
src/basic/string-util.h
src/test/test-string-util.c

index bd79dbfd2473099aeceba5f2cb6a52c9a1a14576..9b63516ce0908f4dec958ce73541eeb84955a153 100644 (file)
@@ -977,22 +977,27 @@ oom:
         return -ENOMEM;
 }
 
-char* strrep(const char *s, unsigned n) {
-        char *r, *p;
+char* strrep(const char *s, size_t n) {
+        char *ret, *p;
         size_t l;
 
         assert(s);
 
         l = strlen(s);
-        p = r = malloc(l * n + 1);
-        if (!r)
+        if (!MUL_ASSIGN_SAFE(&l, n))
+                return NULL;
+        if (!INC_SAFE(&l, 1))
+                return NULL;
+
+        p = ret = malloc(l);
+        if (!ret)
                 return NULL;
 
-        for (unsigned i = 0; i < n; i++)
+        for (size_t i = 0; i < n; i++)
                 p = stpcpy(p, s);
 
         *p = 0;
-        return r;
+        return ret;
 }
 
 int split_pair(const char *s, const char *sep, char **ret_first, char **ret_second) {
index 0143c37a656e298fcd6a315eb8af015feb00de86..5ab4dd9016dd2c43e54ecd9e9a9e7d7ecc731466 100644 (file)
@@ -193,7 +193,7 @@ int strextendf_with_separator(char **x, const char *separator, const char *forma
         })
 #define strprepend(x, ...) strprepend_with_separator(x, NULL, __VA_ARGS__)
 
-char* strrep(const char *s, unsigned n);
+char* strrep(const char *s, size_t n);
 
 #define strrepa(s, n)                                                   \
         ({                                                              \
index 4f12ec710c11e26d0a9070159d7d7ad6a40f8173..094983a1724b85805ccfbf47c88b301dd782f1f4 100644 (file)
@@ -325,6 +325,8 @@ TEST(strrep) {
 
         ASSERT_STREQ(onea, "waldo");
         ASSERT_STREQ(threea, "waldowaldowaldo");
+
+        ASSERT_NULL(strrep("waldo", SIZE_MAX - 1));
 }
 
 TEST(string_has_cc) {