502
Example Language: Java (Bad)
...
// update sales database for number of product sold with product ID
public void updateSalesForProduct(String productID, int amountSold) {
// get the total number of products in inventory database
int productCount = inventory.getProductCount(productID);
// convert integer values to short, the method for the
// sales object requires the parameters to be of type short
short count = (short) productCount;
short sold = (short) amountSold;
// update sales database for product
sales.updateSalesCount(productID, count, sold);
}
...
However, a numeric truncation error can occur if the integer values are higher than the maximum
value allowed for the primitive type short. This can cause unexpected results or loss or corruption
of data. In this case the sales database may be corrupted with incorrect data. Explicit casting
from a from a larger size primitive type to a smaller size primitive type should be prevented.
The following example an if statement is added to validate that the integer values less than the
maximum value for the primitive type short before the explicit cast and the call to the sales method.
Example Language: Java (Good)
...
// update sales database for number of product sold with product ID
public void updateSalesForProduct(String productID, int amountSold) {
// get the total number of products in inventory database
int productCount = inventory.getProductCount(productID);
// make sure that integer numbers are not greater than
// maximum value for type short before converting
if ((productCount < Short.MAX_VALUE) && (amountSold < Short.MAX_VALUE)) {
// convert integer values to short, the method for the
// sales object requires the parameters to be of type short
short count = (short) productCount;
short sold = (short) amountSold;
// update sales database for product
sales.updateSalesCount(productID, count, sold);
else {
// throw exception or perform other processing
...
}
}
...
Observed Examples
Reference Description
CVE-2020-17087 Chain: integer truncation (CWE-197) causes small buffer allocation (CWE-131)
leading to out-of-bounds write (CWE-787) in kernel pool, as exploited in the
wild per CISA KEV.
https://www.cve.org/CVERecord?id=CVE-2020-17087
CVE-2009-0231 Integer truncation of length value leads to heap-based buffer overflow.
https://www.cve.org/CVERecord?id=CVE-2009-0231
CVE-2008-3282 Size of a particular type changes for 64-bit platforms, leading to an integer
truncation in document processor causes incorrect index to be generated.
https://www.cve.org/CVERecord?id=CVE-2008-3282
MemberOf Relationships
This MemberOf relationships table shows additional CWE Catgeories and Views that reference this
weakness as a member. This information is often useful in understanding where a weakness fits
within the context of external information sources.
CWE Version 4.14
CWE-198: Use of Incorrect Byte Ordering
CWE-198: Use of Incorrect Byte Ordering