我们经常发布文档更新,此页面的翻译可能仍在进行中。有关最新信息,请访问英文文档。如果此页面上的翻译有问题,请告诉我们

Configuring code scanning

You can configure how GitHub scans the code in your project for vulnerabilities and errors.

People with write permissions to a repository can configure 代码扫描 for the repository.

代码扫描 适用于所有公共仓库以及启用了 GitHub Advanced Security 的组织拥有的私有仓库。 更多信息请参阅“关于 GitHub Advanced Security”。

本文内容

About 代码扫描 configuration

You can run 代码扫描 on GitHub, using GitHub Actions, or from your continuous integration (CI) system, using the CodeQL runner. For more information about GitHub Actions, see "About GitHub Actions." For more information about the CodeQL runner, see "Running 代码扫描 in your CI system."

This article is about running 代码扫描 on GitHub.

Before you can configure 代码扫描 for a repository, you must set up 代码扫描 by adding a GitHub Actions workflow to the repository. For more information, see "Setting up 代码扫描 for a repository."

一般情况下无需编辑 代码扫描 的默认工作流程。 但是,如果需要,您可以编辑工作流程以自定义某些设置。 例如,您可以编辑 GitHub 的 CodeQL 分析工作流程 来指定扫描频率、要扫描的语言或目录,以及 CodeQL 代码扫描 在代码中的查找内容。 如果您使用一组特定的命令来编译代码,您可能还需要编辑 CodeQL 分析工作流程。

CodeQL analysis is just one type of 代码扫描 you can do in GitHub. GitHub Marketplace contains other 代码扫描 workflows you can use. You can find a selection of these on the "Get started with 代码扫描" page, which you can access from the Security tab. The specific examples given in this article relate to the CodeQL 分析工作流程 file.

Editing a 代码扫描 workflow

GitHub saves workflow files in the .github/workflows directory of your repository. You can find a workflow you have added by searching for its file name. For example, by default, the workflow file for CodeQL 代码扫描 is called codeql-analysis.yml.

  1. In your repository, browse to the workflow file you want to edit.
  2. In the upper right corner of the file view, to open the workflow editor, click . Edit workflow file button
  3. After you have edited the file, click Start commit and complete the "Commit changes" form. You can choose to commit directly to the current branch, or create a new branch and start a pull request. Commit update to codeql.yml workflow

For more information about editing workflow files, see "Learn GitHub Actions."

Configuring frequency

You can configure the CodeQL 分析工作流程 to scan code on a schedule or when specific events occur in a repository.

Scanning code when someone pushes a change, and whenever a pull request is created, prevents developers from introducing new vulnerabilities and errors into the code. Scanning code on a schedule informs you about the latest vulnerabilities and errors that GitHub, security researchers, and the community discover, even when developers aren't actively maintaining the repository.

Scanning on push

By default, the CodeQL 分析工作流程 uses the on.push event to trigger a code scan on every push to the default branch of the repository and any protected branches. For 代码扫描 to be triggered on a specified branch, the workflow must exist in that branch. For more information, see "Workflow syntax for GitHub Actions."

Scanning pull requests

The default CodeQL 分析工作流程 uses the pull_request event to trigger a code scan on pull requests targeted against the default branch. If a pull request is from a private fork, the pull_request event will only be triggered if you've selected the "Run workflows from fork pull requests" option in the repository settings. For more information, see "Disabling or limiting GitHub Actions for a repository."

For more information about the pull_request event, see "Workflow syntax for GitHub Actions."

Avoiding unnecessary scans of pull requests

You might want to avoid a code scan being triggered on specific pull requests targeted against the default branch, irrespective of which files have been changed. You can configure this by specifying on:pull_request:paths-ignore or on:pull_request:paths in the 代码扫描 workflow. For example, if the only changes in a pull request are to files with the file extensions .md or .txt you can use the following paths-ignore array.

on:
  push:
    branches: [main, protected]
  pull_request:
    branches: [main]
    paths-ignore:
      - '**/*.md'
      - '**/*.txt'

Notes

  • on:pull_request:paths-ignore and on:pull_request:paths set conditions that determine whether the actions in the workflow will run on a pull request. They don't determine what files will be analyzed when the actions are run. When a pull request contains any files that are not matched by on:pull_request:paths-ignore or on:pull_request:paths, the workflow runs the actions and scans all of the files changed in the pull request, including those matched by on:pull_request:paths-ignore or on:pull_request:paths, unless the files have been excluded. For information on how to exclude files from analysis, see "Specifying directories to scan."
  • For CodeQL 代码扫描 workflow files, don't use the paths-ignore or paths keywords with the on:push event as this is likely to cause missing analyses. For accurate results, CodeQL 代码扫描 needs to be able to compare new changes with the analysis of the previous commit.

