]> git.ipfire.org Git - thirdparty/ipxe.git/commitdiff
[libc] Prevent strndup() from reading beyond the end of the string
authorMichael Brown <mcb30@ipxe.org>
Sun, 18 May 2014 20:05:39 +0000 (21:05 +0100)
committerMichael Brown <mcb30@ipxe.org>
Sun, 18 May 2014 20:09:49 +0000 (21:09 +0100)
strndup() may be called on a string which is not NUL-terminated.  Use
strnlen() instead of strlen() to ensure that we do not read beyond the
end of such a string.

Add self-tests for strndup(), including a test case with an
unterminated string.

Originally-fixed-by: Marin Hannache <git@mareo.fr>
Signed-off-by: Michael Brown <mcb30@ipxe.org>
src/core/string.c
src/tests/string_test.c

index 190007a47a4daa0eb0bcdcd7ea4bd7dfddbabfe9..e53c283c2eedde31833a6fdeb2d8c6cecc1d34dc 100644 (file)
@@ -337,11 +337,9 @@ void * memchr(const void *s, int c, size_t n)
 
 char * strndup(const char *s, size_t n)
 {
-        size_t len = strlen(s);
+        size_t len = strnlen(s,n);
         char *new;
 
-        if (len>n)
-                len = n;
         new = malloc(len+1);
         if (new) {
                 new[len] = '\0';
index 934c537cfc81e2b9d88fc644238c999ceda8078f..3b48d9f3d5a85e92f9ecd1b1e5bceb25b3aae4d9 100644 (file)
@@ -134,6 +134,26 @@ static void string_test_exec ( void ) {
                ok ( strcmp ( dup, orig ) == 0 );
                free ( dup );
        }
+
+       /* Test strndup() */
+       {
+               const char *normal = "testing testing";
+               const char unterminated[6] = { 'h', 'e', 'l', 'l', 'o', '!' };
+               char *dup;
+               dup = strndup ( normal, 32 );
+               ok ( dup != NULL );
+               ok ( dup != normal );
+               ok ( strcmp ( dup, normal ) == 0 );
+               free ( dup );
+               dup = strndup ( normal, 4 );
+               ok ( dup != NULL );
+               ok ( strcmp ( dup, "test" ) == 0 );
+               free ( dup );
+               dup = strndup ( unterminated, 5 );
+               ok ( dup != NULL );
+               ok ( strcmp ( dup, "hello" ) == 0 );
+               free ( dup );
+       }
 }
 
 /** String self-test */