fix: (system) Fix buffer overflow in stdlib_get_cwd and improve const correctness #1078
+7
−2
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Motivation
The C implementation of
stdlib_get_cwdinsrc/stdlib_system.ccontained a critical buffer overflow vulnerability (Security Issue).malloc(*len)allocated memory exactly equal to the string length, leaving no space for the null terminator.strncpywas used without manually adding the null terminator, which could lead to undefined behavior when the string is used later.mallocfailure, which could cause a crash if memory allocation failed.Additionally,
stdlib_set_cwdaccepted a non-constchar*even though it does not modify the path, violating const correctness.Solution
*len + 1bytes instdlib_get_cwdto ensure space for the null terminator.res[*len] = '\0'to guarantee the string is valid.mallocreturningNULLand set the error code toENOMEMin that case.stdlib_set_cwdsignature to acceptconst char* path.