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

Using strncmp instead of strcmp to make the function robust and safe from buffer overruns. #33449

Merged
merged 1 commit into from
May 14, 2024
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion examples/chip-tool/commands/common/Command.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -171,7 +171,7 @@ bool HandleNullableOptional(Argument & arg, char * argValue, std::function<bool(
if (arg.isNullable())
{
auto * nullable = reinterpret_cast<chip::app::DataModel::Nullable<T> *>(arg.value);
if (strcmp(argValue, "null") == 0)
if (argValue != nullptr && strncmp(argValue, "null", 4) == 0)
Copy link
Contributor

Choose a reason for hiding this comment

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

How can argValue be not null-terminated? So how do we then know the size of it?

Copy link
Contributor Author

Choose a reason for hiding this comment

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

Yes, it is impossible in this case, we use strncmp for argument comparisons in other cases, but in one instance, we use strcmp(argValue, "null").

strncmp would only be necessary if argValue was not null-terminated and had a length of exactly 4, making strcmp unsafe. However, since argValue is always null-terminated in this context, it is safe to use either strncmp(argValue, "null", 4) or strcmp(argValue, "null").

This change is intended to standardize the method used for argument comparison in the code.

Copy link
Contributor

Choose a reason for hiding this comment

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

Just to follow up on the Slack thread about this: "standardizing" breaks the code. The places that use strncmp are doing prefix checks, but this one is supposed to be an equality check. We don't want to treat all strings starting with "null" as the null value.

{
nullable->SetNull();
return true;
Expand Down
Loading