You are viewing an old version of this page. View the current version.

Compare with Current View Page History

« Previous Version 66 Next »

The following excerpt is from the Introduction section of Sun's [[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]] Integer (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.

Noncompliant Code Example

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

 

un -

yes

 

?:

no

Addition

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

Noncompliant Code Example

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;
}

Compliant Solution (Bounds Checking)

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]], 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.

Compliant Solution (Use Long and Downcast)

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;
}

Compliant Solution (Bounds Checking)

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;
}

Compliant Solution (Use BigInteger Class)

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.

Subtraction

Care must be taken while performing the subtraction operation as well since overflows are still possible.

Noncompliant Code Example

public int do_operation(int a,int b)
{
  int temp = a - b;
  // Could result in overflow
  // Perform other processing
  return temp;
}

Compliant Solution (Use Long)

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;

Compliant Code Example (Use BigInteger Class)

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
}

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 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

Division

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)).

Noncompliant Code Example

int a,b,result
result = a/b;

Compliant Solution

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

Remainder Operator

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.
  • 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.

Noncompliant Code Example

int temp = -result;

Compliant Solution

if(a == Integer.MIN_VALUE)
  throw ArithmeticException;
else
  result = -a;

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++,

  • 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, we have undefined behavior. This does not 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.
  • 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]], i.e., it is always between 0 and 63. (If the shift value is greater than 64, then the shift is value % 64)

Noncompliant Code Example

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]]

int i = 0;
while ((-1 << i) != 0)
  i++;

Compliant Solution

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) { /* ... */ }

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

[[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. Be careful while casting numeric types to wider floating-point types      04. Integers (INT)      05. Floating Point (FLP)

  • No labels