You are viewing an old version of this page. View the current version.

Compare with Current View Page History

« Previous Version 115 Next »

Bitwise shifts include left-shift operations of the form shift-expression << additive-expression and right-shift operations of the form shift-expression >> additive-expression. The integer promotions are performed on the operands, each of which has an integer type. The type of the result is that of the promoted left operand. If the value of the right operand is negative or is greater than or equal to the width of the promoted left operand, the behavior is undefined. See also undefined behavior 51 in Annex J of the C Standard.

Do not shift a negative number of bits or by more than the precision of the promoted left operand. The precision of an integer type is the number of bits it uses to represent values, excluding any sign and padding bits. For unsigned integer types the width and the precision are the same, while for signed integer types the width is one greater than the precision.  We use precision instead of width in this rule to prevent a bit change from escaping the value bits to enter the sign bit, which is a violation of INT32-C. Ensure that operations on signed integers do not result in overflow.

In almost every case, an attempt to shift by a negative number of bits or by more than the precision of the operand indicates a bug (logic error). A logic error is different from overflow, in which there is simply a representational deficiency.  In general, shifts should only be performed on unsigned operands (see INT13-C. Use bitwise operators only on unsigned operands).

Noncompliant Code Example (Left Shift, Signed Type)

The result of E1 << E2 is E1 left-shifted E2 bit positions; vacated bits are filled with zeros. If E1 has a signed type and nonnegative value and E1 * 2E2 is representable in the result type, then that is the resulting value; otherwise, the behavior is undefined.

This noncompliant code example fails to ensure that left and right operands have nonnegative values and that the right operand is less than or equal to the precision of the promoted left operand. The example can also produce signed integer overflow; see INT32-C. Ensure that operations on signed integers do not result in overflow for more information.

void func(signed long si_a, signed long si_b) {
  signed long sresult = si_a << si_b;

  /* ... */
}

Shift operators and other bitwise operators should be used only with unsigned integer operands in accordance with INT13-C. Use bitwise operators only on unsigned operands.

Compliant Solution (Left Shift, Signed Type)

This compliant solution eliminates the possibility of overflow resulting from a left-shift operation:

#include <limits.h>
#include <stddef.h>
#include <inttypes.h>
 
extern size_t popcount(uintmax_t);
#define PRECISION(x) popcount(x)

void func(signed long si_a, signed long si_b) {
  signed long result;
  if ((si_a < 0) || (si_b < 0) ||
      (si_b >= PRECISION(ULONG_MAX)) ||
      (si_a > (LONG_MAX >> si_b))) {
    /* Handle error */
  } else {
    result = si_a << si_b;
  }
  /* ... */
}

 

The PRECISION()macro provides the correct precision for any integer type (see INT35-C. Use correct integer precisions)

Noncompliant Code Example (Left Shift, Unsigned Type)

The result of E1 << E2 is E1 left-shifted E2 bit positions; vacated bits are filled with zeros. According to the C Standard, if E1 has an unsigned type, the value of the result is E1 * 2E2, reduced modulo 1 more than the maximum value representable in the result type.

This noncompliant code example fails to ensure that the right operand is less than or equal to the precision of the promoted left operand:

void func(unsigned int ui_a, unsigned int ui_b) {
  unsigned int uresult = ui_a << ui_b;
  /* ... */
}

Compliant Solution (Left Shift, Unsigned Type)

This compliant solution eliminates the possibility of shifting by more bits than exist in the left hand operand:

#include <limits.h>
#include <stddef.h>
#include <inttypes.h>

extern size_t popcount(uintmax_t);
#define PRECISION(x) popcount(x)
 
void func(unsigned int ui_a, unsigned int ui_b) {
  unsigned int uresult = 0;
  if (ui_b >= PRECISION(UINT_MAX)) {
    /* Handle error condition */
  } else {
    uresult = ui_a << ui_b;
  }

  /* ... */
}

Modulo behavior resulting from left-shifting an unsigned integer type is permitted by exception INT30-EX3 to INT30-C. Ensure that unsigned integer operations do not wrap.

Noncompliant Code Example (Right Shift)

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 / 2E2. If E1 has a signed type and a negative value, the resulting value is implementation-defined and can be either an arithmetic (signed) shift:

or a logical (unsigned) shift:

This noncompliant code example fails to test whether the right operand is greater than or equal to the precision of the promoted left operand, allowing undefined behavior:

void func(unsigned int ui_a, unsigned int ui_b) {
  unsigned int uresult = ui_a >> ui_b;
  /* ... */
}

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 INT13-C. Use bitwise operators only on unsigned operands.

Compliant Solution (Right Shift)

This compliant solution eliminates the possibility of shifting by more bits than exist in the left hand operand:

#include <limits.h>
#include <stddef.h>
#include <inttypes.h>

extern size_t popcount(uintmax_t);
#define PRECISION(x) popcount(x)
 
void func(unsigned int ui_a, unsigned int ui_b) {
  unsigned int uresult = 0;
  if (ui_b >= PRECISION(UINT_MAX)) {
    /* Handle error condition */
  } else {
    uresult = ui_a >> ui_b;
  }
  /* ... */
}

Implementation Details

GCC has no options to handle shifts by negative amounts or by amounts outside the width of the type predictably or to trap on them; they are always treated as undefined. Processors may reduce the shift amount modulo the width of the type. For example, 32-bit shifts are implemented using the following instructions on x86-32:

sa[rl]l   %cl, %eax

The sa[rl]l instructions take a bit mask of the least significant 5 bits from %cl to produce a value in the range [0, 31] and then shift %eax that many bits:

// 64-bit shifts on IA-32 platforms become
sh[rl]dl  %eax, %edx
sa[rl]l   %cl, %eax

where %eax stores the least significant bits in the doubleword to be shifted, and %edx stores the most significant bits.

Exceptions

INT34-EX1: The signed integer value zero can be shifted by the width and not the precision.  Assuming a 32-bit int, for example, the following expression is allowed:

 0 << 31;

INT34-EX2: Any positive integer value can be right shifted by the width of the promoted left hand operand.  For example, positive >> 31 is valid for implementations where int has a width of 32 bits. However, any portable shift expression that takes advantage of the full width of a signed integer is guaranteed to have a result of zero, so it is not useful to shift beyond the precision.

Risk Assessment

Although shifting a negative number of bits or more bits than exist in the operand is undefined behavior in C, the risk is generally low because processors frequently reduce the shift amount modulo the width of the type.

Rule

Severity

Likelihood

Remediation Cost

Priority

Level

INT34-C

Low

Unlikely

Medium

P2

L3

Automated Detection

Tool

Version

Checker

Description

Compass/ROSE

 

 

Can detect violations of this rule. Unsigned operands are detected when checking for INT13-C. Use bitwise operators only on unsigned operands

ECLAIR1.2CC2.INT34Partially implemented

Fortify SCA

5.0

 

Can detect violations of this rule with CERT C Rule Pack

LDRA tool suite

9.7.1

403 S

Partially implemented

PRQA QA-C
Unable to render {include} The included page could not be found.

0499
0500
0501
2790
2791 (D)
2792 (A)
2793 (S)

Partially implemented

Related Vulnerabilities

Search for vulnerabilities resulting from the violation of this rule on the CERT website.

Related Guidelines

Bibliography

[Dowd 2006]Chapter 6, "C Language Issues"
[C99 Rationale 2003]Subclause 6.5.7, "Bitwise Shift Operators"
[Seacord 2013]Chapter 5, "Integer Security"
[Viega 2005]Section 5.2.7, "Integer Overflow"

 


  • No labels