Versions Compared

Key

  • This line was added.
  • This line was removed.
  • Formatting was changed.
Comment: Edited and added other sections

Wiki Markup
Java is considered to be a safer language than C or C++. The following excerpt is from the
introduction
 Introduction section of Sun's
Secure Coding Guidelines :"
 \[[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 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).

Wiki Markup
The following excerpt is from the \[[JLS 03|AA. Java References#JLS 03]\] Integer 
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.

Noncompliant Code Example

In the following simple methodthis noncompliant code example, the result could can overflow.

Code Block
bgColor#FFcccc
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 will contain an erroneous result. Although unlike C\C++ the integer overflow is overflows are difficult to exploit by an attacker in Java because due to of the memory properties in this of the Java platform (e.g., explicit array bound bounds checking; , if temp has a negative value as a result of an overflow and we use it is used as an array index, we get an a java.lang.ArrayIndexOutOfBoundsException), the results of this operation are wrong and issue can lead to undefined or incorrect behavior.

All of the following operators can lead to overflowoverflows:

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

 

un -

yes

 

?:

no

...

Addition (and all operations) in Java are is performed in on signed numbers , only as Java does not support unsigned numbers are unsupported.

Noncompliant Code Example

In this example, the addition could operation can result in an overflow.

Code Block
bgColor#FFcccc
public int do_operation(int a,int b)
{
   int temp = a + b;
  //Could result in overflow
  //do other processing
   return temp;
}

Compliant Solution (Bounds Checking)

A solution would be to explicitly Explicitly check the range of each arithmetic operation and throw an ArithmeticException on overflow, ; or otherwise else downcast the value to an integer. For arithmetical performing arithmetic operations on really big large numbers, one should always use the BigInteger Class must be used.

In this platform, according to Sun's Java Data Types:

Wiki Markup
According to \[[Tutorials 08|AA. Java References#Tutorials 08]\], Primitive Data Types:

_ _ -the integer data type is a 32-_ _ -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 Since the long type is guaranteed to be able to hold the result of an int addition, we could can assign the result to a long, and if the result is in the integer range, we can simply downcast. All of the tests overflow condition checks would be the same as those used with signed integers in C because Java does not support unsigned numbers..

Compliant Solution (Use Long and Downcast)

...

Compliant Solution (Bounds Checking)

This is yet another example of explicit range checking.

...

Another compliant approach would be to use the BigInteger class in this example and in the examples of the other operations, using as a wrapper to test for test of the overflow.

Code Block
bgColor#ccccff
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 overflowOverflow!
    //Can proceed
   return false;
}

public int do_operation(int a, int b) throws ArithmeticException
{
      if(overflow(a,b))
         throw ArithmeticException;
      else //we We are within range; safely perform the addition
}

By using With use of the BigInteger class, there is no chance to overflow (see section on BigInteger class), but the performance is degraded, so integer overflows are definitely eliminated. However, due to increased performance costs, it should be used only on really large operations or when limited memory is not a concern.

Subtraction

Care must be taken in while performing the subtraction operations operation as well , as these can overflow as wellsince overflows are still possible.

Noncompliant Code Example

Code Block
bgColor#FFcccc
public int do_operation(int a,int b)
{
   int temp = a - b;
  // Could result in overflow
  //perform Perform other processing
   return temp;
}

Compliant Code Example (Use long)

The appropriate way remediation is to check the range explicitly before doing the subtraction.

Code Block
bgColor#ccccff
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;

Compliant Code Example (Use BigInteger Class)

A BigInteger class can be used as a test-wrapper could be used.

Code Block
bgColor#ccccff
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 behavior is unanticipated, the resulting value may lead to undefined behaviourbehavior.

Noncompliant Code Example

...

Compliant Code Example

Since in this platform the size of the type long (64 bits) is twice the size of the type int (32 bits), we should perform the multiplication should be performed in terms of long, and if . If the product is in the valid integer range, we downcast the result to it can be safely downcast to an int.

Code Block
bgColor#ccccff
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 with C\C++ when manifests, while dividing the Integer.MIN_VALUE with by -1. It
produces Integer.MIN_VALUE unexpectedly (since the result is -(Integer.MIN_VALUE)=Integer.MAX_VALUE +1)).

...

Code Block
bgColor#ccccff
if(a == Integer.MIN_VALUE && b == -1)
throw ArithmeticException;//May be Integer.MIN_VALUE again
else
result = a/b;//safe operation

...

Remainder Operator

Modulo The remainder operation is safer in Java than the corresponding modulo operator in C/C++.

  • If we take the modulo of Integer.MIN_VALUE with -1 the result is always 0 in Java.
  • If the right-hand operand is zero, then the integer remainder operator % will throw an ArithmeticException.

Unary Negation

  • The sign of the remainder is always the same as that of the dividend. For example, -2 % -1 will result in the value -1. Thus its behavior can sometimes be deceptive.

Unary Negation

If we negate Integer.MIN_VALUE, we get Integer.MIN_VALUE. So we explicitly check the range.

...

Code Block
bgColor#ccccff
if(a == Integer.MIN_VALUE)
  throw ArithmeticException;
else
  result = -a;

Shifting

The shift in Java is quite different than in C\C++.

Absolute Value

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.

Shifting

The shift operation in Java is quite different from C\C++,

  1. The right shift is an arithmetic shift, while in C\C++ it is implementation defined (logical or arithmetic).
  1. In C\C++ if the
  2. The right shift in Java is an arithmetic shift, while in C\C++ it is implementation defined (logical or arithmetic).
  3. 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, we have undefined behaviourbehavior. This does not apply in Java because in the case of the integer type it is masked with 0x1F, and as a result we can always have a value that is modulo 31. When the value to be shifted extend to Java as integer types are masked by the last 5 lower order bits of the right operand (or 0x1F). This results in a value modulo 31, inclusive.
  1. Wiki Markup
    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
    actual size of the shift is the value of the
     shift distance is the value of the right-hand operand masked by 63 (0x3D)
    Java Language Specification(§15.19 ),
    \[[JLS 03|AA. Java References#JLS 03]\], 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

  1.  it is always between 0 and 63. (If the shift value is greater than 64, then the shift is {{value % 64}})

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.

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
&

...

INT33-J. Be careful while casting numeric types to wider floating-point types      04. Integers (INT)      05. Floating Point (FLP)