Validate method parameters to ensure that they fall within the bounds of the method's intended design. This practice ensures that operations on the method's parameters yield valid results. Failure to validate method parameters can result in incorrect calculations, runtime exceptions, violation of class invariants and inconsistent object state.
Programmers often assume that validation of arguments passed to private
methods is unnecessary because such methods cannot be accessed directly by code present outside their enclosing class. This assumption is incorrect. Programming errors often arise when legitimate code behaves in unanticipated ways. For example, a tainted value may propagate from a public
API to a private methods via its parameters.
Wiki Markup |
---|
Never use assertions should to validate parameters of {{public}} methods. According to the Java Language Specification \[[JLS 2005|AA. Bibliography#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.
...
Redundant testing of parameters by both the caller and the callee is a style of defensive programming that is largely discredited within the programming community, in part for reasons of performance. Instead, normal practice requires validation on only one side of each interface.
Caller validation of parameters can result in faster code, because the caller may be aware of invariants that prevent invalid values from being passed. Conversely, callee validation of parameters encapsulates the validation code in a single location, reducing the size of the code and raising the likelihood that the validation checks are performed consistently and correctly.
In general, library methods should perform callee validation of their parameters for safety and security reasons. Such validity checks enable the method to survive some forms of improper usage; this improves reliability and security of applications that use the library. Further, callee validation often simplifies debugging when an invalid parameter is detected. Library methods that provide an interface between untrusted client code and trusted library code must perform callee validation of their parameters. Other methods, including private
methods, should validate untrusted and unvalidated arguments that may propagate from a public
API via its arguments.
When defensive copying is necessary, make the defensive copies before parameter validation; validate the copies rather than the original parameters. See guideline SER07-J. Make defensive copies of private mutable components for additional information.
Noncompliant Code Example
The method AbsAddIn this noncompliant code example, setState()
computes and returns the sum of the absolute value of parameters x
and y
. It lacks parameter validation. Consequently, it can produce incorrect results either due to integer overflow or when either or both of its arguments are Math.abs(Integer.MIN_VALUE)
. and useState()
fail to validate their parameters. A malicious caller could pass an invalid state to the library, consequently corrupting it and exposing a vulnerability.
Code Block | ||
---|---|---|
| ||
publicprivate staticObject intmyState 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= null; // Sets some internal state in the library void setfile(Object state) { assertmyState x != Integer.MIN_VALUEstate; } // Performs assertsome yaction != Integer.MIN_VALUE; assert ((x <= Integer.MAX_VALUE - y)); assert ((x >= Integer.MIN_VALUE - y)); return Math.abs(x) + Math.abs(y); } using the file passed earlier void useState() { // Perform some action here } |
Such vulnerabilities are particularly severe when the internal state references sensitive or system-critical dataThe conditions checked by the assertions are reasonable. However, the validation code is omitted when executing with assertions turned off.
Compliant Solution
This compliant solution validates the method arguments by ensuring that values passed to Math.abs()
exclude Integer.MIN_VALUE
and also by checking for integer overflow. Alternatively, the addition could be performed using type long
and the result of the addition stored in a local variable of type long
. This alternate implementation would require a check to ensure that the resulting long
can be represented in the range of the type int
. Failure of this latter check would indicate that an int
version of the addition would have overflowed.parameters and also verifies the internal state before use. This promotes consistency in program execution and reduces potential for vulnerabilities.
Code Block | ||
---|---|---|
| ||
public static int AbsAdd(int x, int yprivate Object myState = null; // Sets some internal state in the library void setfile(Object state) { if ((xstate == 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);null) { // Handle null state } // Defensive copy here when state is mutable if (isInvalidState(state)) { // Handle invalid state } myState = state; } // Performs some action using the state passed earlier void useState() { if (myState == null) { // Handle no state (e.g. null) condition } // ... } |
Exceptions
MET02-EX1EX0: Parameter validation inside a method may be omitted when the stated contract of a method requires that the caller must validate arguments passed to the method. In this case, the validation must be performed by the caller for all invocations of the method.
MET02-EX2EX1: Parameter validation may be omitted for parameters whose type adequately constrains the state of the parameter. This constraint should be clearly documented in the code.
MET02-EX3EX2: Complete validation of all parameters of all methods may introduce added cost and complexity that exceeds its value for all but the most critical code. See, for example, NUM00-J. Detect or prevent integer overflow exception NUM00-EX2. In such cases, consider parameter validation at API boundaries, especially those that may involve interaction with untrusted code.
...
Wiki Markup |
---|
\[[Bloch 2008|AA. Bibliography#Bloch 08]\] Item 38: Check parameters for validity \[[Daconta 2003|AA. Bibliography#Daconta 03]\] Item 7: My Assertions Are Not Gratuitous \[[ESA 2005|AA. Bibliography#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 \[[JLS 2005|AA. Bibliography#JLS 05]\] 14.10 The assert Statement |
...
MET00-J. Avoid ambiguous uses of overloading 05. Methods (MET)