Hardening Self-Hosted CI Runners: Isolation, Ephemerality, and Token Theft in Pipelines
A self-hosted CI runner is the most under-protected compute in most organizations. It has network access to your clusters, it holds cloud credentials, it pulls and pushes images to your registries, and it executes arbitr
A self-hosted CI runner is the most under-protected compute in most organizations. It has network access to your clusters, it holds cloud credentials, it pulls and pushes images to your registries, and it executes arbitrary code written by anyone who can open a pull request. If an attacker lands on a shared, long-lived runner, they do not need to break your production cluster: they just wait for your pipeline to hand them the keys.
This article walks through a concrete hardening path for self-hosted GitHub Actions runners on Kubernetes/OpenShift: making runners truly ephemeral, isolating job workloads at the kernel level, scoping OIDC federation so stolen tokens are near-useless, and detecting exfiltration of pipeline variables.
Why a shared runner is a lateral-movement highway
Think about what actually lives on a runner during a job:
-
GITHUB_TOKEN, injected into the job environment and often withwrite-allpermissions on older repository defaults. -
ACTIONS_RUNTIME_TOKENandACTIONS_ID_TOKEN_REQUEST_TOKEN, which allow minting an OIDC identity token for cloud federation. - Repository and organization secrets exposed as environment variables.
- A kubeconfig or an in-cluster ServiceAccount token, frequently with cluster-wide read access "for the deployment step".
- Build caches,
~/.docker/config.json, SSH keys for private Go/npm modules. - On DinD-based setups, a Docker socket, which is root on the node by design.
Now add the attack surface. Any fork PR workflow, any dependency with a post-install hook, any third-party action referenced by a mutable tag (actions/checkout@v4 is a moving target) can execute code in that context. On a long-lived runner, that code can:
- Read
/proc/*/environof concurrently running jobs from other repositories. - Drop a persistence hook in
~/.bashrc, in the runner'shooks/job-started.sh, or in a shared toolcache directory. - Poison the build cache so the next pipeline, which has production credentials, runs attacker-controlled code.
- Mint an OIDC token and assume a cloud role, then exfiltrate STS credentials to an external endpoint.
The dangerous property is not the compromise of one job. It is the persistence and the shared trust of the runner. Everything below is aimed at removing those two properties.
Ephemeral runners: one pod, one job, no reuse
The first control is architectural. Each job must run on a freshly created pod, with a just-in-time registration token, that is destroyed when the job ends. Actions Runner Controller (ARC) runner scale sets do exactly that by default.
# Controller
helm install arc \
--namespace arc-systems --create-namespace \
oci://ghcr.io/actions/actions-runner-controller-charts/gha-runner-scale-set-controller \
--version 0.9.3
# GitHub App credentials (never a PAT for org-wide runners)
oc create namespace arc-runners-prod
oc create secret generic github-app \
-n arc-runners-prod \
--from-literal=github_app_id=123456 \
--from-literal=github_app_installation_id=7891011 \
--from-file=github_app_private_key=./app-key.pem
Then install a scale set whose pod template is locked down:
# values-prod.yaml, used by the gha-runner-scale-set chart
githubConfigUrl: https://github.com/acme/payments-api
githubConfigSecret: github-app
minRunners: 0
maxRunners: 20
runnerScaleSetName: prod-k8s
containerMode:
type: kubernetes
kubernetesModeWorkVolumeClaim:
accessModes: ["ReadWriteOnce"]
storageClassName: gp3-csi
resources:
requests:
storage: 10Gi
template:
spec:
runtimeClassName: gvisor
automountServiceAccountToken: false
serviceAccountName: arc-runner-prod
securityContext:
runAsNonRoot: true
runAsUser: 1001
fsGroup: 1001
seccompProfile:
type: RuntimeDefault
containers:
- name: runner
image: ghcr.io/actions/actions-runner:2.319.1
command: ["/home/runner/run.sh"]
env:
- name: ACTIONS_RUNNER_REQUIRE_JOB_CONTAINER
value: "false"
securityContext:
allowPrivilegeEscalation: false
readOnlyRootFilesystem: false
capabilities:
drop: ["ALL"]
resources:
requests: {cpu: "500m", memory: 1Gi}
limits: {cpu: "2", memory: 4Gi}
helm install prod-k8s -n arc-runners-prod \
-f values-prod.yaml \
oci://ghcr.io/actions/actions-runner-controller-charts/gha-runner-scale-set --version 0.9.3
Three details matter more than the rest:
-
minRunners: 0plus JIT registration means there is no idle runner sitting around with a valid registration token. -
automountServiceAccountToken: falseprevents a job from calling the Kubernetes API with the runner's identity. If your pipeline needs cluster access, it should federate for it explicitly, not inherit it. - No
dockerd, noprivileged: true, no host socket mounts. Build images with Buildah or Kaniko in rootless mode instead.
Separate scale sets per trust tier
Do not share one scale set between "runs on every fork PR" and "deploys to production". Create at least two namespaces with distinct ServiceAccounts and distinct network policies, and bind the production scale set to protected branches only.
oc get runnerscalesets -A
# NAMESPACE NAME MINRUNNERS MAXRUNNERS
# arc-runners-pr pr-sandbox 0 50
# arc-runners-prod prod-k8s 0 20
On the workflow side, selection is by label:
jobs:
deploy:
runs-on: prod-k8s
environment: production
Kernel-level isolation: seccomp and gVisor
A container boundary is a syscall boundary. CI jobs run arbitrary compilers, test harnesses and package managers, which is exactly the workload profile where kernel exploits get exercised.
seccompProfile: RuntimeDefault is the baseline and costs nothing. For the PR/fork tier, go further with gVisor (runsc), which interposes a user-space kernel between the job and the host.
apiVersion: node.k8s.io/v1
kind: RuntimeClass
metadata:
name: gvisor
handler: runsc
scheduling:
nodeSelector:
sandbox.acme.io/runtime: gvisor
tolerations:
- key: sandbox.acme.io/runtime
operator: Equal
value: gvisor
effect: NoSchedule
On OpenShift, deploy the runsc handler with a MachineConfig that drops a CRI-O runtime stanza on a dedicated machine config pool, then taint those nodes so only sandboxed CI lands there.
oc label node ci-sandbox-0 sandbox.acme.io/runtime=gvisor
oc adm taint node ci-sandbox-0 sandbox.acme.io/runtime=gvisor:NoSchedule
oc get runtimeclass gvisor -o yaml
Expect a 10–25% penalty on syscall-heavy builds. Accept it on the untrusted tier; skip it on the trusted tier if you need the speed.
If you need a custom seccomp profile (for example to block ptrace and process_vm_readv, the two syscalls used to read another process's memory), ship it via the Security Profiles Operator and reference it:
securityContext:
seccompProfile:
type: Localhost
localhostProfile: operator/arc-runners-pr/no-ptrace.json
Lock down egress
Most exfiltration is a plain HTTPS POST. Default-deny egress and allow only what the build needs.
apiVersion: networking.k8s.io/v1
kind: NetworkPolicy
metadata:
name: runner-egress
namespace: arc-runners-pr
spec:
podSelector:
matchLabels:
actions.github.com/scale-set-name: pr-sandbox
policyTypes: ["Egress"]
egress:
- to:
- namespaceSelector:
matchLabels:
kubernetes.io/metadata.name: openshift-dns
ports:
- {protocol: UDP, port: 5353}
- {protocol: TCP, port: 5353}
- to:
- ipBlock:
cidr: 0.0.0.0/0
except:
- 169.254.169.254/32 # cloud instance metadata
- 10.0.0.0/8 # internal networks
ports:
- {protocol: TCP, port: 443}
Better still, force all egress through an authenticated proxy with an allowlist (github.com, your registry, your artifact mirror) and log every denied domain. A denied request to webhook.site or a Pastebin clone is a high-signal alert.
OIDC federation: short-lived, narrowly scoped identities
Static cloud keys stored as repository secrets are the single biggest payoff for an attacker. Replace them with OIDC federation, then make the trust policy so specific that a token stolen from the PR tier cannot touch production.
permissions:
id-token: write
contents: read
jobs:
deploy:
runs-on: prod-k8s
environment: production
steps:
- uses: actions/checkout@692973e3d937129bcbf40652eb9f2f61becf3332 # v4.1.7
- uses: aws-actions/configure-aws-credentials@e3dd6a429d7300a6a4c196c26e071d42e0343502 # v4.0.2
with:
role-to-assume: arn:aws:iam::111122223333:role/gha-payments-deploy
aws-region: eu-west-3
role-duration-seconds: 900
The trust policy is where the security actually lives:
{
"Version": "2012-10-17",
"Statement": [{
"Effect": "Allow",
"Principal": { "Federated": "arn:aws:iam::111122223333:oidc-provider/token.actions.githubusercontent.com" },
"Action": "sts:AssumeRoleWithWebIdentity",
"Condition": {
"StringEquals": {
"token.actions.githubusercontent.com:aud": "sts.amazonaws.com",
"token.actions.githubusercontent.com:sub": "repo:acme/payments-api:environment:production"
}
}
}]
}
Key rules:
- Never use a wildcard
repo:acme/*:*subject. One role per repository and per environment. - Prefer
environment:productionoverref:refs/heads/main. Branch names can be created by anyone with write access; environments can require reviewers. - Set
role-duration-secondsto the minimum that works (900s is the floor forAssumeRoleWithWebIdentity). - Customize the subject claim at the org level if you want to include the job workflow reference:
gh api -X PUT /repos/acme/payments-api/actions/oidc/customization/sub \
-f use_default=false \
-f 'include_claim_keys[]=repo' \
-f 'include_claim_keys[]=environment' \
-f 'include_claim_keys[]=job_workflow_ref'
Environment protection rules
Environments are not just a label; they are the gate that makes the OIDC subject trustworthy.
gh api -X PUT /repos/acme/payments-api/environments/production \
-F 'wait_timer=5' \
-F 'reviewers[][type]=Team' -F 'reviewers[][id]=4567890' \
-F 'deployment_branch_policy[protected_branches]=true' \
-F 'deployment_branch_policy[custom_branch_policies]=false'
With required reviewers plus a protected-branch policy, an attacker who can push a branch cannot mint a environment:production OIDC token without a human approving the deployment.
The same pattern applies in-cluster: use the Kubernetes TokenRequest/OIDC trust between GitHub and your cluster rather than storing a long-lived kubeconfig, and bind the resulting identity to a narrowly scoped Role.
apiVersion: rbac.authorization.k8s.io/v1
kind: Role
metadata:
name: gha-deployer
namespace: payments
rules:
- apiGroups: ["apps"]
resources: ["deployments"]
verbs: ["get", "patch"]
- apiGroups: [""]
resources: ["pods", "pods/log"]
verbs: ["get", "list"]
Detecting exfiltration of pipeline variables
GitHub masks known secret values in logs, but masking is a string replacement: echo $SECRET | base64 defeats it instantly. Detection must happen at the runtime and network layers.
Runtime detection with Falco. Deploy Falco on the CI nodes and alert on behavior that no legitimate build performs.
- rule: Runner reads another process environment
desc: A CI job is reading /proc/<pid>/environ outside its own PID
condition: >
open_read and container
and k8s.ns.name startswith "arc-runners"
and fd.name glob "/proc/*/environ"
output: >
Possible env theft (pod=%k8s.pod.name cmd=%proc.cmdline file=%fd.name user=%user.name)
priority: CRITICAL
tags: [ci, exfiltration]
- rule: Unexpected OIDC token request
desc: ACTIONS_ID_TOKEN_REQUEST_URL called by a non-allowlisted binary
condition: >
spawned_process and container
and k8s.ns.name startswith "arc-runners"
and proc.cmdline contains "ACTIONS_ID_TOKEN_REQUEST"
and not proc.name in (node, Runner.Worker)
output: "OIDC token minted by %proc.name (pod=%k8s.pod.name cmdline=%proc.cmdline)"
priority: WARNING
helm upgrade --install falco falcosecurity/falco \
-n falco --create-namespace \
--set driver.kind=modern_ebpf \
--set-file customRules."ci_rules\.yaml"=./ci_rules.yaml
Network detection. Every DNS query and proxy request from arc-runners-* should be logged and matched against your allowlist. Build a simple alert: first-seen destination domain per repository over the last 30 days.
Cloud-side detection. CloudTrail gives you the OIDC subject in userIdentity.sessionContext. Alert when a role is assumed from an unexpected subject, or when STS credentials issued to a CI session are used from an IP that is not your egress NAT gateway:
aws cloudtrail lookup-events \
--lookup-attributes AttributeKey=EventName,AttributeValue=AssumeRoleWithWebIdentity \
--query 'Events[].CloudTrailEvent' --output text | jq -r '.userIdentity.userName, .sourceIPAddress'
Platform audit log. Stream the GitHub org audit log and alert on environment.remove_protection_rule, repo.actions_enabled, org.runner_group_updated, and self-hosted runner registrations outside of ARC.
Security best practices
-
One job, one pod, one JIT token. No runner reuse, no
minRunners > 0on untrusted tiers. - No Docker socket, no privileged containers. Use rootless Buildah/Kaniko; if DinD is unavoidable, isolate it on its own sandboxed node pool.
-
automountServiceAccountToken: falseby default; grant cluster access through federation and a namespaced Role. -
permissions:block in every workflow. Start fromcontents: readand add scopes per job, never at workflow root. - Pin third-party actions to a full commit SHA and mirror critical actions into an internal org.
-
Never run fork PRs on production-tier runners.
pull_request_targetwithactions/checkoutof the PR head is a remote code execution primitive — treat it as such. - OIDC subject must include the environment, and the environment must have required reviewers and a protected-branch policy.
- Default-deny egress, block 169.254.169.254, force HTTPS through a logging proxy.
- RuntimeDefault seccomp everywhere, gVisor for untrusted tiers, with taints/tolerations so sandboxed nodes are never shared with platform workloads.
- Rotate and expire: STS sessions ≤ 15 minutes, GitHub App installation tokens over PATs, no static cloud keys in secrets.
-
Alert on behavior, not strings:
/proc/*/environreads, unexpected OIDC calls, first-seen egress domains, audit-log protection changes.
Conclusion
A shared, long-lived self-hosted runner concentrates every credential your organization uses, and hands execution on it to anyone who can open a pull request. The fix is not a scanner — it is architecture.
Four things carry most of the risk reduction. Make runners ephemeral so compromise cannot persist or cross jobs. Isolate them with seccomp, gVisor, dropped capabilities and default-deny egress so a container escape is not a node takeover. Replace static credentials with OIDC federation whose subject is pinned to a specific repository and a protected environment, so a token stolen in a fork PR grants nothing. Finally, instrument the runtime and the network, because the only reliable signal of secret exfiltration is behavioral — a process reading another's environment, or a build calling a domain it has never called before.
Start with ephemerality and the permissions: block: they are cheap, they break nothing, and they remove the two conditions that turn a single compromised job into a full environment breach.
Originally published by Dev.to Security. Aggregated on AIWithGhost for educational purposes — full credit and traffic to the original publisher.