...
Also, note that any defensive copying must be performed before validating the parameters and the checks must be performed on the copies instead of the original parameters. (See SER34-J. Make defensive copies of private mutable components)
Noncompliant Code Example
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 can produce incorrect results as a result 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 noncompliant code example uses assertions to validate arguments of a public
method.
Code Block | ||
---|---|---|
| ||
public static int AbsAdd(int x, int y) { assert x != Integer.MIN_VALUE; assert y != Integer.MIN_VALUE; assert ((x <= Integer.MAX_VALUE - y)); assert ((x >= Integer.MIN_VALUE - y)); return Math.abs(x) + Math.abs(y); } |
Compliant Solution
This compliant solution validates the input to Math.abs()
to ensure it is not Integer.MIN_VALUE
and checks for arithmetic 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); } |
Risk Assessment
Failing to validate method parameters can result in inconsistent computations, runtime exceptions and control flow vulnerabilities.
Rule | Severity | Likelihood | Remediation Cost | Priority | Level |
---|---|---|---|---|---|
MET05- J | medium | probable | medium | P8 | L2 |
Automated Detection
TODO
Related Vulnerabilities
Search for vulnerabilities resulting from the violation of this rule on the CERT website.
References
Wiki Markup |
---|
\[[JLS 05|AA. Java References#JLS 05]\] 14.10 The assert Statement \[[Bloch 08|AA. Java References#Bloch 08]\] Item 38: Check parameters for validity \[[ESA 05|AA. Java References#ESA 05]\] Rule 68: Explicitly check method parameters for validity, and throw an adequate exception in case they are not valid. Do not use the assert statement for this purpose \[[Daconta 03|AA. Java References#Daconta 03]\] Item 7: My Assertions Are Not Gratuitous |
...