SafeInt
SafeInt is a C++ template class written by David LeBlanc. SafeInt throws an exception if the results of an integer operation cannot be represented in the specified type. The class is declared as a template, so it can be used with any integer type. Every operator has been overridden except for the subscript operator[] so that operators can be used in normal arithmetic expressions.
SafeInt fails to provide correct integer promotion behavior, but the greatest limitation of SafeInt is that it cannot be used with C applications. Because operators cannot be overloaded in C, safe integer solutions are not as easy to use.
CERT Integer Library
The CERT Coordination Center has recently released a secure integer library for the C Programming Language. The library is available for download from the CERT/CC Secure Coding Initiative web page
The purpose of the library is to provide a collection of utility functions that can assist software developers in writing C programs that are free from 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, and so on) for int, long, long long, and size_t integers. The following example illustrates how the library can be used to add two signed long integer values:
long retsl, xsl, ysl; xsl = LONG_MAX; ysl = 0; retsl = addsl(xsl,ysl);
For short integer types (char and short) it is necessary to truncate the result of the addition using one of the safe conversion functions provided. For example:
char retsc, xsc, ysc; xsc = SCHAR_MAX; ysc = 0; retsc = si2sc(addsi(xsc, ysc));
For error handling, the secure integer library uses the mechanism for runtime-constraint handling defined by ISO/IEC TR 24731.
The implementation uses the high-performance algorithms defined by Henry S. Warren in the book Hacker's Delight.
Conclusions
Integer vulnerabilities result from lost or misrepresented data. The key to preventing these vulnerabilities is to understand the nuances of integer behavior in C and C++ and carefully apply this knowledge in the design and implementation of your systems.
Consider using safe integer operations to eliminate exception conditions, focusing on integers used as indices (or other pointer arithmetic), lengths, sizes, and loop counters.
If integer type range checking is properly applied and safe integer operations are used for values that can pass out of range (particularly due to external manipulation), it is possible to prevent vulnerabilities resulting from integer range errors.
Robert Seacord is a Senior Vulnerability Analyst for CERT/CC, where he leads the secure coding initiative, including the development of secure coding standards for C and C++. He is also the author of three books, including Secure Coding in C and C++ .