Improper Validation of Array Index

The product uses untrusted input when calculating or using an array index, but the product does not validate or incorrectly validates the index to ensure the index references a valid position within the array.


Demonstrations

The following examples help to illustrate the nature of this weakness and describe methods or techniques which can be used to mitigate the risk.

Note that the examples here are by no means exhaustive and any given weakness may have many subtle varieties, each of which may require different detection methods or runtime controls.

Example One

In the code snippet below, an untrusted integer value is used to reference an object in an array.

public String getValue(int index) {
  return array[index];
}

If index is outside of the range of the array, this may result in an ArrayIndexOutOfBounds Exception being raised.

Example Two

The following example takes a user-supplied value to allocate an array of objects and then operates on the array.

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 non-negative 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 Three

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

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.

...

// check that the array index is within the correct

// range of values for the array
if (index >= 0 && index < len) {

...

Example Four

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.

/* 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.

/* 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 Five

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.

// 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) {
  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.

// 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.

ArrayList productArray = new ArrayList(MAX_PRODUCTS);
...
try {
  productSummary = (String) productArray.get(index);
} catch (IndexOutOfBoundsException ex) {...}

Example Six

The following example asks a user for an offset into an array to select an item.

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).

See Also

CISQ Quality Measures - Security

Weaknesses in this category are related to the CISQ Quality Measures for Security. Presence of these weaknesses could reduce the security of the software.

Data Validation Issues

Weaknesses in this category are related to a software system's components for input validation, output validation, or other kinds of validation. Validation is a freque...

SEI CERT C Coding Standard - Guidelines 06. Arrays (ARR)

Weaknesses in this category are related to the rules and recommendations in the Arrays (ARR) section of the SEI CERT C Coding Standard.

Comprehensive CWE Dictionary

This view (slice) covers all the elements in CWE.

CISQ Data Protection Measures

This view outlines the SMM representation of the Automated Source Code Data Protection Measurement specifications, as identified by the Consortium for Information & So...

Weaknesses without Software Fault Patterns

CWE identifiers in this view are weaknesses that do not have associated Software Fault Patterns (SFPs), as covered by the CWE-888 view. As such, they represent gaps in...


Common Weakness Enumeration content on this website is copyright of The MITRE Corporation unless otherwise specified. Use of the Common Weakness Enumeration and the associated references on this website are subject to the Terms of Use as specified by The MITRE Corporation.