CVE-2020-28009: Integer overflow in get_stdinput()
[exim.git] / src / src / string.c
index 4726fbe4e30e0de5b7fa5256dd4c10a6199d1dbd..64d14439e6bab3c2378e8bf594c40a2423d6348c 100644 (file)
@@ -575,7 +575,7 @@ uschar *
 string_copy_dnsdomain(uschar *s)
 {
 uschar *yield;
-uschar *ss = yield = store_get(Ustrlen(s) + 1, is_tainted(s));
+uschar *ss = yield = store_get(Ustrlen(s) + 1, TRUE);  /* always treat as tainted */
 
 while (*s != 0)
   {
@@ -952,12 +952,15 @@ else
     s = ss;
     if (!*s || *++s != sep || sep_is_special) break;
     }
+
+  /* Trim trailing spaces from the returned string */
+
   /* while (g->ptr > 0 && isspace(g->s[g->ptr-1])) g->ptr--; */
   while (  g->ptr > 0 && isspace(g->s[g->ptr-1])
        && (g->ptr == 1 || g->s[g->ptr-2] != '\\') )
     g->ptr--;
   buffer = string_from_gstring(g);
-  gstring_release_unused(g);
+  gstring_release_unused_trc(g, CCS func, line);
   }
 
 /* Update the current pointer and return the new string */
@@ -1091,7 +1094,16 @@ existing length of the string. */
 
 unsigned inc = oldsize < 4096 ? 127 : 1023;
 
+if (g->ptr < 0 || g->ptr > g->size || g->size >= INT_MAX/2)
+  log_write(0, LOG_MAIN|LOG_PANIC_DIE,
+    "internal error in gstring_grow (ptr %d size %d)", g->ptr, g->size);
+
 if (count <= 0) return;
+
+if (count >= INT_MAX/2 - g->ptr)
+  log_write(0, LOG_MAIN|LOG_PANIC_DIE,
+    "internal error in gstring_grow (ptr %d count %d)", g->ptr, count);
+
 g->size = (p + count + inc + 1) & ~inc;                /* one for a NUL */
 
 /* Try to extend an existing allocation. If the result of calling
@@ -1140,17 +1152,25 @@ string_catn(gstring * g, const uschar *s, int count)
 int p;
 BOOL srctaint = is_tainted(s);
 
+if (count < 0)
+  log_write(0, LOG_MAIN|LOG_PANIC_DIE,
+    "internal error in string_catn (count %d)", count);
+
 if (!g)
   {
   unsigned inc = count < 4096 ? 127 : 1023;
-  unsigned size = ((count + inc) &  ~inc) + 1;
+  unsigned size = ((count + inc) &  ~inc) + 1; /* round up requested count */
   g = string_get_tainted(size, srctaint);
   }
 else if (srctaint && !is_tainted(g->s))
   gstring_rebuffer(g);
 
+if (g->ptr < 0 || g->ptr > g->size)
+  log_write(0, LOG_MAIN|LOG_PANIC_DIE,
+    "internal error in string_catn (ptr %d size %d)", g->ptr, g->size);
+
 p = g->ptr;
-if (p + count >= g->size)
+if (count >= g->size - p)
   gstring_grow(g, count);
 
 /* Because we always specify the exact number of characters to copy, we can
@@ -1692,6 +1712,7 @@ int main(void)
 uschar buffer[256];
 
 printf("Testing is_ip_address\n");
+store_init();
 
 while (fgets(CS buffer, sizeof(buffer), stdin) != NULL)
   {