Publicamos atualizações frequentes em nossa documentação, e a tradução desta página ainda pode estar em andamento. Para obter as informações mais recentes, acesse a documentação em inglês. Se houver problemas com a tradução desta página, entre em contato conosco.

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 is available if you have an Segurança Avançada license.

Neste artigo

Nota: Varredura de código está atualmente em versão beta e sujeito a alterações. Para obter mais informações sobre a participação no beta, inscreva-se aqui.

Observação: O administrador do site deve habilitar Varredura de código para your GitHub Enterprise Server instance antes de usar este recurso. Se você desejar usar o GitHub Actions para fazer a varredura do seu código, o administrador do site também deverá habilitar o GitHub Actions e configurar a infraestrutura necessária. Para obter mais informações, consulte "Configurar o Varredura de código para seu aplicativo ".

About Varredura de código configuration

You can run Varredura de código within your GitHub Enterprise Server instance, using GitHub Actions, or from your continuous integration (CI) system, using the Executor do CodeQL. For more information about GitHub Actions, see "About GitHub Actions." For more information about the Executor do CodeQL, see "Running Varredura de código in your CI system."

This article is about running Varredura de código within GitHub Enterprise Server.

Before you can configure Varredura de código for a repository, you must enable Varredura de código by adding a GitHub Actions workflow to the repository. For more information, see "Enabling 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 on GitHub.com contains other Varredura de código workflows you can use. 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 enabled 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."

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. The pull_request event is not triggered if the pull request was opened from a private fork.

For more information about the pull_request event, 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.

Example

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.

on:
  push:
    branches: [main, protected]
  pull_request:
    branches: [main]
  schedule:
    - cron: '0 15 * * 0'

This workflow scans:

  • Every push to the default branch and the protected branch
  • Every pull request to the default branch
  • The default branch at 3 P.M. every Sunday

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. You specify the 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]

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" and "Using labels with self-hosted runners."

You must ensure that Git is in the PATH variable on your self-hosted runners.

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

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 enabled. For example, if the repository initially only contained JavaScript when Varredura de código was enabled, 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

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. Para obter mais informações, consulte "Sobre Varredura de código".

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. As consultas que você desejar executar devem pertencer a um pacote do QL e podem estar no seu próprio repositório ou em qualquer repositório público. Para obter mais informações, consulte "Sobre os pacotes de QL.

As consultas só devem depender das bibliotecas-padrão (ou seja, as bibliotecas referenciadas por uma declaração de LINGUAGEM de importação na sua consulta), ou bibliotecas no mesmo pacote do QL da consulta. As bibliotecas-padrão estão localizadas no repositório github/codeql. Para obter mais informações, consulte "Sobre consultas do CodeQL".

Você pode especificar um único arquivo .ql, um diretório que contém múltiplos arquivos .ql, um arquivo de definição de suite de consultas .qls ou qualquer outra combinação. Para obter mais informações sobre definições do conjunto de consultas, consulte "Criar as conjuntos de consulta do CodeQL".

To add one or more queries, add a with: queries: entry within the uses: github/codeql-action/init@v1 section of the workflow.

- uses: github/codeql-action/init@v1
  with:
    queries: COMMA-SEPARATED LIST OF PATHS

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.

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

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

The configuration file can be located within the local repository, or in a public, remote repository. For remote repositories, you can use the owner/repository/file.yml@branch syntax. The settings in the 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 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 scans by adding a paths-ignore array.

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

Note:

  • 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."
  • ** 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 C/C++, C#, and Java, 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"

queries:
  - 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. Ele também configura o CodeQL para fazer a varredura de arquivos no diretório src (relativas à raiz) e para excluir o diretório node_modules (também relativo à raiz), bem como qualquer arquivo cujo nome termina em .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-ignore: 
  - node_modules
  - '**/*.test.js'
paths:
  - src 

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. Comandos de compilação personalizados não são compatíveis com o Go.

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. For more information about how to configure CodeQL Varredura de código for compiled languages, see "Configuring the CodeQL workflow for compiled languages."

Accessing private repositories

If your workflow for Varredura de código accesses a private repository, other than the repository that contains the workflow, you'll need to configure Git to authenticate with a personal access token. Define the secret in the runner environment by using jobs.<job_id>.steps.env in your workflow before any CodeQL actions. For more information, see "Creating a personal access token for the command line" and "Creating and storing encrypted secrets."

For example, the following configuration has Git replace the full URLs to the github/foo, github/bar, and github/baz repositories on GitHub.com with URLs that include the personal access token that you store in the ACCESS_TOKEN environment variable.

steps:
- name: Configure access to private repositories
  env:
    TOKEN: ${{ secrets.ACCESS_TOKEN }}
  run: |
    git config --global url."https://${TOKEN}@github.com/github/foo".insteadOf "https://github.com/github/foo"
    git config --global url."https://${TOKEN}@github.com/github/bar".insteadOf "https://github.com/github/bar"
    git config --global url."https://${TOKEN}@github.com/github/baz".insteadOf "https://github.com/github/baz"

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ê?

Privacy policy

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.