Lesson 10 · 45 minutes
Scan an infrastructure plan and stop the pipeline on a finding
- Explain infrastructure as code and where a security check fits in a pipeline
- Read a plan file and write rules for it as data
- Fail a pipeline with an exit code and add rules of your own
The lab folder as it stands after this lesson. Unzip it in ~/krlab.
More
The zip holds every file that the course has printed up to here. To start this lesson with the files of the earlier lessons only, take the zip of the lesson before. Type the code yourself first: you learn more.
Scenario
You found an open database port, a public bucket and a role with too many rights after they were live. Your lead wants the next ones stopped earlier: "The platform team does not click in the console. They write the infrastructure as code, and a pipeline applies it. Put a check into that pipeline that reads what is about to be created, and stops it when it is one of the mistakes of this month." A mistake that never reaches the account needs no incident.
Recall
Lesson 6: which four things must be true before the internet reaches a port of a machine?
The machine has a public address, its subnet has a route to an internet gateway, the network ACL allows the request and the answer, and a security group allows the request.
Lesson 8: what does the setting HttpTokens with the value required do?
The metadata service of the machine then accepts only IMDSv2: every GET needs a session token from a PUT. A plain GET, which is all that most forged requests can send, gets the status 401.
The idea
Infrastructure as code (IaC) means that the resources of an account are described in text files, kept in a repository and applied by a program. Terraform is the most used tool of this kind, and AWS has its own, CloudFormation. The gain for security is large: every change is a commit that someone can review, and a program can read the change before it happens.
Terraform works in two steps. plan compares the files with the account and writes a plan: the list of resources that it will create, change or delete. apply carries the plan out. Between the two steps is the place for a check.
- Commit → Plan: the tool lists what will change
- Plan → Scan: rules read the plan as JSON
- Scan → Apply: exit code 0, the change goes on
- Scan → Stop: exit code 1, a person must look
Terraform can print a plan as JSON (terraform show -json). This lesson uses that shape. The parts that a scanner needs are these.
| In the plan | Meaning |
|---|---|
resource_changes | A list with one entry for each resource |
address, type | The name of the resource in the code, such as aws_db_instance.reports, and its kind |
change.actions | What will happen: ["create"], ["update"], ["delete"], ["no-op"], or two actions for a replacement |
change.after | The settings of the resource after the change. null when it is deleted. |
You do not have Terraform, and you do not need it: the plan of this lesson is made by a small program in the same shape, with the attribute names of the Terraform provider for AWS (for example publicly_accessible for a database). A real plan has more parts and many more attributes. Values that are known only after the apply are missing from after: a real scanner must treat "unknown" with care.
A rule says which resource type it reads and which values are wrong. Rules as data, in a file that people can review, are what you built in "Security operations basics", lesson 3, for log events. The idea is the same here: the data is a plan and not a log.
The open tools that do this at work have hundreds of ready rules: Checkov, Trivy (which took over the rules of tfsec) and KICS are three. You do not need them for this lesson. After it, you will know what they do when they print a finding.
Worked example
1. Make the plan
gen_plan.py writes plan.json. Open the block, save the file and run it.
The finished file: gen_plan.py
gen_plan.py
"""gen_plan.py: write a plan file in the JSON shape that "terraform show -json" prints. Made by hand, not by Terraform.
python3 gen_plan.py [seed] [file] default: seed 1, file plan.json
"""
import hashlib
import json
import random
import sys
SEED = int(sys.argv[1]) if len(sys.argv) > 1 else 1
OUT = sys.argv[2] if len(sys.argv) > 2 else "plan.json"
r = random.Random(200 + SEED) # only random() is used
ANY = "0.0.0.0/0"
changes = []
def pick(items):
return items[int(r.random() * len(items))]
def add(kind, name, after, action="create"):
before = None if action == "create" else {}
changes.append({"address": f"{kind}.{name}", "mode": "managed", "type": kind, "name": name,
"provider_name": "registry.terraform.io/hashicorp/aws",
"change": {"actions": [action] if action != "replace" else ["delete", "create"], "before": before,
"after": None if action == "delete" else after, "after_unknown": {"id": True}}})
def ingress(port, cidr, to=None):
return {"from_port": port, "to_port": to or port, "protocol": "tcp", "cidr_blocks": [cidr], "description": ""}
def block(name, value):
return {"bucket": name, "block_public_acls": value, "block_public_policy": value, "ignore_public_acls": value,
"restrict_public_buckets": value}
OFFICE = "203.0.113.0/24"
add("aws_security_group", "web", {"name": "web", "ingress": [ingress(443, ANY)]})
add("aws_security_group", "admin", {"name": "admin", "ingress": [ingress(22, ANY), ingress(8443, OFFICE)]})
add("aws_security_group", "db", {"name": "db", "ingress": [ingress(5432, "10.20.11.0/24")]})
add("aws_security_group", "old_admin", {"name": "old-admin", "ingress": [ingress(3389, ANY)]}, "delete")
add("aws_security_group", "range", {"name": "range", "ingress": [ingress(0, ANY, 65535)]}, "update")
add("aws_db_instance", "orders", {"identifier": "orders", "engine": "postgres", "publicly_accessible": False, "storage_encrypted": True})
add("aws_db_instance", "reports", {"identifier": "reports", "engine": "postgres", "publicly_accessible": True, "storage_encrypted": False})
add("aws_instance", "web", {"instance_type": "t3.small", "metadata_options": [{"http_endpoint": "enabled", "http_tokens": "required"}]})
add("aws_instance", "worker", {"instance_type": "t3.small", "metadata_options": [{"http_endpoint": "enabled", "http_tokens": "optional"}]})
add("aws_s3_bucket", "exports", {"bucket": "larkfield-exports"})
add("aws_s3_bucket_public_access_block", "exports", block("larkfield-exports", False))
add("aws_s3_bucket", "invoices", {"bucket": "larkfield-invoices"})
add("aws_s3_bucket_public_access_block", "invoices", block("larkfield-invoices", True))
add("aws_ebs_volume", "scratch", {"availability_zone": "eu-west-1a", "size": 200, "encrypted": False})
add("aws_iam_policy", "exporter", {"name": "exporter", "policy": json.dumps(
{"Version": "2012-10-17", "Statement": [{"Effect": "Allow", "Action": "s3:*", "Resource": "*"}]})})
add("aws_iam_policy", "reader", {"name": "reader", "policy": json.dumps(
{"Version": "2012-10-17", "Statement": [{"Effect": "Allow", "Action": "s3:GetObject", "Resource": "arn:aws:s3:::larkfield-exports/*"}]})})
for n in range(6 + int(r.random() * 6)): # more resources, some good and some not
kind = pick(["aws_ebs_volume", "aws_instance", "aws_security_group", "aws_db_instance"])
bad = r.random() < 0.4
after = {"aws_ebs_volume": {"availability_zone": "eu-west-1a", "size": 50, "encrypted": not bad},
"aws_instance": {"instance_type": "t3.micro", "metadata_options": [{"http_endpoint": "enabled",
"http_tokens": "optional" if bad else "required"}]},
"aws_security_group": {"name": f"extra-{n}", "ingress": [ingress(pick([22, 3306, 5432]) if bad else 443, ANY if bad else OFFICE)]},
"aws_db_instance": {"identifier": f"extra-{n}", "engine": "mysql", "publicly_accessible": bad, "storage_encrypted": True}}[kind]
add(kind, f"extra_{n}", after, pick(["create", "create", "update", "no-op"]))
plan = {"format_version": "1.2", "terraform_version": "1.9.8", "resource_changes": changes}
text = json.dumps(plan, indent=1) + "\n"
with open(OUT, "w") as out:
out.write(text)
print(f"{OUT}: {len(changes)} resource changes, sha256 {hashlib.sha256(text.encode()).hexdigest()[:12]}")python3 gen_plan.py
python3 -c "
import json
plan = json.load(open('plan.json'))
rc = next(x for x in plan['resource_changes'] if x['address'] == 'aws_security_group.admin')
print(json.dumps({'address': rc['address'], 'type': rc['type'], 'change': rc['change']}, indent=1))" | head -n 22plan.json: 22 resource changes, sha256 762041184246
{
"address": "aws_security_group.admin",
"type": "aws_security_group",
"change": {
"actions": [
"create"
],
"before": null,
"after": {
"name": "admin",
"ingress": [
{
"from_port": 22,
"to_port": 22,
"protocol": "tcp",
"cidr_blocks": [
"0.0.0.0/0"
],
"description": ""
},
{
"from_port": 8443,This security group will be created with an inbound rule for port 22 from 0.0.0.0/0. You know that finding from lesson 6. Here it is still a plan.
2. Write the rules as data
Each rule in iac_rules.json has an id, a severity, a title, the type of resource that it reads, and a list all of conditions that must all hold. A condition has a path into the settings, an operator (eq equal, ne not equal, le at most, ge at least) and a value. In a path, * means "each item of a list". The key each makes the rule test the items of a list one by one: NET-1 tests each inbound rule of a group, so that the port and the range must be wrong in the same rule.
iac_rules.json
[
{"id": "NET-1", "severity": "high", "title": "SSH open to the internet", "type": "aws_security_group", "each": "ingress",
"all": [{"path": "cidr_blocks.*", "op": "eq", "value": "0.0.0.0/0"}, {"path": "from_port", "op": "le", "value": 22},
{"path": "to_port", "op": "ge", "value": 22}]},
{"id": "DB-1", "severity": "high", "title": "Database with a public address", "type": "aws_db_instance",
"all": [{"path": "publicly_accessible", "op": "eq", "value": true}]},
{"id": "DB-2", "severity": "medium", "title": "Database storage not encrypted", "type": "aws_db_instance",
"all": [{"path": "storage_encrypted", "op": "ne", "value": true}]},
{"id": "EC2-1", "severity": "high", "title": "Metadata service without a required token", "type": "aws_instance",
"all": [{"path": "metadata_options.*.http_tokens", "op": "ne", "value": "required"}]},
{"id": "S3-1", "severity": "high", "title": "Public-access block switched off", "type": "aws_s3_bucket_public_access_block",
"all": [{"path": "restrict_public_buckets", "op": "ne", "value": true}]}
]Read NET-1 aloud: in one inbound rule, one of the ranges is 0.0.0.0/0, the first port is at most 22 and the last port is at least 22. So a rule for ports 0 to 65535 is caught too.
3. Save the scanner
iac_scan.py applies the rules to change.after of every resource. Two small functions do the reading. values follows a path and returns everything it finds. holds tests one condition.
def values(item, path):
"""Follow a path such as ingress.*.cidr_blocks.* through dictionaries and lists. * means every item of a list."""
found = [item]
for step in path.split("."):
nxt = []
for x in found:
if step == "*" and isinstance(x, list):
nxt += x
elif isinstance(x, dict) and step in x:
nxt.append(x[step])
found = nxt
return founddef holds(condition, item):
"""A condition holds when one value at its path passes the test. A missing value passes only 'ne'."""
found = values(item, condition["path"])
if not found:
return condition["op"] == "ne"
return any(OPS[condition["op"]](v, condition["value"]) for v in found)Note the second line of holds. A setting that is missing passes ne and fails every other test. So the rule "storage_encrypted is not true" fires when the setting is absent, which is the safe way to read a missing security setting. The scanner skips resources that will be deleted. For a resource of type aws_iam_policy it parses the policy text and calls audit_policy of lesson 3: one check, used in two places. Open the block and save the file.
The finished file: iac_scan.py
iac_scan.py
"""iac_scan.py: check a plan before it is applied. The rules are data.
python3 iac_scan.py [PLAN] [RULES] default: plan.json iac_rules.json
Exit code 1 when a finding is high, so that a pipeline stops.
"""
import json
import sys
from iam_audit import audit_policy
OPS = {"eq": lambda have, want: have == want, "ne": lambda have, want: have != want,
"le": lambda have, want: have <= want, "ge": lambda have, want: have >= want}
def values(item, path):
"""Follow a path such as ingress.*.cidr_blocks.* through dictionaries and lists. * means every item of a list."""
found = [item]
for step in path.split("."):
nxt = []
for x in found:
if step == "*" and isinstance(x, list):
nxt += x
elif isinstance(x, dict) and step in x:
nxt.append(x[step])
found = nxt
return found
def holds(condition, item):
"""A condition holds when one value at its path passes the test. A missing value passes only 'ne'."""
found = values(item, condition["path"])
if not found:
return condition["op"] == "ne"
return any(OPS[condition["op"]](v, condition["value"]) for v in found)
def scan(plan, rules):
out = []
for rc in plan["resource_changes"]:
after = rc["change"]["after"]
if after is None:
continue # the resource is deleted: nothing will exist that could be wrong
for rule in rules:
if rule["type"] != rc["type"]:
continue
items = values(after, rule["each"] + ".*") if "each" in rule else [after]
if any(all(holds(c, item) for c in rule["all"]) for item in items):
out.append({"severity": rule["severity"], "rule": rule["id"], "address": rc["address"], "title": rule["title"]})
if rc["type"] == "aws_iam_policy": # the policy is JSON text inside the plan: reuse the audit of lesson 3
for f in audit_policy(after["name"], json.loads(after["policy"])):
out.append({"severity": f["severity"], "rule": "IAM-" + f["code"], "address": rc["address"], "title": f["text"]})
return out
if __name__ == "__main__":
with open(sys.argv[1] if len(sys.argv) > 1 else "plan.json") as src:
plan = json.load(src)
with open(sys.argv[2] if len(sys.argv) > 2 else "iac_rules.json") as src:
rules = json.load(src)
found = scan(plan, rules)
for f in found:
print(f"{f['severity']:8s} {f['rule']:14s} {f['address']:42s} {f['title']}")
high = sum(f["severity"] in ("critical", "high") for f in found)
print(f"{len(found)} findings, {high} high or critical, in {len(plan['resource_changes'])} resource changes")
sys.exit(1 if high else 0)4. Scan the plan
python3 iac_scan.py
echo "exit code $?"high NET-1 aws_security_group.admin SSH open to the internet
high NET-1 aws_security_group.range SSH open to the internet
high DB-1 aws_db_instance.reports Database with a public address
medium DB-2 aws_db_instance.reports Database storage not encrypted
high EC2-1 aws_instance.worker Metadata service without a required token
high S3-1 aws_s3_bucket_public_access_block.exports Public-access block switched off
high IAM-WILDCARD aws_iam_policy.exporter s3:* on every resource
high EC2-1 aws_instance.extra_0 Metadata service without a required token
high EC2-1 aws_instance.extra_5 Metadata service without a required token
9 findings, 8 high or critical, in 22 resource changes
exit code 1Every line is a mistake that you met in an earlier lesson, found before it exists. The exit code is 1, because findings are high.
5. Use the exit code as a gate
A pipeline is a script that stops when a step fails. && runs the second command only if the first ended with 0, and || only if it did not.
python3 iac_scan.py > scan.txt && echo "APPLY: the plan goes on" || echo "STOP: $(tail -n 1 scan.txt)"STOP: 9 findings, 8 high or critical, in 22 resource changesThat one line is the whole gate. Everything else is the quality of the rules: a rule that fires on harmless changes gets switched off by an annoyed team, and then it protects nothing.
Your turn
Copy iac_rules.json to iac_rules_more.json and add three rules for the mistakes that the first five miss.
NET-2, high: a security group with port 5432 open to0.0.0.0/0.NET-3, high: a security group with port 3389 open to0.0.0.0/0.EBS-1, medium: a resource of typeaws_ebs_volumewhose settingencryptedis nottrue.
Use the same test as NET-1 for the two ports: a rule whose range includes the port counts. Run the scanner with your eight rules on plan.json. Then make a second plan with seed 2 and scan that.
python3 gen_plan.py 2 plan2.jsonplan2.json: 26 resource changes, sha256 0bd40a99c78fThe NET-3 finding is not the group old_admin, although that group opens port 3389 to the internet. Look at its action in the plan, and at the resource that your rule did catch.
Check yourself
The plan holds a security group with port 3389 open to the internet, and your rule NET-3 does not fire on it. Why is that right?
Its action is delete, so change.after is null: after the apply the group does not exist. A scanner judges the state after the change. A rule that fired on deleted resources would stop the very change that removes the problem.
Why does the rule for database encryption use "ne true" and not "eq false"?
With eq false, a database whose plan does not mention the setting passes, although the default of the provider may be "not encrypted". With ne true, a missing setting is a finding. For a security setting, absent must count as wrong until someone writes down the safe value.
A scan of the plan is clean. Name two ways in which the account can still end up misconfigured.
Someone changes a resource by hand in the console after the apply (this is called drift), or a resource is created outside the pipeline altogether. And the rules know only what they were written for. So the plan scan is one control, and the checks on the live account (lessons 3 to 7, and the posture check of lesson 13) are the other.
Field notes
- Scan in two places: the code files on every commit (fast, and it comments on the line), and the plan before the apply (it sees the real values after variables and modules are resolved).
- Give every exception an owner and an end date, in the repository, next to the code. An inline "skip this check" comment with no reason is how a rule dies.
- A plan file can hold secrets, for example a database password in
after. Treat it like a secret, and scan it with the key scanner of lesson 4. - A rule that reads one resource type misses the same mistake in another. These rules read only
aws_s3_bucket_public_access_block, so a bucket with no such resource passes. They read the inlineingressrules of a security group, but real code also writes them asaws_vpc_security_group_ingress_ruleoraws_security_group_rule. Missing is a finding: each of these needs a rule of its own. - Protect the pipeline itself. Its role can create anything, so it is the strongest identity of the account: few people may change the pipeline, and its credentials are temporary (lesson 4).