-
Notifications
You must be signed in to change notification settings - Fork 1.5k
/
SuspiciousCallToStrncat.ql
69 lines (64 loc) · 2.56 KB
/
SuspiciousCallToStrncat.ql
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
/**
* @name Potentially unsafe call to strncat
* @description Calling 'strncat' with an incorrect size argument may result in a buffer overflow.
* @kind problem
* @problem.severity warning
* @security-severity 9.3
* @precision high
* @id cpp/unsafe-strncat
* @tags reliability
* correctness
* security
* external/cwe/cwe-788
* external/cwe/cwe-676
* external/cwe/cwe-119
* external/cwe/cwe-251
*/
import cpp
import Buffer
import semmle.code.cpp.models.implementations.Strcat
import semmle.code.cpp.valuenumbering.GlobalValueNumbering
/**
* Holds if `call` is a call to `strncat` such that `sizeArg` and `destArg` are the size and
* destination arguments, respectively.
*/
predicate interestingCallWithArgs(Call call, Expr sizeArg, Expr destArg) {
exists(StrcatFunction strcat |
strcat = call.getTarget() and
sizeArg = call.getArgument(strcat.getParamSize()) and
destArg = call.getArgument(strcat.getParamDest())
)
}
/**
* Holds if `fc` is a call to `strncat` with size argument `sizeArg` and destination
* argument `destArg`, and `destArg` is the size of the buffer pointed to by `destArg`.
*/
predicate case1(FunctionCall fc, Expr sizeArg, VariableAccess destArg) {
interestingCallWithArgs(fc, sizeArg, destArg) and
exists(VariableAccess va |
va = sizeArg.(BufferSizeExpr).getArg() and
destArg.getTarget() = va.getTarget()
)
}
/**
* Holds if `fc` is a call to `strncat` with size argument `sizeArg` and destination
* argument `destArg`, and `sizeArg` computes the value `sizeof (dest) - strlen (dest)`.
*/
predicate case2(FunctionCall fc, Expr sizeArg, Expr destArg) {
interestingCallWithArgs(fc, pragma[only_bind_into](sizeArg), pragma[only_bind_into](destArg)) and
exists(SubExpr sub, int n |
// The destination buffer is an array of size n
pragma[only_bind_out](destArg.getUnspecifiedType().(ArrayType).getSize()) = n and
// The size argument is equivalent to a subtraction
globalValueNumber(sizeArg).getAnExpr() = sub and
// ... where the left side of the subtraction is the constant n
globalValueNumber(sub.getLeftOperand()).getAnExpr().getValue().toInt() = n and
// ... and the right side of the subtraction is a call to `strlen` where the argument is the
// destination buffer.
globalValueNumber(sub.getRightOperand()).getAnExpr().(StrlenCall).getStringExpr() =
globalValueNumber(destArg).getAnExpr()
)
}
from FunctionCall fc, Expr sizeArg, Expr destArg
where case1(fc, sizeArg, destArg) or case2(fc, sizeArg, destArg)
select fc, "Potentially unsafe call to strncat."