...
It if often assumed that private
methods do not require any validation because they are not directly accessible from code present outside the class. This assumption is misleading as programming errors often arise due to as a result of legit code misbehaving in unanticipated ways. For example, a tainted value may propagate from a public
API to one of the internal methods via its parameters.
...
The method AbsAdd()
takes the absolute value of parameters x
and y
and returns their sum. It does not perform any validation on the input . The code snippet is vulnerable and and consequently, can produce incorrect results as a result because of integer overflow or because of a negative number being returned from the computation Math.abs(Integer.MIN_VALUE)
.
Code Block | ||
---|---|---|
| ||
public static int AbsAdd(int x, int y) {
return Math.abs(x) + Math.abs(y);
}
AbsAdd(Integer.MIN_VALUE, 1);
|
Noncompliant Code Example
...
This compliant solution validates the input to Math.abs()
to ensure it is not Integer.MIN_VALUE
and checks for arithmetic integer overflow. The result of the computation can also be stored in a long
variable to avoid overflow, however, in this case the upper bound of the addition is required to be representable as the type int
.
Code Block | ||
---|---|---|
| ||
public static int AbsAdd(int x, int y) {
if((x == Integer.MIN_VALUE || y == Integer.MIN_VALUE) ||
(x>0 && y>0 && (x > Integer.MAX_VALUE - y)) ||
(x<0 && y<0 && (x < Integer.MIN_VALUE - y)))
throw new IllegalArgumentException();
return Math.abs(x) + Math.abs(y);
}
|
...