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 Varredura de código for the repository.

Varredura de código está disponível para todos os repositórios públicos e para repositórios privados pertencentes a organizações em que Segurança Avançada GitHub está habilitado. Para obter mais informações, consulte "Sobre Segurança Avançada GitHub".

About Varredura de código configuration

You can run Varredura de código on GitHub, using GitHub Actions, or from your continuous integration (CI) system. For more information, see "About GitHub Actions" or "About CodeQL Varredura de código in your CI system."

This article is about running Varredura de código on GitHub using actions.

Before you can configure Varredura de código for a repository, you must set up Varredura de código by adding a GitHub Actions workflow to the repository. For more information, see "Setting up Varredura de código for a repository."

De modo geral, você não precisa editar o fluxo de trabalho padrão para Varredura de código. No entanto, se necessário, você editar o fluxo de trabalho para personalizar algumas das configurações. Por exemplo, você pode editar os Fluxo de trabalho de análise do CodeQL de GitHub para especificar a frequência das digitalizações, as linguagens ou diretórios a serem digitalizados e o que CodeQL Varredura de código procura no seu código. Talvez você precise editar o Fluxo de trabalho de análise do CodeQL se você usar um conjunto específico de comandos para compilar seu código.

CodeQL analysis is just one type of Varredura de código you can do in GitHub. GitHub Marketplace contains other Varredura de código workflows you can use. You can find a selection of these on the "Get started with Varredura de código" page, which you can access from the Security tab. The specific examples given in this article relate to the Fluxo de trabalho de análise do CodeQL file.

Editing a Varredura de código 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 Varredura de código 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 Fluxo de trabalho de análise do 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 Fluxo de trabalho de análise do 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 Varredura de código to be triggered on a specified branch, the workflow must exist in that branch. For more information, see "Workflow syntax for GitHub Actions."

If you scan on push, then the results appear in the Security tab for your repository. For more information, see "Managing code scanning alerts for your repository."

Additionally, when an on:push scan returns results that can be mapped to an open pull request, these alerts will automatically appear on the pull request in the same places as other pull request alerts. The alerts are identified by comparing the existing analysis of the head of the branch to the analysis for the target branch. For more information on Varredura de código alerts in pull requests, see "Triaging Varredura de código alerts in pull requests."

Scanning pull requests

The default Fluxo de trabalho de análise do 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 "Managing GitHub Actions settings for a repository."

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

If you scan pull requests, then the results appear as alerts in a pull request check. For more information, see "Triaging code scanning alerts in pull requests."

Using the pull_request trigger, configured to scan the pull request's merge commit rather than the head commit, will produce more efficient and accurate results than scanning the head of the branch on each push. However, if you use a CI/CD system that cannot be configured to trigger on pull requests, you can still use the on:push trigger and Varredura de código will map the results to open pull requests on the branch and add the alerts as annotations on the pull request. For more information, see "Scanning on push."

Defining the severities causing pull request check failure

By default, only alerts with the severity level of Error or security severity level of Critical or High will cause a pull request check failure, and a check will still succeed with alerts of lower severities. You can change the levels of alert severities and of security severities that will cause a pull request check failure in your repository settings. For more information about severity levels, see "Managing code scanning alerts for your repository."

  1. No, navegue até a página principal do repositório.
  2. No nome do seu repositório, clique em Configurações. Botão de configurações do repositório
  3. Na barra lateral esquerda, clique em Security & analysis (Segurança e análise). aba de "Segurança & análise" nas configurações do repositório
  4. Under "Code scanning", to the right of "Check Failure", use the drop-down menu to select the level of severity you would like to cause a pull request check failure.

Check failure setting

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 Varredura de código 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.

    branches: [main, protected]
    branches: [main]
      - '**/*.md'
      - '**/*.txt'


  • 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 Varredura de código 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 Varredura de código 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 Fluxo de trabalho de análise do 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.


