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.
...
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.
If a method receives data from across a trust boundary, that method must perform callee validation of its parameter for safety and security reasons. This 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.
...
Code Block | ||
---|---|---|
| ||
private Object myState = null; // Sets some internal state in the library void setfile(Object state) { myState = state; } // Performs some action 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 data.
...
This compliant solution validates the method parameters and also verifies the internal state before use. This promotes consistency in program execution and reduces the potential for vulnerabilities.
Code Block | ||
---|---|---|
| ||
private Object myState = null; // Sets some internal state in the library void setfile(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 } // ... } |
...
This may include parameters whose values (as permitted by their type) are not necessarily valid , but are still correctly handled by the function. In the following code, no explicit validation is done of the arguments x
and y
even though their product might not be a valid int
. The code is safe as because it adequately handles all int
values for x
and y
.
...