For more information about using on:pull_request:paths-ignore and on:pull_request:paths to determine when a workflow will run for a pull request, see "Workflow syntax for GitHub Actions."

Scanning on a schedule

If you use the default CodeQL 分析工作流程, the workflow will scan the code in your repository once a week, in addition to the scans triggered by events. To adjust this schedule, edit the cron value in the workflow. For more information, see "Workflow syntax for GitHub Actions."

Note: GitHub only runs scheduled jobs that are in workflows on the default branch. Changing the schedule in a workflow on any other branch has no effect until you merge the branch into the default branch.

Example

The following example shows a CodeQL 分析工作流程 for a particular repository that has a default branch called main and one protected branch called protected.

on:
  push:
    branches: [main, protected]
  pull_request:
    branches: [main]
  schedule:
    - cron: '20 14 * * 1'

This workflow scans:

  • Every push to the default branch and the protected branch
  • Every pull request to the default branch
  • The default branch every Monday at 14:20 UTC

Specifying an operating system

If your code requires a specific operating system to compile, you can configure the operating system in your CodeQL 分析工作流程. Edit the value of jobs.analyze.runs-on to specify the operating system for the machine that runs your 代码扫描 actions.

If you choose to use a self-hosted runner for code scanning, you can specify an operating system by using an appropriate label as the second element in a two-element array, after self-hosted.

jobs:
  analyze:
    name: Analyze
    runs-on: [self-hosted, ubuntu-latest]

For more information, see "About self-hosted runners" and "Adding self-hosted runners."

CodeQL 代码扫描 supports the latest versions of Ubuntu, Windows, and macOS. Typical values for this setting are therefore: ubuntu-latest, windows-latest, and macos-latest. For more information, see "Workflow syntax for GitHub Actions."

If you use a self-hosted runner, you must ensure that Git is in the PATH variable.

Changing the languages that are analyzed

CodeQL 代码扫描 automatically detects code written in the supported languages.

The default CodeQL 分析工作流程 file contains a build matrix called language which lists the languages in your repository that are analyzed. CodeQL automatically populates this matrix when you add 代码扫描 to a repository. Using the language matrix optimizes CodeQL to run each analysis in parallel. We recommend that all workflows adopt this configuration due to the performance benefits of parallelizing builds. For more information about build matrices, see "Managing complex workflows."

如果仓库中包含多种支持的语言的代码,您可以选择要分析的语言。 在有些情况下您可能需要阻止分析某种语言。 例如,项目中可能存在与代码主体语言不同的依赖项,并且您可能不希望看到关于这些依赖项的警报。

If your workflow uses the language matrix then CodeQL is hardcoded to analyze only the languages in the matrix. To change the languages you want to analyze, edit the value of the matrix variable. You can remove a language to prevent it being analyzed or you can add a language that was not present in the repository when 代码扫描 was set up. For example, if the repository initially only contained JavaScript when 代码扫描 was set up, and you later added Python code, you will need to add python to the matrix.

jobs:
  analyze:
    name: Analyze
    ...
    strategy:
      fail-fast: false
      matrix:
        language: ['javascript', 'python']

If your workflow does not contain a matrix called language, then CodeQL is configured to run analysis sequentially. If you don't specify languages in the workflow, CodeQL automatically detects, and attempts to analyze, any supported languages in the repository. If you want to choose which languages to analyze, without using a matrix, you can use the languages parameter under the init action.

- uses: github/codeql-action/init@v1
  with:
    languages: cpp, csharp, python

Analyzing Python dependencies

For GitHub-hosted runners that use Linux only, the CodeQL 分析工作流程 will try to auto-install Python dependencies to give more results for the CodeQL analysis. You can control this behavior by specifying the setup-python-dependencies parameter for the action called by the "Initialize CodeQL" step. By default, this parameter is set to true:

  • If the repository contains code written in Python, the "Initialize CodeQL" step installs the necessary dependencies on the GitHub-hosted runner. If the auto-install succeeds, the action also sets the environment variable CODEQL_PYTHON to the Python executable file that includes the dependencies.

  • If the repository doesn't have any Python dependencies, or the dependencies are specified in an unexpected way, you'll get a warning and the action will continue with the remaining jobs. The action can run successfully even when there are problems interpreting dependencies, but the results may be incomplete.

