Terraform Security
Last updated
Last updated
Learn & practice AWS Hacking:HackTricks Training AWS Red Team Expert (ARTE) Learn & practice GCP Hacking: HackTricks Training GCP Red Team Expert (GRTE)
HashiCorp Terraform is an infrastructure as code tool that lets you define both cloud and on-prem resources in human-readable configuration files that you can version, reuse, and share. You can then use a consistent workflow to provision and manage all of your infrastructure throughout its lifecycle. Terraform can manage low-level components like compute, storage, and networking resources, as well as high-level components like DNS entries and SaaS features.
Terraform creates and manages resources on cloud platforms and other services through their application programming interfaces (APIs). Providers enable Terraform to work with virtually any platform or service with an accessible API.
HashiCorp and the Terraform community have already written more than 1700 providers to manage thousands of different types of resources and services, and this number continues to grow. You can find all publicly available providers on the Terraform Registry, including Amazon Web Services (AWS), Azure, Google Cloud Platform (GCP), Kubernetes, Helm, GitHub, Splunk, DataDog, and many more.
The core Terraform workflow consists of three stages:
Write: You define resources, which may be across multiple cloud providers and services. For example, you might create a configuration to deploy an application on virtual machines in a Virtual Private Cloud (VPC) network with security groups and a load balancer.
Plan: Terraform creates an execution plan describing the infrastructure it will create, update, or destroy based on the existing infrastructure and your configuration.
Apply: On approval, Terraform performs the proposed operations in the correct order, respecting any resource dependencies. For example, if you update the properties of a VPC and change the number of virtual machines in that VPC, Terraform will recreate the VPC before scaling the virtual machines.
Just install terraform in your computer.
Here you have a guide and here you have the best way to download terraform.
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.
However, terraform is a very sensitive component to compromise because it will have privileged access to different locations so it can work properly.
The main way for an attacker to be able to compromise the system where terraform is running is to compromise the repository that stores terraform configurations, because at some point they are going to be interpreted.
Actually, there are solutions out there that execute terraform plan/apply automatically after a PR is created, such as Atlantis:
Atlantis SecurityIf you are able to compromise a terraform file there are different ways you can perform RCE when someone executed terraform plan
or terraform apply
.
Terraform plan is the most used command in terraform and developers/solutions using terraform call it all the time, so the easiest way to get RCE is to make sure you poison a terraform config file that will execute arbitrary commands in a terraform plan
.
Using an external provider
Terraform offers the external
provider which provides a way to interface between Terraform and external programs. You can use the external
data source to run arbitrary code during a plan
.
Injecting in a terraform config file something like the following will execute a rev shell when executing terraform plan
:
Using a custom provider
An attacker could send a custom provider to the Terraform Registry and then add it to the Terraform code in a feature branch (example from here):
The provider is downloaded in the init
and will run the malicious code when plan
is executed
You can find an example in https://github.com/rung/terraform-provider-cmdexec
Using an external reference
Both mentioned options are useful but not very stealthy (the second is more stealthy but more complex than the first one). You can perform this attack even in a stealthier way, by following this suggestions:
Instead of adding the rev shell directly into the terraform file, you can load an external resource that contains the rev shell:
You can find the rev shell code in https://github.com/carlospolop/terraform_external_module_rev_shell/tree/main/modules
In the external resource, use the ref feature to hide the terraform rev shell code in a branch inside of the repo, something like: git@github.com:carlospolop/terraform_external_module_rev_shell//modules?ref=b401d2b
Terraform apply will be executed to apply all the changes, you can also abuse it to obtain RCE injecting a malicious Terraform file with local-exec.
You just need to make sure some payload like the following ones ends in the main.tf
file:
Follow the suggestions from the previous technique the perform this attack in a stealthier way using external references.
You can have secret values used by terraform dumped running terraform apply
by adding to the terraform file something like:
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:
There are 2 ways to destroy resources:
Insert a resource with a random name into the state file pointing to the real resource to destroy
Because terraform will see that the resource shouldn't exit, it'll destroy it (following the real resource ID indicated). Example from the previous page:
Modify the resource to delete in a way that it's not possible to update (so it'll be deleted a recreated)
For an EC2 instance, modifying the type of the instance is enough to make terraform delete a recreate it.
It's also possible to create a custom provider and just replace one of the providers in the terraform state file for the malicious one or add an empty resource with the malicious provider. Example from the original research:
In case you encounter a situation where hashicorp/external
was blacklisted, you can re-implement the external
provider by doing the following. Note: We use a fork of external provider published by https://registry.terraform.io/providers/nazarewk/external/latest. You can publish your own fork or re-implementation as well.
Then you can use external
as per normal.
Snyk offers a comprehensive Infrastructure as Code (IaC) scanning solution that detects vulnerabilities and misconfigurations in Terraform, CloudFormation, Kubernetes, and other IaC formats.
Features:
Real-time scanning for security vulnerabilities and compliance issues.
Integration with version control systems (GitHub, GitLab, Bitbucket).
Automated fix pull requests.
Detailed remediation advice.
Sign Up: Create an account on Snyk.
Checkov is a static code analysis tool for infrastructure as code (IaC) and also a software composition analysis (SCA) tool for images and open source packages.
It scans cloud infrastructure provisioned using Terraform, Terraform plan, Cloudformation, AWS SAM, Kubernetes, Helm charts, Kustomize, Dockerfile, Serverless, Bicep, OpenAPI, ARM Templates, or OpenTofu and detects security and compliance misconfigurations using graph-based scanning.
It performs Software Composition Analysis (SCA) scanning which is a scan of open source packages and images for Common Vulnerabilities and Exposures (CVEs).
From the docs: terraform-compliance
is a lightweight, security and compliance focused test framework against terraform to enable negative testing capability for your infrastructure-as-code.
compliance: Ensure the implemented code is following security standards, your own custom standards
behaviour driven development: We have BDD for nearly everything, why not for IaC ?
portable: just install it from pip
or run it via docker
. See Installation
pre-deploy: it validates your code before it is deployed
easy to integrate: it can run in your pipeline (or in git hooks) to ensure all deployments are validated.
segregation of duty: you can keep your tests in a different repository where a separate team is responsible.
Unfortunately if the code is using some providers you don't have access to you won't be able to perform the terraform plan
and run this tool.
From the docs: tfsec uses static analysis of your terraform code to spot potential misconfigurations.
☁️ Checks for misconfigurations across all major (and some minor) cloud providers
⛔ Hundreds of built-in rules
🪆 Scans modules (local and remote)
➕ Evaluates HCL expressions as well as literal values
↪️ Evaluates Terraform functions e.g. concat()
🔗 Evaluates relationships between Terraform resources
🧰 Compatible with the Terraform CDK
🙅 Applies (and embellishes) user-defined Rego policies
📃 Supports multiple output formats: lovely (default), JSON, SARIF, CSV, CheckStyle, JUnit, text, Gif.
🛠️ Configurable (via CLI flags and/or config file)
⚡ Very fast, capable of quickly scanning huge repositories
Find security vulnerabilities, compliance issues, and infrastructure misconfigurations early in the development cycle of your infrastructure-as-code with KICS by Checkmarx.
KICS stands for Keeping Infrastructure as Code Secure, it is open source and is a must-have for any cloud native project.
From the docs: Terrascan is a static code analyzer for Infrastructure as Code. Terrascan allows you to:
Seamlessly scan infrastructure as code for misconfigurations.
Monitor provisioned cloud infrastructure for configuration changes that introduce posture drift, and enables reverting to a secure posture.
Detect security vulnerabilities and compliance violations.
Mitigate risks before provisioning cloud native infrastructure.
Offers flexibility to run locally or integrate with your CI\CD.
Learn & practice AWS Hacking:HackTricks Training AWS Red Team Expert (ARTE) Learn & practice GCP Hacking: HackTricks Training GCP Red Team Expert (GRTE)