Improper Validation Of Array Index

ID

java.improper_validation_of_array_index

Severity

low

Resource

Injection

Language

Java

Tags

CWE:129, NIST.SP.800-53

Description

Improper neutralization of external input in array index.

Rationale

Improper validation of array index occurs when an array index is not properly checked before being used to access an element in the array. This could result in unexpected behavior or crashes due to out-of-bounds access, commonly resulting in an ArrayIndexOutOfBoundsException. This type of vulnerability can lead to program instability and can potentially be exploited to compromise an application’s integrity.

An example commonly seen in practice is as follows:

public class ArrayIndexExample {
    public static void accessArray(int index) {
        int[] numbers = {0, 1, 2, 3, 4};
        System.out.println("The number is: " + numbers[index]);
    }

    public static void main(String[] args) {
        accessArray(5); // Attempt to access index out of bounds
    }
}

In this snippet, if accessArray is called with an index of 5, it will produce an ArrayIndexOutOfBoundsException because the numbers array only contains five elements, with indices 0 through 4.

Remediation

To remediate improper validation of array index issues in Java, always ensure the index is within the bounds of the array before attempting to access it. You can achieve this by checking that the index is greater than or equal to zero and less than the length of the array.

Here’s the corrected version of the previous example with proper validation:

public class ArrayIndexExample {
    public static void accessArray(int index) {
        int[] numbers = {0, 1, 2, 3, 4};
        if(index >= 0 && index < numbers.length) {
            System.out.println("The number is: " + numbers[index]);
        } else {
            System.out.println("Index out of bounds: " + index);
        }
    }

    public static void main(String[] args) {
        accessArray(5); // Proper handling of out-of-bounds index
    }
}

By implementing these checks, the application will avoid runtime exceptions related to improper array index usage, resulting in a more robust and stable program. It is also advisable to follow good coding practices and have proper exception handling in place to improve program resilience further.

Configuration

The rule has the following configurable parameters:

  • checkArrayInitialSize, that indicates if the array’s initial size improper validation should be checked too.

  • sources, that indicates the source kinds to check.

  • neutralizations, that indicates the neutralization kinds to check.