This guideline has not been reviewed recently and may be outdated. Please review it and comment to reflect any newly available information.
The first line of defense against integer vulnerabilities is range checking, either explicitly or through strong typing. One approach is to enforce limits on integer values originating from untrusted sources (see INT04-CPP. Enforce limits on integer values originating from untrusted sources). However, it is difficult to guarantee that multiple input variables cannot be manipulated to cause an error to occur in an operation somewhere in a program.
An alternative or ancillary approach is to protect each operation. However, because of the large number of integer operations that are susceptible to these problems and the number of checks required to prevent or detect exceptional conditions, this approach can be prohibitively labor intensive and expensive to implement.
A more economical solution to this problem is to use a secure integer library for all operations on integers where one or more of the inputs can be influenced by an untrusted source and the resulting value, if incorrect, can result in a security flaw including integer values used in any of the following ways:
- as an array index
- in any pointer arithmetic
- as a length or size of an object
- as the bound of an array (for example, a loop counter)
- as an argument to a memory allocation function
- in security critical code
The following example shows when secure integer operations are not required:
In this example, the integer
i is used in a tightly controlled loop and is not subject to manipulation by an untrusted source, so using secure integers provides no value and only introduces unnecessary overhead.
One example of a secure integer library for C++ is SafeInt by David LeBlanc.
Integer behavior in C is relatively complex, and it is easy to make subtle errors that turn into exploitable vulnerabilities. While not strictly necessary, using a secure integer library can provide an encapsulated solution against these errors.
Search for vulnerabilities resulting from the violation of this rule on the CERT website.
[ISO/IEC TR 24731-1:2007]
[ISO/IEC PDTR 24772] "TRJ Use of Libraries"
[MITRE 07] CWE ID 606,"Unchecked Input for Loop Condition"; CWE ID 190,"Integer Overflow (Wrap or Wraparound)"
[Seacord 05a] Chapter 5, "Integers"
[Warren 02] Chapter 2, "Basics"