The following excerpt is from Sun's Secure Coding Guidelines document [[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 (Java arithmetic throws an exception only on a division by zero).
The following excerpt is from the Java Language Specification [[JLS 03]] 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.
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 |
Addition
Addition (as with all arithmetic operations) in Java is performed on signed numbers only as unsigned numbers are unsupported.
Noncompliant Code Example
In this noncompliant code example, the result of the addition can overflow.
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 the int
type can store, then the variable temp
will contain an erroneous result. Unlike C and C++ integer overflows are harder to exploit in Java. For example, if temp
has a negative value as a result of an overflow and is used as an array index, java.lang.ArrayIndexOutOfBoundsException
) results whereas this is a more pernicious issue in C and C++ wherein memory regions outside the array bounds can be maliciously altered. In Java, wrapped values typically result in incorrect computations and unanticipated outcomes.
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
or smaller, the arithmetic can be done using variables of type long
. For performing arithmetic operations on numbers of type long
, the BigInteger
Class must be used.
According to the Java Tutorials [[Tutorials 08]], Primitive Data Types:
_ _ -the integer data type is a 32-bit signed two's complement integer. It has a minimum value of -2,147,483,648 and a maximum value of 2,147,483,647 (inclusive).
_ _ - the long
data type is a 64-bit signed two's complement integer. It has a minimum value of -9,223,372,036,854,775,808 and a maximum value of 9,223,372,036,854,775,807 (inclusive). Use this data type when you need a range of values wider than those provided by int.
Since 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 a variable of type long
, and if the result is in the integer range, we can simply downcast 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 the value. If the value cannot be represented as a value of type int
, it throws an ArithmeticException
. Otherwise, it downcasts the result to a value of type int
.
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(); } return (int)temp; // Value within range can perform the addition }
Compliant Solution (Bounds Checking)
This compliant solution uses range checking to ensure that the result will not overflow.
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(); } return a + b; //Value within range can perform the addition }
Compliant Solution (Use BigInteger Class)
This compliant solution uses the BigInteger
class as a wrapper to test for the overflow.
public boolean overflow(long a, long b) { BigInteger ba = new java.math.BigInteger(String.valueOf(a)); BigInteger bb = new java.math.BigInteger(String.valueOf(b)); BigInteger br = ba.add(bb); return (br.compareTo(BigInteger.valueOf(Long.MAX_VALUE)) == 1 || br.compareTo(BigInteger.valueOf(Long.MIN_VALUE))== -1); } public long do_operation(long a, long b) throws ArithmeticException { if(overflow(a,b)) { throw new ArithmeticException(); } // Within range; safely perform the addition return a + b; }
With use of the BigInteger
class, integer overflows are definitely 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 since overflows (or underflows) are still 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
.
public int do_operation(int a, int b) { int temp = a - b; // Could result in overflow return temp; }
Compliant Solution (Use Long)
This compliant solution suggests explicit range checking before performing the subtraction.
public int do_operation(int a,int b) { long temp = (long)a - (long)b; if(temp < Integer.MIN_VALUE || temp > Integer.MAX_VALUE) { throw new ArithmeticException(); } return (int) temp; }
Compliant Solution (Bounds Checking)
This compliant solution uses range checking to ensure that the result will not overflow.
public int do_operation(int a, int b) throws ArithmeticException { if( b>0 ? a < Integer.MIN_VALUE + b : a > Integer.MAX_VALUE + b ) { throw new ArithmeticException(); } return a - b; //Value within range can perform the addition }
Compliant Code Example (Use BigInteger Class)
The BigInteger
class can be used as a test-wrapper as shown in this compliant solution.
public boolean underflow(long a, long b) { BigInteger ba = new BigInteger(String.valueOf(a)); BigInteger bb = new BigInteger(String.valueOf(b)); BigInteger br = ba.subtract(bb); return (br.compareTo(BigInteger.valueOf(Long.MAX_VALUE)) == 1 || br.compareTo(BigInteger.valueOf(Long.MIN_VALUE)) == -1); } public long do_operation(long a, long b) throws ArithmeticException { if(underflow(a,b)) { throw new ArithmeticException(); } // 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
int a,b,result //do stuff result = a*b; // May result in overflow
Compliant Solution
Since 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
.
int a,b,result; long temp = (long) a * (long)b; if(temp > Integer.MAX_VALUE || temp < Integer.MIN_VALUE) { throw new ArithmeticException(); // Overflow } result = (int) temp; // 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 (since 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.
int a,b,result result = a/b;
Compliant Solution
This compliant solution handles the the special case of Integer.MIN_VALUE
and -1
being used as the dividend and divisor, respectively.
if(a == Integer.MIN_VALUE && b == -1) { throw new ArithmeticException(); // May be Integer.MIN_VALUE and -1 } result = a/b; // Safe operation
Remainder Operator
The remainder operation is safer in Java than the corresponding modulo operator in C/C++.
- If the modulo of
Integer.MIN_VALUE
with -1 is taken the result is always 0 in Java.
- 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
will result in the value-1
. As a result its behavior can sometimes be deceptive.
Refer to INT02-J. Do not assume a positive remainder when using the % 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
.
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.
if(result == Integer.MIN_VALUE) { throw new ArithmeticException(); } 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 (there is an extra minimum negative value -128), there is no equivalent positive value (+128) for Integer.MIN_VALUE. As a result, Math.abs(Integer.MIN_VALUE)
always returns a non positive Integer.MIN_VALUE
.
Shifting
The shift operation in Java is quite different from C/C++,
- The right shift is an arithmetic shift, while in C/C++ it is implementation defined (logical or arithmetic).
- The types
boolean, float and double
cannot use the bit shifting operators.
- In C/C++ if the value being left shifted is negative or the right-hand operator of the shift operation is negative or greater than or equal to the width of the promoted left operand, there is undefined behavior. This does not extend to Java. 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.
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]], i.e., it is always between 0 and 63. (If the shift value is greater than 64, then the shift isvalue % 64
.)
Refer to INT36-J. Use shift operators correctly for further details about the behavior of the shift operators.
Noncompliant Code Example
In this example, the programmer wishes to shift the value i
of type int
until, after 32 iterations, the value becomes 0. Unfortunately, this loop never terminates as an attempt to shift a value of type int
by 32 bits results in the original value rather than the value 0. [[Bloch 05]]
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.
for (int val = -1; val != 0; val <<= 1) { /* ... */ }
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 |
---|---|---|---|---|---|
INT34- 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
[[SCG 07]] Introduction
[[JLS 03]] 4.2.2 Integer Operations and 15.22 Bitwise and Logical Operators
[[Tutorials 08]] Primitive Data Types
[[Seacord 05]] Chapter 5. Integers
[[Bloch 05]] Puzzle 27: Shifty i's
[[MITRE 09]] CWE ID 682 "Incorrect Calculation", CWE ID 190 "Integer Overflow or Wraparound", CWE ID 191 "Integer Underflow (Wrap or Wraparound)"
INT33-J. Do not cast numeric types to wider floating-point types without range checking 06. Integers (INT) INT35-J. Do not attempt to store signed values in the char integral type