496
The following code is intended to read an incoming packet from a socket and extract one or more
headers.
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 4:
This example processes user input comprised of a series of variable-length structures. The first 2
bytes of input dictate the size of the structure to be processed.
Example Language: C (Bad)
char* processNext(char* strm) {
char buf[512];
short len = *(short*) strm;
strm += sizeof(len);
if (len <= 512) {
memcpy(buf, strm, len);
process(buf);
return strm + len;
}
else {
return -1;
}
}
The programmer has set an upper bound on the structure size: if it is larger than 512, the input will
not be processed. The problem is that len is a signed short, so the check against the maximum
structure length is done with signed values, but len is converted to an unsigned integer for the call
to memcpy() and the negative bit will be extended to result in a huge value for the unsigned integer.
If len is negative, then it will appear that the structure has an appropriate size (the if branch will be
taken), but the amount of memory copied by memcpy() will be quite large, and the attacker will be
able to overflow the stack with data in strm.
Example 5:
In the following example, it is possible to request that memcpy move a much larger segment of
memory than assumed:
Example Language: C (Bad)
int returnChunkSize(void *) {
CWE Version 4.14
CWE-195: Signed to Unsigned Conversion Error
CWE-195: Signed to Unsigned Conversion Error