diff options
author | Cody Wong <codycswong@google.com> | 2023-10-22 19:45:13 +0800 |
---|---|---|
committer | Travis Geiselbrecht <travisg@gmail.com> | 2023-11-04 13:16:24 -0700 |
commit | 94a15119b2fe50a076f73e502566895e357b77ff (patch) | |
tree | e00fd6189485ac311ab2a4c085d5bd4f47bfd119 | |
parent | ec261bcf45459c0f1d95151b6cfb33910098420c (diff) | |
download | lk-94a15119b2fe50a076f73e502566895e357b77ff.tar.gz |
[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 <codycswong@google.com>
-rw-r--r-- | lib/libc/string/strncpy.c | 2 |
1 files changed, 1 insertions, 1 deletions
diff --git a/lib/libc/string/strncpy.c b/lib/libc/string/strncpy.c index 017fdab4..55ce44d7 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'; |