Versions Compared

Key

  • This line was added.
  • This line was removed.
  • Formatting was changed.

Validating method parameters ensures that any operations that use Validate method arguments to ensure that they fall within the bounds of the method's intended design. This practice ensures that operations on the method's arguments parameters yield consistent valid results. Failure to do so validate method arguments can result in incorrect calculations, runtime exceptions, violation of class invariants, and inconsistent object state.

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

Wiki Markup
Assertions should not be used 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.

Another problem with using assertions for argument checking is that erroneous arguments should result in an appropriate runtime exception (such as IllegalArgumentException, IndexOutOfBoundsException or NullPointerException). An assertion failure will not throw an appropriate exception. Again, it is not illegal to use assertions for argument checking on public methods, but it is generally inappropriate.

Redundant testing of arguments 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 arguments can result in faster code because the caller may be aware of invariants that prevent invalid values from being passed. Conversely, callee validation of arguments 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.

Methods that receive arguments across a trust boundary must perform callee validation of their arguments for safety and security reasons. This precaution applies to all public methods of a library. Other methods, including private methods, should validate arguments that are both untrusted and unvalidated when those arguments may propagate from a public method via its arguments.

When defensive copying is necessary, make the defensive copies before argument validation, and validate the copies rather than the original arguments (see SER06Also 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 guideline SER07-J. Make defensive copies of private mutable components during deserialization for additional information).)

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 and consequently, can produce incorrect results because of integer overflow or a negative number being returned from the computation Math.abs(Integer.MIN_VALUE)In this noncompliant code example, setState() and useState() fail to validate their arguments. A malicious caller could pass an invalid state to the library, consequently corrupting the library and exposing a vulnerability.

Code Block
bgColor#FFcccc

public static int AbsAdd(int x, int yprivate Object myState = null;

// Sets some internal state in the library
void setState(Object state) {
  myState =  return Math.abs(x) + Math.abs(y);
}
AbsAdd(Integer.MIN_VALUE, 1);

Noncompliant Code Example

state;
}

// Performs some action using the state passed earlier
void useState() {
  // Perform some action here
}

Such vulnerabilities are particularly severe when the internal state contains or refers to sensitive or system-critical data.

Compliant Solution

This compliant solution both validates the method arguments and verifies the internal state before use. This practice promotes consistency in program execution and reduces the potential for vulnerabilitiesThis noncompliant code example uses assertions to validate arguments of a public method.

Code Block
bgColor#FFcccc

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

#ccccff
private Object myState = null;

// Sets some internal state in the library
void setState(Object state) {
  if (state == 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

MET00-J-EX0: Argument 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.

MET00-J-EX1: Argument validation may be omitted for arguments whose type adequately constrains the state of the argument. This constraint should be clearly documented in the code.

This exception may apply to arguments whose values (as permitted by their type) are not necessarily valid but are still correctly handled by the method. In the following code, the arguments x and y are not validated even though their product might not be a valid int. The code is safe because it adequately handles all int values for x and yThis compliant solution validates the input to Math.abs() to ensure it is not Integer.MIN_VALUE and checks for 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
bgColor#ccccff

public static int AbsAddproduct(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)))long result = (long) x * y;
  if (result < Integer.MIN_VALUE || result > Integer.MAX_VALUE) {
    // Handle throwerror
 new IllegalArgumentException();
}
  return Math.abs(xint) + Math.abs(y)result;
}

MET00-J-EX2: Complete validation of all arguments of all methods may introduce added cost and complexity that exceeds its value for all but the most critical code. In such cases, consider argument validation at API boundaries, especially those that may involve interaction with untrusted code.

Risk Assessment

Failing Failure to validate method parameters arguments can result in inconsistent computations, runtime exceptions, and control flow vulnerabilities.

Guideline Rule

Severity

Likelihood

Remediation Cost

Priority

Level

MET02MET00-J

medium High

probable Likely

medium High

P8 P9

L2

Automated Detection

TODO

Related Vulnerabilities

Search for vulnerabilities resulting from the violation of this rule on the CERT website.

Bibliography

Wiki Markup
\[[JLS 2005|AA. Bibliography#JLS 05]\] 14.10 The assert Statement
\[[Bloch 2008|AA. Bibliography#Bloch 08]\] Item 38: Check parameters for validity
\[[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
\[[Daconta 2003|AA. Bibliography#Daconta 03]\] Item 7: My Assertions Are Not Gratuitous

Related Guidelines

ISO/IEC TR 24772:2010

Argument Passing to Library Functions [TRJ]

Bibliography

[Bloch 2008]

Item 38, "Check Parameters for Validity"

 

...

Image Added Image Added MET01-J. Avoid ambiguous uses of overloading      16. Methods (MET)      Image Modified