Versions Compared

Key

  • This line was added.
  • This line was removed.
  • Formatting was changed.

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 standard integer promotions are first 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 an expression by a negative number of bits or by a number greater than or equal to 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; whereas for signed integer types, the width is one greater than the precision. This rule uses precision instead of width because, in In almost every case, an attempt to shift by a negative number of bits or by more bits than exist in greater than or equal to 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 be performed only on unsigned operands. (See INT32INT13-C. Ensure that operations on signed integers do not result in overflowUse bitwise operators only on unsigned operands.)

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. If E1 has a signed type and nonnegative value and . The following diagram illustrates the left-shift operation.

Image Added

According to the C Standard, if E1 has an unsigned type, the value of the result is E1 * 2E2 is , reduced modulo 1 more than the maximum value representable in the result type, then that is the resulting value; otherwise, the behavior is undefined.

Image Removed

This noncompliant code example can result in undefined behavior because there is no check to ensure that left and right operands have nonnegative values and fails to ensure that the right operand is less than or equal to the width 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.:

Code Block
bgColor#FFcccc
langc
void func(signedunsigned longint siui_a, signedunsigned longint siui_b) {
  signedunsigned longint sresulturesult = siui_a << siui_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,

...

Unsigned Type)

This compliant solution eliminates the possibility of overflow resulting from a left-shift operationof shifting by greater than or equal to the number of bits that exist in the precision of the left operand:

Code Block
bgColor#ccccff
langc
#include <limits.h>
#include <stddef.h>
#include <inttypes.h>
 
extern size_t popcount(uintmax_t);
#define UWIDTHPRECISION(x) popcount(x)
 
