The following excerpt is from the Introduction section of Sun's \[[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 the same caution as in C and C++. Integer operations can result in overflow or underflow because Java does not provide any indication of these conditions and silently wraps (Java throws only a division by zero exception).
The following excerpt is from the \[[JLS 03|AA. Java References#JLS 03]\] Integer (Overflow): |
The built-in integer operators do not indicate overflow or underflow in any way. Integer operators can throw a
NullPointerExceptionif 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 anArithmeticExceptionif the right-hand operand is zero, and the increment and decrement operators ++ and - which can throw anOutOfMemoryErrorif boxing conversion is required and there is not sufficient memory available to perform the conversion.
In this noncompliant code example, the result can overflow.
public int do_operation(int a, int b)
{
int temp = a + b;
//Could result in overflow
//perform other processing
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. Although unlike C\C++ integer overflows are difficult to exploit due to of the memory properties of the Java platform (e.g., explicit array bounds checking, if temp has a negative value as a result of an overflow and it is used as an array index, we get a java.lang.ArrayIndexOutOfBoundsException), the issue can lead to undefined or incorrect behavior.
All of the following operators 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 (and all operations) in Java is performed on signed numbers only as unsigned numbers are unsupported.
In this example, the addition operation can result in an overflow.
public int do_operation(int a,int b)
{
int temp = a + b;
//Could result in overflow
//do other processing
return temp;
}
|
Explicitly check the range of each arithmetic operation and throw an ArithmeticException on overflow; or else downcast the value to an integer. For performing arithmetic operations on large numbers, the BigInteger Class must be used.
According to \[[Tutorials 08|AA. Java References#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 the long type is guaranteed to hold the result of an int addition, we can assign the result to a long, and if the result is in the integer range, we can simply downcast. All the overflow condition checks would be the same as those used with signed integers in C.
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 ArithmeticException;
else //Value within range can perform the addition
//Do stuff
return (int)temp;
}
|
This is yet another example of explicit range checking.
public int do_operation(int a, int b) throws ArithmeticException
{
int temp;
if(a>0 && b>0 && (a >Integer.MAX_VALUE - b) || a<0 && b<0 && (a < Integer.MIN_VALUE -b))
throw ArithmeticException;
else
temp = a + b;//Value within range can perform the addition
//Do stuff return
temp;
}
|
Another compliant approach would be to use the BigInteger class as a wrapper to test for the overflow.
public boolean overflow(int a, int b)
{
java.math.BigInteger ba = new java.math.BigInteger(String.valueOf(a));
java.math.BigInteger bb = new java.math.BigInteger(String.valueOf(b));
java.math.BigInteger br = ba.add(bb);
if(br.compareTo(java.math.BigInteger.valueOf(Integer.MAX_VALUE)) == 1
|| br.compareTo(java.math.BigInteger.valueOf(Integer.MIN_VALUE))== -1)
return true;// Overflow!
//Can proceed
return false;
}
public int do_operation(int a, int b) throws ArithmeticException
{
if(overflow(a,b))
throw ArithmeticException;
else // We are within range; safely perform the addition
}
|
With use of the BigInteger class, integer overflows are definitely eliminated. However, due to increased performance costs, it should be used only on large operations or when limited memory is not a concern.
Care must be taken while performing the subtraction operation as well since overflows are still possible.
public int do_operation(int a,int b)
{
int temp = a - b;
// Could result in overflow
// Perform other processing
return temp;
}
|
The appropriate remediation is to check the range explicitly before the subtraction.
int a,b,result; long temp = (long)a-(long)b; if(temp < Integer.MIN_VALUE || temp > Integer.MAX_VALUE) throw ArithmeticException; else result = (int) temp; |
A BigInteger class can be used as a test-wrapper.
public boolean underflow(int a, int b)
{
java.math.BigInteger ba = new java.math.BigInteger(String.valueOf(a));
java.math.BigInteger bb = new java.math.BigInteger(String.valueOf(b));
java.math.BigInteger br = ba.subtract(bb);
if(br.compareTo(java.math.BigInteger.valueOf(Integer.MAX_VALUE)) == 1
|| br.compareTo(java.math.BigInteger.valueOf(Integer.MIN_VALUE))== -1)
return true;//We have underflow
//Can proceed
return false;
}
public int do_operation(int a, int b) throws ArithmeticException
{
if(undeflow(a,b))
throw ArithmeticException;
else //we are within range safely perform the addition
}
|
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.
int a,b,result //do stuff result = a*b;//May result in overflow |
Since the size of the type long (64 bits) is twice the size of the type int (32 bits), the multiplication should be performed in terms of long. If the product is in the valid integer range, it can be safely downcast to an int.
int a,b,result; long temp = (long) a\* (long)b; if(temp > Integer.MAX_VALUE || temp < Integer.MIN_VALUE) throw ArithmeticException;//overflow else result = (int) temp;//Value within range, safe to downcast |
Although Java throws a java.lang.ArithmeticException: / by zero exception 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)).
int a,b,result result = a/b; |
if(a == Integer.MIN_VALUE && b == -1) throw ArithmeticException;//May be Integer.MIN_VALUE again else result = a/b;//safe operation |
The remainder operation is safer in Java than the corresponding modulo operator in C/C++.
Integer.MIN_VALUE with -1 the result is always 0 in Java.ArithmeticException.-2 % -1 will result in the value -1. Thus its behavior can sometimes be deceptive.If we negate Integer.MIN_VALUE, we get Integer.MIN_VALUE. So we explicitly check the range.
int temp = -result; |
if(a == Integer.MIN_VALUE) throw ArithmeticException; else result = -a; |
A related pitfall is the use of the Math.abs method that takes an integer as a parameter and returns its absolute value. Due to the asymmetry between the representation of negative and positive integer values (there is an extra minimum negative value), there is no equivalent positive value for Integer.MIN_VALUE. Thus, Math.abs(Integer.MIN_VALUE) always returns a non positive Integer.MIN_VALUE.
The shift operation in Java is quite different from C\C++,
boolean, float and double cannot use the bit shifting operators.When the value to be shifted (left-operand) is a {{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}}) |
In this example, the programmer wishes to shift the integer {{i}} until, after 32 iterations, the value becomes 0. Unfortunately, this loop never terminates as an attempt to shift an integer value by 32 bits results in the integer itself rather than the value 0. \[[Bloch 05|AA. Java References#Bloch 05]\] |
int i = 0; while ((-1 << i) != 0) i++; |
This compliant solution shows how instead of repeatedly shifting the value -1 with a different shift distance, one can save the result of the previous shift and continue shifting bit by bit on each successive iteration.
for (int val = -1; val != 0; val <<= 1) { /* ... */ }
|
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 |
TODO
Search for vulnerabilities resulting from the violation of this rule on the CERT website.
\[[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 |
INT33-J. Be careful while casting numeric types to wider floating-point types 04. Integers (INT) 05. Floating Point (FLP)