Skip to content
All posts

Penetration Testing

Secrets in CI/CD Pipelines: How We Audit Them and Stop Leaks

In our lab one workflow had five paths to the same cloud key. Our audit script, why log masking failed, a tuned detection and the OIDC fix.

MAMuaaz AhmadPenetration Tester

· 17 min read

On this page

A build pipeline is the one system that holds the keys to production and runs code written by other people, by design. That is why secrets leak there: not through one big mistake, but through four or five small ones that each look harmless in review.

When we test an organisation's delivery pipeline, secrets are the first thing we follow. This post walks through a lab we built around a small payments service: a repository with the mistakes we see most often, the read-only audit script we use to find them, an experiment showing why log masking is not a control, a detection for a stolen CI key that we tuned against generated cloud logs, and the fixed pipeline with the audit run again.

Where pipeline secrets actually leak

A CI/CD platform such as GitHub Actions stores secrets encrypted and hands them to a job as environment variables when the job starts. The platform is not usually the weak point. The weak points are what the job does with them, who controls the code the job runs, and how long the secret stays useful once it escapes.

The assumption that breaks is "the secret is stored safely, so it is safe". Storage is one step. A secret is exposed every time a job starts, to every process in that job, for as long as the credential is valid. For a static cloud access key, that can mean years.

OWASP lists this area across several of its Top 10 CI/CD Security Risks, notably poisoned pipeline execution (CICD-SEC-4), insufficient credential hygiene (CICD-SEC-6) and ungoverned use of third-party services (CICD-SEC-8). MITRE ATT&CK tracks the attacker side as Unsecured Credentials: Credentials In Files (T1552.001).

This is not theoretical. In March 2025 the widely used tj-actions/changed-files action was compromised (CVE-2025-30066). CISA's alert says the compromise exposed secrets such as access keys, GitHub tokens, npm tokens and private keys through workflow logs, and notes the secrets "may be obfuscated as a double-encoded base64 payload". Every repository that referenced the action by a tag ran the malicious version without changing a line.

The lab: one repository, five leak paths

We built payments-api, a small service with three commits, in a typical shape. The cloud keys in it are AWS's own documented example keys (AKIAIOSFODNN7EXAMPLE), so nothing here is a live credential.

  1. Commit 1 adds the service and a .env file with a database URL and an AWS key pair.
  2. Commit 2 removes .env and adds it to .gitignore. This is the usual "fix".
  3. Commit 3 adds the CI workflow and a deploy script.

This is the workflow, trimmed only of blank lines:

name: ci
on:
  pull_request_target:
    types: [opened, synchronize]
  push:
    branches: [main]
env:
  AWS_ACCESS_KEY_ID: ${{ secrets.AWS_ACCESS_KEY_ID }}
  AWS_SECRET_ACCESS_KEY: ${{ secrets.AWS_SECRET_ACCESS_KEY }}
  NPM_TOKEN: ${{ secrets.NPM_TOKEN }}
jobs:
  build:
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v4
        with:
          ref: ${{ github.event.pull_request.head.sha }}
      - uses: some-org/changed-files-lite@v2
      - name: Announce
        run: |
          echo "Building PR: ${{ github.event.pull_request.title }}"
      - name: Test
        run: make test
      - name: Deploy
        if: github.ref == 'refs/heads/main'
        run: ./scripts/deploy.sh

Each of the following is a separate root cause. Any one of them is enough to lose the key.

1. Git history keeps what the working tree drops

Deleting a file in a new commit does not remove it from the repository. Every clone, fork and CI checkout with full history still has commit 1. Anyone with read access to the repository has the key.

2. pull_request_target runs the contributor's code with your secrets

pull_request_target exists so that a workflow can label or comment on pull requests from forks. Unlike pull_request, it runs in the context of the base repository, with access to its secrets and a token that can write. That is safe only while the workflow never runs code from the pull request. The ref: line above checks out the pull request's head commit, and the next steps run make test on it. Whoever opens the pull request controls the Makefile, so they control a process that holds the AWS key. GitHub's secure-use guidance is blunt about this: workflows using this trigger "must not explicitly check out untrusted code". GitHub Security Lab calls this pattern a "pwn request".

We do not need to show the malicious pull request to make the point. The root cause is visible in two lines of YAML: the trigger and the ref.

3. Workflow-level env gives every step every secret

Secrets declared under the top-level env: are exported to every step, including third-party actions. some-org/changed-files-lite needs no cloud access, but it runs with the AWS key in its environment. If that action is ever compromised, it inherits the key.

