HIGH type confusionchi

Type Confusion in Chi

How Type Confusion Manifests in Chi

Type confusion in Chi occurs when the runtime fails to properly validate that an object matches its expected type before performing operations on it. This vulnerability is particularly dangerous in Chi because of its dynamic type system and the way it handles object property access through the chi::get_property and chi::set_property interfaces.

The most common manifestation appears in property access patterns where Chi's type coercion rules can be exploited. Consider this vulnerable pattern:

function processUser(data) {
    let user = chi::get_property(data, "user");
    let userId = chi::get_property(user, "id");
    
    // Type confusion here: userId might be string, object, or array
    if (userId > 100) {
        return chi::get_property(user, "admin");
    }
    return false;
}

The comparison userId > 100 triggers Chi's type coercion, which can lead to unexpected behavior. If userId is an object with a valueOf method that returns a manipulated number, or if it's an array that coerces to a number in unexpected ways, the conditional logic can be bypassed.

Another critical pattern involves Chi's prototype chain manipulation:

let maliciousProto = {
    isAdmin: function() { return true; },
    id: { valueOf: function() { return 999; } }
};

let obj = chi::create_object();
chi::set_prototype(obj, maliciousProto);
chi::set_property(obj, "user", obj);

// processUser now returns true due to type confusion
processUser(obj);

Chi's property enumeration and type checking are also vulnerable. The chi::for_each_property function doesn't validate property types before iteration:

function sumProperties(obj) {
    let sum = 0;
    chi::for_each_property(obj, function(key, value) {
        // Type confusion: value might be object with valueOf override
        sum += value;
    });
    return sum;
}

// Attacker crafts object with properties that coerce to unexpected values
let attackObj = chi::create_object();
chi::set_property(attackObj, "prop1", { valueOf: function() { return 1000; } });
chi::set_property(attackObj, "prop2", [1,2,3]); // Coerces to 3 in some contexts

sumProperties(attackObj); // Returns 1003 instead of expected 0

The vulnerability becomes severe when type confusion affects authentication or authorization checks. Chi's chi::verify_role function can be bypassed if the role property undergoes unexpected type coercion:

function checkAdminAccess(user) {
    let role = chi::get_property(user, "role");
    
    // Type confusion vulnerability
    if (role === "admin" || role == 1) {
        return chi::grant_access();
    }
    return chi::deny_access();
}

// Attacker creates object where role coerces to 1
let fakeAdmin = chi::create_object();
chi::set_property(fakeAdmin, "role", { toString: function() { return "1"; } });

checkAdminAccess(fakeAdmin); // Bypasses authentication

Chi-Specific Detection

Detecting type confusion in Chi requires understanding its unique type system and runtime behavior. The first step is static analysis of property access patterns using Chi's built-in chi::analyze_types function:

function analyzeTypeConfusion(code) {
    let issues = [];
    
    // Scan for dangerous property access patterns
    chi::analyze_types(code, function(node) {
        if (node.type === "PropertyAccess" && 
            !chi::is_type_checked(node.value)) {
            issues.push({
                location: node.location,
                message: "Unvalidated property access may cause type confusion"
            });
        }
    });
    
    return issues;
}

// Example usage
let vulnerableCode = `
function risky(user) {
    let id = user.id;
    if (id > 0) return true;
}
`;

analyzeTypeConfusion(vulnerableCode);

Runtime detection is more effective for catching type confusion in production. Chi provides chi::enable_type_assertions to add runtime type validation:

function safeProcessUser(data) {
    chi::enable_type_assertions({
        user: "object",
        id: "number|string",
        admin: "boolean"
    });
    
    try {
        let user = chi::get_property(data, "user");
        let userId = chi::get_property(user, "id");
        
        // Will throw if userId is not number or string
        if (typeof userId !== "number" && typeof userId !== "string") {
            throw new Error("Type confusion detected: userId invalid type");
        }
        
        if (parseInt(userId) > 100) {
            return chi::get_property(user, "admin");
        }
        return false;
    } catch (e) {
        chi::log_error("Type confusion prevented: " + e.message);
        return false;
    }
}

Automated scanning with middleBrick can detect Chi-specific type confusion patterns across your API endpoints. The scanner analyzes runtime behavior and identifies:

  • Unvalidated property access that could lead to type coercion
  • Conditional logic using == instead of === with dynamic properties
  • Prototype chain manipulations that bypass type checks
  • Array/object coercion in numeric contexts

middleBrick's Chi-specific scanner runs these checks automatically:

# Scan a Chi API endpoint for type confusion vulnerabilities
middlebrick scan https://api.example.com/chi-endpoint \
  --type=chi \
  --checks=type-confusion,property-authorization,authentication

# Results include:
# - Type confusion risk score (0-100)
# - Specific vulnerable code paths
# - Remediation guidance for Chi
# - Severity levels for each finding

The scanner also tests for type confusion in API responses, ensuring that data returned to clients doesn't contain objects that can be coerced into unexpected types.

