1770
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 code shows a simple BankAccount class with deposit and withdraw methods.
Example Language: Java (Bad)
public class BankAccount {
public final int MAXIMUM_WITHDRAWAL_LIMIT = 350;
// variable for bank account balance
private double accountBalance;
// constructor for BankAccount
public BankAccount() {
accountBalance = 0;
}
// method to deposit amount into BankAccount
public void deposit(double depositAmount) {...}
// method to withdraw amount from BankAccount
public void withdraw(double withdrawAmount) {
if (withdrawAmount < MAXIMUM_WITHDRAWAL_LIMIT) {
double newBalance = accountBalance - withdrawAmount;
accountBalance = newBalance;
}
else {
System.err.println("Withdrawal amount exceeds the maximum limit allowed, please try again...");
...
}
}
// other methods for accessing the BankAccount object
...
CWE Version 4.14
CWE-839: Numeric Range Comparison Without Minimum Check
CWE-839: Numeric Range Comparison Without Minimum Check