CWE-704: Incorrect Type Conversion or Cast

Learn about CWE-704 (Incorrect Type Conversion or Cast), its security impact, exploitation methods, and prevention guidelines.

What is Incorrect Type Conversion or Cast?

• Overview: Incorrect Type Conversion or Cast occurs when a program fails to correctly convert data from one type to another, which can lead to unexpected behavior or vulnerabilities.

• Exploitation Methods:

  • Attackers can exploit this by providing data that, when improperly cast, causes the program to behave incorrectly.
  • Common attack patterns include type confusion, where the wrong type is assumed, potentially leading to memory corruption or bypassing security checks.

• Security Impact:

  • Direct consequences include crashes, data corruption, or unauthorized access to data.
  • Potential cascading effects include the ability to execute arbitrary code or escalate privileges.
  • Business impact can involve data breaches, system downtime, or reputational damage.

• Prevention Guidelines:

  • Specific code-level fixes include using explicit type checks and validation before casting.
  • Security best practices involve avoiding unnecessary type casts and using strong typing where possible.
  • Recommended tools and frameworks include static analysis tools to detect improper type conversions and using languages or compilers that enforce stricter type checking.
Corgea can automatically detect and fix Incorrect Type Conversion or Cast in your codebase. [Try Corgea free today](https://corgea.app).

Technical Details

Likelihood of Exploit: Not specified

Affected Languages: C, C++, Not Language-Specific

Affected Technologies: Not specified

Vulnerable Code Example

C Example

// vulnerable.c {7-10}
// This function attempts to read an integer from user input and stores it in a char variable.
// This can lead to incorrect type casting and potential data loss or corruption.
#include <stdio.h>
#include <stdlib.h>

void processInput() {
    char userInput[256];
    int userNumber;
    
    printf("Enter a number: ");
    fgets(userInput, sizeof(userInput), stdin);
    userNumber = atoi(userInput);  // Convert string to integer
    char numberInChar = userNumber; // Incorrect type conversion from int to char

    // Potentially dangerous operation if numberInChar is used for further logic
    printf("You entered: %d\n", numberInChar); // Data loss can occur here
}

int main() {
    processInput();
    return 0;
}

Explanation

In this vulnerable code example, an integer is being read from user input and then converted to a char without checking if the integer value is within the valid range for a char (0 to 127 for unsigned char or -128 to 127 for signed char). This can lead to data loss or incorrect behavior if the integer value is outside this range.

How to fix Incorrect Type Conversion or Cast?

To fix the issue, ensure that the type conversion is safe and does not lead to unexpected data loss or corruption. If you're converting an int to a char, ensure that the value fits within the char range. Alternatively, you can handle the conversion with checks or use appropriate data types that prevent such issues. Additionally, consider using safer functions like sscanf for input parsing to directly store the input in the correct type.

Fixed Code Example

// fixed.c {7-14}
// This function safely reads an integer from user input and handles type conversion appropriately.
#include <stdio.h>

void processInput() {
    char userInput[256];
    int userNumber;
    char numberInChar;

    printf("Enter a number between 0 and 127: ");
    fgets(userInput, sizeof(userInput), stdin);
    
    if (sscanf(userInput, "%d", &userNumber) == 1) {
        if (userNumber >= 0 && userNumber <= 127) { // Ensure safe conversion range
            numberInChar = (char)userNumber; // Explicitly cast with checks
            printf("You entered: %d\n", numberInChar);
        } else {
            printf("Number out of range for char conversion.\n"); // Handle out of range input
        }
    } else {
        printf("Invalid input.\n"); // Handle invalid input
    }
}

int main() {
    processInput();
    return 0;
}

Explanation

In the fixed code, sscanf is used to securely parse the input into an integer. The code then checks that the parsed integer is within the valid range for a char (0 to 127 for this example) before performing the type conversion. This prevents data loss and potential vulnerabilities from incorrect type casting. Additionally, error handling is added to manage invalid inputs and out-of-range values, ensuring robust and secure input processing.

Corgea Logo

Find this vulnerability and fix it with Corgea

Scan your codebase for CWE-704: Incorrect Type Conversion or Cast and get remediation guidance

Start for free and no credit card needed.