Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

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

Merged
merged 1 commit into from
Nov 4, 2023

Conversation

mob5566
Copy link
Contributor

@mob5566 mob5566 commented Oct 22, 2023

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.

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 <[email protected]>
Copy link
Member

@travisg travisg left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Oh wow, good find. This code is over 20 years old, i should probably re-examine most of this, but in general the assumption is it was stable so haven't gone back to write unit tests or whatnot.

@travisg travisg merged commit 94a1511 into littlekernel:master Nov 4, 2023
257 checks passed
@travisg
Copy link
Member

travisg commented Nov 4, 2023

Thanks!

@mob5566
Copy link
Contributor Author

mob5566 commented Nov 5, 2023

You're welcome!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

2 participants