CWE-786: Access of Memory Location Before Start of Buffer
Description
The product reads or writes to a buffer using an index or pointer that references a memory location prior to the beginning of the buffer.
Submission Date :
Oct. 21, 2009, 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 example asks a user for an offset into an array to select an item. The programmer allows the user to specify which element in the list to select, however an attacker can provide an out-of-bounds offset, resulting in a buffer over-read (CWE-126).
char *items[] = {"boat", "car", "truck", "train"};int index = GetUntrustedOffset();printf("You selected %s\n", items[index-1]);int main (int argc, char **argv) {}
Example - 3
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.