...
Non-Compliant Code Example (left shift)
Wiki Markup |
---|
The result of {{E1 << E2}} is {{E1}} left-shifted {{E2 bit positions; vacated bits are filled with zeros. If {{E1}} has an unsigned type, the value of the result is {{E1 |
* 2^E2^, reduced modulo one more than the maximum value representable in the result type. If E1 has a signed type and nonnegative value, and E1 * 2^E2^ is representable in the result type, then that is the resulting value; otherwise, the behavior is undefined. * 2 ^E2^}}, reduced modulo one more than the maximum value representable in the result type. As a result, left shift operations can result in an integer overflow condition (see \[[INT32-C|INT32-C. Ensure that integer operations do not result in an overflow]\]). If {{E1}} has a signed type and nonnegative value, and {{E1 * 2 ^E2^}} is representable in the result type, then that is the resulting value; otherwise, the behavior is undefined. |
The following code can result in undefined behavior because there is no check to ensure that left and right operands have nonnegative values, and that the right operand is greater than or equal to the width of the promoted left operand.
Code Block |
---|
|
signed int si1, si2 |
Code Block |
---|
|
unsigned int ui1, ui2, result;
result = ui1si1 >><< ui2si2;
|
Compliant Solution (unsigned)
This compliant solution tests the suspect shift operation to guarantee there is no possibility of unsigned overflow.
Code Block |
---|
|
unsigned int ui1si1, ui2si2, result;
if ( (ui2si2 < 0) || (si2 < 0) || (ui2si2 >= sizeof(unsigned int)*CHAR_BIT) ) {
/* handle error condition */
}
result = ui1si1 >><< ui2;
si2;
|
In C99, the CHAR_BIT
macro defines the number of bits for smallest object that is not a bit-field (byte). A byte, therefore, contains CHAR_BIT
bits.
Non-Compliant Code Example (right shift)
...
This code can result in an unsigned overflow during the shift operation of the unsigned operands ui1
and ui2
. If this behavior is unanticipated, the resulting value may be used to allocate insufficient memory for a subsequent operation or in some other manner that could lead to an exploitable vulnerability.
Code Block |
---|
|
signed int si1, si2, result;
result = ui1 >> ui2;
|
Compliant Solution (left shift)
This compliant solution tests the suspect shift operation to guarantee there is no possibility of unsigned overflow.
Code Block |
---|
|
unsigned int ui1, ui2, result;
if ( (ui2 < 0) || (ui2 >= sizeof(unsigned int)*CHAR_BIT) ) {
/* handle error condition */
}
result = ui1 >> ui2;
|
References
- ISO/IEC 9899-1999 Section 6.5, "Expressions," and Section 7.10, "Sizes of integer types <limits.h>"
- Seacord 05 Chapter 5, "Integers"
- Viega 05 Section 5.2.7, "Integer overflow"
- Dowd 06 Chapter 6, "C Language Issues"