Chi-Specific Remediation

Remediating type confusion in Chi requires a defense-in-depth approach using Chi's native type safety features. The first line of defense is strict type validation using chi::validate_type:

function secureProcessUser(data) {
    // Strict type validation at function entry
    chi::validate_type(data, {
        user: {
            type: "object",
            required: true,
            properties: {
                id: { type: ["number", "string"], required: true },
                admin: { type: "boolean", required: false }
            }
        }
    });
    
    let user = chi::get_property(data, "user");
    let userId = chi::get_property(user, "id");
    
    // Additional runtime validation
    if (typeof userId !== "number" && typeof userId !== "string") {
        throw new Error("Invalid userId type: " + typeof userId);
    }
    
    // Use strict equality and explicit type conversion
    if (parseInt(userId) > 100) {
        return chi::get_property(user, "admin");
    }
    return false;
}

For property access patterns, use Chi's type-safe property retrieval:

function getTypeSafeProperty(obj, prop, expectedType) {
    let value = chi::get_property(obj, prop);
    
    if (value === undefined) {
        throw new Error(`Property ${prop} is undefined`);
    }
    
    let actualType = chi::typeof(value);
    if (actualType !== expectedType) {
        throw new Error(`Type mismatch: expected ${expectedType}, got ${actualType}`);
    }
    
    return value;
}

// Usage
function safeAuthCheck(user) {
    try {
        let id = getTypeSafeProperty(user, "id", "number");
        let role = getTypeSafeProperty(user, "role", "string");
        
        if (role === "admin" && id > 100) {
            return true;
        }
        return false;
    } catch (e) {
        chi::log_security_event("Type confusion prevented", e.message);
        return false;
    }
}

Chi's prototype system requires special handling to prevent prototype pollution attacks that can lead to type confusion:

function secureObjectCreation() {
    let obj = chi::create_object();
    
    // Lock prototype to prevent manipulation
    chi::freeze_prototype(obj);
    
    // Use sealed objects for sensitive data
    let userData = chi::create_object();
    chi::seal_object(userData);
    
    // Only allow specific properties
    chi::define_property(userData, "id", {
        value: 0,
        writable: true,
        configurable: false,
        enumerable: true
    });
    
    return userData;
}

// Safe property setting with type validation
function safeSetProperty(obj, prop, value, expectedType) {
    if (chi::typeof(value) !== expectedType) {
        throw new Error(`Cannot set ${prop}: expected ${expectedType}`);
    }
    
    // Check if property exists and is configurable
    if (!chi::has_property(obj, prop)) {
        throw new Error(`Property ${prop} does not exist`);
    }
    
    chi::set_property(obj, prop, value);
}

For API endpoints, implement comprehensive type checking middleware:

function typeSafeMiddleware(req, res, next) {
    try {
        // Validate request body types
        chi::validate_request(req, {
            body: {
                type: "object",
                properties: {
                    userId: { type: "number" },
                    action: { type: "string" }
                }
            },
            headers: {
                type: "object",
                properties: {
                    "x-auth-token": { type: "string" }
                }
            }
        });
        
        next();
    } catch (e) {
        chi::log_security_event("Type validation failed", e.message);
        res.status(400).json({
            error: "Invalid request format",
            details: e.message
        });
    }
}

// Apply middleware to routes
chi::use(typeSafeMiddleware);
chi::post("/api/user", processUser);

middleBrick's remediation guidance for Chi type confusion includes specific code patterns and configuration recommendations. The scanner provides:

  • Exact line numbers where type confusion occurs
  • Replacement code snippets using Chi's type safety features
  • Configuration for chi::enable_type_assertions
  • Recommendations for using chi::validate_type middleware

The key principle is never to trust dynamic property values without explicit type validation, especially in security-critical contexts like authentication and authorization checks.

Related CWEs: inputValidation

CWE IDNameSeverity
CWE-20Improper Input Validation HIGH
CWE-22Path Traversal HIGH
CWE-74Injection CRITICAL
CWE-77Command Injection CRITICAL
CWE-78OS Command Injection CRITICAL
CWE-79Cross-site Scripting (XSS) HIGH
CWE-89SQL Injection CRITICAL
CWE-90LDAP Injection HIGH
CWE-91XML Injection HIGH
CWE-94Code Injection CRITICAL

Frequently Asked Questions

How does type confusion differ in Chi compared to other languages?
Chi's type coercion rules are more permissive than statically-typed languages, and its prototype-based inheritance system allows for prototype pollution attacks that can lead to type confusion. Unlike JavaScript's strict mode, Chi doesn't have built-in type safety unless explicitly enabled with chi::enable_type_assertions.
Can middleBrick detect type confusion in Chi without access to source code?
Yes, middleBrick uses black-box scanning techniques to detect type confusion patterns through runtime analysis. It sends crafted requests that trigger type coercion and analyzes responses for unexpected behavior, identifying vulnerable code paths without requiring source code access.