A comparison can be complete and still wrong, if it looks at the wrong thing. That is CWE-1025: the code compares two entities but examines the wrong factors or characteristics, which leads to incorrect results and resultant weaknesses.
How it happens
MITRE's example is the common Java mistake of using == on strings. For objects, == compares references, not values:
String str1 = new String("Hello");
String str2 = new String("Hello");
if (str1 == str2) {
System.out.println("str1 == str2"); // never runs
}
The two strings hold the same text but are different objects, so the branch is skipped. The fix compares values:
if (str1.equals(str2)) {
System.out.println("str1 equals str2");
}
In MITRE's words, the code might inadvertently compare references to objects instead of the relevant contents, causing two equal objects to be considered unequal. The record lists no observed CVEs and gives the consequence as varying by context. If the comparison guards a check, such as a permission or a duplicate test, the wrong answer can undermine it.
How to find it
MITRE recommends manual static analysis: test the comparison scheme before production with positive and negative tests.
- Search for reference equality operators on non primitive values.
- Enable compiler and linter warnings about comparing strings or boxed values by reference.
- Write tests that build equal values separately and compare them.
How to fix it
- Use the language's value equality method for objects.
- Define equality methods deliberately for your own types, and include every relevant field.
- Cover both equal and unequal cases in tests.
- Turn on static analysis rules for this pattern.
Quick check
Why does the Java example print nothing?
The operator compares object references. The two strings are separate objects, so the references differ even though the text matches.