rspec/rules/S2184/java/rule.adoc
Egon Okerman d1417e82f8
Modify CWE and OWASP Top 10 links to follow standard link format (APPSEC-1134) (#3529)
* Fix all CWE references

* Fix all OWASP references

* Fix missing CWE prefixes
2024-01-15 17:15:56 +01:00

84 lines
2.3 KiB
Plaintext

== Why is this an issue?
include::../description.adoc[]
=== Noncompliant code example
[source,java]
----
float twoThirds = 2/3; // Noncompliant; int division. Yields 0.0
long millisInYear = 1_000*3_600*24*365; // Noncompliant; int multiplication. Yields 1471228928
long bigNum = Integer.MAX_VALUE + 2; // Noncompliant. Yields -2147483647
long bigNegNum = Integer.MIN_VALUE-1; //Noncompliant, gives a positive result instead of a negative one.
Date myDate = new Date(seconds * 1_000); //Noncompliant, won't produce the expected result if seconds > 2_147_483
...
public long compute(int factor){
return factor * 10_000; //Noncompliant, won't produce the expected result if factor > 214_748
}
public float compute2(long factor){
return factor / 123; //Noncompliant, will be rounded to closest long integer
}
----
=== Compliant solution
[source,java]
----
float twoThirds = 2f/3; // 2 promoted to float. Yields 0.6666667
long millisInYear = 1_000L*3_600*24*365; // 1000 promoted to long. Yields 31_536_000_000
long bigNum = Integer.MAX_VALUE + 2L; // 2 promoted to long. Yields 2_147_483_649
long bigNegNum = Integer.MIN_VALUE-1L; // Yields -2_147_483_649
Date myDate = new Date(seconds * 1_000L);
...
public long compute(int factor){
return factor * 10_000L;
}
public float compute2(long factor){
return factor / 123f;
}
----
or
[source,java]
----
float twoThirds = (float)2/3; // 2 cast to float
long millisInYear = (long)1_000*3_600*24*365; // 1_000 cast to long
long bigNum = (long)Integer.MAX_VALUE + 2;
long bigNegNum = (long)Integer.MIN_VALUE-1;
Date myDate = new Date((long)seconds * 1_000);
...
public long compute(long factor){
return factor * 10_000;
}
public float compute2(float factor){
return factor / 123;
}
----
== Resources
* CWE - https://cwe.mitre.org/data/definitions/190[CWE-190 - Integer Overflow or Wraparound]
* https://wiki.sei.cmu.edu/confluence/x/AjdGBQ[CERT, NUM50-J.] - Convert integers to floating point for floating-point operations
* https://wiki.sei.cmu.edu/confluence/x/I9cxBQ[CERT, INT18-C.] - Evaluate integer expressions in a larger size before comparing or assigning to that size
ifdef::env-github,rspecator-view[]
'''
== Implementation Specification
(visible only on this page)
include::../message.adoc[]
'''
== Comments And Links
(visible only on this page)
include::../comments-and-links.adoc[]
endif::env-github,rspecator-view[]