1666
The programmer attempts to encode the ampersand character in the user-controlled string.
However, the length of the string is validated before the encoding procedure is applied.
Furthermore, the programmer assumes encoding expansion will only expand a given character by
a factor of 4, while the encoding of the ampersand expands by 5. As a result, when the encoding
procedure expands the string it is possible to overflow the destination buffer if the attacker provides
a string of many ampersands.
Example 5:
In the following C/C++ code, 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.
Example Language: C (Bad)
char* trimTrailingWhitespace(char *strMessage, int length) {
char *retMessage;
char *message = malloc(sizeof(char)*(length+1));
// copy input string to a temporary string
char message[length+1];
int index;
for (index = 0; index < length; index++) {
message[index] = strMessage[index];
}
message[index] = '\0';
// trim trailing whitespace
int len = index-1;
while (isspace(message[len])) {
message[len] = '\0';
len--;
}
// return string without trailing whitespace
retMessage = message;
return retMessage;
}
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.
Example 6:
The following code allocates memory for a maximum number of widgets. It then gets a userspecified
number of widgets, making sure that the user does not request too many. It then
initializes the elements of the array using InitializeWidget(). Because the number of widgets can
vary for each request, the code inserts a NULL pointer to signify the location of the last widget.
Example Language: C (Bad)
int i;
unsigned int numWidgets;
Widget **WidgetList;
numWidgets = GetUntrustedSizeValue();
if ((numWidgets == 0) || (numWidgets > MAX_NUM_WIDGETS)) {
ExitError("Incorrect number of widgets requested!");
}
WidgetList = (Widget **)malloc(numWidgets * sizeof(Widget *));
printf("WidgetList ptr=%p\n", WidgetList);
for(i=0; i<numWidgets; i++) {
WidgetList[i] = InitializeWidget();
}
WidgetList[numWidgets] = NULL;
showWidgets(WidgetList);
CWE Version 4.14
CWE-787: Out-of-bounds Write
CWE-787: Out-of-bounds Write