Java is considered to be a safer language than C or C++. The following excerpt is from the introduction of Sun's Secure Coding Guidelines :
"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 in fact true, the arithmetic operations in the Java platform require the same caution as in C\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 Java Language Specification (Overflow):
"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."
See the following example.
In the following simple method, the result could 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 that the int type can store or less than the minimum value that the int type can store, then the variable temp has a wrong result stored. Although unlike C\C++ the integer overflow is difficult to exploit by an attacker in Java because of the memory properties in this platform (e.g., explicit array bound checking; if temp has a negative value as a result of an overflow and we use it as an array index, we get an java.lang.ArrayIndexOutOfBoundsException), the results of this operation are wrong and can lead to undefined or incorrect behavior.
All of the following operators can lead to overflow:
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 are performed in signed numbers, as Java does not support unsigned numbers.
In this example the addition could result in overflow.
public int do_operation(int a,int b)
{
int temp = a + b;
//Could result in overflow
//do other processing
return temp;
}
|
A solution would be to explicitly check the range of each arithmetic operation and throw an ArithmeticException on overflow, or otherwise downcast the value to an integer. For arithmetical operations on really big numbers, one should always use the BigInteger Class.
In this platform, according to Sun's Java 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.
So because long is guaranteed to be able to hold the result of an int addition, we could assign the result to a long, and if the result is in the integer range, we simply downcast. All of the tests would be the same as with signed integers in C because Java does not support unsigned numbers.
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 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 in this example and in the examples of the other operations, using a wrapper for test of 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;//We have 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
}
|
By using the BigInteger class, there is no chance to overflow (see section on BigInteger class), but the performance is degraded, so it should be used only on really large operations.
Care must be taken in subtraction operations as well, as these can overflow as well.
public int do_operation(int a,int b)
{
int temp = a - b;
//Could result in overflow
//perform other processing
return temp;
}
|
The appropriate way is to check the range explicitly before doing 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 as a test-wrapper could be used.
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 behaviour is unanticipated, the resulting value may lead to undefined behaviour.
int a,b,result //do stuff result = a*b;//May result in overflow |
Since in this platform the size of type long (64 bits) is twice the size of type int (32 bits), we should perform the multiplication in terms of long, and if the product is in the integer range, we downcast the result to 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, there is the same issue as in C\C++ when dividing the Integer.MIN_VALUE with -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 |
Modulo operation is safer in Java than C/C++.
Integer.MIN_VALUE with -1 the result is always 0 in Java.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; |
The shift in Java is quite different than in C\C++.
long, only the last 6 bits of the right-hand operand are used to perform the shift. The actual size of the shift is the value of the right-hand operand masked by 63 (0x3D) Java Language Specification(§15.19 ), i.e., the shift distance is always between 0 and 63. (If the shift value is greater than 64, then the shift is value%64.)35 00000000 00000000 00000000 00100011
31 -> 0x1f 00000000 00000000 00000000 00011111
&
INT33-J. Be careful while casting numeric types to wider floating-point types 04. Integers (INT) 05. Floating Point (FLP)