littlekernel / lk

LK embedded kernel
MIT License
3.11k stars 611 forks source link

[libc][string] fix strncpy potential buffer overflow #389

Closed mob5566 closed 8 months ago

mob5566 commented 8 months ago

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.

travisg commented 8 months ago

Thanks!

mob5566 commented 8 months ago

You're welcome!