Versions Compared

Key

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

...

The method Double.valueOf(String s) can return NaN or an infinite double as specified by its contract. Programs should install checks to ensure that all floating point inputs (especially those obtained from the user) do not contain either of these values before proceeding to operate on them. The methods Double.isNaN(double d) and Double.isInfinite(double d) can be used for this purpose.

Noncompliant Code Example

This noncompliant code example accepts user data without validating it.

...

In this compliant solution, entering NaN for val would force currentBalance to also equal NaN, corrupting its value. If this value is used in other expressions, every resulting value will become NaN, possibly corrupting important data.

Compliant Solution

This compliant solution validates the floating point input before using it. The value is tested to ensure that it is neither infinity, negative infinity nor NaN.

Code Block
bgColor#ccccff
double currentBalance; // User's cash balance

void doDeposit(String s){
  double val;
  try {
    val = Double.valueOf(userInput);
  }
  catch(NumberFormatException e) {
    // Handle input format error
  }

  if (Double.isInfinite(val)){
    // Handle infinity error
  }

  if (Double.isNaN(val)) {
    // Handle NaN error
  }

  if(val >= Double.MAX_VALUE - currentBalance) {
    // Handle range error
  }
  currentBalance += val;
}

Exceptions

EX1: Occasionally, NaN or infinity may be acceptable as expected inputs to a program. In such cases, explicit checks may not be necessary. However, such programs must be prepared to handle these inputs gracefully and should not allow the propagation of taint to other values by using them in mathematical expressions where they are inappropriate.

Risk Assessment

Incorrect or missing validation of floating point input can result in miscalculations and unexpected results, possibly leading to inconsistent program behavior and Denial of Service (DoS).

Recommendation

Severity

Likelihood

Remediation Cost

Priority

Level

FLP04- J

low

probable

medium

P4

L3

Automated Detection

TODO

Related Vulnerabilities

HARMONY-6242, HARMONY-6268

Other Languages

This rule appears in the C Secure Coding Standard as FLP04-C. Check floating point inputs for exceptional values
This rule appears in the C++ Secure Coding Standard as FLP04-CPP. Check floating point inputs for exceptional values.

References

Wiki Markup
\[[IEEE 754|https://www.securecoding.cert.org/confluence/display/seccode/AA.+C+References#AA.CReferences-IEEE7542006|IEEE 754]\]
\[[IEEE 1003.1, 2004|https://www.securecoding.cert.org/confluence/display/seccode/AA.+C+References#AA.CReferences-IEEE1003|IEEE 1003.1, 2004]\]

...