跳至主要内容

为 CodeQL CLI 编写自定义查询

您可以编写自己的 CodeQL 查询,以查找特定的漏洞和错误。

谁可以使用此功能?

CodeQL 可用于以下仓库类型

This article is specifically about writing queries to use with the database analyze command to produce interpreted results. For conceptual information about custom queries, see Custom CodeQL queries.

编写有效查询

在运行自定义分析之前,您需要编写一个有效查询,并将其保存为扩展名为 .ql 的文件。我们提供了大量文档以帮助您编写查询。欲了解更多信息,请参阅 CodeQL 查询

包含查询元数据

使用 database analyze 命令运行查询时,必须包含以下两个属性,以确保结果得到正确解释。

  • 查询标识符 (@id):由小写字母或数字组成的单词序列,使用 /- 分隔,用于标识和分类查询。

  • 查询类型 (@kind):将查询标识为简单警报 (@kind problem)、通过一系列代码位置记录的警报 (@kind path-problem)、用于提取器故障排除 (@kind diagnostic),或汇总指标 (@kind metric@tags summary)。

For more information about these metadata properties, see Metadata for CodeQL queries and the Query metadata style guide.

在 SARIF 文件中为自定义 CodeQL 查询提供查询帮助

For information about query help and documentation formats, see Custom CodeQL queries.

在运行代码扫描分析时将查询帮助包含在 SARIF 文件中

  1. 以以下任意一种格式编写查询帮助

    • Markdown 文件:将 Markdown 文件与查询一起保存,文件名相同(例如,my-query.md 对应于 my-query.ql
    • .qhelp 文件:使用 .qhelp 格式编写查询帮助,然后在运行分析之前将其转换为 Markdown。欲了解更多信息,请参阅 查询帮助文件测试查询帮助文件
  2. 使用 --sarif-add-query-help 选项运行 codeql database analyze

    codeql database analyze <database> --format=sarif-latest --output=results.sarif --sarif-add-query-help
    

    注意

    --sarif-add-query-help 选项自 CodeQL CLI v2.7.1 起可用。

  3. 将 SARIF 文件上传至 GitHub。

后续步骤

要共享和使用您的自定义查询,请参阅 Publishing and using CodeQL packs.

© . This site is unofficial and not affiliated with GitHub, Inc.