Safeguard
Application Security•

CWE-597: Wrong Operator in a String Comparison

In Java, == on strings compares objects, not text. When that result feeds a security decision, a style slip becomes a vulnerability. What to use instead.

Safeguard Security Team
2 min read

CWE-597 is the use of the wrong operator when comparing strings, such as == where .equals() belongs. It is closely related to comparing object references, and MITRE lists Java, JavaScript, and PHP as the languages where it shows up.

How it happens

In Java, == and != on two strings compare the objects for equality, not their string values. As MITRE puts it, chances are good the two references will never be equal.

// Vulnerable pattern
if (user.getRole() == "ADMIN") { ... }

The record is careful about impact: this weakness often only affects program correctness. But if the equality is used for a security decision, the unintended comparison result could be leveraged to affect program security.

The other languages have the opposite trap. MITRE's mitigation text notes that in JavaScript you use == to compare string values, and that PHP converts a string to a number when comparing a numeric value to a string. The right operator depends on the language, which is why the mistake follows people who switch between them.

What an attacker gains

Not much when the code is only formatting a label. A lot when the string is a role, a token, a hash, or a path prefix. A comparison that is always false can disable a check. One that is always true, through type coercion in the loose-comparison languages, can grant access.

How to find it

Static analysis (SAST) can find some instances by flagging reference or loose comparison on string-typed values. Prioritise hits inside authentication, authorization, and validation code.

How to fix it

MITRE rates this mitigation as high effectiveness: use the language's correct value comparison.

  • Java: use .equals() to compare string values.
  • JavaScript: use == to compare string values (and note that a strict === avoids type coercion surprises with non-strings).
  • PHP: use == to compare a numeric value to a string, remembering PHP converts the string to a number.
if ("ADMIN".equals(user.getRole())) { ... }

Add a lint rule or compiler warning for string == in Java so the mistake is caught on the first commit.

Quick check

When does this weakness become a security issue? When the comparison result is used for a security decision. Otherwise it usually affects only correctness.

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.