Numeric Range Comparison Without Minimum Check

The program checks a value to ensure that it is less than or equal to a maximum, but it does not also verify that the value is greater than or equal to the minimum.


Description

Some programs use signed integers or floats even when their values are only expected to be positive or 0. An input validation check might assume that the value is positive, and only check for the maximum value. If the value is negative, but the code assumes that the value is positive, this can produce an error. The error may have security consequences if the negative value is used for memory allocation, array access, buffer access, etc. Ultimately, the error could lead to a buffer overflow or other type of memory corruption.

The use of a negative number in a positive-only context could have security implications for other types of resources. For example, a shopping cart might check that the user is not requesting more than 10 items, but a request for -3 items could cause the application to calculate a negative price and credit the attacker's account.

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

The following code is intended to read an incoming packet from a socket and extract one or more headers.

DataPacket *packet;
int numHeaders;
PacketHeader *headers;

sock=AcceptSocketConnection();
ReadPacket(packet, sock);
numHeaders =packet->headers;

if (numHeaders > 100) {
  ExitError("too many headers!");
}
headers = malloc(numHeaders * sizeof(PacketHeader);
ParsePacketHeaders(packet, headers);

The code performs a check to make sure that the packet does not contain too many headers. However, numHeaders is defined as a signed int, so it could be negative. If the incoming packet specifies a value such as -3, then the malloc calculation will generate a negative number (say, -300 if each header can be a maximum of 100 bytes). When this result is provided to malloc(), it is first converted to a size_t type. This conversion then produces a large value such as 4294966996, which may cause malloc() to fail or to allocate an extremely large amount of memory (CWE-195). With the appropriate negative numbers, an attacker could trick malloc() into using a very small positive number, which then allocates a buffer that is much smaller than expected, potentially leading to a buffer overflow.

Example Two

The following code reads a maximum size and performs a sanity check on that size. It then performs a strncpy, assuming it will not exceed the boundaries of the array. While the use of "short s" is forced in this particular example, short int's are frequently used within real-world code, such as code that processes structured data.

int GetUntrustedInt () {
  return(0x0000FFFF);
}

void main (int argc, char **argv) {

  char path[256];
  char *input;
  int i;
  short s;
  unsigned int sz;

  i = GetUntrustedInt();
  s = i;
  /* s is -1 so it passes the safety check - CWE-697 */
  if (s > 256) {
    DiePainfully("go away!\n");
  }

  /* s is sign-extended and saved in sz */
  sz = s;

  /* output: i=65535, s=-1, sz=4294967295 - your mileage may vary */
  printf("i=%d, s=%d, sz=%u\n", i, s, sz);

  input = GetUserInput("Enter pathname:");

  /* strncpy interprets s as unsigned int, so it's treated as MAX_INT
  (CWE-195), enabling buffer overflow (CWE-119) */
  strncpy(path, input, s);
  path[255] = '\0'; /* don't want CWE-170 */
  printf("Path is: %s\n", path);

}

This code first exhibits an example of CWE-839, allowing "s" to be a negative number. When the negative short "s" is converted to an unsigned integer, it becomes an extremely large positive integer. When this converted integer is used by strncpy() it will lead to a buffer overflow (CWE-119).

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 code shows a simple BankAccount class with deposit and withdraw methods.

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

}

The withdraw method includes a check to ensure that the withdrawal amount does not exceed the maximum limit allowed, however the method does not check to ensure that the withdrawal amount is greater than a minimum value (CWE-129). Performing a range check on a value that does not include a minimum check can have significant security implications, in this case not including a minimum range check can allow a negative value to be used which would cause the financial application using this class to deposit money into the user account rather than withdrawing. In this example the if statement should the modified to include a minimum range check, as shown below.

public class BankAccount {


  public final int MINIMUM_WITHDRAWAL_LIMIT = 0;
  public final int MAXIMUM_WITHDRAWAL_LIMIT = 350;

  ...

  // method to withdraw amount from BankAccount
  public void withdraw(double withdrawAmount) {


    if (withdrawAmount < MAXIMUM_WITHDRAWAL_LIMIT &&
    withdrawAmount > MINIMUM_WITHDRAWAL_LIMIT) {


      ...

Note that this example does not protect against concurrent access to the BankAccount balance variable, see CWE-413 and CWE-362.

While it is out of scope for this example, note that the use of doubles or floats in financial calculations may be subject to certain kinds of attacks where attackers use rounding errors to steal money.

See Also

Numeric Errors

Weaknesses in this category are related to improper calculation or conversion of numbers.

Comprehensive CWE Dictionary

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

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

CWE Cross-section

This view contains a selection of weaknesses that represent the variety of weaknesses that are captured in CWE, at a level of abstraction that is likely to be useful t...


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.