4. Tags move; commit SHAs do not

@v2 is a git tag. Its owner, or anyone who takes over the owner's account, can point it at new code. That is exactly how the tj-actions compromise reached so many pipelines. Only a full 40-character commit SHA is immutable.

5. Untrusted text pasted into a shell script

${{ github.event.pull_request.title }} is expanded into the script before the shell runs it. A pull request title is attacker-controlled text, so quote characters in the title become shell syntax. This is script injection, and in a job with secrets in scope it is another path to them.

The deploy script adds a sixth problem, which we cover in the masking section below:

#!/usr/bin/env bash
set -euxo pipefail
AUTH=$(printf '{"id":"%s","secret":"%s"}' "$AWS_ACCESS_KEY_ID" "$AWS_SECRET_ACCESS_KEY" | base64 -w0)
curl -s -H "X-Deploy-Auth: $AUTH" https://deploy.example.com/release

How we audit a pipeline: our script and its output

In our engagements we read every workflow by hand, but we start with a small script so that nothing obvious is missed across dozens of repositories. ci_audit.py is read-only. It does two things.

History scan. It walks git log --all -p, looks only at added lines, and applies a short list of patterns: AWS access key IDs, AWS secret keys next to their variable name, credentials embedded in URLs, and a generic password=/token= rule. The generic rule is the noisy one, so it ignores values under 12 characters, values with low Shannon entropy (under 3.0 bits per character), and anything containing ${{, which is a reference to a stored secret rather than a secret. For each hit it checks whether the value is still in HEAD.

for rule, rx in RULES.items():
    for m in rx.finditer(line[1:]):
        value = m.group(m.lastindex or 0)
        if rule == "generic-secret" and (entropy(value) < 3.0 or "${{" in value):
            continue
        findings.append((commit, date, path, rule, value, value in head))

Workflow lint. It parses each file in .github/workflows/ and flags the patterns from the previous section: pull_request_target combined with a checkout of the pull request's head; secrets in top-level env; uses: references that are not a 40-character SHA (rated lower for GitHub's own actions/ organisation, higher for third parties); ${{ github.event.* }} inside run:; no top-level permissions: block; and, for any script the workflow runs, shell tracing (set -x) or base64 transformation near secret variables.

One parsing detail cost us time. In YAML 1.1, which PyYAML implements, the bare key on is read as the boolean True. A naive wf["on"] raises a KeyError on every real workflow file, so the script reads wf.get(True, wf.get("on")). Our test workflows also failed to parse at first because run: echo "Building PR: ..." contains a colon followed by a space, which YAML treats as a mapping. GitHub rejects the same file, so we used a block scalar (run: |).

This is the output against the lab repository:

muaaz@futaqsec: ~/ci-secrets-audit
$ python3 ci_audit.py payments-api
# history scan: payments-api
[!] f379ced 2026-09-02 .env credential-in-url Lab-******** (removed from HEAD, still in history)
[!] f379ced 2026-09-02 .env aws-access-key-id AKIA******** (removed from HEAD, still in history)
[!] f379ced 2026-09-02 .env aws-secret-key wJal******** (removed from HEAD, still in history)
# workflow: .github/workflows/ci.yml
CRITICAL build step 1: pull_request_target checks out untrusted PR code, with secrets in scope
HIGH secrets in workflow-level env, visible to every step and action: AWS_ACCESS_KEY_ID, AWS_SECRET_ACCESS_KEY, NPM_TOKEN
HIGH build step 3: untrusted event data interpolated into a shell script
HIGH scripts/deploy.sh: shell tracing (set -x) on a script that handles secrets
HIGH scripts/deploy.sh: secret is transformed (base64 etc.); the masked log value no longer matches
MEDIUM no top-level permissions: GITHUB_TOKEN gets the repository default
MEDIUM build step 2: some-org/changed-files-lite@v2 pinned to a movable tag, not a commit SHA
LOW build step 1: actions/checkout@v4 pinned to a movable tag, not a commit SHA
ci_audit.py against the vulnerable repository. Real output from our lab; values are redacted by the script.

The script is a starting point, not the audit. What it cannot see is where we spend most of the time: which secrets are stored at organisation level and shared by every repository, which self-hosted runners persist files between jobs, who can approve deployments to the production environment, and what each cloud key is actually allowed to do. A key that can only upload to one bucket is a nuisance when it leaks. A key with iam:* is the whole account.

Why log masking is not a control

CI platforms redact registered secrets from job logs, so teams often treat logs as safe. GitHub's own guidance says "automatic redaction is not guaranteed" because "there are multiple ways a secret value can be transformed". We wanted to see how much that matters in practice.

We did not have the hosted runner's masking code in the lab, so we modelled a generous version of it in Python: mask_model.py replaces each registered secret, and the base64 encoding of each secret, wherever it appears in a log line. Then we ran the real deploy script with tracing on (with curl stubbed to a local script that prints a status line) and piped its output through the model.

muaaz@futaqsec: ~/ci-secrets-audit
$ PATH=./stubbin:$PATH ./payments-api/scripts/deploy.sh 2>&1 | python3 mask_model.py
++ printf '{"id":"%s","secret":"%s"}' *** ***
++ base64 -w0
+ AUTH=eyJpZCI6IkFLSUFJT1NGT0ROTjdFWEFNUExFIiwic2VjcmV0Ijoid0phbHJYVXRuRkVNSS9LN01ERU5HL2JQeFJmaUNZRVhBTVBMRUtFWSJ9
+ curl -s -H 'X-Deploy-Auth: eyJpZCI6IkFLSUFJT1NGT0ROTjdFWEFNUExFIiwic2VjcmV0Ijoid0phbHJYVXRuRkVNSS9LN01ERU5HL2JQeFJmaUNZRVhBTVBMRUtFWSJ9' https://deploy.example.com/release
HTTP/1.1 202 Accepted
$ grep -o "X-Deploy-Auth: [A-Za-z0-9+/=]*" masked.log | cut -d' ' -f2 | base64 -d
{"id":"AKIAIOSFODNN7EXAMPLE","secret":"wJalrXUtnFEMI/K7MDENG/bPxRfiCYEXAMPLEKEY"}
[!] HIGH: both halves of the key pair recovered from a "masked" log
deploy.sh under set -x, piped through our masking model. Real output.

The first trace line shows masking working: the raw values became ***. Two lines later the same values sit in the log in full, base64-encoded as part of a larger string.

The reason is worth understanding. Base64 turns every 3 input bytes into 4 output characters. The encoding of a secret on its own only appears inside a longer encoded string if the secret starts at a byte offset that is a multiple of 3, and its last partial group happens to line up with the bytes that follow. Here the key starts at byte 7 (after {"id":"), so its encoded form shares no characters with the masked pattern. The secret key does start on a multiple of 3 (byte 39), but it is 40 bytes long, so its final encoded character is mixed with the quote that follows and the pattern still misses. In an earlier version of the script we joined the values as id:secret, and our model caught almost all of it by luck of alignment. Changing the format so that the key moved seven bytes along defeated it completely. A filter that depends on byte alignment is not a control.

The fixes are simple. Never use set -x in a script that handles secrets. Do not build derived credentials in shell. If you must create a derived value, register it with ::add-mask:: before anything prints it. Better still, use a credential that is worthless by the time anyone reads the log, which is the point of the remediation below.

Detecting a leaked CI key in use

Prevention will eventually fail somewhere, so we want to know when a CI identity is used by something other than CI. The real platform for this is AWS CloudTrail. We did not run it in the lab. Instead we generated CloudTrail-format events for one week (gen_logs.py) and tested the logic in Python on those events. The scenario:

  • Normal deploys: one run a day on runner-01 (egress IP 192.0.2.10), each making three calls with the AWS CLI.
  • A nightly clean-up job on a second runner, runner-02 (192.0.2.11), using the Go SDK.
  • A developer testing the CI key from a laptop (192.0.2.77), outside any run.
  • An attacker using the key from 192.0.2.200 with Boto3: identity check, list buckets, read two objects, then CreateAccessKey to stay in even after the original key is rotated.

Our first rule was the obvious one: alert when the CI key is used from any IP other than the runner's.

muaaz@futaqsec: ~/ci-secrets-audit
$ python3 detect_ci_key.py v1
v1: 34 CI-key events, 13 alerts
HIGH 2026-11-17T01:02:00Z 192.0.2.11 DeleteObjects aws-sdk-go-v2/1.30.3
HIGH 2026-11-18T01:02:00Z 192.0.2.11 DeleteObjects aws-sdk-go-v2/1.30.3
HIGH 2026-11-19T01:02:00Z 192.0.2.11 DeleteObjects aws-sdk-go-v2/1.30.3
HIGH 2026-11-19T14:12:05Z 192.0.2.77 GetCallerIdentity aws-cli/2.15.0
HIGH 2026-11-20T01:02:00Z 192.0.2.11 DeleteObjects aws-sdk-go-v2/1.30.3
HIGH 2026-11-21T01:02:00Z 192.0.2.11 DeleteObjects aws-sdk-go-v2/1.30.3
HIGH 2026-11-21T02:47:10Z 192.0.2.200 GetCallerIdentity Boto3/1.35.2
HIGH 2026-11-21T02:47:50Z 192.0.2.200 ListBuckets Boto3/1.35.2
HIGH 2026-11-21T02:48:30Z 192.0.2.200 GetObject Boto3/1.35.2
HIGH 2026-11-21T02:49:10Z 192.0.2.200 GetObject Boto3/1.35.2
CRITICAL 2026-11-21T02:49:50Z 192.0.2.200 CreateAccessKey Boto3/1.35.2
HIGH 2026-11-22T01:02:00Z 192.0.2.11 DeleteObjects aws-sdk-go-v2/1.30.3
HIGH 2026-11-23T01:02:00Z 192.0.2.11 DeleteObjects aws-sdk-go-v2/1.30.3
Rule v1 on one week of generated CloudTrail events. Real output.

Seven of the thirteen alerts were the nightly job. That is the kind of noise that gets a rule switched off within a week. Adding the second runner's IP to an allowlist would fix it, but then any process on that runner, at any time, is trusted. User agent was no help either: the nightly job and the attacker both used an SDK rather than the CLI.

The better signal was already in our hands. The CI system records every run: which runner, when it started, when it ended. Rule v2 accepts a CI-key call only if it comes from the egress IP of the runner that was executing a run at that moment, with two minutes of grace either side for clock skew and CloudTrail delivery timestamps.

def v2(e):
    t = ts(e["eventTime"])
    return not any(ts(r["start"]) - GRACE <= t <= ts(r["end"]) + GRACE
                   and runners[r["runner"]] == e["sourceIPAddress"] for r in runs)
muaaz@futaqsec: ~/ci-secrets-audit
$ python3 detect_ci_key.py v2
v2: 34 CI-key events, 6 alerts
HIGH 2026-11-19T14:12:05Z 192.0.2.77 GetCallerIdentity aws-cli/2.15.0
HIGH 2026-11-21T02:47:10Z 192.0.2.200 GetCallerIdentity Boto3/1.35.2
HIGH 2026-11-21T02:47:50Z 192.0.2.200 ListBuckets Boto3/1.35.2
HIGH 2026-11-21T02:48:30Z 192.0.2.200 GetObject Boto3/1.35.2
HIGH 2026-11-21T02:49:10Z 192.0.2.200 GetObject Boto3/1.35.2
CRITICAL 2026-11-21T02:49:50Z 192.0.2.200 CreateAccessKey Boto3/1.35.2
Rule v2 on the same events. Real output.

The nightly job is gone. The attacker's five calls remain, and CreateAccessKey is raised to critical because it means the incident outlives a key rotation. We left the developer's laptop call as an alert on purpose. It is not an attack, but a CI key on a laptop is a leak in its own right, and someone should ask why it is there.

Two limits to be honest about. The rule needs run history from the CI platform, which means joining two data sources in the SIEM. And with GitHub-hosted runners the egress IPs are shared cloud ranges, so the IP check is weaker and the run-window check does most of the work. Both limits largely disappear with the fix below, because an OIDC credential lasts minutes and is bound to one run.

Remediation: a pipeline with nothing worth stealing

We split the workflow in two and changed how the deploy job gets cloud access.

-on:
-  pull_request_target:
-    types: [opened, synchronize]
+on:
+  pull_request:
+permissions:
+  contents: read
-env:
-  AWS_ACCESS_KEY_ID: ${{ secrets.AWS_ACCESS_KEY_ID }}
-  AWS_SECRET_ACCESS_KEY: ${{ secrets.AWS_SECRET_ACCESS_KEY }}
-  NPM_TOKEN: ${{ secrets.NPM_TOKEN }}
 jobs:
-  build:
+  test:
     runs-on: ubuntu-latest
     steps:
-      - uses: actions/checkout@v4
-        with:
-          ref: ${{ github.event.pull_request.head.sha }}
-      - uses: some-org/changed-files-lite@v2
+      - uses: actions/checkout@11bd71901bbe5b1630ceea73d27597364c9af683 # v4.2.2
+        with:
+          persist-credentials: false
       - name: Announce
-        run: |
-          echo "Building PR: ${{ github.event.pull_request.title }}"
+        env:
+          PR_TITLE: ${{ github.event.pull_request.title }}
+        run: 'echo "Building PR: $PR_TITLE"'

The pull-request workflow (pr.yml) now uses pull_request, so code from forks runs with no secrets and a read-only token. The title reaches the shell as an environment variable, so it is data, not syntax. The unused third-party action is gone and the remaining one is pinned to a verified commit SHA.

Deployment moved to its own workflow (deploy.yml) that runs only on pushes to main, in a GitHub production environment that can require a reviewer. It holds no AWS key at all. The job requests an OIDC token (id-token: write) and exchanges it for a role session that lasts minutes, following GitHub's AWS OIDC guide:

    environment: production
    permissions:
      contents: read
      id-token: write
    steps:
      - uses: aws-actions/configure-aws-credentials@e3dd6a429d7300a6a4c196c26e071d42e0343502 # v4.0.2
        with:
          role-to-assume: arn:aws:iam::111122223333:role/payments-api-deploy
          aws-region: eu-west-2

The security of this rests on the role's trust policy. The sub condition must name the repository and the environment. A wildcard such as repo:example-org/* lets any repository in the organisation, including a test repository anyone can push to, assume the production role.

"Condition": {
  "StringEquals": {
    "token.actions.githubusercontent.com:aud": "sts.amazonaws.com",
    "token.actions.githubusercontent.com:sub": "repo:example-org/payments-api:environment:production"
  }
}

The deploy script lost set -x and the hand-built credential header, and now calls the AWS CLI with the role session. We ran the audit again:

muaaz@futaqsec: ~/ci-secrets-audit
$ python3 ci_audit.py payments-api-fixed
# history scan: payments-api-fixed
[!] f379ced 2026-09-02 .env credential-in-url Lab-******** (removed from HEAD, still in history)
[!] f379ced 2026-09-02 .env aws-access-key-id AKIA******** (removed from HEAD, still in history)
[!] f379ced 2026-09-02 .env aws-secret-key wJal******** (removed from HEAD, still in history)
# workflow: .github/workflows/deploy.yml
# workflow: .github/workflows/pr.yml
ci_audit.py after the fix. Real output.

Both workflows are clean. The history findings remain, and that is correct.

The order we follow when a pipeline secret has leaked:

  1. Revoke or rotate the secret at the provider. Do not wait for the investigation.
  2. Search the provider's logs for use of that credential from the date of the leaking commit or run, and look for new credentials it created (CreateAccessKey, new deploy keys, new OAuth apps).
  3. Remove the path that leaked it (the workflow fix above), then replace the static secret with a short-lived one where the provider supports it.
  4. Add the audit script, or a maintained scanner, as a required check so the same pattern cannot merge again.

Checklist

  • No long-lived cloud keys in CI. Use OIDC federation with a sub condition naming repository and environment.
  • No pull_request_target workflow checks out or runs pull-request code.
  • Secrets are declared on the step that needs them, never in top-level env.
  • Every third-party action is pinned to a full commit SHA, with the version in a comment.
  • Every workflow has permissions: set, defaulting to contents: read.
  • No ${{ github.event.* }} inside run:; pass it through env: instead.
  • No set -x in scripts that touch secrets; derived values are registered with ::add-mask::.
  • History has been scanned, and every secret found has been rotated, not just deleted.
  • An alert fires when a CI identity is used outside a CI run.

When we run a penetration test that includes the delivery pipeline, these are the questions we answer with evidence rather than settings screenshots. Pipelines are also where developer-targeted attacks land, as we described in our analysis of malware hidden in a coding assignment, and a compromised third-party script is the same problem one layer up, as in the Optimizely Web compromise.

Tooling and references

  • CI/CD
  • Secrets Management
  • DevSecOps
  • Supply Chain
  • Detection Engineering
MA

Written by

Muaaz Ahmad

Penetration Tester, FutaqSec

Keep reading

Penetration Testing11 min read

Three "Low" API Findings That Added Up to a Critical

Sequential IDs, a legacy API version and an unchecked field: each Low alone. Chained in our lab, they gave any trial user another tenant's data.

Muaaz Ahmad

Not sure where to start?

A 30-minute scoping call is enough to understand your environment and recommend the right first step. No obligation.

Book a free consultation