Programs must not allow mathematical operations to exceed the integer ranges provided by their primitive integer data types. According to The Java Language Specification (JLS), §4.2.2, "Integer Operations" [JLS 2015]:
The built-in integer operators do not indicate overflow or underflow in any way. Integer operators can throw a
NullPointerException
if unboxing conversion of anull
reference is required. Other than that, the only integer operators that can throw an exception are the integer divide operator/
and the integer remainder operator%
, which throw anArithmeticException
if the right-hand operand is zero, and the increment and decrement operators ++ and -- which can throw anOutOfMemoryError
if boxing conversion is required and there is insufficient memory to perform the conversion.
The integral types in Java, representation, and inclusive ranges are shown in the following table taken from the JLS, §4.2.1, "Integral Types and Values" [JLS 2015]:
Wiki Markup |
---|
According to Sun's Secure Coding Guidelines document \[[SCG 07|AA. Java References#SCG 07]\]: |
The (Java) language is type-safe, and the runtime provides automatic memory management and range-checking on arrays. These features also make Java programs immune to the stack-smashing and buffer overflow attacks possible in the C and C++ programming languages, and that have been described as the single most pernicious problem in computer security today.
While this statement is true, arithmetic operations in the Java platform require as much caution as in C and C++. Integer operations can result in overflow because Java does not provide any indication of overflow conditions and silently wraps. While integer overflows in vulnerable C and C++ programs may result in execution of arbitrary code, in Java, wrapped values typically result in incorrect computations and unanticipated outcomes.
Wiki Markup |
---|
According to the Java Language Specification \[[JLS 05|AA. Java References#JLS 05]\], section 4.2.2 Integer Operations: |
The built-in integer operators do not indicate overflow or underflow in any way. Integer operators can throw a
NullPointerException
if unboxing conversion of anull
reference is required. Other than that, the only integer operators that can throw an exception are the integer divide operator/
and the integer remainder operator%
, which throw anArithmeticException
if the right-hand operand is zero, and the increment and decrement operators ++ and -- which can throw anOutOfMemoryError
if boxing conversion is required and there is not sufficient memory available to perform the conversion.
...
Type | Representation | Inclusive Range |
---|---|---|
| 8-bit signed two's-complement | −128 to 127 |
| 16-bit signed two's-complement | −32,768 to 32,767 |
| 32-bit signed two's-complement | −2,147,483,648 to 2,147,483,647 |
| 64-bit signed two's-complement | −9,223,372,036,854,775,808 to 9,223,372,036,854,775,807 |
|
16-bit unsigned integers representing UTF-16 code units |
...
|
The following table shows the integer overflow behavior of the integral operators.
Operator | Overflow | Operator | Overflow | Operator | Overflow | Operator | Overflow | |||
---|---|---|---|---|---|---|---|---|---|---|
| Yes |
| Yes |
| No |
| No | |||
| Yes |
| Yes |
| No |
| No | |||
| Yes |
| Yes |
| No |
| No | |||
| Yes |
| No |
| No |
| No | |||
| No |
| No |
| No |
| No | |||
| Yes |
| No |
| No |
| No | |||
| Yes |
| No |
| No | |||||
| No |
| No | Unary | No | |||||
| Yes |
| No | Unary | Yes |
Because the ranges of Java types are not symmetric (the negation of each minimum value is one more than each maximum value), even operations such as unary negation can overflow if applied to a minimum value. Because the java.lang.math.abs()
method returns the absolute value of any number, it can also overflow if given the minimum int
or long
as an argument.
When a mathematical operation cannot be represented using the supplied integer types, Java's built-in integer operators silently wrap the result without indicating overflow. The silent wrap can result in incorrect computations and unanticipated outcomes. Failure to account for integer overflow has resulted in failures of real systems, for example, when implementing the compareTo()
method. The meaning of the return value of the compareTo()
method is defined only in terms of its sign and whether it is zero; the magnitude of the return value is irrelevant. Consequently, an apparent but incorrect optimization would be to subtract the operands and return the result. For operands of opposite signs, this approach can result in integer overflow, consequently violating the compareTo()
contract [Bloch 2008].
Comparison of Compliant Techniques
Following are the three main techniques for detecting unintended integer overflow:
- Precondition testing. Check the inputs to each arithmetic operator to ensure that overflow cannot occur. Throw an
ArithmeticException
when the operation would overflow if it were performed; otherwise, perform the operation.
- Upcasting. Cast the inputs to the next larger primitive integer type and perform the arithmetic in the larger size. Check each intermediate result for overflow of the original smaller type and throw an
ArithmeticException
if the range check fails. Note that the range check must be performed after each arithmetic operation; larger expressions without per-operation bounds checking can overflow the larger type. Downcast the final result to the original smaller type before assigning to a variable of the original smaller type. This approach cannot be used for typelong
becauselong
is already the largest primitive integer type.
BigInteger
. Convert the inputs into objects of typeBigInteger
and perform all arithmetic usingBigInteger
methods. TypeBigInteger
is the standard arbitrary-precision integer type provided by the Java standard libraries. The arithmetic operations implemented as methods of this type cannot overflow; instead, they produce the numerically correct result. Consequently, compliant code performs only a single range check just before converting the final result to the original smaller type and throws anArithmeticException
if the final result is outside the range of the original smaller type.
The precondition testing technique requires different precondition tests for each arithmetic operation. This approach can be somewhat more difficult to implement and to audit than either of the other two approaches.
The upcast technique is the preferred approach when applicable. The checks it requires are simpler than those of the previous technique; it is substantially more efficient than using BigInteger
. Unfortunately, it cannot be applied to operations involving type long
, as there is no bigger type to upcast to.
The BigInteger
technique is conceptually the simplest of the three techniques because arithmetic operations on BigInteger
cannot overflow. However, it requires the use of method calls for each operation in place of primitive arithmetic operators, which can obscure the intended meaning of the code. Operations on objects of type BigInteger
can also be significantly less efficient than operations on the original primitive integer type.
Precondition Testing
The following code example shows the necessary precondition checks required for each arithmetic operation on arguments of type int
. The checks for the other integral types are analogous. These methods throw an exception when an integer overflow would otherwise occur; any other conforming error handling is also acceptable. Since ArithmeticException
inherits from RuntimeException
, we do not need to declare it in a throws
clause.
Code Block | ||
---|---|---|
| ||
static final int safeAdd(int left, int right) {
if (right > 0 ? left > Integer.MAX_VALUE - right
: left < Integer.MIN_VALUE - right) {
throw new ArithmeticException("Integer overflow");
}
return left + right;
}
static final int safeSubtract(int left, int right) {
if (right > 0 ? left < Integer.MIN_VALUE + right
: left > Integer.MAX_VALUE + right |
Wiki Markup |
---|
According to the Java Language Specification \[[JLS 05|AA. Java References#JLS 05]\], section 4.2.1 "Integral Types and Values", the values of the integral types are integers in the following ranges: |
- For byte, from â“128 to 127, inclusive
- For short, from â“32768 to 32767, inclusive
- For int, from â“2147483648 to 2147483647, inclusive
- For long, from â“9223372036854775808 to 9223372036854775807, inclusive
- For char, from '\u0000' to '\uffff' inclusive, that is, from 0 to 65535
The table shown below enlists the operators that can lead to overflows:
Operator | Overflow |
| Operator | Overflow |
| Operator | Overflow |
| Operator | Overflow |
---|---|---|---|---|---|---|---|---|---|---|
yes |
| yes |
| no |
| | no | |||
yes |
| yes |
| | no |
| | no | ||
yes |
| yes |
| | no |
| | no | ||
yes |
| no |
| \ | no |
| | no | ||
no |
| no |
| | no |
| | no | ||
| yes |
| | no |
| | no |
| | no |
| yes |
| | no |
| | no |
| | no |
| no |
| | no |
| un | no |
| || | no |
yes |
| | no |
| yes |
| | no |
Wiki Markup |
---|
Failing to account for integer overflow has resulted in failures in real systems, for instance, when implementing the {{compareTo()}} method. The {{compareTo()}} method does not care about the magnitude of the operands but only about the sign. Consequently, an optimization is to simply subtract the operands and return the result. For nonpositive operands, this can result in integer overflow and violation of the {{compareTo()}} contract. \[[Bloch 08, item 12|AA. Java References#Bloch 08]\] |
Addition
Addition (as with all arithmetic operations) in Java is performed on signed numbers only as unsigned numbers are unsupported. One exception is the unsigned char
type. Performing arithmetic operations that use operands of type char
is strongly discouraged.
Noncompliant Code Example
In this noncompliant code example, the result of the addition can overflow.
Code Block | ||
---|---|---|
| ||
public int do_operation(int a, int b){
// May result in overflow
int temp = a + b;
return temp;
}
|
If the result of the addition is greater than the maximum value or less than the minimum value that can be represented as an int
, then the variable temp
will contain an erroneous result. This does not apply to shorter types such as byte
and short
because the operands are promoted to an int
before the operation is carried out in cases where the value may not be representable. The compiler disallows storing the result of such an operation in a variable of type shorter than an int
.
Compliant Solution (Bounds Checking)
Explicitly check the range of each arithmetic operation and throw an ArithmeticException
on overflow. When performing operations on values of type int
, the arithmetic can be performed using variables of type long
. For performing arithmetic operations on numbers of type long
, the BigInteger
Class must be used.
Because a variable of the long
type is guaranteed to hold the result of an addition, subtraction or multiplication of values of type int
, the result can be assigned to such a variable, and if the result is in the integer range, we can simply downcast it to a value of type int
.
Compliant Solution (Use long
and Downcast)
This compliant solution uses a variable of type long
to store the result of the addition and proceeds to range check its value.
If the value cannot be represented in a variable of type int
, it throws an ArithmeticException
. Otherwise, it down casts the result to a value of type int
.
Code Block | ||
---|---|---|
| ||
public int do_operation(int a, int b) throws ArithmeticException {
long temp = (long)a + (long)b;
if (temp > Integer.MAX_VALUE || temp < Integer.MIN_VALUE) {
throw new ArithmeticException("Out of range");
}
return (int)temp; // Value within range; can perform the addition
}
|
Compliant Solution (Bounds Checking)
This compliant solution range checks the operand values to ensure that the result does not overflow.
Code Block | ||
---|---|---|
| ||
public int do_operation(int a, int b) throws ArithmeticException { if( b > 0 ? a > Integer.MAX_VALUE - b : a < Integer.MIN_VALUE - b ) { throw new ArithmeticException("NotInteger in rangeoverflow"); } return aleft +- bright; } static final // Value within range so addition can be performed } |
Compliant Solution (Use BigInteger Class)
This compliant solution uses the BigInteger
class as a wrapper to test for the overflow.
Code Block | ||
---|---|---|
| ||
public boolean overflow(long a, long b) { BigInteger ba = new BigInteger(String.valueOf(a)); BigInteger bb = new BigInteger(String.valueOf(b)); BigInteger br = ba.add(bb); return (br.compareTo(BigInteger.valueOf(Long.MAX_VALUE)) == 1 || int safeMultiply(int left, int right) { if (right > 0 ? left > Integer.MAX_VALUE/right || left < Integer.MIN_VALUE/right : br.compareTo(BigInteger.valueOf(Long(right < -1 ? left > Integer.MIN_VALUE)) == -1); } public long do_operation(long a, long b) throws ArithmeticException { if(overflow(a,b)) { /right throw new ArithmeticException("Not in range");|| left < Integer.MAX_VALUE/right } // Within range; safely perform the addition return a + b; } |
With use of the BigInteger
class, integer overflows are eliminated. However, due to increased performance costs, it should be used only when other methods are not appropriate.
Subtraction
Care must be taken while performing the subtraction operation as well because overflows (or underflows) are possible.
Noncompliant Code Example
In this noncompliant code example, the subtraction operation may overflow negatively when a
is a negative integer and b
is a large positive integer such that their sum is not representable as a value of type int
. It can also overflow when a
is positive and b
is negative and their sum is not representable as a value of type int
.
Code Block | ||
---|---|---|
| ||
public int do_operation(int a, int b : right == -1 && left == Integer.MIN_VALUE) ) { throw new ArithmeticException("Integer overflow"); } return left * right; } static final int safeDivide(int left, int right) { if ((left == Integer.MIN_VALUE) && (right == -1)) { int temp =throw a - bnew ArithmeticException("Integer overflow"); //} Could resultreturn inleft overflow return temp/ right; } |
Compliant Solution (Use Long)
This compliant solution suggests explicit range checking before performing the subtraction.
Code Block | ||
---|---|---|
| ||
public int do_operation(int a,int b static final int safeNegate(int a) { if (a == Integer.MIN_VALUE) { long tempthrow =new ArithmeticException(long)a - (long)b"Integer overflow"); } if(temp < Integer.MIN_VALUE || temp > Integer.MAXreturn -a; } static final int safeAbs(int a) { if (a == Integer.MIN_VALUE) { throw new ArithmeticException("NotInteger in rangeoverflow"); } return Math.abs(inta) temp; } |
Compliant Solution (Bounds Checking)
These method calls are likely to be inlined by most just-in-time (JIT) systems.
These checks can be simplified when the original type is char
. Because the range of type char
includes only positive values, all comparisons with negative values may be omitted.
Noncompliant Code Example
Either operation in this noncompliant code example could result in an overflow. When overflow occurs, the result will be incorrectThis compliant solution uses range checking to ensure that the result will not overflow.
Code Block | ||
---|---|---|
| ||
public static int do_operationmultAccum(int aoldAcc, int b)newVal, throwsint ArithmeticExceptionscale) { if(b > 0 ? a < Integer.MIN_VALUE + b : a > Integer.MAX_VALUE + b ) { throw new ArithmeticException("Not in range"); } return a - b; // Value within range; can perform the addition// May result in overflow return oldAcc + (newVal * scale); } |
Compliant Solution (Precondition Testing)
This compliant solution uses the safeAdd()
and safeMultiply()
methods defined in the "Precondition Testing" section to perform secure integral operations or throw ArithmeticException
on overflow:
Code Block | ||
---|---|---|
| ||
public static int multAccum(int oldAcc, int newVal, int scale) {
return safeAdd(oldAcc, safeMultiply(newVal, scale));
}
|
Compliant Solution (
...
Java 8, Math.*Exact()
)
This compliant solution uses the addExact()
and multiplyExact()
methods defined in the Math
class. These methods were added to Java as part of the Java 8 release, and they also either return a mathematically correct value or throw ArithmeticException
. The Math
class also provides SubtractExact()
and negateExact()
but does not provide any methods for safe division or absolute value.
The BigInteger
class can be used as a overflow-test wrapper as shown in this compliant solution.
Code Block | ||
---|---|---|
| ||
public booleanstatic int underflow(long a, long bmultAccum(int oldAcc, int newVal, int scale) { BigInteger ba = new BigInteger(String.valueOf(a)); BigInteger bb = new BigInteger(String.valueOf(b)); BigInteger br = ba.subtract(bb); return (br.compareTo(BigInteger.valueOf(return Math.addExact(oldAcc, Math.multiplyExact(newVal, scale)); } |
Compliant Solution (Upcasting)
This compliant solution shows the implementation of a method for checking whether a value of type long
falls within the representable range of an int
using the upcasting technique. The implementations of range checks for the smaller primitive integer types are similar.
Code Block | ||
---|---|---|
| ||
public static long intRangeCheck(long value) { if ((value < Integer.MIN_VALUE) || (value > IntegerLong.MAX_VALUE)) == 1 ||{ throw new ArithmeticException("Integer overflow"); br.compareTo(BigInteger.valueOf(Long.MIN_VALUE)) == -1)} return value; } public long do_operation(long a, long b) throws ArithmeticExceptionstatic int multAccum(int oldAcc, int newVal, int scale) { if(underflow(a,b)) { throw new ArithmeticException("Not in range"); } // Within range; safely perform the subtraction return a - b; } |
Multiplication
This noncompliant code example can result in a signed integer overflow during the multiplication of the signed operands a
and b
. If this behavior is unanticipated, the resulting value may lead to undefined behavior.
Noncompliant Code Example
Code Block | ||
---|---|---|
| ||
int a, b, result
//do stuff
result = a * b; // May result in overflow
|
Compliant Solution
Because the size of the type long
(64 bits) is twice the size of the type int
(32 bits), the multiplication should be performed using a variable of type long
. If the product is in the range of the int
type, it can be safely downcast to a value of type int
.
final long res = intRangeCheck(
((long) oldAcc) + intRangeCheck((long) newVal * (long) scale)
);
return (int) res; // Safe downcast
}
|
Note that this approach cannot be applied to values of type long
because long
is the largest primitive integral type. Use the BigInteger
technique instead when the original variables are of type long
.
Compliant Solution (BigInteger
)
This compliant solution uses the BigInteger
technique to detect overflow:
Code Block | ||
---|---|---|
| ||
private static final BigInteger bigMaxInt =
BigInteger.valueOf(Integer.MAX_VALUE);
private static final BigInteger bigMinInt =
BigInteger.valueOf(Integer.MIN_VALUE);
public static BigInteger intRangeCheck(BigInteger val) {
if (val.compareTo(bigMaxInt) == 1 ||
val.compareTo(bigMinInt) == -1) {
| ||
Code Block | ||
| ||
int a, b, result; long temp = (long) a * (long)b; if(temp > Integer.MAX_VALUE || temp < Integer.MIN_VALUE) { throw new ArithmeticException("NotInteger in rangeoverflow"); // Overflow } result = (int)return tempval; // Value within range, safe to downcast |
Division
Although Java throws a java.lang.ArithmeticException
for division by zero, the same issue as with C/C++ manifests, while dividing the Integer.MIN_VALUE
by -1. It produces Integer.MIN_VALUE
unexpectedly (as the result is -(Integer.MIN_VALUE) = Integer.MAX_VALUE + 1
)).
Noncompliant Code Example
This noncompliant code example divides a
and b
without checking the range of the result.
Code Block | ||
---|---|---|
| ||
int a;
int b;
int result;
result = a/b;
|
Compliant Solution
This compliant solution handles the special case of Integer.MIN_VALUE
and -1
being used as the dividend and divisor, respectively.
Code Block | ||
---|---|---|
| ||
if(a == Integer.MIN_VALUE && b == -1) {
throw new ArithmeticException("Not in range"); // May be Integer.MIN_VALUE and -1
}
result = a/b; // Safe operation
|
Remainder Operator
The remainder operator in Java has the following behavior for corner cases:
- If the modulo of
Integer.MIN_VALUE
with -1 is taken the result is always 0.
- If the right-hand operand is zero, then the integer remainder operator % will throw an
ArithmeticException
.
- The sign of the remainder is always the same as that of the dividend. For example,
-3
%-2
results in the value-1
. This behavior can sometimes be deceptive.
Refer to INT02-J. Do not assume a positive remainder when using the remainder operator for more details.
Unary Negation
If Integer.MIN_VALUE
is negated, the same value Integer.MIN_VALUE
is obtained. Range checking is important in this case as well.
Noncompliant Code Example
This noncompliant code example tries to negate the result without checking whether it is Integer.MIN_VALUE
.
Code Block | ||
---|---|---|
| ||
int temp = -result;
|
Compliant Solution
This compliant solution explicitly checks whether the input is Integer.MIN_VALUE
and throws an exception if it is; otherwise, it negates the result.
Code Block | ||
---|---|---|
| ||
if(result == Integer.MIN_VALUE) {
throw new ArithmeticException("Not in range");
}
temp = -result;
|
Absolute Value
A related pitfall is the use of the Math.abs()
method that takes a parameter of type int
and returns its absolute value. Because of the asymmetry between the representation of negative and positive integer values (Integer.MAX_VALUE
is 2147483647 and Integer.MIN_VALUE
is -2147483648, which means there is one more negative integer than positive integers), there is no equivalent positive value (+2147483648) for Integer.MIN_VALUE
.
Shifting
The shift operation in Java has the following properties:
- The right shift is an arithmetic shift
- The types
boolean, float and double
cannot use the bit shifting operators.
- If the value to be shifted is of type
int
, only the five lowest-order bits of the right-hand operand are used as the shift distance. That is, the shift distance is the value of the right-hand operand masked by 31 (0x1F). This results in a value modulo 31, inclusive.
Wiki Markup When the value to be shifted (left-operand) is of type {{long}}, only the last 6 bits of the right-hand operand are used to perform the shift. The shift distance is the value of the right-hand operand masked by 63 (0x3D) \[[JLS 03|AA. Java References#JLS 03]\], i.e., it is always between 0 and 63. (If the shift value is greater than 64, then the shift is {{value % 64}}.)
Refer to INT05-J. Use shift operators correctly for further details about the behavior of the shift operators.
Noncompliant Code Example
Wiki Markup |
---|
This noncompliant code example attempts to shift the value {{i}} of type {{int}} until, after 32 iterations, the value becomes 0. Unfortunately, this loop never terminates because an attempt to shift a value of type {{int}} by 32 bits results in the original value rather than the value 0. \[[Bloch 05|AA. Java References#Bloch 05]\] |
Code Block | ||
---|---|---|
| ||
int i = 0;
while ((-1 << i) != 0)
i++;
|
Compliant Solution
This compliant solution initially sets the value val
to -1 and repeatedly shifts the value by one place on each successive iteration.
Code Block | ||
---|---|---|
| ||
for (int val = -1; val != 0; val <<= 1) { /* ... */ }
|
Noncompliant Code Example (Concurrent code)
This noncompliant code example uses an AtomicInteger
which is part of the concurrency utilities. The concurrency utilities do not enforce checks for integer overflow.
Code Block | ||
---|---|---|
| ||
class InventoryManager {
private final AtomicInteger itemsInInventory = new AtomicInteger(100);
//...
public final void returnItem() {
itemsInInventory++;
}
}
|
Consequently, itemsInInventory
may wrap around to Integer.MIN_VALUE
after the increment operation.
Noncompliant Code Example (Concurrent code - TOCTOU condition in check)
This noncompliant code example install a check for integer overflow, however, there is a time-of-check-time-of-use vulnerability between the check and the increment operation.
Code Block | ||
---|---|---|
| ||
class InventoryManager {
private volatile int itemsInInventory = 100;
// ...
public final void returnItem() {
if (itemsInInventory == Integer.MAX_VALUE) {
throw new IllegalStateException("Out of bounds");
}
itemsInInventory++;
}
}
|
Compliant Solution (java.util.concurrent.atomic classes
)
The java.util.concurrent
utilities can be used to atomically manipulate a shared variable. This compliant solution defines intemsInInventory
as a java.util.concurrent.atomic.AtomicInteger
variable, allowing composite operations to be performed atomically.
Code Block | ||
---|---|---|
| ||
class InventoryManager {
private final AtomicInteger itemsInInventory = new AtomicInteger(100);
public final void returnItem() {
while (true) {
int old = itemsInInventory.get();
if (old == Integer.MAX_VALUE) {
throw new IllegalStateException("Out of bounds");
}
int next = old + 1; // Decrement
if (itemsInInventory.compareAndSet(old, next)) {
break;
}
} // end while
} // end removeItem()
}
|
Wiki Markup |
---|
The {{compareAndSet()}} method takes two arguments, the expected value of a variable when the method is invoked and the updated value. This compliant solution uses this method to atomically set the value of {{itemsInInventory}} to the updated value if and only if the current value equals the expected value \[[API 06|AA. Java References#API 06]\]. The while loop ensures that the {{removeItem()}} method succeeds in decrementing the most recent value of {{itemsInInventory}} as long as the inventory count is greater than {{MIN_INVENTORY}}. Refer to [CON01-J. Ensure that compound operations on shared variables are atomic] for more details. |
Exceptions
EX1: Depending on the functionality, integer overflow may be benign. For instance, the Object.hashcode()
method may return all representable values of type int
.
Risk Assessment
Failure to perform explicit range checking can lead to integer overflows causing unexpected program control flow or unanticipated program behavior.
Rule | Severity | Likelihood | Remediation Cost | Priority | Level |
---|---|---|---|---|---|
INT00- J | medium | unlikely | medium | P4 | L3 |
Automated Detection
TODO
Related Vulnerabilities
Search for vulnerabilities resulting from the violation of this rule on the CERT website.
Other Languages
This rule appears in the C Secure Coding Standard as INT32-C. Ensure that operations on signed integers do not result in overflow.
This rule appears in the C++ Secure Coding Standard as INT32-CPP. Ensure that operations on signed integers do not result in overflow.
References
Wiki Markup |
---|
\[[SCG 07|AA. Java References#SCG 07]\] Introduction
\[[JLS 03|AA. Java References#JLS 03]\] 4.2.2 Integer Operations and 15.22 Bitwise and Logical Operators
\[[Tutorials 08|AA. Java References#Tutorials 08]\] Primitive Data Types
\[[Seacord 05|AA. Java References#Seacord 05]\] Chapter 5. Integers
\[[Bloch 05|AA. Java References#Bloch 05]\] Puzzle 27: Shifty i's
\[[MITRE 09|AA. Java References#MITRE 09]\] [CWE ID 682|http://cwe.mitre.org/data/definitions/682.html] "Incorrect Calculation", [CWE ID 190|http://cwe.mitre.org/data/definitions/190.html] "Integer Overflow or Wraparound", [CWE ID 191|http://cwe.mitre.org/data/definitions/191.html] "Integer Underflow (Wrap or Wraparound)" |
}
public static int multAccum(int oldAcc, int newVal, int scale) {
BigInteger product =
BigInteger.valueOf(newVal).multiply(BigInteger.valueOf(scale));
BigInteger res =
intRangeCheck(BigInteger.valueOf(oldAcc).add(product));
return res.intValue(); // Safe conversion
}
|
Noncompliant Code Example (AtomicInteger
)
Operations on objects of type AtomicInteger
suffer from the same overflow issues as other integer types. The solutions are generally similar to the solutions already presented; however, concurrency issues add additional complications. First, potential issues with time-of-check, time-of-use (TOCTOU) must be avoided (see VNA02-J. Ensure that compound operations on shared variables are atomic for more information). Second, use of an AtomicInteger
creates happens-before relationships between the various threads that access it. Consequently, changes to the number of accesses or order of accesses can alter the execution of the overall program. In such cases, you must either choose to accept the altered execution or carefully craft your implementation to preserve the exact number of accesses and order of accesses to the AtomicInteger
.
This noncompliant code example uses an AtomicInteger
, which is part of the concurrency utilities. The concurrency utilities lack integer overflow checks.
Code Block | ||
---|---|---|
| ||
class InventoryManager {
private final AtomicInteger itemsInInventory = new AtomicInteger(100);
//...
public final void nextItem() {
itemsInInventory.getAndIncrement();
}
}
|
Consequently, itemsInInventory
can wrap around to Integer.MIN_VALUE
when the nextItem()
method is invoked when itemsInInventory == Integer.MAX_VALUE
.
Compliant Solution (AtomicInteger
)
This compliant solution uses the get()
and compareAndSet()
methods provided by AtomicInteger
to guarantee successful manipulation of the shared value of itemsInInventory
. This solution has the following characteristics:
- The number and order of accesses to
itemsInInventory
remain unchanged from the noncompliant code example. - All operations on the value of
itemsInInventory
are performed on a temporary local copy of its value. - The overflow check in this example is performed in inline code rather than encapsulated in a method call. This is an acceptable alternative implementation. The choice of method call versus inline code should be made according to your organization's standards and needs.
Code Block | ||
---|---|---|
| ||
class InventoryManager {
private final AtomicInteger itemsInInventory =
new AtomicInteger(100);
public final void nextItem() {
while (true) {
int old = itemsInInventory.get();
if (old == Integer.MAX_VALUE) {
throw new ArithmeticException("Integer overflow");
}
int next = old + 1; // Increment
if (itemsInInventory.compareAndSet(old, next)) {
break;
}
} // End while
} // End nextItem()
}
|
The two arguments to the compareAndSet()
method are the expected value of the variable when the method is invoked and the intended new value. The variable's value is updated only when the current value and the expected value are equal [API 2006] (refer to VNA02-J. Ensure that compound operations on shared variables are atomic for more details).
Exceptions
NUM00-J-EX0: Depending on circumstances, integer overflow could be benign. For example, many algorithms for computing hash codes use modular arithmetic, intentionally allowing overflow to occur. Such benign uses must be carefully documented.
NUM00-J-EX1: Prevention of integer overflow is unnecessary for numeric fields that undergo bitwise operations and not arithmetic operations (see NUM01-J. Do not perform bitwise and arithmetic operations on the same data for more information).
Risk Assessment
Failure to perform appropriate range checking can lead to integer overflows, which can cause unexpected program control flow or unanticipated program behavior.
Rule | Severity | Likelihood | Remediation Cost | Priority | Level |
---|---|---|---|---|---|
NUM00-J | Medium | Unlikely | Medium | P4 | L3 |
Automated Detection
Automated detection of integer operations that can potentially overflow is straightforward. Automatic determination of which potential overflows are true errors and which are intended by the programmer is infeasible. Heuristic warnings might be helpful.
Tool | Version | Checker | Description | ||||||
---|---|---|---|---|---|---|---|---|---|
CodeSonar |
| JAVA.MATH.ABSRAND | Abs on random (Java) | ||||||
Coverity | 7.5 | BAD_SHIFT | Implemented | ||||||
Parasoft Jtest |
| CERT.NUM00.ICO CERT.NUM00.BSA CERT.NUM00.CACO | Avoid calculations which result in overflow or NaN Do not use an integer outside the range of [0, 31] as the amount of a shift Avoid using compound assignment operators in cases which may cause overflow | ||||||
PVS-Studio |
| V5308, V6117 |
Related Guidelines
INT32-C. Ensure that operations on signed integers do not result in overflow | |
Wrap-around Error [XYY] | |
CWE-682, Incorrect Calculation |
Android Implementation Details
Mezzofanti for Android contained an integer overflow that prevented the use of a big SD card. Mezzofanti contained an expression:
(int) StatFs.getAvailableBlocks() * (int) StatFs.getBlockSize()
to calculate the available memory in an SD card, which could result in a negative value when the available memory is larger than Integer.MAX_VALUE
. Note that these methods are deprecated in API level 18 and replaced by getAvailableBlocksLong()
and getBlockSizeLong()
.
Bibliography
[API 2006] | Class |
Puzzle 27, "Shifty i's" | |
[Bloch 2008] | Item 12, "Minimize the Accessibility of Classes and Members" |
[JLS 2015] | §4.2.1, "Integral Types and Values" |
Chapter 5, "Integers" | |
[Seacord 2015] |
...
06. Integers (INT) 06. Integers (INT) INT01-J. Range check before casting integers to narrower types