...
In almost every case, an attempt to shift by a negative number of bits or by more bits than exist in the operand indicates a bug (logic error). This is different from overflow, where there is simply a representational deficiency. (See guideline rule INT32-C. Ensure that operations on signed integers do not result in overflow.)
...
Shift operators, and other bitwise operators, should only be used with unsigned integer operands, in accordance with guideline recommendation INT13-C. Use bitwise operators only on unsigned operands.
...
The result of E1 >> E2
is E1
right-shifted E2
bit positions. If E1
has an unsigned type or if E1
has a signed type and a nonnegative value, the value of the result is the integral part of the quotient of E1
/ 2
E2
. If E1
has a signed type and a negative value, the resulting value is implementation defined and may can be either an arithmetic (signed) shift:
...
Making assumptions about whether a right shift is implemented as an arithmetic (signed) shift or a logical (unsigned) shift can also lead to vulnerabilities. See guideline recommendation INT13-C. Use bitwise operators only on unsigned operands.
...
|
|
|
| ||||||
|
|
|
|
...
Search for vulnerabilities resulting from the violation of this rule on the CERT website.
Related Guidelines
CERT C++ Secure Coding Standard: INT34-CPP. Do not shift a negative number of bits or more bits than exist in the operand
ISO/IEC 9899:1999 Section 6.5.7, "Bitwise shift operators"
ISO/IEC TR 24772 "XYY Wrap-around Error"
ISO/IEC 2003 Section 6.5.7, "Bitwise shift operators"
Bibliography
A test program for this rule is available at www.securecoding.cert.org
Wiki Markup |
---|
\[[Dowd 2006|AA. Bibliography#Dowd 06]\] Chapter 6, "C Language Issues" \[[ISO/IEC 9899:1999|AA. Bibliography#ISO/IEC 9899-1999]\] Section 6.5.7, "Bitwise shift operators" \[[ISO/IEC PDTR 24772|AA. Bibliography#ISO/IEC PDTR 24772]\] "XYY Wrap-around Error" \[[Seacord 2005a|AA. Bibliography#Seacord 05]\] Chapter 5, "Integers" \[[Viega 2005|AA. Bibliography#Viega 05]\] Section 5.2.7, "Integer overflow" \[[ISO/IEC 2003|AA. Bibliography#ISO/IEC 03]\] Section 6.5.7, "Bitwise shift operators" |
...
INT33-C. Ensure that division and modulo operations do not result in divide-by-zero errors 04. Integers (INT) INT35-C. Evaluate integer expressions in a larger size before comparing or assigning to that size