| name | type-confusion-anti-pattern |
| description | Security anti-pattern for type confusion vulnerabilities (CWE-843). Use when generating or reviewing code in dynamic languages that compares values, processes JSON/user input, or uses loose equality. Detects weak typing exploits and type coercion attacks. |
Type Confusion Anti-Pattern
Severity: High
Summary
Programs misinterpret data types through loose comparisons, implicit coercion, or improper input handling. Attackers exploit type confusion in weakly-typed languages (JavaScript, PHP) and dynamic data structures (JSON) to bypass security checks, manipulate logic, or achieve code execution.
The Anti-Pattern
The anti-pattern is using loose equality (==) or trusting incoming data types without explicit validation.
BAD Code Example
function checkAdminAccess(userId) {
if (userId == 0) {
return true;
}
return false;
}
GOOD Code Example
function checkAdminAccessSecure(userId) {
if (userId === 0) {
return true;
}
return false;
}
function processProductId(productId) {
if (typeof productId !== 'string' || !/^\d+$/.test(productId)) {
throw new Error("Invalid product ID format.");
}
return parseInt(productId, 10);
}
Detection
- Code Review:
- Loose equality operators: Search for
== in JavaScript or PHP code (prefer ===).
- Implicit type conversions: Look for contexts where a variable of one type might be implicitly converted to another, especially when performing comparisons or operations.
- Dynamic language features: Be cautious with how user-provided data is used in contexts where the language might automatically infer or coerce types.
- Input Validation: Check if all incoming user input (JSON body, query parameters, form data) is explicitly validated for its expected data type before being processed.
- Dynamic Queries: Review code that constructs queries for NoSQL databases (like MongoDB) or other systems using user input. Attackers can often inject operators (
$gt, $ne) by changing the input's type from a string to an object.
Prevention
Related Security Patterns & Anti-Patterns
References