The first line of defense against integer vulnerabilities should be range checking, either explicitly or through strong typing. However, it is difficult to guarantee that multiple input variables cannot be manipulated to cause an error to occur in some 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 safe integer library for all operations on integers where one or more of the inputs could be influenced by an untrusted source and the resulting value, if incorrect, would result in a security flaw. The following example shows when safe 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 safe integers would add unnecessary performance overhead.
The IntegerLib IntegerLib.zip was developed by the CERT/CC and is freely available.
The purpose of this library is to provide a collection of utility functions that can assist software developers in writing C and C++ programs that are free from common integer problems such as integer overflow, integer truncation, and sign errors that are a common source of software vulnerabilities.
Functions have been provided for all integer operations subject to overflow such as addition, subtraction, multiplication, division, unary negation, etc.) for
long long, and
size_t integers. The following example illustrates how the library can be used to add two
signed long integer values:
For short integer types (
short) it is necessary to truncate the result of the addition using one of the safe conversion functions provided, for example:
For error handling, the secure integer library uses the mechanism for runtime-constraint handling defined by ISO/IEC TR 24731-2006.
The implementation uses the high performance algorithms defined by Henry S. Warren in the book "Hacker's Delight".