Codeql 入门教程
字数 1077 2025-08-20 18:17:53
CodeQL 入门教程
1. CodeQL 简介
CodeQL 是一个可以对代码进行分析的引擎,安全人员可以用它作为挖洞的辅助工具或直接进行漏洞挖掘,节省重复操作的精力。它支持多种编程语言,包括 Python、Java、JavaScript、C/C++、C# 和 Go。
2. 安装与配置
2.1 下载与安装
- 选择一个安装目录(如
/opt/codeql) - 下载 CodeQL 引擎并解压到目录
- 下载 Semmle 的 QL 库:
cd codeql && git clone https://github.com/Semmle/ql - 安装 VSCode 插件:在插件市场搜索 "CodeQL" 并安装
2.2 目录结构
安装完成后,目录下应有两个主要目录:
codeql:引擎主程序ql:查询库
3. 创建数据库
使用 codeql database create 命令创建查询数据库:
codeql database create ./codeql -s . --language=python
对于编译型语言(如 C/C++),可能需要提供编译命令:
codeql database create ./codeql -s . --language=cpp --command="make"
4. 基本查询语法
4.1 查询结构
CodeQL 查询格式与 SQL 类似:
from int i
where i = 3
select i
from:定义变量where:声明限制条件select:选择要输出的数据
4.2 定义类型
CodeQL 中可以定义类和函数:
// 函数定义
predicate isLarge(int i) {
i > 5
}
// 类定义
class LargeNumber extends int {
// 类变量声明
int threshold
// 覆盖父类函数
override string toString() {
result = "Large number: " + this.toString()
}
}
4.3 导入包
导入语法与 Python 类似:
import python
5. 代码审计应用
5.1 查找特定函数调用
查找所有 redirect 函数调用:
import python
from Call c, Name n
where c.getFunc() = n and n.getId() = "redirect"
select c, "redirect"
5.2 查找请求参数获取
查找 request.GET.get() 或 request.POST.get() 调用:
import python
from Attribute a, Attribute b
where a.getName() = "get" and a.getObject() = b
and (b.getName() = "GET" or b.getName() = "POST")
select a, "get request var"
5.3 排除测试文件
定义谓词排除测试文件:
predicate isNoTest(Expr e) {
not e.getLocation().getFile().getBaseName().matches("debug%") and
not e.getLocation().getFile().getBaseName().matches("test%")
}
5.4 复杂查询示例
查找同时包含请求参数获取和重定向的函数:
import python
from Attribute a, Attribute b, Call c,
Function f, Assign assign, Name n,
Call redirectCall, Name n1
where a.getName() = "get" and a.getObject() = b
and (b.getName() = "GET" or b.getName() = "POST")
and f.getAStmt() = assign
and c.getFunc() = a
and assign.getValue() = c
and redirectCall.getFunc() = n1 and n1.getId() = "redirect"
and (assign.getScope() = f and redirectCall.getScope() = f)
select f
6. 语言支持与文档
CodeQL 支持的语言:
- Python
- Java
- JavaScript
- C/C++
- C#
- Go
文档访问方式:
- 将 URL 中的语言名称替换即可访问对应文档:
https://help.semmle.com/qldoc/python→https://help.semmle.com/qldoc/java等
7. 注意事项
- PHP 目前不支持,由于其动态特性难以实现有效的污点跟踪和变量分析
- 文档不够完善,使用人数较少,很多问题需要自行查阅文档解决
- 对于编译型语言,可能需要手动提供编译命令
- VSCode 插件安装后需要配置 CodeQL 目录
8. 总结
CodeQL 是一个强大的静态代码分析工具,通过编写查询可以高效地发现代码中的潜在问题。虽然学习曲线较陡峭,文档也不够完善,但一旦掌握可以显著提高代码审计的效率。建议从简单查询开始,逐步构建更复杂的分析逻辑。