348
return productSummary;
}
public String getProductSummary(int index) {
return products[index];
}
In this example the integer value used as the array index that is provided by the user may be
outside the allowable range of indices for the array which may provide unexpected results or cause
the application to fail. The integer value used for 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: Java (Good)
// Method called from servlet to obtain product information
public String displayProductSummary(int index) {
String productSummary = new String("");
try {
String productSummary = getProductSummary(index);
} catch (Exception ex) {...}
return productSummary;
}
public String getProductSummary(int index) {
String productSummary = "";
if ((index >= 0) && (index < MAX_PRODUCTS)) {
productSummary = products[index];
}
else {
System.err.println("index is out of bounds");
throw new IndexOutOfBoundsException();
}
return productSummary;
}
An alternative in Java would be to use one of the collection objects such as ArrayList that will
automatically generate an exception if an attempt is made to access an array index that is out of
bounds.
Example Language: Java (Good)
ArrayList productArray = new ArrayList(MAX_PRODUCTS);
...
try {
productSummary = (String) productArray.get(index);
} catch (IndexOutOfBoundsException ex) {...}
Example 6:
The following example asks a user for an offset into an array to select an item.
Example Language: C (Bad)
int main (int argc, char **argv) {
char *items[] = {"boat", "car", "truck", "train"};
int index = GetUntrustedOffset();
printf("You selected %s\n", items[index-1]);
}
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).
Observed Examples
Reference Description
CVE-2005-0369 large ID in packet used as array index
CWE Version 4.14
CWE-129: Improper Validation of Array Index
CWE-129: Improper Validation of Array Index