Alternatively, you can install Python dependencies manually on any operating system. You will need to add setup-python-dependencies and set it to false, as well as set CODEQL_PYTHON to the Python executable that includes the dependencies, as shown in this workflow extract:

jobs:
  CodeQL-Build:

    runs-on: ubuntu-latest

    steps:
    - name: Checkout repository
      uses: actions/checkout@v2
    - name: Set up Python
      uses: actions/setup-python@v2
      with:
        python-version: '3.x'
    - name: Install dependencies
      run: |
        python -m pip install --upgrade pip
        if [ -f requirements.txt ];
        then pip install -r requirements.txt;
        fi
        # Set the `CODEQL-PYTHON` environment variable to the Python executable
        # that includes the dependencies
        echo "CODEQL_PYTHON=$(which python)" >> $GITHUB_ENV
    - name: Initialize CodeQL
      uses: github/codeql-action/init@v1
      with:
        languages: python
        # Override the default behavior so that the action doesn't attempt
        # to auto-install Python dependencies
        setup-python-dependencies: false

Running additional queries

使用 CodeQL 扫描代码时,CodeQL 分析引擎将从代码生成数据库并对其运行查询。 更多信息请参阅“关于 代码扫描”。

CodeQL 分析使用默认的查询集,但除了默认查询外,您还可以指定更多的查询来运行。 要运行的查询必须属于仓库中的 QL 包。 更多信息请参阅“关于 QL 包”。

查询只能依赖于标准库(即查询中的 import LANGUAGE 语句引用的库)或与查询相同的 QL 包中的库。 标准库位于 github/codeql 仓库中。 更多信息请参阅“关于 CodeQL 查询。”

您可以指定一个 .ql 文件(一个目录中包含多个 .ql 文件)、一个 .qls 查询套件定义文件或任意组合。 有关查询套件定义的更多信息,请参阅“创建 CodeQL 查询套件”。

不建议直接从 github/codeql 仓库引用查询套件,如 github/codeql/cpp/ql/src@main。 此类查询不可使用与其他查询所用版本相同的 CodeQL 版本编译,否则可能导致分析过程中出错。

To add one or more queries, add a with: queries: entry within the uses: github/codeql-action/init@v1 section of the workflow. If the queries are in a private repository, use the external-repository-token parameter to specify a token that has access to the private repository.

- uses: github/codeql-action/init@v1
  with:
    queries: COMMA-SEPARATED LIST OF PATHS
    # Optional. Provide a token to access private repositories.
    external-repository-token: ${{ secrets.ACCESS_TOKEN }}

You can also specify query suites in the value of queries. Query suites are collections of queries, usually grouped by purpose or language.

以下查询套件内置于 CodeQL 代码扫描,可供使用。

查询套件描述
security-extended严重性和精度低于默认查询的查询
security-and-quality来自 security-extended 的查询,加上可维护性和可靠性查询

在指定查询套件时,CodeQL 分析引擎将运行套件中包含的查询,以及默认查询集。

If you are also using a configuration file for custom settings, any additional queries specified in your workflow are used instead of any specified in the configuration file. If you want to run the combined set of additional queries specified here and in the configuration file, prefix the value of queries in the workflow with the + symbol. For more information, see "Using a custom configuration file."

In the following example, the + symbol ensures that the specified additional queries are used together with any queries specified in the referenced configuration file.

- uses: github/codeql-action/init@v1
  with:
    config-file: ./.github/codeql/codeql-config.yml
    queries: +security-and-quality,octo-org/python-qlpack/show_ifs.ql@main
    external-repository-token: ${{ secrets.ACCESS_TOKEN }}

Using a custom configuration file

As an alternative to specifying which queries to run in the workflow file, you can do this in a separate configuration file. You can also use a configuration file to disable the default queries and to specify which directories to scan during analysis.

In the workflow file, use the config-file parameter of the init action to specify the path to the configuration file you want to use. This example loads the configuration file ./.github/codeql/codeql-config.yml.

- uses: github/codeql-action/init@v1
  with:
    config-file: ./.github/codeql/codeql-config.yml

配置文件可以放在您分析的仓库内或外部仓库中。 使用外部仓库允许您在一个位置指定多个仓库的配置选项。 引用位于外部仓库中的配置文件时,您可以使用 OWNER/REPOSITORY/FILENAME@BRANCH 语法。 例如,monacorp/shared/codeql-config.yml@main

If the configuration file is located in an external private repository, use the external-repository-token parameter of the init action to specify a token that has access to the private repository.

uses: github/codeql-action/init@v1
with:
  external-repository-token: ${{ secrets.ACCESS_TOKEN }}

