1. 引入
静态应用程序安全测试(Static application security testing)简称SAST,是透过审查程式源代码来识别漏洞,提升软件安全性的作法。
Joern 是一个强大的开源静态应用安全测试(SAST)工具,专注于代码的语义分析。它通过将源代码转换为代码属性图(Code Property Graph, CPG),并使用专用查询语言 CPGQL 进行漏洞检测。
CPGQL(Code Property Graph Query Language)是 Joern 平台用于查询代码属性图(Code Property Graph, CPG)的专用查询语言。CPG 是一种将源代码的多种属性(如语法结构、控制流、数据流等)整合为统一图结构的表示方法,而 CPGQL 则提供了灵活强大的图查询能力。CPGQL 基于图论,支持节点(Node)、边(Edge)和路径(Path)的查询。
本文参考1中的查询语句,复现部分CPGQL,目的是为了熟悉Joern的使用,更好的理解CPGQL。
2. 整体过程
如下C代码与CPGQL均来自Joern官网(参考1)。
- 安装Joern,参考2,本文在ubuntu22.04下进行
wget https://github.com/joernio/joern/releases/latest/download/joern-install.sh
chmod +x ./joern-install.sh
sudo ./joern-install.sh
注意,如果网速慢,需要打开joern-install.sh,对其中curl命令加proxy(curl -x "http:xxxxyyyzzzeeeddd"
)。
- 将如下有有缺陷的c语言代码保存为
insecure_gets.c
int insecure_gets() {char str[DST_BUFFER_SIZE];gets(str);printf("%s", str);return 0;
}
这段代码使用了 C 标准库中的gets()函数,这是一个严重的安全隐患,可能导致缓冲区溢出攻击。
- 使用Joern将C代码转换为代码属性图CPG
/opt/joern/joern-cli/joern-parse insecure_gets.c --output insecure_gets.cpg.bin
- 使用Joern加载CPG
joern /data/yinbin/projects/ybresearch/joernlearn/insecure_gets.cpg.bin
- 在Joern的Shell中加载该CPG
joern> open("insecure_gets.cpg.bin")
val res2: Option[io.joern.console.workspacehandling.Project] = Some(value = Project(projectFile = ProjectFile(inputPath = "/data/yinbin/projects/ybresearch/joernlearn/insecure_gets.cpg.bin",name = "insecure_gets.cpg.bin"),path = /data/yinbin/projects/ybresearch/joernlearn/workspace/insecure_gets.cpg.bin,cpg = Some(value = Cpg[Graph[72 nodes]]))
)
使用open命令即可加载。
- 执行CPGQL
这里执行的CPGQL为({cpg.method("(?i)gets").callIn}).l
,含义如下:
cpg
:代表整个代码属性图(Code Property Graph)的根节点。method("(?i)gets")
:查找名称匹配正则表达式"(?i)gets"
的方法:(?i)
:正则修饰符,表示忽略大小写(匹配gets
、GETS
、Gets
等)。gets
:目标函数名。
callIn
:获取调用这些方法的所有调用点(即查找哪些代码调用了gets()
)。.l
:将查询结果转换为列表并返回。
这个查询等价于:
“找出代码库中所有调用了
gets()
函数的位置,无论大小写。”
具体运行过程如下:
joern> ({cpg.method("(?i)gets").callIn}).l|
val res3: List[io.shiftleft.codepropertygraph.generated.nodes.Call] = List(Call(argumentIndex = -1,argumentName = None,code = "gets(str)",columnNumber = Some(value = 3),dispatchType = "STATIC_DISPATCH",dynamicTypeHintFullName = IndexedSeq(),lineNumber = Some(value = 3),methodFullName = "gets",name = "gets",offset = None,offsetEnd = None,order = 3,possibleTypes = IndexedSeq(),signature = "",typeFullName = "ANY")
)
这个结果说明:
- code = “gets(str)”
- 调用gets()的代码行,参数为str(对应之前代码示例中的char str[DST_BUFFER_SIZE])。
- lineNumber = Some(value = 3)
- 调用发生在第 3 行(与之前的代码示例一致)。
- columnNumber = Some(value = 3)
- 调用从第 3 列开始(缩进后的位置)。
- methodFullName = “gets”
- 被调用方法的全名是gets。
- dispatchType = “STATIC_DISPATCH”
- 静态调用(编译时确定调用目标)。
3. 总结
本文给出了从安装Joern到用Joern执行CPGQL找到C语言中不安全函数调用的流程的完整示例。
4. 参考
- joern官方查询语句说明,https://queries.joern.io/
- 深入浅出Joern(一)Joern与CPG是什么,https://lorexxar.cn/2023/08/21/joern-and-cpg/