From 4d09bdd430cf5035e804496c2f7dd2fff2618ab7 Mon Sep 17 00:00:00 2001 From: Cody Wong Date: Sun, 22 Oct 2023 19:45:13 +0800 Subject: [PATCH] [libc][string] fix strncpy potential buffer overflow The wrong placement of the increment for index `i` causes an unexpected behavior, which the `strncpy` writes an extra '\0'. For example: The `src` string is "abc". The buffer size of `dest` is 5. When we call `strncpy(dest, src, 5)`, the first `for` loop copies the characters, 'a', 'b', and 'c', to the `dest[0:2]`. In the 4th iteration, however, the `for` loop breaks due to the termination of `src` whereas the value of `i` stays 3. At the moment, it has copied 4 bytes, including the '\0' of `src`. In the second `for` loop, we have `i = 3` and `count = 5`, so the loop copies two more '\0' to the `dest`. As a result, the `strncpy` copies 6 bytes to the `dest` buffer, leading to buffer overflow. Fix the issue by increasing the index `i` before every copy. Signed-off-by: Cody Wong --- lib/libc/string/strncpy.c | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/lib/libc/string/strncpy.c b/lib/libc/string/strncpy.c index 017fdab40a..55ce44d7f6 100644 --- a/lib/libc/string/strncpy.c +++ b/lib/libc/string/strncpy.c @@ -17,7 +17,7 @@ strncpy(char *dest, char const *src, size_t count) { char *tmp = dest; size_t i; - for (i = 0; i < count && (*dest++ = *src++) != '\0'; i++) + for (i = 0; i++ < count && (*dest++ = *src++) != '\0'; ) ; for (; i < count; i++) *dest++ = '\0';