Catching insecure Terraform before apply with Checkov or Conftest
Scan the Terraform plan JSON, not just the .tf files, so values from tfvars are checked too. Checkov's built-in checks, a custom Checkov YAML policy, and a Conftest Rego policy that blocks SSH open to the internet, with tests.
Back in 2019 I wrote a small Go program to find vulnerable security groups in an AWS account. It worked, but it found problems after they were already live. If your infrastructure is in Terraform, there's a better place to catch them: between plan and apply, when nothing has been created yet.
In this blog we will look at two tools for that, Checkov and Conftest, and run both against the plan JSON. Then we write one custom policy in each: no SSH from 0.0.0.0/0. That rule is just a general example everyone understands. This is an advanced post, you should be comfortable with plan files and have seen testing Terraform with terraform test, check blocks and tflint, which covers the other half of checking Terraform before it runs.
Versions I used: Terraform 1.17.1, AWS provider 6.73.0, Checkov 3.4.5 (pip, in a virtualenv), Conftest 0.71.1 with OPA 1.21.1 (go install).
Scanning the plan instead of the .tf files
Both tools can scan .tf files directly. See, the problem here is that .tf files don't hold the final values. Variables come from tfvars files, from CI, from module defaults three levels down. I tested this on purpose. My example has an SSH rule whose CIDR comes from a variable.
variable "admin_cidr" {
description = "Who may SSH in. Set this to your office or VPN range."
type = string
default = "10.0.0.0/8"
}
resource "aws_vpc_security_group_ingress_rule" "ssh" {
security_group_id = aws_security_group.app.id
description = "SSH for admins"
cidr_ipv4 = var.admin_cidr
ip_protocol = "tcp"
from_port = 22
to_port = 22
}
And a prod.tfvars with one line, the kind of thing someone puts in "just for today".
admin_cidr = "0.0.0.0/0"
Scanning the directory with checkov -d . gave 5 failed checks and none of them was the SSH rule. It sees the default only. Scanning the plan made with -var-file=prod.tfvars gave 6, and the extra one was this.
Check: CKV_AWS_24: "Ensure no security groups allow ingress from 0.0.0.0:0 to port 22"
FAILED for resource: aws_vpc_security_group_ingress_rule.ssh
That difference is the reason for this whole post.
Making the plan JSON
terraform plan -var-file=prod.tfvars -out=tfplan
terraform show -json tfplan > tfplan.json
Every resource that will change is in .resource_changes, with the planned values in .change.after.
jq '.resource_changes[] | select(.address=="aws_vpc_security_group_ingress_rule.ssh") | .change.after' tfplan.json
One honest note. I don't have an AWS account on the machine where I wrote this, so I made the plan with fake keys and an override file that turns off every call the provider makes at startup (skip_credentials_validation, skip_requesting_account_id, skip_metadata_api_check) plus -refresh=false. That works for a config that only creates things. With a real account you just run the normal plan.
Be careful where tfplan.json goes. It has every value in clear text, sensitive ones too (they're only flagged in after_sensitive). Don't upload it as a public CI artifact.
Checkov
Install it in a virtualenv so it doesn't disturb anything else.
python3 -m venv .venv-checkov
.venv-checkov/bin/pip install checkov
.venv-checkov/bin/checkov -f tfplan.json --framework terraform_plan --compact --quiet
It comes with hundreds of checks, and on my example it found the SSH rule, an old style security group with inline 0.0.0.0/0 on all TCP ports (that one failed the port 22, 80 and 3389 checks), and two security groups not attached to anything.
About --framework terraform_plan: my first runs worked without it, but as soon as I added a custom policy directory, Checkov crashed with a Python traceback deep inside its JSON decoder (JSONArray() missing 1 required positional argument). I was on Python 3.15, which is very new, so I suspect that. Limiting it to the plan framework made the crash go away and it's what you want anyway.
A custom Checkov policy
Checkov already has the SSH check, so for the custom one I went a step further: anything open to the whole internet must be port 80 or 443. Checkov takes YAML policies for this.
metadata:
id: "CKV2_CUSTOM_1"
name: "Ingress open to the internet must be port 80 or 443 only"
category: "NETWORKING"
definition:
or:
- cond_type: attribute
resource_types:
- aws_vpc_security_group_ingress_rule
attribute: cidr_ipv4
operator: not_equals
value: "0.0.0.0/0"
- and:
- cond_type: attribute
resource_types:
- aws_vpc_security_group_ingress_rule
attribute: from_port
operator: within
value:
- 80
- 443
- cond_type: attribute
resource_types:
- aws_vpc_security_group_ingress_rule
attribute: to_port
operator: within
value:
- 80
- 443
Read it as "pass if the CIDR is not the world, or if both ports are 80 or 443". Save it in checkov_policies/ and point Checkov at the folder.
checkov -f tfplan.json --framework terraform_plan \
--external-checks-dir checkov_policies --check CKV2_CUSTOM_1 --compact
Check: CKV2_CUSTOM_1: "Ingress open to the internet must be port 80 or 443 only"
PASSED for resource: aws_vpc_security_group_ingress_rule.https
Check: CKV2_CUSTOM_1: "Ingress open to the internet must be port 80 or 443 only"
FAILED for resource: aws_vpc_security_group_ingress_rule.ssh
Skipping a check
Sometimes a finding is fine. My app security group gets attached to an instance in another stack, so "not attached to anything" is noise. Checkov reads a skip comment inside the resource.
resource "aws_security_group" "app" {
#checkov:skip=CKV2_AWS_5:attached to the instance in another stack
name = "app"
description = "shorty app server"
vpc_id = var.vpc_id
}
This caught me out actually. When scanning the plan JSON the comment was ignored, the check still failed. Of course, the JSON has no comments in it. You need to tell Checkov where the .tf files are so it can pick the comments up.
checkov -f tfplan.json --framework terraform_plan --repo-root-for-plan-enrichment .
After that the output said SKIPPED for resource: aws_security_group.app with my reason next to it. I like that the reason shows up in the output, it makes review easier.
Conftest
Conftest runs Open Policy Agent policies written in Rego against any JSON or YAML. It knows nothing about AWS, which is both the downside and the point: you write exactly the rule you mean. Install with Go.
go install github.com/open-policy-agent/conftest@latest
Here's the SSH rule. It looks at both the standalone rule resource and inline ingress blocks, ignores deletes, and treats protocol -1 (all traffic) as covering port 22. OPA 1.x uses the newer Rego syntax with if and contains, so older examples you find online may not parse.
package main
import rego.v1
changing(rc) if {
some action in rc.change.actions
action in {"create", "update"}
}
world(cidr) if cidr in {"0.0.0.0/0", "::/0"}
covers_ssh(protocol, _, _) if protocol in {"-1", "all"}
covers_ssh(protocol, from, to) if {
protocol in {"tcp", "6"}
from <= 22
to >= 22
}
deny contains msg if {
some rc in input.resource_changes
rc.type == "aws_vpc_security_group_ingress_rule"
changing(rc)
r := rc.change.after
some cidr in [object.get(r, "cidr_ipv4", null), object.get(r, "cidr_ipv6", null)]
world(cidr)
covers_ssh(r.ip_protocol, object.get(r, "from_port", 0), object.get(r, "to_port", 65535))
msg := sprintf("%s opens SSH (port 22) to %s", [rc.address, cidr])
}
deny contains msg if {
some rc in input.resource_changes
rc.type == "aws_security_group"
changing(rc)
some rule in rc.change.after.ingress
some cidr in array.concat(rule.cidr_blocks, rule.ipv6_cidr_blocks)
world(cidr)
covers_ssh(rule.protocol, rule.from_port, rule.to_port)
msg := sprintf("%s has an inline rule opening SSH (port 22) to %s", [rc.address, cidr])
}
conftest test tfplan.json -p policy
FAIL - tfplan.json - main - aws_security_group.legacy has an inline rule opening SSH (port 22) to 0.0.0.0/0
FAIL - tfplan.json - main - aws_vpc_security_group_ingress_rule.ssh opens SSH (port 22) to 0.0.0.0/0
2 tests, 0 passed, 0 warnings, 2 failures, 0 exceptions
Exit code is 1, so CI fails. Without prod.tfvars only the legacy group was left.
A policy is code, so it gets tests. Rego tests sit next to the policy, in policy/ssh_test.rego.
package main
import rego.v1
rule(after) := {"resource_changes": [{
"address": "aws_vpc_security_group_ingress_rule.x",
"type": "aws_vpc_security_group_ingress_rule",
"change": {"actions": ["create"], "after": after},
}]}
test_ssh_from_world_denied if {
count(deny) == 1 with input as rule({"cidr_ipv4": "0.0.0.0/0", "ip_protocol": "tcp", "from_port": 22, "to_port": 22})
}
test_ssh_from_vpn_allowed if {
count(deny) == 0 with input as rule({"cidr_ipv4": "10.8.0.0/16", "ip_protocol": "tcp", "from_port": 22, "to_port": 22})
}
test_all_traffic_ipv6_denied if {
count(deny) == 1 with input as rule({"cidr_ipv6": "::/0", "ip_protocol": "-1"})
}
conftest verify -p policy
My file has five tests (also HTTPS from the world and a delete), all five passed.
One gap to know about. If a CIDR is only known after apply, for example it comes from another resource being created in the same plan, it isn't in .change.after at all, it's flagged in after_unknown. Neither tool can judge a value that doesn't exist yet.
Picking one
Honestly, both, they're cheap. Checkov gives you a few hundred checks for free on day one. Conftest is where your own rules live, the ones that are about how your team does things. If I had to pick one for a small setup I'd start with Checkov and add Conftest the first time I needed a rule Checkov can't express in YAML.
The script I ended up with runs both and fails if either fails.
#!/bin/bash
set -uo pipefail
cd "$(dirname "$0")"
terraform plan -input=false -out=tfplan "$@" >/dev/null || exit 1
terraform show -json tfplan > tfplan.json
rc=0
conftest test tfplan.json -p policy || rc=1
checkov -f tfplan.json --framework terraform_plan \
--external-checks-dir checkov_policies --compact --quiet \
--repo-root-for-plan-enrichment . || rc=1
exit $rc
Run it as ./check.sh -var-file=prod.tfvars in CI right after plan, and only allow apply when it exits 0. If you lock down your workflows as in securing GitHub Actions workflows, give this job read only permissions, it doesn't need anything more.
That's it. Start by fixing what the built-in checks find, then add one custom rule for the mistake your team makes most.