CWE-191: Integer Underflow (Wrap or Wraparound)

Description

The product subtracts one value from another, such that the result is less than the minimum allowable integer value, which produces a value that is not equal to the correct result.

Submission Date :

July 19, 2006, midnight

Modification Date :

2023-06-29 00:00:00+00:00

Organization :

MITRE
Extended Description

This can happen in signed and unsigned cases.

Example Vulnerable Codes

Example - 1

The following example subtracts from a 32 bit signed integer.



int i;i = -2147483648;i = i - 1;return 0;
#include <stdio.h>#include <stdbool.h>main (void){}

The example has an integer underflow. The value of i is already at the lowest negative value possible, so after subtracting 1, the new value of i is 2147483647.

Example - 2

This code performs a stack allocation based on a length calculation.


int a = 5, b = 6;size_t len = a - b;char buf[len];    // Just blows up the stack}

Since a and b are declared as signed ints, the "a - b" subtraction gives a negative result (-1). However, since len is declared to be unsigned, len is cast to an extremely large positive number (on 32-bit systems - 4294967295). As a result, the buffer buf[len] declaration uses an extremely large size to allocate on the stack, very likely more than the entire computer's memory space.

Miscalculations usually will not be so obvious. The calculation will either be complicated or the result of an attacker's input to attain the negative value.

Related Weaknesses

This table shows the weaknesses and high level categories that are related to this weakness. These relationships are defined to give an overview of the different insight to similar items that may exist at higher and lower levels of abstraction.

Visit http://cwe.mitre.org/ for more details.