CWE-124: Buffer Underwrite ('Buffer Underflow')
Description
The product writes to a buffer using an index or pointer that references a memory location prior to the beginning of the buffer.
Submission Date :
July 19, 2006, midnight
Modification Date :
2023-06-29 00:00:00+00:00
Organization :
MITRE
Extended Description
This typically occurs when a pointer or its index is decremented to a position before the buffer, when pointer arithmetic results in a position before the beginning of the valid memory location, or when a negative index is used.
Example - 1
In the following C/C++ example, a utility function is used to trim trailing whitespace from a character string. The function copies the input string to a local character string and uses a while statement to remove the trailing whitespace by moving backward through the string and overwriting whitespace with a NUL character. However, this function can cause a buffer underwrite if the input character string contains all whitespace. On some systems the while statement will move backwards past the beginning of a character string and will call the isspace() function on an address outside of the bounds of the local buffer.
// // copy input string to a temporary string//
message[index] = strMessage[index];
// // trim trailing whitespace//
message[len] = '\0';len--;
// // return string without trailing whitespace//
char *retMessage;char *message = malloc(sizeof(char)*(length+1));char message[length+1];int index;for (index = 0; index < length; index++) {}message[index] = '\0';int len = index-1;while (isspace(message[len])) {}retMessage = message;return retMessage;char* trimTrailingWhitespace(char *strMessage, int length) {}
Example - 2
The following is an example of code that may result in a buffer underwrite, if find() returns a negative value to indicate that ch is not found in srcBuf: If the index to srcBuf is somehow under user control, this is an arbitrary write-what-where condition.
...strncpy(destBuf, &srcBuf[find(srcBuf, ch)], 1024);...int main() {}
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.