]> git.ipfire.org Git - thirdparty/curl.git/commitdiff
strdup: don't allow Curl_strndup to read past a null terminator
authorJay Satiro <raysatiro@yahoo.com>
Thu, 2 Nov 2023 22:56:06 +0000 (18:56 -0400)
committerJay Satiro <raysatiro@yahoo.com>
Fri, 3 Nov 2023 03:44:46 +0000 (23:44 -0400)
- Use malloc + strncpy instead of Curl_memdup to dupe the string before
  null terminating it.

Prior to this change if Curl_strndup was passed a length longer than
the allocated string then it could copy out of bounds.

This change is for posterity. Curl_strndup was added in the parent
commit and currently none of the calls to it pass a length that would
cause it to read past the allocated length of the input.

Follow-up to d3b3ba35.

Closes https://github.com/curl/curl/pull/12254

lib/strdup.c

index 5336da7c6381c7002a61a8a527045d157e63eab6..ea2b6d0c0a3a3b0d226338ea127b93e4312e1a4d 100644 (file)
@@ -103,18 +103,20 @@ void *Curl_memdup(const void *src, size_t length)
  *
  * Curl_strndup(source, length)
  *
- * Copies the 'source' data to a newly allocated buffer (that is
- * returned). Copies 'length' bytes then adds a null terminator.
+ * Copies the 'source' string to a newly allocated buffer (that is returned).
+ * Copies not more than 'length' bytes then adds a null terminator.
  *
  * Returns the new pointer or NULL on failure.
  *
  ***************************************************************************/
 void *Curl_strndup(const void *src, size_t length)
 {
-  char *b = Curl_memdup(src, length + 1);
-  if(b)
-    b[length] = 0;
-  return b;
+  char *buf = malloc(length + 1);
+  if(!buf)
+    return NULL;
+  strncpy(buf, src, length);
+  buf[length] = 0;
+  return buf;
 }
 
 /***************************************************************************