Safeguard
Application Security•

CWE-1025 Comparison Using Wrong Factors: Reference vs Value

Comparing object references instead of contents makes equal things look different. CWE-1025 covers the Java string example and how to prevent it.

Safeguard Security Team
2 min read

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

  1. Use the language's value equality method for objects.
  2. Define equality methods deliberately for your own types, and include every relevant field.
  3. Cover both equal and unequal cases in tests.
  4. 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.

Sources

Never miss an update

Weekly insights on software supply chain security, delivered to your inbox.

Self-healing security runs on Safeguard.

Your first fix PR is minutes away.

No sales call required, even your agent can complete the purchase over MCP.