Versions Compared

Key

  • This line was added.
  • This line was removed.
  • Formatting was changed.

...

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 has been described as the single most pernicious problem in computer security today.

While this statement is true, arithmetic operations in the Java platform require just as much caution as in C and C++ as do because integer operations can result in overflow. Java does not provide any indication of overflow conditions and silently wraps. While integer overflows in vulnerable C and C++ programs may can result in the execution of arbitrary code, ; in Java, wrapped values typically result in incorrect computations and unanticipated outcomes.

According to the Java Language Specification, 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 a null 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 an ArithmeticException if the right-hand operand is zero, and the increment and decrement operators ++ and -- which can throw an OutOfMemoryError if boxing conversion is required and there is not sufficient memory available to perform the conversion.

...

According to the Java Language Specification, Section 4.2.1, "Integral Types and Values," the values of the integral types are integers in the following ranges:

...

Wiki Markup
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 signsigns, this can result in integer overflow;, consequently violating the {{compareTo()}} contract \[[Bloch 2008, itemItem 12|AA. Bibliography#Bloch 08]\].

...

The three main techniques for detecting unintended integer overflow are:

  • Pre-condition testing of the inputs. 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, otherwise perform the operation. We call this technique "Pre-condition the inputs" hereafter, for convenience.
  • Use a larger type and downcast. 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; throw an ArithmeticException if the range check fails. Note that the range check must be performed after each arithmetic operation. Downcast the final result to the original smaller type before assigning to the result variable. This approach cannot be use for type long, because long is already the largest primitive integer type.
  • Use BigInteger. Convert the inputs into objects of type BigInteger and perform all arithmetic using BigInteger methods. Throw an ArithmeticException if the final result is outside the range of the original smaller type; otherwise, otherwise convert back to the intended result type.

...

The "Use BigInteger" technique is conceptually the simplest of the three techniques. However, it requires the use of method calls for each operation in place of primitive arithmetic operators; this may obscure the intended meaning of the code. This technique will execute more slowly and will use more memory than either of the other techniques; performance degradation may could be substantial.

Noncompliant Code Example

...

Code Block
bgColor#FFcccc
public int multAccum(int oldAcc, int newVal, int scale) {
  // May result in overflow 
  return oldAcc + (newVal * scale);
}

Compliant Solution (Pre-

...

Condition the

...

Inputs)

The code example below shows the necessary pre-conditioning checks required for each arithmetic operation on arguments of type int. The checks for the other integral types are analogous. In this example, we choose (for simplicity) to throw an exception when integer overflow would occur; any other appropriate error handling is also acceptable.

...

Note that although these pre-conditioning checks are correct, more efficient code may well could be possible. FurtherAlso, the checks can be simplified when the original type was is char. Because the range of type char includes only positive values, all comparisons with negative values may be omitted.

...

For all integral types other than long, the next larger integral type can represent the result of any single integral operation. For example, operations on values of type int, can be safely performed using type long. Therefore, we can perform an operation using the larger type and range-check before down casting downcasting to the original type. Note, however, that this guarantee holds only for a one arithmetic operation; larger expressions without per-operation bounds checks may overflow the larger type.

...

Type BigInteger is the standard arbitrary-precision integer type provided by the Java standard libraries. The arithmetic operations implemented as methods of this type cannot themselves overflow; instead, they produce the numerically correct result. As a consequence, compliant code performs only a single range check — just check—just before converting the final result to the original smaller type. This property provides conceptual simplicity. An unfortunate consequence of this technique is that compliant code must be written using method calls in place of primitive arithmetic operators; this may can obscure the intent of the code.

Note that operations on objects of type BigInteger may can be significantly less efficient than operations on the original primitive integer type. Whether this loss of efficiency is important will depend on the context in which the code is used.

...

Operations on objects of type AtomicInteger suffer from the same overflow issues as do the other integer types. The solutions are generally similar to those shown above; however, concurrency issues add additional complications. First, avoid possible issues with time-of-check-time-of-use. (see See guidleine VNA02-J. Ensure that compound operations on shared variables are atomic for more information). Secondly, use of an AtomicInteger creates happens-before relationships between the various threads that access it. Consequently, changes to the number or order of accesses may alter the execution of the overall program. In such cases you must either choose to accept the altered execution or carefully craft the implementation of your compliant technique to preserve the exact number 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.

...

This compliant solution uses the get() and compareAndSet() methods provided by AtomicInteger to guarantee successful manipulation of the shared value of itemsInInventory. Note thatthe following:

  1. The number and order of accesses to itemsInInventory remains unchanged from the noncompliant code example.
  2. All operations on the value of itemsInInventory are performed on a temporary local copy of its value.
  3. 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 vs. inline code should be made according to your organization's standards and needs.

...

Wiki Markup
The 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 if, and only if, the current value and the expected value are equal \[[API 2006|AA. Bibliography#API 06]\] class [{{AtomicInteger}}|http://download.oracle.com/javase/6/docs/api/java/util/concurrent/atomic/AtomicInteger.html]. Refer to guideline [VNA02-J. Ensure that compound operations on shared variables are atomic] for more details.

...

INT00-EX1: Depending on circumstances, integer overflow may could be benign. For instance, the Object.hashcode() method may could return all representable values of type int; further, many algorithms for computing hashcodes intentionally allow overflow to occur.

...

Failure to perform appropriate range checking can lead to integer overflows, which may can cause unexpected program control flow or unanticipated program behavior.

...

Automated detection of integer operations that may 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 may could be helpful.

Related Vulnerabilities

Search for vulnerabilities resulting from the violation of this guideline on the CERT website.

Other Languages

Related Guidelines

This guideline appears in the C Secure Coding Standard as : INT32-C. Ensure that operations on signed integers do not result in overflow.This guideline appears in

the C++ Secure Coding Standard as : INT32-CPP. Ensure that operations on signed integers do not result in overflow.

Bibliography

MITRE CWE: CWE-682 "Incorrect Calculation"

MITRE CWE: CWE-190 "Integer Overflow or Wraparound"

MITRE CWE: CWE-191 "Integer Underflow (Wrap or Wraparound)"

Bibliography

Wiki Markup
\[[
Wiki Markup
\[[API 2006|AA. Bibliography#API 06]\] class [{{AtomicInteger}}|http://download.oracle.com/javase/6/docs/api/java/util/concurrent/atomic/AtomicInteger.html]
\[[Bloch 2005|AA. Bibliography#Bloch 05]\] Puzzle 27: Shifty i's\[[SCG 2007|AA. Bibliography#SCG 07]\] Introduction
\[[JLS 2003|AA. Bibliography#JLS 03]\] 4.2.2 Integer Operations and 15.22 Bitwise and Logical Operators
\[[MITRE 2009|AA. Bibliography#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)"
\[[Seacord 2005|AA. Bibliography#Seacord 05]\] Chapter 5. Integers
\[[Tutorials 2008|AA. Bibliography#Tutorials 08]\] Primitive Data Types

...