Skip to content

C/C++: Detect ambiguous assignment of comparison results - #22336

Open
theinfosecguy wants to merge 1 commit into
github:mainfrom
theinfosecguy:cpp-ambiguous-assignment-condition
Open

C/C++: Detect ambiguous assignment of comparison results#22336
theinfosecguy wants to merge 1 commit into
github:mainfrom
theinfosecguy:cpp-ambiguous-assignment-condition

Conversation

@theinfosecguy

Copy link
Copy Markdown
Contributor

Adds cpp/ambiguous-assignment-of-comparison to flag conditions such as:

if ((status = read_status() < 0))

The query distinguishes this from explicitly grouped assign-then-compare and compare-then-assign expressions. It includes C and C++ tests, query help, and query-suite integration.

Local targeted and neighboring tests pass. The motivating regression is detected, and a run against git/git produced no alerts.

Fixes #22286

@ryao ryao left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

While I am happy you did the work for me to get this into a PR and made what appear to be improvements, would you add an Original-patch-by: to the commit message to credit my prior work?

Also, have you run your variant against any major corpora (e.g. Linux, curl, OpenZFS) to verify the lack of FPs in production code, like I did with the original version? If it helps:

https://docs.github.com/en/code-security/how-tos/find-and-fix-code-vulnerabilities/scan-from-the-command-line/download-databases

if ((status = read_status() < 0)) // BAD: assigns the comparison result.
return status;

if ((status = read_status()) < 0) // GOOD: assigns first, then compares.

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

This isn't the only good variant. The following is good too, because it shows that the developer really meant it.

  if ((status = (read_status() < 0))) // GOOD: explicitly assigns the comparison result.
    return status;

not isExplicitlyGrouped(comparison) and
occursInCondition(assignment) and
// Assigning a comparison result to a Boolean is normally intentional.
not assignment.getLValue().getUnspecifiedType() instanceof BoolType and

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

While this is normally intentional, I believe not isExplicitlyGrouped(comparison) precludes this.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Projects

None yet

Development

Successfully merging this pull request may close these issues.

C: Implicit compare-then-assign in branch conditions should be flagged

3 participants