The settings in the configuration file are written in YAML format.

Specifying additional queries

You specify additional queries in a queries array. Each element of the array contains a uses parameter with a value that identifies a single query file, a directory containing query files, or a query suite definition file.

queries:
  - uses: ./my-basic-queries/example-query.ql
  - uses: ./my-advanced-queries
  - uses: ./codeql-qlpacks/complex-python-qlpack/rootAndBar.qls

Optionally, you can give each array element a name, as shown in the example configuration files below.

For more information about additional queries, see "Running additional queries" above.

Disabling the default queries

If you only want to run custom queries, you can disable the default security queries by using disable-default-queries: true.

Specifying directories to scan

For the interpreted languages that CodeQL supports (Python and JavaScript/TypeScript), you can restrict 代码扫描 to files in specific directories by adding a paths array to the configuration file. You can exclude the files in specific directories from analysis by adding a paths-ignore array.

paths:
  - src
paths-ignore:
  - src/node_modules
  - '**/*.test.js'

Note:

  • The paths and paths-ignore keywords, used in the context of the 代码扫描 configuration file, should not be confused with the same keywords when used for on.<push|pull_request>.paths in a workflow. When they are used to modify on.<push|pull_request> in a workflow, they determine whether the actions will be run when someone modifies code in the specified directories. For more information, see "Workflow syntax for GitHub Actions."
  • ** characters can only be at the start or end of a line, or surrounded by slashes, and you can't mix ** and other characters. For example, foo/**, **/foo, and foo/**/bar are all allowed syntax, but **foo isn't. However you can use single stars along with other characters, as shown in the example. You'll need to quote anything that contains a * character.

For compiled languages, if you want to limit 代码扫描 to specific directories in your project, you must specify appropriate build steps in the workflow. The commands you need to use to exclude a directory from the build will depend on your build system. For more information, see "Configuring the CodeQL workflow for compiled languages."

You can quickly analyze small portions of a monorepo when you modify code in specific directories. You'll need to both exclude directories in your build steps and use the paths-ignore and paths keywords for on.<push|pull_request> in your workflow.

Example configuration files

当您扫描代码时,此配置文件将 security-and-quality 查询套件添加到 CodeQL 运行的查询列表。 有关可供使用的查询套件的更多信息,请参阅“运行其他查询”。

name: "My CodeQL config"

queries:
  - uses: security-and-quality

以下配置文件禁用默认查询,并指定一组要运行的自定义查询。 它还配置 CodeQL 扫描 src 目录中的文件(相对于根目录),并且排除 src/node_modules 目录以及名称以 .test.js 结尾的任何文件。 因此,src/node_modules 中的文件以及名称以 .test.js 结尾的文件被排除在分析之外。

name: "My CodeQL config"

disable-default-queries: true

queries:
  - name: Use an in-repository QL pack (run queries in the my-queries directory)
    uses: ./my-queries
  - name: Use an external JavaScript QL pack (run queries from an external repo)
    uses: octo-org/javascript-qlpack@main
  - name: Use an external query (run a single query from an external QL pack)
    uses: octo-org/python-qlpack/show_ifs.ql@main
  - name: Use a query suite file (run queries from a query suite in this repo)
    uses: ./codeql-qlpacks/complex-python-qlpack/rootAndBar.qls

paths:
  - src 
paths-ignore: 
  - src/node_modules
  - '**/*.test.js'

Configuring 代码扫描 for compiled languages

对于受支持的编译语言,您可以使用 CodeQL 分析工作流程 中的 autobuild 操作来构建代码。 这样您无需为 C/C++、C# 和 Java 指定显式构建命令。 CodeQL 也运行 Go 项目的构建来设置项目。 但是,与其他编译语言相比,仓库中的所有 Go 文件都是提取的,而不仅仅是构建的文件。 Go 不支持自定义构建命令。

如果仓库中的 C/C++、C# 或 Java 代码含有非标准的构建过程,autobuild 可能会失败。 您需要从工作流程中删除 autobuild 步骤,然后手动添加构建步骤。 For more information about how to configure CodeQL 代码扫描 for compiled languages, see "Configuring the CodeQL workflow for compiled languages."

Uploading 代码扫描 data to GitHub

GitHub can display code analysis data generated externally by a third-party tool. You can upload code analysis data with the upload-sarif action. For more information, see "Uploading a SARIF file to GitHub."

此文档对您有帮助吗?

Privacy policy

帮助我们创建出色的文档!

所有 GitHub 文档都是开源的。看到错误或不清楚的内容了吗?提交拉取请求。

做出贡献

或, 了解如何参与。