void func(signedunsigned longint siui_a, signedunsigned longint siui_b) {
  signedunsigned longint result;
  if ((si_a < 0) || (si_b < 0) ||uresult = 0;
   if   (siui_b >= UWIDTH(ULONG_MAX)) ||
      (si_a > (LONG_MAX >> si_b)PRECISION(UINT_MAX)) {
    /* Handle error */
  } else {
    resulturesult = siui_a << siui_b;
  }
  /* ... */
}

 

The UWIDTHPRECISION() macro provides and popcount() function provide the correct width precision for an unsigned any integer type. (see INT19See INT35-C. Correctly compute integer widths). This solution also complies with INT34-C. Do not shift a negative number of bits or more bits than exist in the operandUse correct integer precisions.)

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 (Left Shift,

...

Signed 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 If E1 has an unsigned type, the value of the result is a signed type and nonnegative value, and E1 * 2E2, reduced modulo 1 more than the maximum value is representable in the result type, then that is the resulting value; otherwise, the behavior is undefined.

This noncompliant code example can result in undefined behavior because there is no check to ensure fails to ensure that left and right operands have nonnegative values and that the right operand is less than or equal to the width precision of the promoted left operand:. This example does check for signed integer overflow in compliance with INT32-C. Ensure that operations on signed integers do not result in overflow.

Code Block
bgColor#FFcccc
langc
#include <limits.h>
#include <stddef.h>
#include <inttypes.h>

void func(unsignedsigned intlong uisi_a, unsigned int ui_b) signed long si_b) {
  signed long result;
  if (si_a > (LONG_MAX >> si_b)) {
    /* Handle error */
  } else {
  unsigned int uresultresult = uisi_a << uisi_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 undefined behavior resulting from a left-shift operation on unsigned integersIn addition to the check for overflow, this compliant solution ensures that both the left and right operands have nonnegative values and that the right operand is less than the precision of the promoted left operand:

Code Block
bgColor#ccccff
langc
#include <limits.h>
#include <stddef.h>
#include <inttypes.h>
 
extern size_t popcount(uintmax_t);
#define UWIDTHPRECISION(x) popcount(x)
 
void func(unsignedsigned intlong uisi_a, unsignedsigned intlong uisi_b) {
  signed long result;
   unsigned int uresult = 0;
  if (uiif ((si_a < 0) || (si_b < 0) ||
      (si_b >= UWIDTH(UINT_MAX PRECISION(ULONG_MAX)) ||
      (si_a > (LONG_MAX >> si_b))) {
    /* Handle error condition */
  } else {
    uresultresult = uisi_a << uisi_b;
  }

  /* ... */
}

Modulo behavior resulting from left-shifting an unsigned integer type is permitted by this standard.

...



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 width precision of the promoted left operand, allowing undefined behavior:

Code Block
bgColor#FFcccc
langc
void func(unsigned int ui_a, unsigned int ui_b) {
  unsigned int uresult = ui_a >> ui_b;

  /* ... */
}

Making When working with signed operands, 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 tests the suspect shift operations to guarantee there is no possibility of undefined behavioreliminates the possibility of shifting by greater than or equal to the number of bits that exist in the precision of the left operand:

Code Block
bgColor#ccccff
langc
#include <limits.h>
#include <stddef.h>
#include <inttypes.h>

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

 The UWIDTH() macro provides the correct width for an unsigned integer type and is defined in INT19-C. Correctly compute integer widths; see that rule for more information.

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 right shifts are implemented using the following instructions instruction on IAx86-32:

Code Block
sa[rl]lsarl   %cl, %eax

The sa[rl]l instructions take sarl instruction takes 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:

Code Block
// 64-bit right shifts on IA-32 platforms become
sh[rl]dlshrdl  %eax%edx, %edx
sa[rl]l%eax
sarl   %cl, %eax%edx

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

Risk Assessment

Although shifting a negative number of bits or more shifting a number of bits than exist in the greater than or equal to the width of the promoted left 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

Astrée
Include Page
Astrée_V
Astrée_V

precision-shift-width
precision-shift-width-constant

Fully checked
Axivion Bauhaus Suite

Include Page
Axivion Bauhaus Suite_V
Axivion Bauhaus Suite_V

CertC-INT34Can detect shifts by a negative or an excessive number of bits and right shifts on negative values.
CodeSonar
Include Page
CodeSonar_V
CodeSonar_V

LANG.ARITH.BIGSHIFT
LANG.ARITH.NEGSHIFT

Shift amount exceeds bit width
Negative shift amount

Compass/ROSE

 

 



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

Coverity
Include Page
Coverity_V
Coverity_V

BAD_SHIFT

Implemented
Cppcheck
Include Page
Cppcheck_V
Cppcheck_V
shiftNegative, shiftTooManyBits

Context sensitive analysis
Warns whenever Cppcheck sees a negative shift for a POD expression
(The warning for shifting too many bits is written only if Cppcheck has sufficient type information and you use --platform to specify the sizes of the standard types.)

Cppcheck Premium

Include Page
Cppcheck Premium_V
Cppcheck Premium_V

shiftNegative, shiftTooManyBits

premium-cert-int34-c

Context sensitive analysis
Warns whenever Cppcheck sees a negative shift for a POD expression
(The warning for shifting too many bits is written only if Cppcheck has sufficient type information and you use --platform to specify the sizes of the standard types.)
ECLAIR
Include Page
ECLAIR_V
ECLAIR_V
CC2.INT34Partially implemented

Fortify SCA

5.0

 

Helix QAC

Include Page
Helix QAC_V
Helix QAC_V

C0499, C2790, 

C++2790,  C++3003

DF2791, DF2792, DF2793


Klocwork

Include Page
Klocwork_V
Klocwork_V

MISRA.SHIFT.RANGE.2012

Can detect violations of this rule with CERT C Rule Pack


LDRA tool suite
Include Page
LDRA_V
LDRA_V

51 S, 403 S, 479 S

Partially implemented

PRQA QA-C Include PagePRQA_VPRQA_V

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

Parasoft C/C++test
Include Page
Parasoft_V
Parasoft_V
CERT_C-INT34-a

Avoid incorrect shift operations

Polyspace Bug Finder

Include Page
Polyspace Bug Finder_V
Polyspace Bug Finder_V

CERT C: Rule INT34-C


Checks for:

  • Shift of a negative value
  • Shift operation overflow

Rule partially covered.

PVS-Studio

Include Page
PVS-Studio_V
PVS-Studio_V

V610
RuleChecker

Include Page
RuleChecker_V
RuleChecker_V

precision-shift-width-constant

Partially checked
TrustInSoft Analyzer

Include Page
TrustInSoft Analyzer_V
TrustInSoft Analyzer_V

shift

Exhaustively verified (see one compliant and one non-compliant example).

Partially implemented

Related Vulnerabilities

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

Related Guidelines

Key here (explains table format and definitions)

Taxonomy

Taxonomy item

Relationship

CERT C
Secure Coding Standard
INT13-C. Use bitwise operators only on unsigned operands

INT19
Prior to 2018-01-12: CERT: Unspecified Relationship
CERT CINT35-C.
Correctly compute integer widths
Use correct integer precisionsPrior to 2018-01-12: CERT: Unspecified Relationship
CERT CINT32-C. Ensure that operations on signed integers do not result in overflow
CERT C++ Secure Coding StandardINT34-CPP. Do not shift a negative number of bits or more bits than exist in the operand
Prior to 2018-01-12: CERT: Unspecified Relationship
ISO/IEC TR 24772:2013Arithmetic Wrap-
around
Around Error [FIF]

Bibliography

Prior to 2018-01-12: CERT: Unspecified Relationship
CWE 2.11CWE-6822017-07-07: CERT: Rule subset of CWE
CWE 2.11CWE-7582017-07-07: CERT: Rule subset of CWE

CERT-CWE Mapping Notes

Key here for mapping notes

CWE-758 and INT34-C

Independent( INT34-C, INT36-C, MEM30-C, MSC37-C, FLP32-C, EXP33-C, EXP30-C, ERR34-C, ARR32-C)

CWE-758 = Union( INT34-C, list) where list =


  • Undefined behavior that results from anything other than incorrect bit shifting


CWE-682 and INT34-C

Independent( INT34-C, FLP32-C, INT33-C) CWE-682 = Union( INT34-C, list) where list =


  • Incorrect calculations that do not involve out-of-range bit shifts


Bibliography

...

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

...


...

Image Modified Image Modified Image Modified