2134
/* capture the sizes of all messages */
int getsizes(int sock, int count, int *sizes) {
...
char buf[BUFFER_SIZE];
int ok;
int num, size;
// read values from socket and added to sizes array
while ((ok = gen_recv(sock, buf, sizeof(buf))) == 0)
{
// continue read from socket until buf only contains '.'
if (DOTLINE(buf))
break;
else if (sscanf(buf, "%d %d", &num, &size) == 2)
sizes[num - 1] = size;
}
...
}
In this example the message number retrieved from the buffer could be a value that is outside the
allowable range of indices for the array and could possibly be a negative number. Without proper
validation of the value to be used for the array index an array overflow could occur and could
potentially lead to unauthorized access to memory addresses and system crashes. The value of
the array index should be validated to ensure that it is within the allowable range of indices for the
array as in the following code.
Example Language: C (Good)
/* capture the sizes of all messages */
int getsizes(int sock, int count, int *sizes) {
...
char buf[BUFFER_SIZE];
int ok;
int num, size;
// read values from socket and added to sizes array
while ((ok = gen_recv(sock, buf, sizeof(buf))) == 0)
{
// continue read from socket until buf only contains '.'
if (DOTLINE(buf))
break;
else if (sscanf(buf, "%d %d", &num, &size) == 2) {
if (num > 0 && num <= (unsigned)count)
sizes[num - 1] = size;
else
/* warn about possible attempt to induce buffer overflow */
report(stderr, "Warning: ignoring bogus data for message sizes returned by server.\n");
}
}
...
}
Example 2:
In the following example the method displayProductSummary is called from a Web service servlet
to retrieve product summary information for display to the user. The servlet obtains the integer
value of the product number from the user and passes it to the displayProductSummary method.
The displayProductSummary method passes the integer value of the product number to the
getProductSummary method which obtains the product summary from the array object containing
the project summaries using the integer value of the product number as the array index.
Example Language: Java (Bad)
// Method called from servlet to obtain product information
public String displayProductSummary(int index) {
String productSummary = new String("");
try {
CWE Version 4.14
CWE-1285: Improper Validation of Specified Index, Position, or Offset in Input
CWE-1285: Improper Validation of Specified Index, Position, or Offset in Input