Using integers
Incorrectly using both signed and unsigned integers, as well as incorrectly performing arithmetic on them, can result in a number of issues. These issues range from stability problems, such as Denial of Service (DoS), to arbitrary code execution in the affected program.
Recommendations
There are a set of core rules that can help mitigate issues when dealing with integers:
- Don't use signed integers, shorts, or chars when storing sizes that are supplied by network data.
- Don't use signed integers, shorts, or chars for any variables that represent natural or countable items. Use signed variables only if a negative value makes sense in that context.
- When performing arithmetic in conditional statements, ensure that the arithmetic is always balanced.
- When casting, consider sign extension and zero extension in addition to truncation.
- Where possible, avoid mixing types in expressions. Try to use consistent types or cast to consistent types, keeping the above guidelines in mind.
- Remember that memory and copy functions in C/C++ treat all integers as unsigned.
Further reading
Integer overflows and underflows
Integers can overflow and underflow. Consider the following function that results in an integer overflow:
#include <stdio.h>
int main(int argc, char * argv[]) {
int intFoo=0;
fprintf(stdout,"[i] %d %u\n",intFoo,intFoo);
intFoo -= 1;
fprintf(stdout,"[i] %d %u\n",intFoo,intFoo);
return 0;
}
Calling this function results in the following:
[i] 0 0 [i] -1 4294967295
Since unsigned integers range from 0 to 232 - 1, subtracting 1 from 0 causes the value to wrap around and result in a potentially undesired value.
For applications that are written in a non-memory safe language like C and C++, these overflow issues can lead to memory corruption and catastrophic security compromises. If you do not catch exceptions and deal with them appropriately, integer underflow or overflow can result in a DoS and might lead to unexpected application behavior. In the case of security-relevant components, these issues can then allow other types of security breaches. For example, inducing an integer overflow can circumvent the functionality of an access control system.