The following example shows a Fluxo de trabalho de análise do CodeQL for a particular repository that has a default branch called main and one protected branch called protected.

    branches: [main, protected]
    branches: [main]
    - 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 Fluxo de trabalho de análise do CodeQL. Edit the value of jobs.analyze.runs-on to specify the operating system for the machine that runs your Varredura de código 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.

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

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

CodeQL Varredura de código 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.

Specifying the location for CodeQL databases

In general, you do not need to worry about where the Fluxo de trabalho de análise do CodeQL places CodeQL databases since later steps will automatically find databases created by previous steps. However, if you are writing a custom workflow step that requires the CodeQL database to be in a specific disk location, for example to upload the database as a workflow artifact, you can specify that location using the db-location parameter under the init action.

- uses: github/codeql-action/init@v1
    db-location: '${{ github.workspace }}/codeql_dbs'

The Fluxo de trabalho de análise do CodeQL will expect the path provided in db-location to be writable, and either not exist, or be an empty directory. When using this parameter in a job running on a self-hosted runner or using a Docker container, it's the responsibility of the user to ensure that the chosen directory is cleared between runs, or that the databases are removed once they are no longer needed. This is not necessary for jobs running on GitHub-hosted runners, which obtain a fresh instance and a clean filesystem each time they run. For more information, see "About GitHub-hosted runners."

If this parameter is not used, the Fluxo de trabalho de análise do CodeQL will create databases in a temporary location of its own choice.

Changing the languages that are analyzed

CodeQL Varredura de código automatically detects code written in the supported languages.

  • C/C++
  • C#
  • Go
  • Java
  • JavaScript/TypeScript
  • Python
  • Ruby

Note: CodeQL analysis for Ruby is currently in beta. During the beta, analysis of Ruby will be less comprehensive than CodeQL analysis of other languages.

For more information, see the documentation on the CodeQL website: "Supported languages and frameworks."

The default Fluxo de trabalho de análise do 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 Varredura de código 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."

Se o seu repositório contiver código em mais de uma das linguagens compatíveis, você poderá escolher quais linguagens deseja analisar. Há vários motivos para impedir que uma linguagem seja analisada. Por exemplo, o projeto pode ter dependências em uma linguagem diferente do texto principal do seu código, e você pode preferir não ver os alertas para essas dependências.

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 Varredura de código was set up. For example, if the repository initially only contained JavaScript when Varredura de código was set up, and you later added Python code, you will need to add python to the matrix.

    name: Analyze
      fail-fast: false
        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
    languages: cpp, csharp, python

Analyzing Python dependencies

For GitHub-hosted runners that use Linux only, the Fluxo de trabalho de análise do 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:

    runs-on: ubuntu-latest
      security-events: write
      actions: read

      - name: Checkout repository
        uses: actions/checkout@v2
      - name: Set up Python
        uses: actions/setup-python@v2
          python-version: '3.x'
      - name: Install dependencies
        run: |
          python -m pip install --upgrade pip
          if [ -f requirements.txt ];
          then pip install -r requirements.txt;
          # 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
          languages: python
          # Override the default behavior so that the action doesn't attempt
          # to auto-install Python dependencies
          setup-python-dependencies: false

Configuring a category for the analysis

Use category to distinguish between multiple analyses for the same tool and commit, but performed on different languages or different parts of the code. The category you specify in your workflow will be included in the SARIF results file.

This parameter is particularly useful if you work with monorepos and have multiple SARIF files for different components of the monorepo.

    - name: Perform CodeQL Analysis
      uses: github/codeql-action/analyze
        # Optional. Specify a category to distinguish between multiple analyses
        # for the same tool and ref. If you don't use `category` in your workflow, 
        # GitHub will generate a default category name for you
        category: "my_category"

If you don't specify a category parameter in your workflow, GitHub will generate a category name for you, based on the name of the workflow file triggering the action, the action name, and any matrix variables. For example:

  • The .github/workflows/codeql-analysis.yml workflow and the analyze action will produce the category .github/workflows/codeql.yml:analyze.
  • The .github/workflows/codeql-analysis.yml workflow, the analyze action, and the {language: javascript, os: linux} matrix variables will produce the category .github/workflows/codeql-analysis.yml:analyze/language:javascript/os:linux.

