Skip to content

Commit 7edf552

Browse files
committed
Adding BadOverflowGuard qhelp, example code for help, and ql file.
1 parent 936ecfc commit 7edf552

File tree

4 files changed

+69
-0
lines changed

4 files changed

+69
-0
lines changed
Lines changed: 20 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,20 @@
1+
<!DOCTYPE qhelp PUBLIC
2+
"-//Semmle//qhelp//EN"
3+
"qhelp.dtd">
4+
<qhelp>
5+
<overview>
6+
<p>Checking for overflow of an addition by comparing against one of the arguments of the addition fails if the size of all the argument types are smaller than 4 bytes. This is because the result of the addition is promoted to a 4 byte int.</p>
7+
</overview>
8+
9+
<recommendation>
10+
<p>Check the overflow by comparing the addition against a value that is at least 4 bytes.</p>
11+
</recommendation>
12+
13+
<example>
14+
<p>In this example, the result of the comparison will result in an integer overflow.</p>
15+
<sample src="BadOverflowGuardBadCode.c" />
16+
17+
<p>To fix the bug, check the overflow by comparing the addition against a value that is at least 4 bytes.</p>
18+
<sample src="BadOverflowGuardGoodCode.c" />
19+
</example>
20+
</qhelp>
Lines changed: 31 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,31 @@
1+
/**
2+
* @name Bad overflow check
3+
* @description Checking for overflow of an addition by comparing against one
4+
* of the arguments of the addition fails if the size of all the
5+
* argument types are smaller than 4 bytes. This is because the
6+
* result of the addition is promoted to a 4 byte int.
7+
* @kind problem
8+
* @problem.severity error
9+
* @tags security
10+
* external/cwe/cwe-190
11+
* external/cwe/cwe-191
12+
* @id cpp/badoverflowguard
13+
*/
14+
15+
import cpp
16+
17+
/*
18+
* Example:
19+
*
20+
* uint16 v, uint16 b
21+
* if ((v + b < v) <-- bad check for overflow
22+
*/
23+
24+
from AddExpr a, Variable v, RelationalOperation cmp
25+
where
26+
a.getAnOperand() = v.getAnAccess() and
27+
forall(Expr op | op = a.getAnOperand() | op.getType().getSize() < 4) and
28+
cmp.getAnOperand() = a and
29+
cmp.getAnOperand() = v.getAnAccess() and
30+
not a.getExplicitlyConverted().getType().getSize() < 4
31+
select cmp, "Bad overflow check"
Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,9 @@
1+
unsigned short CheckForInt16OverflowBadCode(unsigned short v, unsigned short b)
2+
{
3+
if (v + b < v) // BUG: "v + b" will be promoted to 32 bits
4+
{
5+
// ... do something
6+
}
7+
8+
return v + b;
9+
}
Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,9 @@
1+
unsigned short CheckForInt16OverflowCorrectCode(unsigned short v, unsigned short b)
2+
{
3+
if (v + b > 0x00FFFF)
4+
{
5+
// ... do something
6+
}
7+
8+
return v + b;
9+
}

0 commit comments

Comments
 (0)