CWE-704: Incorrect Type Conversion or Cast

Description

The product does not correctly convert an object, resource, or structure from one type to a different type.

Submission Date :

Sept. 9, 2008, midnight

Modification Date :

2023-10-26 00:00:00+00:00

Organization :

MITRE
Example Vulnerable Codes

Example - 1

In this example, depending on the return value of accecssmainframe(), the variable amount can hold a negative value when it is returned. Because the function is declared to return an unsigned value, amount will be implicitly cast to an unsigned number.


int amount = 0;...amount = accessmainframe();...return amount;unsigned int readdata () {}

If the return value of accessmainframe() is -1, then the return value of readdata() will be 4,294,967,295 on a system that uses 32-bit integers.

Example - 2

The following code uses a union to support the representation of different types of messages. It formats messages differently, depending on their type.




char *name;int nameID;int msgType;union {};

// /* This particular value for nameID is used to make the code architecture-independent. If coming from untrusted input, it could be any value. */// 
printf("Message: %s\n", buf.name);
printf("Message: Use ID %d\n", buf.nameID);struct MessageBuffer buf;char *defaultMessage = "Hello World";buf.msgType = NAME_TYPE;buf.name = defaultMessage;printf("Pointer of buf.name is %p\n", buf.name);buf.nameID = (int)(defaultMessage + 1);printf("Pointer of buf.name is now %p\n", buf.name);if (buf.msgType == NAME_TYPE) {}else {}#define NAME_TYPE 1#define ID_TYPE 2struct MessageBuffer{};int main (int argc, char **argv) {}

The code intends to process the message as a NAME_TYPE, and sets the default message to "Hello World." However, since both buf.name and buf.nameID are part of the same union, they can act as aliases for the same memory location, depending on memory layout after compilation.

As a result, modification of buf.nameID - an int - can effectively modify the pointer that is stored in buf.name - a string.

Execution of the program might generate output such as:

Pointer of name is 10830Pointer of name is now 10831Message: ello World

Notice how the pointer for buf.name was changed, even though buf.name was not explicitly modified.

In this case, the first "H" character of the message is omitted. However, if an attacker is able to fully control the value of buf.nameID, then buf.name could contain an arbitrary pointer, leading to out-of-bounds reads or writes.

Related Weaknesses

This table shows the weaknesses and high level categories that are related to this weakness. These relationships are defined to give an overview of the different insight to similar items that may exist at higher and lower levels of abstraction.

Visit http://cwe.mitre.org/ for more details.

© cvefeed.io
Latest DB Update: Dec. 22, 2024 7:08