Skip to content

Commit 6628857

Browse files
Merge pull request #237 from github/jeongsoolee09/Types
Implement Types Package
2 parents db66281 + b33391d commit 6628857

32 files changed

+4594
-547
lines changed
Lines changed: 216 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,216 @@
1+
# INT34-C: Bit shift should not be done by a negative operand or an operand of greater-or-equal precision than that of another
2+
3+
This query implements the CERT-C rule INT34-C:
4+
5+
> Do not shift an expression by a negative number of bits or by greater than or equal to the number of bits that exist in the operand
6+
7+
8+
## Description
9+
10+
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](https://wiki.sei.cmu.edu/confluence/display/c/BB.+Definitions#BB.Definitions-undefinedbehavior). (See [undefined behavior 51](https://wiki.sei.cmu.edu/confluence/display/c/CC.+Undefined+Behavior#CC.UndefinedBehavior-ub_51).)
11+
12+
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 almost every case, an attempt to shift by a number of bits 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 [INT13-C. Use bitwise operators only on unsigned operands](https://wiki.sei.cmu.edu/confluence/display/c/INT13-C.+Use+bitwise+operators+only+on+unsigned+operands).)
13+
14+
## Noncompliant Code Example (Left Shift, Unsigned Type)
15+
16+
The result of `E1 << E2` is `E1` left-shifted `E2` bit positions; vacated bits are filled with zeros. The following diagram illustrates the left-shift operation.
17+
18+
![](ShiftLeft.JPG)
19+
20+
According to the C Standard, if `E1` has an unsigned type, the value of the result is `E1` \* `2``<sup>E2</sup>`, reduced modulo 1 more than the maximum value representable in the result type.
21+
22+
This noncompliant code example fails to ensure that the right operand is less than the precision of the promoted left operand:
23+
24+
```cpp
25+
void func(unsigned int ui_a, unsigned int ui_b) {
26+
unsigned int uresult = ui_a << ui_b;
27+
/* ... */
28+
}
29+
```
30+
31+
## Compliant Solution (Left Shift, Unsigned Type)
32+
33+
This compliant solution eliminates the possibility of shifting by greater than or equal to the number of bits that exist in the precision of the left operand:
34+
35+
```cpp
36+
#include <limits.h>
37+
#include <stddef.h>
38+
#include <inttypes.h>
39+
40+
extern size_t popcount(uintmax_t);
41+
#define PRECISION(x) popcount(x)
42+
43+
void func(unsigned int ui_a, unsigned int ui_b) {
44+
unsigned int uresult = 0;
45+
if (ui_b >= PRECISION(UINT_MAX)) {
46+
/* Handle error */
47+
} else {
48+
uresult = ui_a << ui_b;
49+
}
50+
/* ... */
51+
}
52+
```
53+
The `PRECISION()` macro and `popcount()` function provide the correct precision for any integer type. (See [INT35-C. Use correct integer precisions](https://wiki.sei.cmu.edu/confluence/display/c/INT35-C.+Use+correct+integer+precisions).)
54+
55+
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](https://wiki.sei.cmu.edu/confluence/display/c/INT30-C.+Ensure+that+unsigned+integer+operations+do+not+wrap).
56+
57+
## Noncompliant Code Example (Left Shift, Signed Type)
58+
59+
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` \* `2``<sup>E2</sup>` is representable in the result type, then that is the resulting value; otherwise, the behavior is undefined.
60+
61+
This noncompliant code example fails to ensure that left and right operands have nonnegative values and that the right operand is less than the 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](https://wiki.sei.cmu.edu/confluence/display/c/INT32-C.+Ensure+that+operations+on+signed+integers+do+not+result+in+overflow).
62+
63+
```cpp
64+
#include <limits.h>
65+
#include <stddef.h>
66+
#include <inttypes.h>
67+
68+
void func(signed long si_a, signed long si_b) {
69+
signed long result;
70+
if (si_a > (LONG_MAX >> si_b)) {
71+
/* Handle error */
72+
} else {
73+
result = si_a << si_b;
74+
}
75+
/* ... */
76+
}
77+
```
78+
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](https://wiki.sei.cmu.edu/confluence/display/c/INT13-C.+Use+bitwise+operators+only+on+unsigned+operands).
79+
80+
## Compliant Solution (Left Shift, Signed Type)
81+
82+
In 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:
83+
84+
```cpp
85+
#include <limits.h>
86+
#include <stddef.h>
87+
#include <inttypes.h>
88+
89+
extern size_t popcount(uintmax_t);
90+
#define PRECISION(x) popcount(x)
91+
92+
void func(signed long si_a, signed long si_b) {
93+
signed long result;
94+
if ((si_a < 0) || (si_b < 0) ||
95+
(si_b >= PRECISION(ULONG_MAX)) ||
96+
(si_a > (LONG_MAX >> si_b))) {
97+
/* Handle error */
98+
} else {
99+
result = si_a << si_b;
100+
}
101+
/* ... */
102+
}
103+
104+
```
105+
Noncompliant Code Example (Right Shift)
106+
107+
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``<sup>E2</sup>`. If `E1` has a signed type and a negative value, the resulting value is [implementation-defined](https://wiki.sei.cmu.edu/confluence/display/c/BB.+Definitions#BB.Definitions-implementation-definedbehavior) and can be either an arithmetic (signed) shift
108+
109+
![](ShiftRight.JPG)
110+
111+
or a logical (unsigned) shift
112+
113+
![](LogicalShiftRight.JPG)
114+
115+
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:
116+
117+
```cpp
118+
void func(unsigned int ui_a, unsigned int ui_b) {
119+
unsigned int uresult = ui_a >> ui_b;
120+
/* ... */
121+
}
122+
```
123+
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](https://wiki.sei.cmu.edu/confluence/display/c/BB.+Definitions#BB.Definitions-vulnerability). (See [INT13-C. Use bitwise operators only on unsigned operands](https://wiki.sei.cmu.edu/confluence/display/c/INT13-C.+Use+bitwise+operators+only+on+unsigned+operands).)
124+
125+
## Compliant Solution (Right Shift)
126+
127+
This compliant solution eliminates the possibility of shifting by greater than or equal to the number of bits that exist in the precision of the left operand:
128+
129+
```cpp
130+
#include <limits.h>
131+
#include <stddef.h>
132+
#include <inttypes.h>
133+
134+
extern size_t popcount(uintmax_t);
135+
#define PRECISION(x) popcount(x)
136+
137+
void func(unsigned int ui_a, unsigned int ui_b) {
138+
unsigned int uresult = 0;
139+
if (ui_b >= PRECISION(UINT_MAX)) {
140+
/* Handle error */
141+
} else {
142+
uresult = ui_a >> ui_b;
143+
}
144+
/* ... */
145+
}
146+
```
147+
**Implementation Details**
148+
149+
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 instruction on x86-32:
150+
151+
```cpp
152+
sarl %cl, %eax
153+
154+
```
155+
The `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:
156+
157+
```cpp
158+
// 64-bit right shifts on IA-32 platforms become
159+
shrdl %edx, %eax
160+
sarl %cl, %edx
161+
162+
```
163+
where `%eax` stores the least significant bits in the doubleword to be shifted, and `%edx` stores the most significant bits.
164+
165+
## Risk Assessment
166+
167+
Although shifting a negative number of bits or shifting a number of bits 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.
168+
169+
<table> <tbody> <tr> <th> Rule </th> <th> Severity </th> <th> Likelihood </th> <th> Remediation Cost </th> <th> Priority </th> <th> Level </th> </tr> <tr> <td> INT34-C </td> <td> Low </td> <td> Unlikely </td> <td> Medium </td> <td> <strong>P2</strong> </td> <td> <strong>L3</strong> </td> </tr> </tbody> </table>
170+
171+
172+
## Automated Detection
173+
174+
<table> <tbody> <tr> <th> Tool </th> <th> Version </th> <th> Checker </th> <th> Description </th> </tr> <tr> <td> <a> Astrée </a> </td> <td> 22.04 </td> <td> <strong>precision-shift-width</strong> <strong>precision-shift-width-constant</strong> </td> <td> Fully checked </td> </tr> <tr> <td> <a> Axivion Bauhaus Suite </a> </td> <td> 7.2.0 </td> <td> <strong>CertC-INT34</strong> </td> <td> Can detect shifts by a negative or an excessive number of bits and right shifts on negative values. </td> </tr> <tr> <td> <a> CodeSonar </a> </td> <td> 7.2p0 </td> <td> <strong>LANG.ARITH.BIGSHIFT</strong> <strong>LANG.ARITH.NEGSHIFT</strong> </td> <td> Shift amount exceeds bit width Negative shift amount </td> </tr> <tr> <td> <a> Compass/ROSE </a> </td> <td> </td> <td> </td> <td> Can detect violations of this rule. Unsigned operands are detected when checking for <a> INT13-C. Use bitwise operators only on unsigned operands </a> </td> </tr> <tr> <td> <a> Coverity </a> </td> <td> 2017.07 </td> <td> <strong>BAD_SHIFT</strong> </td> <td> Implemented </td> </tr> <tr> <td> <a> Cppcheck </a> </td> <td> 1.66 </td> <td> <strong>shiftNegative, shiftTooManyBits</strong> </td> <td> 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 <code>--platform</code> to specify the sizes of the standard types.) </td> </tr> <tr> <td> <a> ECLAIR </a> </td> <td> 1.2 </td> <td> <strong>CC2.INT34</strong> </td> <td> Partially implemented </td> </tr> <tr> <td> <a> Helix QAC </a> </td> <td> 2022.4 </td> <td> <strong>C0499, C2790, </strong> <strong>C++2790, C++3003</strong> <strong>DF2791, DF2792, DF2793</strong> </td> <td> </td> </tr> <tr> <td> <a> Klocwork </a> </td> <td> 2022.4 </td> <td> <strong>MISRA.SHIFT.RANGE.2012</strong> </td> <td> </td> </tr> <tr> <td> <a> LDRA tool suite </a> </td> <td> 9.7.1 </td> <td> <strong>51 S, 403 S, 479 S</strong> </td> <td> Partially implemented </td> </tr> <tr> <td> <a> Parasoft C/C++test </a> </td> <td> 2022.2 </td> <td> <strong>CERT_C-INT34-a</strong> </td> <td> Avoid incorrect shift operations </td> </tr> <tr> <td> <a> Polyspace Bug Finder </a> </td> <td> R2022b </td> <td> <a> CERT C: Rule INT34-C </a> </td> <td> Checks for: Shift of a negative valuehift of a negative value, shift operation overflowhift operation overflow. Rule partially covered. </td> </tr> <tr> <td> <a> PRQA QA-C </a> </td> <td> 9.7 </td> <td> <strong>0499, 2790 \[C\], 2791 \[D\], 2792 \[A\], 2793 \[S\]</strong> </td> <td> Partially implemented </td> </tr> <tr> <td> <a> PRQA QA-C++ </a> </td> <td> 4.4 </td> <td> <strong>2791, 2792, 2793, 3003, 3321, 3322</strong> </td> <td> </td> </tr> <tr> <td> <a> PVS-Studio </a> </td> <td> 7.23 </td> <td> <a> V610 </a> </td> <td> </td> </tr> <tr> <td> <a> RuleChecker </a> </td> <td> 22.04 </td> <td> <strong>precision-shift-width-constant</strong> </td> <td> Partially checked </td> </tr> <tr> <td> <a> TrustInSoft Analyzer </a> </td> <td> 1.38 </td> <td> <strong>shift</strong> </td> <td> Exhaustively verified (see <a> one compliant and one non-compliant example </a> ). </td> </tr> </tbody> </table>
175+
176+
177+
## Related Vulnerabilities
178+
179+
Search for [vulnerabilities](https://wiki.sei.cmu.edu/confluence/display/c/BB.+Definitions#BB.Definitions-vulnerability) resulting from the violation of this rule on the [CERT website](https://www.kb.cert.org/vulnotes/bymetric?searchview&query=FIELD+KEYWORDS+contains+INT34-C).
180+
181+
## Related Guidelines
182+
183+
[Key here](https://wiki.sei.cmu.edu/confluence/display/c/How+this+Coding+Standard+is+Organized#HowthisCodingStandardisOrganized-RelatedGuidelines) (explains table format and definitions)
184+
185+
<table> <tbody> <tr> <th> Taxonomy </th> <th> Taxonomy item </th> <th> Relationship </th> </tr> <tr> <td> <a> CERT C </a> </td> <td> <a> INT13-C. Use bitwise operators only on unsigned operands </a> </td> <td> Prior to 2018-01-12: CERT: Unspecified Relationship </td> </tr> <tr> <td> <a> CERT C </a> </td> <td> <a> INT35-C. Use correct integer precisions </a> </td> <td> Prior to 2018-01-12: CERT: Unspecified Relationship </td> </tr> <tr> <td> <a> CERT C </a> </td> <td> <a> INT32-C. Ensure that operations on signed integers do not result in overflow </a> </td> <td> Prior to 2018-01-12: CERT: Unspecified Relationship </td> </tr> <tr> <td> <a> ISO/IEC TR 24772:2013 </a> </td> <td> Arithmetic Wrap-Around Error \[FIF\] </td> <td> Prior to 2018-01-12: CERT: Unspecified Relationship </td> </tr> <tr> <td> <a> CWE 2.11 </a> </td> <td> <a> CWE-682 </a> </td> <td> 2017-07-07: CERT: Rule subset of CWE </td> </tr> <tr> <td> <a> CWE 2.11 </a> </td> <td> <a> CWE-758 </a> </td> <td> 2017-07-07: CERT: Rule subset of CWE </td> </tr> </tbody> </table>
186+
187+
188+
## CERT-CWE Mapping Notes
189+
190+
[Key here](https://wiki.sei.cmu.edu/confluence/pages/viewpage.action?pageId=87152408#HowthisCodingStandardisOrganized-CERT-CWEMappingNotes) for mapping notes
191+
192+
**CWE-758 and INT34-C**
193+
194+
Independent( INT34-C, INT36-C, MEM30-C, MSC37-C, FLP32-C, EXP33-C, EXP30-C, ERR34-C, ARR32-C)
195+
196+
CWE-758 = Union( INT34-C, list) where list =
197+
198+
* Undefined behavior that results from anything other than incorrect bit shifting
199+
**CWE-682 and INT34-C**
200+
201+
Independent( INT34-C, FLP32-C, INT33-C) CWE-682 = Union( INT34-C, list) where list =
202+
203+
* Incorrect calculations that do not involve out-of-range bit shifts
204+
205+
## Bibliography
206+
207+
<table> <tbody> <tr> <td> \[ <a> C99 Rationale 2003 </a> \] </td> <td> 6.5.7, "Bitwise Shift Operators" </td> </tr> <tr> <td> \[ <a> Dowd 2006 </a> \] </td> <td> Chapter 6, "C Language Issues" </td> </tr> <tr> <td> \[ <a> Seacord 2013b </a> \] </td> <td> Chapter 5, "Integer Security" </td> </tr> <tr> <td> \[ <a> Viega 2005 </a> \] </td> <td> Section 5.2.7, "Integer Overflow" </td> </tr> </tbody> </table>
208+
209+
210+
## Implementation notes
211+
212+
None
213+
214+
## References
215+
216+
* CERT-C: [INT34-C: Do not shift an expression by a negative number of bits or by greater than or equal to the number of bits that exist in the operand](https://wiki.sei.cmu.edu/confluence/display/c)
Lines changed: 105 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,105 @@
1+
/**
2+
* @id c/cert/expr-shiftedby-negative-or-greater-precision-operand
3+
* @name INT34-C: Bit shift should not be done by a negative operand or an operand of greater-or-equal precision than that of another
4+
* @description Shifting an expression by an operand that is negative or of precision greater or
5+
* equal to that or the another causes representational error.
6+
* @kind problem
7+
* @precision very-high
8+
* @problem.severity error
9+
* @tags external/cert/id/int34-c
10+
* external/cert/obligation/rule
11+
*/
12+
13+
import cpp
14+
import codingstandards.c.cert
15+
import semmle.code.cpp.rangeanalysis.SimpleRangeAnalysis
16+
import semmle.code.cpp.ir.internal.ASTValueNumbering
17+
import semmle.code.cpp.controlflow.Guards
18+
19+
/*
20+
* Precision predicate based on a sample implementation from
21+
* https://wiki.sei.cmu.edu/confluence/display/c/INT35-C.+Use+correct+integer+precisions
22+
*/
23+
24+
/**
25+
* A function whose name is suggestive that it counts the number of bits set.
26+
*/
27+
class PopCount extends Function {
28+
PopCount() { this.getName().toLowerCase().matches("%popc%nt%") }
29+
}
30+
31+
/**
32+
* A macro which is suggestive that it is used to determine the precision of an integer.
33+
*/
34+
class PrecisionMacro extends Macro {
35+
PrecisionMacro() { this.getName().toLowerCase().matches("precision") }
36+
}
37+
38+
class LiteralZero extends Literal {
39+
LiteralZero() { this.getValue() = "0" }
40+
}
41+
42+
class BitShiftExpr extends BinaryBitwiseOperation {
43+
BitShiftExpr() {
44+
this instanceof LShiftExpr or
45+
this instanceof RShiftExpr
46+
}
47+
}
48+
49+
int getPrecision(IntegralType type) {
50+
type.isExplicitlyUnsigned() and result = type.getSize() * 8
51+
or
52+
type.isExplicitlySigned() and result = type.getSize() * 8 - 1
53+
}
54+
55+
predicate isForbiddenShiftExpr(BitShiftExpr shift, string message) {
56+
(
57+
(
58+
getPrecision(shift.getLeftOperand().getExplicitlyConverted().getUnderlyingType()) <=
59+
upperBound(shift.getRightOperand()) and
60+
message =
61+
"The operand " + shift.getLeftOperand() + " is shifted by an expression " +
62+
shift.getRightOperand() + " whose upper bound (" + upperBound(shift.getRightOperand()) +
63+
") is greater than or equal to the precision."
64+
or
65+
lowerBound(shift.getRightOperand()) < 0 and
66+
message =
67+
"The operand " + shift.getLeftOperand() + " is shifted by an expression " +
68+
shift.getRightOperand() + " which may be negative."
69+
) and
70+
/*
71+
* Shift statement is not at a basic block where
72+
* `shift_rhs < PRECISION(...)` is ensured
73+
*/
74+
75+
not exists(GuardCondition gc, BasicBlock block, Expr precisionCall, Expr lTLhs |
76+
block = shift.getBasicBlock() and
77+
(
78+
precisionCall.(FunctionCall).getTarget() instanceof PopCount
79+
or
80+
precisionCall = any(PrecisionMacro pm).getAnInvocation().getExpr()
81+
)
82+
|
83+
globalValueNumber(lTLhs) = globalValueNumber(shift.getRightOperand()) and
84+
gc.ensuresLt(lTLhs, precisionCall, 0, block, true)
85+
) and
86+
/*
87+
* Shift statement is not at a basic block where
88+
* `shift_rhs < 0` is ensured
89+
*/
90+
91+
not exists(GuardCondition gc, BasicBlock block, Expr literalZero, Expr lTLhs |
92+
block = shift.getBasicBlock() and
93+
literalZero instanceof LiteralZero
94+
|
95+
globalValueNumber(lTLhs) = globalValueNumber(shift.getRightOperand()) and
96+
gc.ensuresLt(lTLhs, literalZero, 0, block, true)
97+
)
98+
)
99+
}
100+
101+
from BinaryBitwiseOperation badShift, string message
102+
where
103+
not isExcluded(badShift, Types1Package::exprShiftedbyNegativeOrGreaterPrecisionOperandQuery()) and
104+
isForbiddenShiftExpr(badShift, message)
105+
select badShift, message
Loading
16.7 KB
Loading
15.7 KB
Loading

0 commit comments

Comments
 (0)