Running CodeQL runner in your CI system

You can use the Ejecutor de CodeQL to perform CodeQL escaneo de código in a third-party continuous integration system.

El Escaneo de código se encuentra disponible para todos los repositorios públicos y para los privados que pertenecen a organizaciones en donde se habilitó la GitHub Advanced Security. Para obtener más información, consulta la sección "Acerca de GitHub Advanced Security".

Nota: El Ejecutor de CodeQL se va a obsoletizar. Por favor, utiliza la versión 2.6.2 de CodeQL CLI o superior en su lugar. GitHub Enterprise Server 3.3 será la última serie de lanzamiento que será compatible con el Ejecutor de CodeQL. En Nube de GitHub Enterprise, el Ejecutor de CodeQL será compatible hasta marzo del 2022. Para obtener más información, consulta la obsoletización del ejecutor de CodeQL.

About the Ejecutor de CodeQL

The Ejecutor de CodeQL is a tool you can use to run escaneo de código on code that you're processing in a third-party continuous integration (CI) system. Escaneo de código es una característica que utilizas para analizar el código en un repositorio de GitHub para encontrar vulnerabilidades de seguridad y errores de código. Cualquier problema que se identifique con el análisis se muestra en GitHub. For information, see "About escaneo de código with CodeQL."

In many cases it is easier to set up CodeQL escaneo de código using the CodeQL CLI directly in your CI system.

Alternatively, you can use GitHub Actions to run escaneo de código within GitHub. For information, see "Setting up escaneo de código for a repository."

The Ejecutor de CodeQL is a command-line tool that runs CodeQL analysis on a checkout of a GitHub repository. You add the runner to your third-party system, then call the runner to analyze code and upload the results to GitHub. These results are displayed as escaneo de código alerts in the repository.

Note:

  • The Ejecutor de CodeQL uses the CodeQL CLI to analyze code and therefore has the same license conditions. It's free to use on public repositories that are maintained on GitHub.com, and available to use on private repositories that are owned by customers with an Advanced Security license. For information, see "GitHub CodeQL Terms and Conditions" and "CodeQL CLI."

Downloading the Ejecutor de CodeQL

You can download the Ejecutor de CodeQL from https://github.com/github/codeql-action/releases. On some operating systems, you may need to change permissions for the downloaded file before you can run it.

On Linux:

chmod +x codeql-runner-linux

On macOS:

chmod +x codeql-runner-macos
sudo xattr -d com.apple.quarantine codeql-runner-macos

On Windows, the codeql-runner-win.exe file usually requires no change to permissions.

Adding the Ejecutor de CodeQL to your CI system

Once you download the Ejecutor de CodeQL and verify that it can be executed, you should make the runner available to each CI server that you intend to use for escaneo de código. For example, you might configure each server to copy the runner from a central, internal location. Alternatively, you could use the REST API to get the runner directly from GitHub, for example:

wget https://github.com/github/codeql-action/releases/latest/download/codeql-runner-linux
chmod +x codeql-runner-linux

In addition to this, each CI server also needs:

  • A GitHub App or personal access token for the Ejecutor de CodeQL to use. You must use an access token with the repo scope, or a GitHub App with the security_events write permission, and metadata and contents read permissions. For information, see "Building GitHub Apps" and "Creating a personal access token."
  • Access to the CodeQL bundle associated with this release of the Ejecutor de CodeQL. This package contains queries and libraries needed for CodeQL analysis, plus the CodeQL CLI, which is used internally by the runner. For information, see "CodeQL CLI."

The options for providing access to the CodeQL bundle are:

  1. Allow the CI servers access to https://github.com/github/codeql-action so that the Ejecutor de CodeQL can download the bundle automatically.
  2. Manually download/extract the bundle, store it with other central resources, and use the --codeql-path flag to specify the location of the bundle in calls to initialize the Ejecutor de CodeQL.

Calling the Ejecutor de CodeQL

You should call the Ejecutor de CodeQL from the checkout location of the repository you want to analyze. The two main commands are:

  1. init required to initialize the runner and create a CodeQL database for each language to be analyzed. These databases are populated and analyzed by subsequent commands.
  2. analyze required to populate the CodeQL databases, analyze them, and upload results to GitHub.

For both commands, you must specify the URL of GitHub, the repository OWNER/NAME, and the GitHub Apps or personal access token to use for authentication. You also need to specify the location of the CodeQL bundle, unless the CI server has access to download it directly from the github/codeql-action repository.

You can configure where the Ejecutor de CodeQL stores the CodeQL bundle for future analysis on a server using the --tools-dir flag and where it stores temporary files during analysis using --temp-dir.

To view the command-line reference for the runner, use the -h flag. For example, to list all commands run: codeql-runner-OS -h, or to list all the flags available for the init command run: codeql-runner-OS init -h (where OS varies according to the executable that you are using). For more information, see "Configuring escaneo de código in your CI system."

Notas:

  • La carga de SARIF es compatible con un máximo de 5000 resultados por carga. Cualquier resultado que sobrepase este límite se ignorará. Si una herramienta genera demasiados resultados, debes actualizar la configuración para enfocarte en los resultados de las reglas o consultas más importantes.

  • Para cada carga, la carga de SARIF es compatible con un tamaño máximo de 10 MB para el archivo comprimido de gzip. Cualquier carga que esté sobre este límite, se rechazará. Si tu archivo SARIF es demasiado grande porque contiene demasiados resultados, debes actualizar la configuración para enfocarte en los resultados de las reglas o consultas más importantes.

Basic example

This example runs CodeQL analysis on a Linux CI server for the octo-org/example-repo repository hosted on https://github.com. The process is very simple because the repository contains only languages that can be analyzed by CodeQL directly, without being built (that is, Go, JavaScript, Python, and TypeScript).

