Safeguard
Application Security•

CWE-1024 Comparison of Incompatible Types in Code

Comparing values of different types can give results you did not intend, especially in JavaScript and PHP. CWE-1024 explained with safe patterns.

Safeguard Security Team
2 min read

Some languages will happily compare a string to a number and give you an answer. The answer may not be the one you meant.

CWE-1024 is the weakness where the product compares two entities of different, incompatible types that cannot be guaranteed to give correct results when compared directly. MITRE lists JavaScript and PHP among the affected languages, and notes it applies elsewhere too.

How it happens

Loosely typed languages convert values silently when you use a loose equality operator. The conversion rules are complex, and code that works in testing can behave differently with unexpected input.

// Risky: loose equality converts types before comparing
if (userInput == storedValue) { grant(); }
// Better: strict equality, after checking the type
if (typeof userInput === "string" && userInput === storedValue) { grant(); }
// Risky: loose comparison
if ($token == $expected) { ... }

// Better: strict comparison of same typed values
if (is_string($token) && hash_equals($expected, $token)) { ... }

MITRE records the consequence only as varying by context, and lists no observed CVEs. The impact depends on what the comparison guards. If it guards a security decision, a wrong result is a bypass.

How to find it

MITRE lists two methods. Automated static analysis can find some instances. Manual static analysis should test the comparison scheme thoroughly before production, with positive and negative tests.

  • Search for loose equality operators in code that handles authentication, tokens or permissions.
  • Turn on linter rules that require strict equality.
  • Test with inputs of unexpected types, such as numbers, arrays, null and empty strings.

How to fix it

  1. Use strict comparison operators where the language has them.
  2. Validate and convert input to the expected type before comparing.
  3. Use dedicated comparison functions for secrets.
  4. Enforce types at API boundaries with schemas.
  5. Add tests with wrong typed inputs.

Quick check

Why are JavaScript and PHP named?

Both can convert operand types implicitly in loose comparisons, so mixed type comparisons can return unintended results.

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.