Make BUF_strndup() read-safe on arbitrary inputs
authorAlessandro Ghedini <alessandro@ghedini.me>
Wed, 16 Sep 2015 15:54:05 +0000 (17:54 +0200)
committerEmilia Kasper <emilia@openssl.org>
Tue, 22 Sep 2015 17:50:53 +0000 (19:50 +0200)
BUF_strndup was calling strlen through BUF_strlcpy, and ended up reading
past the input if the input was not a C string.

Make it explicitly part of BUF_strndup's contract to never read more
than |siz| input bytes. This augments the standard strndup contract to
be safer.

The commit also adds a check for siz overflow and some brief documentation
for BUF_strndup().

Reviewed-by: Matt Caswell <matt@openssl.org>
crypto/buffer/buf_str.c
include/openssl/buffer.h

index 1e8d7f6f105049baf04c1b1f371c78cf334b5790..bca363c28e5b69c28795368771e394cd025a7e9f 100644 (file)
@@ -57,6 +57,7 @@
  */
 
 #include <stdio.h>
+#include <limits.h>
 #include "internal/cryptlib.h"
 #include <openssl/buffer.h>
 
@@ -85,12 +86,18 @@ char *BUF_strndup(const char *str, size_t siz)
 
     siz = BUF_strnlen(str, siz);
 
+    if (siz >= INT_MAX)
+        return (NULL);
+
     ret = OPENSSL_malloc(siz + 1);
     if (ret == NULL) {
         BUFerr(BUF_F_BUF_STRNDUP, ERR_R_MALLOC_FAILURE);
         return (NULL);
     }
-    BUF_strlcpy(ret, str, siz + 1);
+
+    memcpy(ret, str, siz);
+    ret[siz] = '\0';
+
     return (ret);
 }
 
index af30a90b865a78d9d92b0eb2fb703f6457a921d3..61cff9ca36e09a75101729a0489fd3f38efae739 100644 (file)
@@ -90,7 +90,13 @@ size_t BUF_MEM_grow(BUF_MEM *str, size_t len);
 size_t BUF_MEM_grow_clean(BUF_MEM *str, size_t len);
 size_t BUF_strnlen(const char *str, size_t maxlen);
 char *BUF_strdup(const char *str);
+
+/*
+ * Returns a pointer to a new string which is a duplicate of the string |str|,
+ * but guarantees to never read past the first |siz| bytes of |str|.
+ */
 char *BUF_strndup(const char *str, size_t siz);
+
 void *BUF_memdup(const void *data, size_t siz);
 void BUF_reverse(unsigned char *out, unsigned char *in, size_t siz);