346
Example Language: Java (Bad)
private void buildList ( int untrustedListSize ){
if ( 0 > untrustedListSize ){
die("Negative value supplied for list size, die evil hacker!");
}
Widget[] list = new Widget [ untrustedListSize ];
list[0] = new Widget();
}
This example attempts to build a list from a user-specified value, and even checks to ensure a nonnegative
value is supplied. If, however, a 0 value is provided, the code will build an array of size 0
and then try to store a new Widget in the first location, causing an exception to be thrown.
Example 3:
In the following code, the method retrieves a value from an array at a specific array index location
that is given as an input parameter to the method
Example Language: C (Bad)
int getValueFromArray(int *array, int len, int index) {
int value;
// check that the array index is less than the maximum
// length of the array
if (index < len) {
// get the value at the specified index of the array
value = array[index];
}
// if array index is invalid then output error message
// and return value indicating error
else {
printf("Value is: %d\n", array[index]);
value = -1;
}
return value;
}
However, this method only verifies that the given array index is less than the maximum length of
the array but does not check for the minimum value (CWE-839). This will allow a negative value
to be accepted as the input array index, which will result in a out of bounds read (CWE-125) and
may allow access to sensitive memory. The input array index should be checked to verify that is
within the maximum and minimum range required for the array (CWE-129). In this example the if
statement should be modified to include a minimum range check, as shown below.
Example Language: C (Good)
...
// check that the array index is within the correct
// range of values for the array
if (index >= 0 && index < len) {
...
Example 4:
The following example retrieves the sizes of messages for a pop3 mail server. The message sizes
are retrieved from a socket that returns in a buffer the message number and the message size,
the message number (num) and size (size) are extracted from the buffer and the message size is
placed into an array using the message number for the array index.
Example Language: C (Bad)
/* capture the sizes of all messages */
int getsizes(int sock, int count, int *sizes) {
CWE Version 4.14
CWE-129: Improper Validation of Array Index
CWE-129: Improper Validation of Array Index