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
- Use strict comparison operators where the language has them.
- Validate and convert input to the expected type before comparing.
- Use dedicated comparison functions for secrets.
- Enforce types at API boundaries with schemas.
- 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.