Skip to content

Commit 35c0098

Browse files
committed
Initial commit
0 parents  commit 35c0098

File tree

89 files changed

+38737
-0
lines changed

Some content is hidden

Large Commits have some content hidden by default. Use the searchbox below for content that may be hidden.

89 files changed

+38737
-0
lines changed

ReadMe.md

Lines changed: 91 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,91 @@
1+
# About CppCodeAnalyzer
2+
3+
It is a parsing tool based on python for C/C++ to construct code property graph, which is the python version of [CodeParser](https://github.com/for-just-we/CodeParser), most of functions of CppCodeAnalyzer are similar to Joern, the differences are that:
4+
5+
- The grammar we utilize here is from the repo of [grammars-v4](https://github.com/antlr/grammars-v4) Antlr official, which means the input of module ast (Antlr AST) is quite different from Joern, but the output customized AST is the same, so the parsing module in ast package is different from Joern.
6+
7+
- When constructing CFG, CppCodeAnalyzer takes `for-range` and `try-catch` into consideration.
8+
9+
* when parsing code such as `for (auto p: vec){ xxx }`, the CFG is like in graph 1
10+
11+
* when parsing `try-catch`, we simple ignore statements in catch block because in normal states they are not going to be executed, and the control flow in `try-catch` is quite hard to compute.
12+
13+
* when parsing use-def information by udg package, we take the information of pointer uses. For example, `memcpy(dest, src, 100);` defines symbol `* dest` and uses symbol `* src`, Joern considered pointer define with variable `Tainted` but did not consider pointer uses.
14+
15+
Graph 1
16+
```mermaid
17+
graph LR
18+
EmptyCondition --> A[auto p: vec]
19+
A --> B[xxx]
20+
B --> EmptyCondition
21+
EmptyCondition --> Exit
22+
```
23+
24+
The pipeline of CppCodeAnalyzer is similar to Joern, which could be illustrated as:
25+
26+
```mermaid
27+
graph LR
28+
AntlrAST --Transform --> AST -- control flow analysis --> CFG
29+
CFG -- dominate analysis --> CDG
30+
CFG -- symbol def use analysis --> UDG
31+
UDG -- data dependence analysis --> DDG
32+
```
33+
34+
If you want more details, coule refer to [Joern工具工作流程分析](https://blog.csdn.net/qq_44370676/article/details/125089161)
35+
36+
- package ast transform Antlr AST to customized AST.
37+
38+
- package cfg conduct control flow analysis and convert customized AST into CFG.
39+
40+
- package cdg conduct statement dominate analysis and construct control dependence relations between statements.
41+
42+
- package udg analyze the symbols defined and used in each statement independently.
43+
44+
- package ddg construct data dependence relations between statements with def-use information computed in udg package.
45+
46+
47+
# Usage
48+
49+
The testfile in directionary `test/mainToolTests` illustrated the progress of each module, you could refer to those test cases to learn how to use API in CppCodeAnalyzer.
50+
51+
52+
# Our motivations
53+
54+
- When we conduct experiments with Joern tool parsing SARD datasets, we find some error.The statement `wchar_t data[50] = L'A';` should be in a single CFG node, but each token in the statement is assigned to a CFG node, after we check the source code, we believe the root cause is the grammar used by [Joern](https://github.com/octopus-platform/joern/blob/dev/projects/extensions/joern-fuzzyc/src/main/java/antlr/Function.g4#L13).
55+
56+
- Also, most researches utilize python to write deep-learning programs, it could be more convenient to parse code with python because the parsing module could directly connect to deep-learning module, there would be no need to write scripts to parse output of Joern.
57+
58+
# Challenges
59+
60+
- Parsing control-flow in `for-range` and `try-catch` is difficult, there are no materials depicting CFG in `for-range` and `try-catch`.
61+
62+
- Parsing def-use information of pointer variable is difficult. For example, in `*(p+i+1) = a[i][j];`, symbols defined include `* p` and used include `p, i, j, a, * a`. However, this is not very accurate, but computing the location of memory staticlly is difficult. This could brings following problems.
63+
64+
```cpp
65+
s1: memset(source, 100, 'A');
66+
s2: source[99] = '\0';
67+
s3: memcpy(data, source, 100);
68+
```
69+
70+
- In results of CppCodeAnalyzer, s1 and s2 define symbol `* source` , but the later kills the front. So, there is only DDG edge `s2 -> s3` in DDG.
71+
72+
- However, s1 defines `* source`, s2 defines `* ( source + 99)`, a precise DDG should contains edge `s1 -> s3, s2 -> s3`
73+
74+
Also, our tool is much more slower than Joern, normally parsing a file in SARD dataset needs 20 - 30 seconds, so we recommand dump output CPG into json format first if you need to train a model.
75+
76+
77+
# Extra Tools
78+
79+
The package `extraTools` contains some preprocess code for vulnerability detectors IVDetect, SySeVR and DeepWuKong. The usage could refer to file in `test/extraToolTests`
80+
81+
82+
# References
83+
84+
85+
> [Yamaguchi, F. , Golde, N. , Arp, D. , & Rieck, K. . (2014). Modeling and Discovering Vulnerabilities with Code Property Graphs. IEEE Symposium on Security and Privacy. IEEE.](https://ieeexplore.ieee.org/document/6956589)
86+
87+
> [Li Y , Wang S , Nguyen T N . Vulnerability Detection with Fine-grained Interpretations. 2021.](https://arxiv.org/abs/2106.10478)
88+
89+
> [SySeVR: A Framework for Using Deep Learning to Detect Software Vulnerabilities\[J\]. IEEE Transactions on Dependable and Secure Computing, 2021, PP(99):1-1.](https://arxiv.org/abs/1807.06756)
90+
91+
> [Cheng X , Wang H , Hua J , et al. DeepWukong[J]. ACM Transactions on Software Engineering and Methodology (TOSEM), 2021.](https://dl.acm.org/doi/10.1145/3436877)

extraTools/__init__.py

Whitespace-only changes.

extraTools/vuldetect/__init__.py

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1 @@
1+
# This package is used to support DL-based vulnerability detectors like SySeVR

extraTools/vuldetect/deepwukong.py

Lines changed: 287 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,287 @@
1+
from mainTool.ast.statements.jumps import ReturnStatement
2+
from mainTool.utils.graphUtils import Edge
3+
from mainTool.CPG import CodeEdge
4+
from extraTools.vuldetect.utils.sinkPoint import SyVCPoint, CallExprTool, XFGPoint
5+
from extraTools.vuldetect.utils.symbolized import SymbolizingTool
6+
from mainTool.CPG import *
7+
from typing import List, Set, Tuple
8+
import json
9+
10+
# generating xfg defined in DeepWuKong
11+
# following paper DeepWukong: Statically Detecting Software Vulnerabilities Using Deep Graph Neural Network
12+
13+
class XFG(object):
14+
def __init__(self, keyLine: List[int], keyContent: str):
15+
# control dependence edges
16+
self.cdes: List[CodeEdge] = list()
17+
# data dependence edges
18+
self.ddes: List[CodeEdge] = list()
19+
# key line 行号,文件Id
20+
self.keyLine: List[int] = keyLine
21+
# 内容
22+
# slice覆盖到的行号以及每一行所在的文件
23+
self.lineNumbers: List[List[int]] = list()
24+
self.keyLineContent: str = keyContent
25+
# 文件id对文件名
26+
self.id2file: Dict[int, str] = None
27+
# slice中每个语句对应的token序列
28+
self.lineContents: List[str] = list()
29+
30+
def __hash__(self):
31+
return hash(json.dumps(self.lineContents))
32+
33+
def toJson(self) -> Dict:
34+
return {
35+
"keyline": self.keyLine,
36+
"id2file": self.id2file,
37+
"line-Nos": self.lineNumbers,
38+
"line-contents": self.lineContents,
39+
"control-dependences": [edge.toJson() for edge in self.cdes],
40+
"data-dependences": [edge.toJson() for edge in self.ddes]
41+
}
42+
43+
44+
# 一个程序中所有function都由一个SliceTool对象处理
45+
# cpgs is all cpgs from functions of a program (could be a file sometimes)
46+
class XFGSliceTool(object):
47+
def __init__(self, cpgs: List[CPG], sensitive_apis: Set[str], symbolizingTool: SymbolizingTool):
48+
self.cpgs: List[CPG] = cpgs
49+
self.funcName2cpg: Dict[str, CPG] = {cpg.name: cpg for cpg in cpgs}
50+
self.sensitive_apis: Set[str] = sensitive_apis #
51+
self.symbolizingTool: SymbolizingTool = symbolizingTool
52+
53+
self.slices: Set[XFG] = set() # store all code gadgets of a program
54+
# backward information of data-deoendence for each statement
55+
self.funcName2backDataInfo: Dict[str, Dict[int, Set[int]]] = dict()
56+
# forward information of data-deoendence for each statement
57+
self.funcName2forwDataInfo: Dict[str, Dict[int, Set[int]]] = dict()
58+
# backward information of control-deoendence for each statement
59+
self.funcName2backControlInfo: Dict[str, Dict[int, Set[int]]] = dict()
60+
# forward information of control-deoendence for each statement
61+
self.funcName2forwControlInfo: Dict[str, Dict[int, Set[int]]] = dict()
62+
# 将文件名映射
63+
self.files: List[str] = list()
64+
for cpg in self.cpgs:
65+
self.generateForAndBackInfos(cpg)
66+
if cpg.file not in self.files:
67+
self.files.append(cpg.file)
68+
self.file2Id: Dict[str, int] = { file: i for i, file in enumerate(self.files) }
69+
70+
71+
72+
def generateForAndBackInfos(self, cpg: CPG):
73+
# backward
74+
backDataInfo: Dict[int, Set[int]] = dict()
75+
# forward
76+
forwDataInfo: Dict[int, Set[int]] = dict()
77+
78+
# forward and backward for data dependence
79+
for edge in cpg.DDGEdges:
80+
# backward
81+
if edge.destination not in backDataInfo.keys():
82+
backDataInfo[edge.destination] = set()
83+
backDataInfo[edge.destination].add(edge.source)
84+
# forward
85+
if edge.source not in forwDataInfo.keys():
86+
forwDataInfo[edge.source] = set()
87+
forwDataInfo[edge.source].add(edge.destination)
88+
89+
self.funcName2backDataInfo[cpg.name] = backDataInfo
90+
self.funcName2forwDataInfo[cpg.name] = forwDataInfo
91+
92+
# backward
93+
backControlInfo: Dict[int, Set[int]] = dict()
94+
# forward
95+
forwControlInfo: Dict[int, Set[int]] = dict()
96+
97+
# forward and backward for control dependence
98+
for edge in cpg.CDGEdges:
99+
# backward
100+
if edge.destination not in backControlInfo.keys():
101+
backControlInfo[edge.destination] = set()
102+
backControlInfo[edge.destination].add(edge.source)
103+
# forward
104+
if edge.source not in forwControlInfo.keys():
105+
forwControlInfo[edge.source] = set()
106+
forwControlInfo[edge.source].add(edge.destination)
107+
108+
self.funcName2backControlInfo[cpg.name] = backControlInfo
109+
self.funcName2forwControlInfo[cpg.name] = forwControlInfo
110+
111+
112+
def generateSliceForProgram(self):
113+
sinkTool: XFGPoint = XFGPoint(self.sensitive_apis)
114+
slicesCpg = list(filter(lambda cpg: cpg.joinSlice, self.cpgs))
115+
for cpg in slicesCpg:
116+
for i, stmt in enumerate(cpg.statements):
117+
# 是否算SySe
118+
if sinkTool.judgeSink(stmt):
119+
coveredFileIds: Set[int] = set()
120+
lineNumber: int = stmt.location.startLine
121+
xfg: XFG = XFG([lineNumber, self.file2Id[cpg.file]], stmt.getEscapedCodeStr())
122+
123+
backwardFunctionChain: List[str] = list() # store function call chain in backward slices
124+
backwardCDEdges: List[Edge[ASTNode]] = list() # store control dependence edges
125+
backwardDDEdges: List[Edge[ASTNode]] = list() # store data dependence edges
126+
backwardLineContents: List[ASTNode] = list()
127+
backwardLineInfo: List[List[int]] = list()
128+
backwardIdxs: List[int] = [i]
129+
self.generateBackwardSlice(cpg.name, backwardIdxs, backwardLineContents, backwardFunctionChain,
130+
backwardLineInfo, backwardCDEdges, backwardDDEdges, coveredFileIds)
131+
132+
forwardFunctionChain: List[str] = list() # store function call chain in backward slices
133+
forwardCDEdges: List[Edge[ASTNode]] = list() # store control dependence edges
134+
forwardDDEdges: List[Edge[ASTNode]] = list() # store data dependence edges
135+
forwardLineContents: List[ASTNode] = list()
136+
forwardLineInfo: List[List[int]] = list()
137+
forwardIdxs: List[int] = [i]
138+
self.generateForwardSlice(cpg.name, forwardIdxs, forwardLineContents, forwardFunctionChain,
139+
forwardLineInfo, forwardCDEdges, forwardDDEdges, coveredFileIds)
140+
141+
idx = forwardLineContents.index(stmt)
142+
forwardLineContents.pop(idx)
143+
forwardLineInfo.pop(idx)
144+
lines = backwardLineInfo + forwardLineInfo
145+
contents = backwardLineContents + forwardLineContents
146+
lineInfos = list()
147+
148+
for lineCont in zip(lines, contents):
149+
lineInfos.append((lineCont[0][1], lineCont[0][0], lineCont[1]))
150+
151+
# XFG中的内容,先按文件Id排序,再按行号排序
152+
lineInfos.sort(key=lambda x: x[1])
153+
lineInfos.sort(key=lambda x: x[0])
154+
155+
astNode2idx: Dict[ASTNode, int] = dict()
156+
157+
for i, lineInfo in enumerate(lineInfos):
158+
xfg.lineNumbers.append([lineInfo[1], lineInfo[0]])
159+
xfg.lineContents.append(self.symbolizingTool.symbolize(
160+
lineInfo[2].getEscapedCodeStr()))
161+
astNode2idx[lineInfo[2]] = i
162+
163+
cdEdgeSet: Set[Tuple[int, int]] = set()
164+
cdEdges = backwardCDEdges + forwardCDEdges
165+
for edge in cdEdges:
166+
cdEdgeSet.add((astNode2idx[edge.source], astNode2idx[edge.destination]))
167+
for edge in cdEdgeSet:
168+
xfg.cdes.append(CodeEdge(edge[0], edge[1]))
169+
170+
xfg.cdes.sort(key=lambda edge: edge.destination)
171+
xfg.cdes.sort(key=lambda edge: edge.source)
172+
173+
ddEdgeSet: Set[Tuple[int, int]] = set()
174+
ddEdges = backwardDDEdges + forwardDDEdges
175+
for edge in ddEdges:
176+
ddEdgeSet.add((astNode2idx[edge.source], astNode2idx[edge.destination]))
177+
for edge in ddEdgeSet:
178+
xfg.ddes.append(CodeEdge(edge[0], edge[1]))
179+
180+
xfg.ddes.sort(key=lambda edge: edge.destination)
181+
xfg.ddes.sort(key=lambda edge: edge.source)
182+
xfg.id2file = {fileId: self.files[fileId] for fileId in coveredFileIds}
183+
self.slices.add(xfg)
184+
185+
186+
187+
188+
def generateBackwardSlice(self, functionName: str, sliceIdxs: List[int], slices: List[ASTNode],
189+
functionChain: List[str], sliceLines: List[List[int]], cdEdges: List[Edge[ASTNode]],
190+
ddEdges: List[Edge[ASTNode]], coveredFileIds: Set[int]):
191+
if functionName in functionChain:
192+
return
193+
# sliceIdxs stores all indexes of nodes of slices
194+
cpg: CPG = self.funcName2cpg[functionName]
195+
functionChain.append(functionName)
196+
# computes all nodes with program-dependence with startIdx in a single function first
197+
dataInfo: Dict[int, Set[int]] = self.funcName2backDataInfo[functionName]
198+
controlInfo: Dict[int, Set[int]] = self.funcName2backControlInfo[functionName]
199+
200+
workList: List[int] = sliceIdxs.copy()
201+
while len(workList) > 0:
202+
curIdx: int = workList.pop(0)
203+
# data dependence
204+
for o in dataInfo.get(curIdx, set()):
205+
edge = Edge(cpg.statements[o], cpg.statements[curIdx])
206+
if edge not in ddEdges:
207+
ddEdges.append(edge)
208+
if o not in sliceIdxs:
209+
sliceIdxs.append(o)
210+
workList.append(o)
211+
# control dependence
212+
for o in controlInfo.get(curIdx, set()):
213+
edge = Edge(cpg.statements[o], cpg.statements[curIdx])
214+
if edge not in cdEdges:
215+
cdEdges.append(edge)
216+
if o not in sliceIdxs:
217+
sliceIdxs.append(o)
218+
workList.append(o)
219+
220+
coveredFileIds.add(self.file2Id[cpg.file])
221+
sliceIdxs.sort()
222+
for id in sliceIdxs:
223+
# 添加slice行代码
224+
slices.append(cpg.statements[id])
225+
# 添加slice行行号和文件id
226+
sliceLines.append([cpg.statements[id].location.startLine, self.file2Id[cpg.file]])
227+
callTool = CallExprTool()
228+
callTool.judgeCall(cpg.statements[id])
229+
if callTool.functionName is not None and callTool.functionName in self.funcName2cpg.keys():
230+
otherCpg: CPG = self.funcName2cpg[callTool.functionName]
231+
# 以前面一行代码的return语句为起点反向遍历
232+
assert isinstance(otherCpg.statements[-1], ReturnStatement)
233+
newStartIdxs: List[int] = [len(otherCpg.statements)]
234+
self.generateBackwardSlice(otherCpg.name, newStartIdxs, slices, functionChain, sliceLines,
235+
cdEdges, ddEdges, coveredFileIds)
236+
237+
238+
def generateForwardSlice(self, functionName: str, sliceIdxs: List[int], slices: List[ASTNode],
239+
functionChain: List[str], sliceLines: List[List[int]], cdEdges: List[Edge[ASTNode]],
240+
ddEdges: List[Edge[ASTNode]], coveredFileIds: Set[int]):
241+
if functionName in functionChain:
242+
return
243+
# sliceIdxs stores all indexes of nodes of slices
244+
cpg: CPG = self.funcName2cpg[functionName]
245+
functionChain.append(functionName)
246+
# computes all nodes with program-dependence with startIdx in a single function first
247+
dataInfo: Dict[int, Set[int]] = self.funcName2forwDataInfo[functionName]
248+
controlInfo: Dict[int, Set[int]] = self.funcName2forwControlInfo[functionName]
249+
250+
workList: List[int] = sliceIdxs.copy()
251+
while len(workList) > 0:
252+
curIdx: int = workList.pop(0)
253+
# data dependence
254+
for o in dataInfo.get(curIdx, set()):
255+
edge = Edge(cpg.statements[curIdx], cpg.statements[o])
256+
if edge not in ddEdges:
257+
ddEdges.append(edge)
258+
if o not in sliceIdxs:
259+
ddEdges.append(edge)
260+
sliceIdxs.append(o)
261+
workList.append(o)
262+
# control dependence
263+
for o in controlInfo.get(curIdx, set()):
264+
edge = Edge(cpg.statements[curIdx], cpg.statements[o])
265+
if edge not in cdEdges:
266+
cdEdges.append(edge)
267+
if o not in sliceIdxs:
268+
cdEdges.append(edge)
269+
sliceIdxs.append(o)
270+
workList.append(o)
271+
272+
coveredFileIds.add(self.file2Id[cpg.file])
273+
sliceIdxs.sort()
274+
for id in sliceIdxs:
275+
# 添加slice行代码
276+
slices.append(cpg.statements[id])
277+
# 添加slice行行号和文件id
278+
sliceLines.append([cpg.statements[id].location.startLine, self.file2Id[cpg.file]])
279+
callTool = CallExprTool()
280+
callTool.judgeCall(cpg.statements[id])
281+
if callTool.functionName is not None and callTool.functionName in self.funcName2cpg.keys():
282+
otherCpg: CPG = self.funcName2cpg[callTool.functionName]
283+
# 以前面一行代码的return语句为起点反向遍历
284+
assert callTool.argNum > 0
285+
newStartIdxs: List[int] = list(range(callTool.argNum))
286+
self.generateForwardSlice(otherCpg.name, newStartIdxs, slices, functionChain, sliceLines,
287+
cdEdges, ddEdges, coveredFileIds)

0 commit comments

Comments
 (0)