...
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 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.
Wiki Markup |
---|
Assertions should not be used to validate parameters of {{public}} methods. According to the Java Language Specification \[[JLS 05|AA. Java References#JLS 05]\], section 14.10 "The {{assert}} Statement": |
Along similar lines, assertions should not be used for argument-checking in
public
methods. Argument-checking is typically part of the contract of a method, and this contract must be upheld whether assertions are enabled or disabled.Another problem with using assertions for argument checking is that erroneous arguments should result in an appropriate runtime exception (such as
IllegalArgumentException
,IndexOutOfBoundsException
orNullPointerException
). An assertion failure will not throw an appropriate exception. Again, it is not illegal to use assertions for argument checking onpublic
methods, but it is generally inappropriate.
...
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 due to 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) { 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
Validating to check that This compliant solution validates the input to Math.abs()
to ensure it is not Integer.MIN_VALUE
and checking checks for arithmetic overflow is the correct approach to method parameter validation in this case. 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> Integer.MAX_VALUE - y)) || (x<0 && y<0 && (x < Integer.MIN_VALUE - y))) throw new IllegalArgumentException(); return Math.abs(x) + Math.abs(y); } |
...
Failing to validate method parameters can result in inconsistent computations, runtime exceptions and control flow vulnerabilities in the worst case.
Rule | Severity | Likelihood | Remediation Cost | Priority | Level |
---|---|---|---|---|---|
MET05- J | medium | probable | medium | P8 | L2 |
...