In this example, the server has access to download the CodeQL bundle directly from the github/codeql-action repository, so there is no need to use the --codeql-path flag.

  1. Check out the repository to analyze.

  2. Move into the directory where the repository is checked out.

  3. Initialize the Ejecutor de CodeQL and create CodeQL databases for the languages detected.

    $ echo "$TOKEN" | /path/to-runner/codeql-runner-linux init --repository octo-org/example-repo
        --github-url https://github.com --github-auth-stdin
    > Cleaning temp directory /srv/checkout/example-repo/codeql-runner
    > ...
    > Created CodeQL database at /srv/checkout/example-repo/codeql-runner/codeql_databases/javascript.
  4. Llena las bases de datos de CodeQL, analízalas, y carga los resultados aGitHub. Los resultados aparecerán en la pestaña de Seguridad de tu repositorio.

    $ echo "$TOKEN" | /path/to-runner/codeql-runner-linux analyze --repository octo-org/example-repo
        --github-url https://github.com --github-auth-stdin
        --commit 5b6a3078b31dc346e5ce7b86837d6abbe7a18bbd --ref refs/heads/my-branch
    > Finalizing database creation
    > ...
    > POST /repos/octo-org/example-repo/code-scanning/sarifs - 202 in 786ms
    > Successfully uploaded results
  5. Para cargar los resultados del escaneo de código como verificaciones de solicitudes de cambios, especifica la solicitud de cambios utilizando el mrcador --ref . Te recomendamos configurar el Ejecutor de CodeQL para que se ejecute en el evento de webhook pull_request.

    $ echo "$TOKEN" | /path/to-runner/codeql-runner-linux analyze --repository octo-org/example-repo
        --github-url https://github.com --github-auth-stdin
        --commit 1dc7a1346e5ce7b86835b68bbda3078b37d6abbe --ref refs/pull/123/merge
    > Finalizing database creation
    > ...
    > POST /repos/octo-org/example-repo/code-scanning/sarifs - 202 in 786ms
    > Successfully uploaded results

Para obtener más información sobre cómo ver las alertas del escaneo de código, consulta la sección "Clasificar las alertas de las solicitudes de cambios del escaneo de código" y "Administrar las alertas del escaneo de código para tu repositorio".

Compiled language example

This example is similar to the previous example, however this time the repository has code in C/C++, C#, or Java. To create a CodeQL database for these languages, the CLI needs to monitor the build. At the end of the initialization process, the runner reports the command you need to set up the environment before building the code. You need to run this command, before calling the normal CI build process, and then running the analyze command.

  1. Check out the repository to analyze.

  2. Move into the directory where the repository is checked out.

  3. Initialize the Ejecutor de CodeQL and create CodeQL databases for the languages detected.

    $ echo "$TOKEN" | /path/to-runner/codeql-runner-linux init --repository octo-org/example-repo-2
        --github-url https://github.com --github-auth-stdin
    > Cleaning temp directory /srv/checkout/example-repo-2/codeql-runner
    > ...
    > CodeQL environment output to "/srv/checkout/example-repo-2/codeql-runner/codeql-env.json"
      and "/srv/checkout/example-repo-2/codeql-runner/codeql-env.sh".
      Please export these variables to future processes so that CodeQL can monitor the build, for example by running 
      ". /srv/checkout/example-repo-2/codeql-runner/codeql-env.sh".
  4. Source the script generated by the init action to set up the environment to monitor the build. Note the leading dot and space in the following code snippet.

    $ . /srv/checkout/example-repo-2/codeql-runner/codeql-env.sh
  5. Build the code. On macOS, you need to prefix the build command with the environment variable $CODEQL_RUNNER. For more information, see "Troubleshooting Ejecutor de CodeQL in your CI system."

  6. Llena las bases de datos de CodeQL, analízalas, y carga los resultados aGitHub. Los resultados aparecerán en la pestaña de Seguridad de tu repositorio.

    $ echo "$TOKEN" | /path/to-runner/codeql-runner-linux analyze --repository octo-org/example-repo
        --github-url https://github.com --github-auth-stdin
        --commit 5b6a3078b31dc346e5ce7b86837d6abbe7a18bbd --ref refs/heads/my-branch
    > Finalizing database creation
    > ...
    > POST /repos/octo-org/example-repo/code-scanning/sarifs - 202 in 786ms
    > Successfully uploaded results
  7. Para cargar los resultados del escaneo de código como verificaciones de solicitudes de cambios, especifica la solicitud de cambios utilizando el mrcador --ref . Te recomendamos configurar el Ejecutor de CodeQL para que se ejecute en el evento de webhook pull_request.

    $ echo "$TOKEN" | /path/to-runner/codeql-runner-linux analyze --repository octo-org/example-repo
        --github-url https://github.com --github-auth-stdin
        --commit 1dc7a1346e5ce7b86835b68bbda3078b37d6abbe --ref refs/pull/123/merge
    > Finalizing database creation
    > ...
    > POST /repos/octo-org/example-repo/code-scanning/sarifs - 202 in 786ms
    > Successfully uploaded results

Para obtener más información sobre cómo ver las alertas del escaneo de código, consulta la sección "Clasificar las alertas de las solicitudes de cambios del escaneo de código" y "Administrar las alertas del escaneo de código para tu repositorio".

Note: If you use a containerized build, you need to run the Ejecutor de CodeQL in the container where your build task takes place.

Further reading

¿Te ayudó este documento?

Política de privacidad

¡Ayúdanos a hacer geniales estos documentos!

Todos los documentos de GitHub son de código abierto. ¿Notas algo que esté mal o que no sea claro? Emite una solicitud de cambios.

Haz una contribución

O, aprende cómo contribuir.