The category value will appear as the <run> property in SARIF v2.1.0. For more information, see "SARIF support for Varredura de código."

Your specified category will not overwrite the details of the runAutomationDetails object in the SARIF file, if included.

Running additional queries

Ao usar CodeQL para fazer a varredura do código, o mecanismo de análise de CodeQL gera um banco de dados do código e executa consultas no mesmo. A análise de CodeQL usa um conjunto-padrão de consultas, mas você pode especificar outras consultas a serem executadas, além das consultas-padrão.

You can run extra queries if they are part of a CodeQL pack (beta) published to the GitHub Container registry or a QL pack stored in a repository. For more information, see "About Varredura de código with CodeQL."

The options available to specify the additional queries you want to run are:

  • packs to install one or more CodeQL query packs (beta) and run the default query suite or queries for those packs.
  • queries to specify a single .ql file, a directory containing multiple .ql files, a .qls query suite definition file, or any combination. Para obter mais informações sobre definições do conjunto de consultas, consulte "Criar as conjuntos de consulta do CodeQL".

You can use both packs and queries in the same workflow.

Não recomendamos fazer referência a conjuntos de consulta diretamente do repositório github/codeql, como github/codeql/cpp/ql/src@main. Tais consultas não podem ser compiladas com a mesma versão do CodeQL que é usada para outras consultas, que poderia gerar erros durante a análise.

Using CodeQL query packs

Note: The CodeQL package management functionality, including CodeQL packs, is currently in beta and subject to change.

To add one or more CodeQL query packs (beta), add a with: packs: entry within the uses: github/codeql-action/init@v1 section of the workflow. Within packs you specify one or more packages to use and, optionally, which version to download. Where you don't specify a version, the latest version is downloaded. If you want to use packages that are not publicly available, you need to set the GITHUB_TOKEN environment variable to a secret that has access to the packages. For more information, see "Authentication in a workflow" and "Encrypted secrets."

Note: For workflows that generate CodeQL databases for multiple languages, you must instead specify the CodeQL query packs in a configuration file. For more information, see "Specifying CodeQL query packs" below.

In the example below, scope is the organization or personal account that published the package. When the workflow runs, the three CodeQL query packs are downloaded from GitHub and the default queries or query suite for each pack run. The latest version of pack1 is downloaded as no version is specified. Version 1.2.3 of pack2 is downloaded, as well as the latest version of pack3 that is compatible with version 1.2.3.

- uses: github/codeql-action/init@v1
    # Comma-separated list of packs to download
    packs: scope/pack1,scope/pack2@1.2.3,scope/pack3@~1.2.3

Using queries in QL packs

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 checkout the private repository.

- uses: github/codeql-action/init@v1
    # Optional. Provide a token to access queries stored in 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.

Os conjuntos de consulta a seguir foram criados em CodeQL Varredura de código e estão disponíveis para uso.

Suite de consultaDescrição
security-extendedConsultas de menor gravidade e precisão que as consultas-padrão
security-and-qualityConsultas de security-extended, mais consultas de manutenção e confiabilidade

Ao especificar um conjunto de pesquisas, o mecanismo de análise de CodeQL executará as consultas contidas no conjunto para você além do conjunto-padrão de consultas.

Working with custom configuration files

If you also use a configuration file for custom settings, any additional packs or queries specified in your workflow are used instead of those specified in the configuration file. If you want to run the combined set of additional packs or queries, prefix the value of packs or 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 packs and queries are used together with any specified in the referenced configuration file.

- uses: github/codeql-action/init@v1
    config-file: ./.github/codeql/codeql-config.yml
    queries: +security-and-quality,octo-org/python-qlpack/show_ifs.ql@main
    packs: +scope/pack1,scope/pack2@v1.2.3

Using a custom configuration file

A custom configuration file is an alternative way to specify additional packs and queries to run. You can also use the 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
    config-file: ./.github/codeql/codeql-config.yml

