Integer conversions, both implicit and explicit (using a cast), must be guaranteed not to result in lost or misinterpreted data. This is particularly true for integer values that originate from untrusted sources and are used in any of the following ways:
- as As an array index
- in In any pointer arithmetic
- as As a length or size of an object
- as As the bound of an array (for example, a loop counter)
- as As an argument to a memory allocation function
- in In security-critical code
The only integer type conversions that are guaranteed to be safe for all data values and all possible conforming implementations are conversions of an integral value to a wider type of the same signedness. Section 6.3.1.3 of the C Standard [ISO/IEC 9899:2011] says,
...
Tool | Version | Checker | Description | |||||||||||||||||
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
Compass/ROSE | Can detect violations of this rule. However, false warnings may be raised if | |||||||||||||||||||
| NEGATIVE_RETURNS
MISRA_CAST | Can find array accesses, loop bounds, and other expressions that may contain dangerous implied integer conversions that would result in unexpected behavior.Coverity* Include Page | | Coverity_V | Coverity_V | REVERSE_NEGATIVE | Can find instances where a negativity check occurs after the negative value has been used for something else. | |||||||||||||
Include Page | Coverity_V | Coverity_V | MISRA_CAST | Can find the instances where an integer expression is implicitly converted to a narrower integer type, or implicitly converting the signedness of an integer value or implicitly converting the type of a complex expression. | ||||||||||||||||
Fortify SCA | 5.0 | Can detect violations of this rule with CERT C Rule Pack. | ||||||||||||||||||
| PRECISION.LOSS | |||||||||||||||||||
| 93 S | Fully implemented. | ||||||||||||||||||
PRQA QA-C |
| 2850 (C) | Partially implemented |
...
[Dowd 2006] | Chapter 6, "C Language Issues" ("Type Conversions," pp. 223–270) |
[ISO/IEC 9899:2011] | Section 6.3.1.3, "Signed and Unsigned Integers" |
[Seacord 2005a2013] | Chapter 5, "IntegersInteger Security" |
[Viega 2005] | Section 5.2.9, "Truncation Error" Section 5.2.10, "Sign Extension Error" Section 5.2.11, "Signed to Unsigned Conversion Error" Section 5.2.12, "Unsigned to Signed Conversion Error" |
[Warren 2002] | Chapter 2, "Basics" |
[xorl 2009] | "CVE-2009-1376: Pidgin MSN SLP Integer Truncation" |
...