# AWS CodeBuild - Untrusted PR Webhook Bypass (CodeBreach-style)

{{#include ../../../../banners/hacktricks-training.md}}

Hierdie aanvalsvector verskyn wanneer 'n **publieke PR-workflow** gekoppel is aan 'n **geprivilegieerde CodeBuild-projek** met swak webhook-kontroles.

As 'n eksterne aanvaller CodeBuild kan laat uitvoer op hul pull request, kan hulle gewoonlik **willekeurige kode-uitvoering binne die build** kry (build-skripte, dependency hooks, toets-skripte, ens.), en dan skuif na geheime, IAM-credentials, of source-provider credentials.

## Why this is dangerous

CodeBuild webhook-filters word geëvalueer met regex-patrone (vir nie-`EVENT` filters). In die `ACTOR_ACCOUNT_ID` filter beteken dit 'n swak patroon kan meer gebruikers pas as beoog.
As onbetroubare PRs in 'n projek gebou word wat geprivilegieerde AWS role-permissies of GitHub-credentials het, kan dit 'n volledige supply-chain kompromie word.

Wiz het 'n praktiese ketting gewys waar:

1. 'n webhook actor allowlist 'n **unanchored regex** gebruik het.
2. 'n aanvaller 'n GitHub ID geregistreer het wat as 'n **superstring** van 'n vertroude ID gematch het.
3. 'n kwaadwillige PR CodeBuild ge-trigger het.
4. Build-kode-uitvoering gebruik is om geheue te dump en source-provider credentials/tokens te herstel.

## Misconfigurations that allow external PR code execution

Die volgende is hoë-risiko foute en hoe aanvallers elkeen misbruik:

1. **`EVENT` filters allow untrusted triggers**
- Algemene riskante events: `PULL_REQUEST_CREATED`, `PULL_REQUEST_UPDATED`, `PULL_REQUEST_REOPENED`.
- Ander events wat gevaarlik kan raak as dit aan geprivilegieerde builds gekoppel is: `PUSH`, `PULL_REQUEST_CLOSED`, `PULL_REQUEST_MERGED`, `RELEASED`, `PRERELEASED`, `WORKFLOW_JOB_QUEUED`.
- Sleg: `EVENT="PUSH, PULL_REQUEST_CREATED, PULL_REQUEST_UPDATED"` in 'n geprivilegieerde projek.
- Beter: gebruik PR comment approval en minimaliseer trigger-events vir geprivilegieerde projekte.
- Misbruik: aanvaller open/update PR of push na 'n branch wat hulle beheer, en hul kode voer uit in CodeBuild.

2. **`ACTOR_ACCOUNT_ID` regex is weak**
- Sleg: ongeankerde patrone soos `123456|7890123`.
- Beter: exact-match anchoring `^(123456|7890123)$`.
- Misbruik: regex oor-pass laat ongemagtigde GitHub IDs deur allowlists glip.

3. **Other regex filters are weak or missing**
- `HEAD_REF`
  - Sleg: `refs/heads/.*`
  - Beter: `^refs/heads/main$` (of 'n eksplisiete vertroude lys)
- `BASE_REF`
  - Sleg: `.*`
  - Beter: `^refs/heads/main$`
- `FILE_PATH`
  - Sleg: geen padbeperkings
  - Beter: sluit riskante files uit soos `^buildspec\\.yml$`, `^\\.github/workflows/.*`, `(^|/)package(-lock)?\\.json$`
- `COMMIT_MESSAGE`
  - Sleg: vertrouensmerk met lose match soos `trusted`
  - Beter: gebruik nie commit message as 'n trust boundary vir PR-uitvoering nie
- `REPOSITORY_NAME` / `ORGANIZATION_NAME`
  - Sleg: `.*` in org/globale webhooks
  - Beter: slegs eksakte repo/org matches
- `WORKFLOW_NAME`
  - Sleg: `.*`
  - Beter: eksakte workflow-name matches slegs (of vermy dit as trust-kontrole)
- Misbruik: aanvaller vervaardig ref/path/message/repo konteks om permissive regex te bevredig en builds te trigger.

4. **`excludeMatchedPattern` is misused**
- Om hierdie vlag verkeerd te stel kan die bedoelde logika omkeer.
- Sleg: `FILE_PATH '^buildspec\\.yml$'` met `excludeMatchedPattern=false` wanneer die bedoeling was om buildspec-wysigings te blokkeer.
- Beter: dieselfde patroon met `excludeMatchedPattern=true` om builds wat `buildspec.yml` raak te weier.
- Misbruik: verdedigers dink hulle weier riskante events/paaie/actors, maar laat eintlik toe.

5. **Multiple `filterGroups` create accidental bypasses**
- CodeBuild evalueer groepe as OR (een slaag-groep is genoeg).
- Sleg: een streng groep + een permissiewe fallback-groep (bv. net `EVENT=PULL_REQUEST_UPDATED`).
- Beter: verwyder fallback-groepe wat nie actor/ref/path-beperkings afdwing nie.
- Misbruik: aanvaller hoef slegs die swakste groep te bevredig.

6. **Comment approval gate disabled or too permissive**
- `pullRequestBuildPolicy.requiresCommentApproval=DISABLED` is die minste veilig.
- Te breë approver-rolle verminder kontrole.
- Sleg: `requiresCommentApproval=DISABLED`.
- Beter: `ALL_PULL_REQUESTS` of `FORK_PULL_REQUESTS` met minimale approver-rolle.
- Misbruik: fork/drive-by PRs hardloop outomaties sonder vertroude maintainer-goedkeuring.

7. **No restrictive branch/path strategy for PR builds**
- Gebrek aan verdediging-in-diepte met `HEAD_REF` + `BASE_REF` + `FILE_PATH`.
- Sleg: net `EVENT` + `ACTOR_ACCOUNT_ID`, geen ref/path-beperkings nie.
- Beter: kombineer eksakte `ACTOR_ACCOUNT_ID` + `BASE_REF` + `HEAD_REF` + `FILE_PATH` beperkings.
- Misbruik: aanvaller wysig build-insette (buildspec/CI/dependencies) en kry arbitraire opdrag-uitvoering.

8. **Public visibility + status URL exposure**
- Openbare build-/check-URL's verbeter aanvaller-recon en iteratiewe toetsing.
- Sleg: `projectVisibility=PUBLIC_READ` met sensitiewe logs/config in openbare builds.
- Beter: hou projekte privaat tensy daar 'n sterk besigheidsbehoefte is, en saniteer logs/artifacts.
- Misbruik: aanvaller ontdek projekpatrone/gedrag en fynslif dan payloads en bypass-pogings.

## Token leakage from memory

Wiz se uiteensetting verduidelik dat source-provider credentials in die build runtime-konteks teenwoordig is en gesteel kan word na 'n build-kompromie (byvoorbeeld via memory dumping), wat repository-oorsig moontlik maak as scopes wyd is.

AWS het hardening bekendgestel na die openbaarmaking, maar die kernlesing bly: **never execute untrusted PR code in privileged build contexts** en aanvaar dat aanvaller-gekontroleerde build-kode poog om credentials te steel.

Vir bykomende credential theft techniques in CodeBuild, kyk ook:

{{#ref}}
aws-codebuild-token-leakage.md
{{#endref}}

## Finding CodeBuild URLs in GitHub PRs

As CodeBuild commit status terugrapporteer aan GitHub, verskyn die CodeBuild build-URL gewoonlik in:

1. **PR page** -> **Checks** tab (of die statusreël in Conversation/Commits).
2. **Commit page** -> status/checks afdeling -> **Details** skakel.
3. **PR commits list** -> klik die check context geheg aan 'n commit.

Vir openbare projekte kan hierdie skakel build-metadata/configuratie aan ongesertifiseerde gebruikers blootstel.

<details>
<summary>Skrip: detect CodeBuild-URLs in 'n PR en toets of dit openbaar lyk</summary>
```bash
#!/usr/bin/env bash
set -euo pipefail

# Usage:
#   ./check_pr_codebuild_urls.sh <owner> <repo> <pr_number>
#
# Requirements: gh, jq, curl

OWNER="${1:?owner}"
REPO="${2:?repo}"
PR="${3:?pr_number}"

for bin in gh jq curl timeout; do
command -v "$bin" >/dev/null || { echo "[!] Missing dependency: $bin" >&2; exit 1; }
done

tmp_commits="$(mktemp)"
tmp_urls="$(mktemp)"
trap 'rm -f "$tmp_commits" "$tmp_urls"' EXIT

gh_api() {
timeout 20s gh api "$@" 2>/dev/null || true
}

# Get all commit SHAs in the PR (bounded call to avoid hangs)
gh_api "repos/${OWNER}/${REPO}/pulls/${PR}/commits" --paginate --jq '.[].sha' > "$tmp_commits"
if [ ! -s "$tmp_commits" ]; then
echo "[!] No commits found (or API call timed out/failed)." >&2
exit 1
fi

echo "[*] PR commits:"
cat "$tmp_commits"
echo

echo "[*] Searching commit statuses/check-runs for CodeBuild URLs..."

while IFS= read -r sha; do
[ -z "$sha" ] && continue

# Classic commit statuses (target_url)
gh_api "repos/${OWNER}/${REPO}/commits/${sha}/status" \
--jq '.statuses[]? | .target_url // empty' 2>/dev/null || true

# GitHub Checks API (details_url)
gh_api "repos/${OWNER}/${REPO}/commits/${sha}/check-runs" \
--jq '.check_runs[]? | .details_url // empty' 2>/dev/null || true
done < "$tmp_commits" | sort -u > "$tmp_urls"

grep -Ei 'codebuild|codebuild\.aws\.amazon\.com|console\.aws\.amazon\.com/.*/codebuild' "$tmp_urls" || true

echo
echo "[*] Public-access heuristic:"
echo "    - If URL redirects to signin.aws.amazon.com -> likely not public"
echo "    - If URL is directly reachable (HTTP 200) without auth redirect -> potentially public"
echo

cb_urls="$(grep -Ei 'codebuild|codebuild\.aws\.amazon\.com|console\.aws\.amazon\.com/.*/codebuild' "$tmp_urls" || true)"
if [ -z "$cb_urls" ]; then
echo "[*] No CodeBuild URLs found in PR statuses/check-runs."
exit 0
fi

while IFS= read -r url; do
[ -z "$url" ] && continue
final_url="$(timeout 20s curl -4 -sS -L --connect-timeout 5 --max-time 20 -o /dev/null -w '%{url_effective}' "$url" || true)"
code="$(timeout 20s curl -4 -sS -L --connect-timeout 5 --max-time 20 -o /dev/null -w '%{http_code}' "$url" || true)"

if echo "$final_url" | grep -qi 'signin\.aws\.amazon\.com'; then
verdict="NOT_PUBLIC_OR_AUTH_REQUIRED"
elif [ "$code" = "200" ]; then
verdict="POTENTIALLY_PUBLIC"
else
verdict="UNKNOWN_CHECK_MANUALLY"
fi

printf '%s\t%s\t%s\n' "$verdict" "$code" "$url"
done <<< "$cb_urls"
```
Getoets en werk met:
```bash
bash /tmp/check_pr_codebuild_urls.sh carlospolop codebuild-codebreach-ctf-lab 1
```
</details>

## Vinnige ouditkontrolelys
```bash
# Enumerate projects
aws codebuild list-projects

# Inspect source/webhook configuration
aws codebuild batch-get-projects --names <project-name>

# Inspect global source credentials configured in account
aws codebuild list-source-credentials
```
Kontroleer elke projek vir:

- `webhook.filterGroups` containing PR events.
- `ACTOR_ACCOUNT_ID` patterns that are not anchored with `^...$`.
- `pullRequestBuildPolicy.requiresCommentApproval` equal to `DISABLED`.
- Ontbrekende tak/pad-beperkings.
- Hoë-privilegie `serviceRole`.
- Risikovolle scope en hergebruik van source credentials.

## Verstevigingsriglyne

1. Vereis kommentaargoedkeuring vir PR-builds (`ALL_PULL_REQUESTS` of `FORK_PULL_REQUESTS`).
2. As jy actor allowlists gebruik, anker regexes en hou dit presies.
3. Voeg `FILE_PATH`-beperkings by om onbetroubare wysigings aan `buildspec.yml` en CI-skripte te voorkom.
4. Skil vertroude release-builds van onbetroubare PR-builds in verskillende projekte/rolle.
5. Gebruik fynkorrelige, minst-bevoorregte source-provider tokens (verkies toegewyde lae-bevoegdheid identiteite).
6. Oudit voortdurend webhook-filters en die gebruik van source credentials.

## References

- [Wiz: CodeBreach - AWS CodeBuild ACTOR_ID regex bypass and token theft](https://www.wiz.io/blog/wiz-research-codebreach-vulnerability-aws-codebuild)
- [AWS CodeBuild API - WebhookFilter](https://docs.aws.amazon.com/codebuild/latest/APIReference/API_WebhookFilter.html)
- [AWS CLI - codebuild create-webhook](https://docs.aws.amazon.com/cli/latest/reference/codebuild/create-webhook.html)
- [AWS CodeBuild User Guide - Best practices for webhooks](https://docs.aws.amazon.com/codebuild/latest/userguide/webhooks.html)

{{#include ../../../../banners/hacktricks-training.md}}
