1769
Example Language: C (Bad)
DataPacket *packet;
int numHeaders;
PacketHeader *headers;
sock=AcceptSocketConnection();
ReadPacket(packet, sock);
numHeaders =packet->headers;
if (numHeaders > 100) {
ExitError("too many headers!");
}
headers = malloc(numHeaders * sizeof(PacketHeader);
ParsePacketHeaders(packet, headers);
The code performs a check to make sure that the packet does not contain too many headers.
However, numHeaders is defined as a signed int, so it could be negative. If the incoming packet
specifies a value such as -3, then the malloc calculation will generate a negative number (say,
-300 if each header can be a maximum of 100 bytes). When this result is provided to malloc(), it is
first converted to a size_t type. This conversion then produces a large value such as 4294966996,
which may cause malloc() to fail or to allocate an extremely large amount of memory (CWE-195).
With the appropriate negative numbers, an attacker could trick malloc() into using a very small
positive number, which then allocates a buffer that is much smaller than expected, potentially
leading to a buffer overflow.
Example 2:
The following code reads a maximum size and performs a sanity check on that size. It then
performs a strncpy, assuming it will not exceed the boundaries of the array. While the use of "short
s" is forced in this particular example, short int's are frequently used within real-world code, such as
code that processes structured data.
Example Language: C (Bad)
int GetUntrustedInt () {
return(0x0000FFFF);
}
void main (int argc, char **argv) {
char path[256];
char *input;
int i;
short s;
unsigned int sz;
i = GetUntrustedInt();
s = i;
/* s is -1 so it passes the safety check - CWE-697 */
if (s > 256) {
DiePainfully("go away!\n");
}
/* s is sign-extended and saved in sz */
sz = s;
/* output: i=65535, s=-1, sz=4294967295 - your mileage may vary */
printf("i=%d, s=%d, sz=%u\n", i, s, sz);
input = GetUserInput("Enter pathname:");
/* strncpy interprets s as unsigned int, so it's treated as MAX_INT
(CWE-195), enabling buffer overflow (CWE-119) */
strncpy(path, input, s);
path[255] = '\0'; /* don't want CWE-170 */
printf("Path is: %s\n", path);
}
This code first exhibits an example of CWE-839, allowing "s" to be a negative number. When the
negative short "s" is converted to an unsigned integer, it becomes an extremely large positive
integer. When this converted integer is used by strncpy() it will lead to a buffer overflow (CWE-119).
Example 3:
CWE Version 4.14
CWE-839: Numeric Range Comparison Without Minimum Check
CWE-839: Numeric Range Comparison Without Minimum Check