O arquivo de configuração pode ser localizado no repositório que você está analisando ou em um repositório externo. O uso de um repositório externo permite especificar opções de configuração para vários repositórios em um único lugar. Ao fazer referência a um arquivo de configuração localizado em um repositório externo, você pode usar a sintaxe OWNER/REPOSITORY/FILENAME@BRANCH. Por exemplo, octo-org/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
    external-repository-token: ${{ secrets.ACCESS_TOKEN }}

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

Specifying CodeQL query packs

Note: The CodeQL package management functionality, including CodeQL packs, is currently in beta and subject to change.

You specify CodeQL query packs in an array. Note that the format is different from the format used by the workflow file.

  # Use the latest version of 'pack1' published by 'scope'
  - scope/pack1 
  # Use version 1.23 of 'pack2' 
  - scope/pack2@v1.2.3
  # Use the latest version of 'pack3' compatible with 1.23
  - scope/pack3@~1.2.3

If you have a workflow that generates more than one CodeQL database, you can specify any CodeQL query packs to run in a custom configuration file using a nested map of packs.

  # Use these packs for JavaScript analysis
    - scope/js-pack1
    - scope/js-pack2
  # Use these packs for Java analysis
    - scope/java-pack1
    - scope/java-pack2@v1.0.0

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.

  - uses: ./my-basic-queries/example-query.ql
  - uses: ./my-advanced-queries
  - uses: ./query-suites/my-security-queries.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, Ruby and JavaScript/TypeScript), you can restrict Varredura de código 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.

  - src
  - src/node_modules
  - '**/*.test.js'


  • The paths and paths-ignore keywords, used in the context of the Varredura de código 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."
  • The filter pattern characters ?, +, [, ], and ! are not supported and will be matched literally.
  • ** 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 Varredura de código 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

Este arquivo de configuração adiciona o suite de consulta de security-and-quality para a lista de consultas executadas por CodeQL ao fazer a varredura do seu código. Para obter mais informações sobre o suite de consultas disponível para uso, consulte "Executar consultas adicionais".

name: "My CodeQL config"

  - uses: security-and-quality

O seguinte arquivo de configuração desabilita as consultas-padrão e especifica um conjunto de consultas personalizadas para serem executadas. Também configura CodeQL para fazer a varredura de arquivos no diretório src (relativo à raiz), exceto o diretório src/node_modules e os arquivos cujo nome termina com .test.js. Os arquivos em src/node_modules e arquivos com nomes terminados em .test.js são, portanto, excluídos da análise.

name: "My CodeQL config"

disable-default-queries: true

  - 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

  - src 
  - src/node_modules
  - '**/*.test.js'

Configuring Varredura de código for compiled languages

Para as linguagens compiladas compatíveis, você pode usar a ação autobuild no Fluxo de trabalho de análise do CodeQL para criar o seu código. Isso evita que você tenha que especificar comandos de criação explícitos para C/C++, C#, e Java. CodeQL também executa uma criação para projetos Go para configurar o projeto. Entretanto, diferente das outras linguagens compiladas, todos os Go no repositório são extraídos, não apenas aqueles construídos. Você pode usar comandos de criação personalizados para ignorar arquivos de Go de extração que não são tocados pela compilação.

Se o código de C/C++, C#, ou Java no seu repositório tiver um processo de criação não padrão, poderá ocorrer uma falha no autobuild. Você deverá remover a etapa autobuild do fluxo de trabalho e adicionar manualmente etapas de criação. Se você quiser especificar quais arquivos de Go no seu repositório devem ser extraídos, você deverá adicionar as etapas de criação. For more information about how to configure CodeQL Varredura de código for compiled languages, see "Configuring the CodeQL workflow for compiled languages."

Uploading Varredura de código 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."

Esse documento ajudou você?

Política de Privacidade

Ajude-nos a tornar esses documentos ótimos!

Todos os documentos do GitHub são de código aberto. Você percebeu que algo que está errado ou não está claro? Envie um pull request.

Faça uma contribuição

Ou, aprenda como contribuir.