这是开源代码分析平台 Joern 的核心查询数据库。它有两个用途:
查询数据库作为一个独立的库分发,其中包括 Joern 作为依赖项。这意味着无需安装 Joern 即可使用数据库中的查询。
同时,数据库是一个 Joern 扩展,即在启动时动态加载后,其功能可在交互式 Joern shell 和 Joern 脚本中使用。
你可以 fork 这个项目来构建自己的自定义查询和扫描器,或者发送 PR 到本仓库,以便它们被考虑纳入默认发行版。
安装脚本会下载 joern 并将其安装到一个子目录中。查询数据库会作为扩展安装。
./install.sh
你可以按如下方式运行所有查询:
./joern-scan path/to/code
例如:
mkdir foo
echo "int foo(int a, int b, int c, int d, int e, int f) {}" > foo/foo.c
./joern-scan foo
对目录 foo 中的示例代码运行所有查询,确定函数 foo 参数过多。
请遵循以下规则,以获得无痛查询编写体验:
io.joern.scanners 中的查询会在运行时自动被识别,因此请将你的查询放在那里。@q 开头,并且必须放在一个查询包中。一个查询包只是一个派生自 QueryBundle 的 object。sbt scalafmt Test/scalafmt 格式化代码。以 src/main/scala/io/joern/scanners/c/Metrics.scala 中的查询包 Metrics 为例:
object Metrics extends QueryBundle {
@q
def tooManyParameters(n: Int = 4): Query =
Query.make(
name = "too-many-params",
author = Crew.fabs,
title = s"Number of parameters larger than $n",
description = s"This query identifies functions with more than $n formal parameters",
score = 1.0,
withStrRep({ cpg =>
cpg.method.internal.filter(_.parameter.size > n)
}),
tags = List(QueryTags.metrics)
)
@q
def tooHighComplexity(n: Int = 4): Query =
Query.make(
name = "too-high-complexity",
author = Crew.fabs,
title = s"Cyclomatic complexity higher than $n",
description = s"This query identifies functions with a cyclomatic complexity higher than $n",
score = 1.0,
withStrRep({ cpg =>
cpg.method.internal.filter(_.controlStructure.size > n)
}),
tags = List(QueryTags.metrics)
)
...
}
相应的查询测试位于 src/test/scala/io/joern/scanners。例如,度量查询的测试位于 src/test/scala/io/joern/scanners/c/MetricsTests.scala:
class MetricsTests extends Suite {
override val code = """
int too_many_params(int a, int b, int c, int d, int e) {
}
...
"""
"find functions with too many parameters" in {
Metrics.tooManyParameters(4)(cpg).map(_.evidence) match {
case List(List(method: nodes.Method)) =>
method.name shouldBe "too_many_params"
case _ => fail
}
}
...
}
这些测试可以在查询开发过程中从 IntelliJ IDE 单独运行。
我们使用 Scala 构建工具(sbt)。请确保已安装 sbt。版本无关紧要,因为 sbt 会根据构建文件(build.sbt)获取所需版本。
一旦安装了 sbt,你可以按如下方式构建和测试数据库:
sbt test
你可以测试新开发的查询
如果你想用 joern-scan 测试新创建的查询,请按如下方式操作:
sbt joerncli/stage
./querydb-install.sh && ./joern-scan <src>
在运行 install.sh 后,你可以启动
./joern-scan --dump
创建一个名为 querydb.json 的文件,其中包含所有可用查询的列表及其元信息。