Bitwise operators include the complement operator (~), bitwise shift operators ( >> and <<), bitwise AND operator (&), bitwise exclusive OR operator (^), and bitwise inclusive OR operator (|). Bitwise operators should only be used with unsigned integer operands, as the results of some bitwise operations on signed integers is implementation - defined.
Noncompliant Code Example (right shift)
| Wiki Markup |
|---|
The right-shift operation may be implemented as either an arithmetic (signed) shift or a logical (unsigned) shift. If {{E1}} in the expression {{E1 >> E2}} has a signed type and a negative value, the resulting value is implementation- defined. Also, be careful to avoid [undefined behavior|BB. Definitions#undefined behavior] while performing a bitwise shift (see [INT34-C. Do not shift a negative number of bits or more bits than exist in the operand]). This noncompliant code example can result in an error condition on [implementations|BB. Definitions#implementation] in which an arithmetic shift is performed and the sign bit can be propagated as the number is shifted \[[Dowd 06|AA. C References#Dowd 06]\]. |
...
In this compliant solution, stringify is declared as an unsigned integer. The value of the result of the right- shift operation is the integral part of the quotient of stringify / 2 242^24^.
| Code Block | ||
|---|---|---|
| ||
int rc = 0;
unsigned int stringify = 0x80000000;
char buf[sizeof("256")];
rc = snprintf(buf, sizeof(buf), "%u", stringify >> 24);
if (rc == -1 || rc >= sizeof(buf)) {
/* handle error */
}
|
...
INT13-EX2: If the right hand side operand to a shift operator is known at compile time, it is acceptable for the value to be represented with a signed type in the compiler so long as the provided it is positive.
| Code Block | ||
|---|---|---|
| ||
#define SHIFT 24 foo = 15u >> SHIFT; |
Risk Assessment
Improper range checking Performing bitwise operations on signed numbers can lead to buffer overflows and the execution of arbitrary code by an attacker in some cases, unexpected or implementation defined behavior in others.
Recommendation | Severity | Likelihood | Remediation Cost | Priority | Level |
|---|---|---|---|---|---|
INT13-C | high | unlikely | medium | P6 | L2 |
...