Skip to content
Tech Atlas, home
Search
Esc
  • All roadmapsBrowse every learning path
  • ExploreFind a technology area
  • ProjectsGuided projects and builds
  • My AtlasYour learning dashboard
Lesson 3 of 6 · Lab · 30 min · revision 2

Posture Scanning and Fixing Misconfigurations in IaC

Scan a deliberately misconfigured Terraform stack with Checkov, rank the findings by exposure, fix a public bucket, an open SSH rule, an unencrypted database and a bucket without a customer-managed key in code, re-scan to show them cleared, and add a CI gate that fails when a misconfiguration is reintroduced.

Contentsand lesson path

What you will learn

  • Run a posture scan against a sandbox account, prioritise misconfigurations such as public storage, open network rules and unencrypted data, and remediate them in infrastructure as code.

Prerequisites: Cloud Basics

01. Goal and setup

A posture scan checks cloud resources against a set of secure-configuration rules and reports what fails. You can scan a running account, or scan the infrastructure as code (IaC) that will build it, before anything is deployed. IaC is the practice of writing resources as files, here Terraform's HashiCorp Configuration Language (HCL), so that changes go through code review and a pipeline. Scanning the code is cheaper: a public bucket that never gets created cannot leak.

In this lab you scan a deliberately broken Terraform stack with Checkov, an open-source IaC scanner, rank the findings by exposure, fix them in the code, re-scan, and add a continuous-integration (CI) gate that blocks a reintroduced problem. Nothing is deployed: the scanner reads the HCL text, so you need no cloud account and no Terraform, only Python 3.12 and the uv package manager. Work in a folder called iac-lab, with the stack under iac-lab/stack; the first command creates both.

This lab uses Checkov 3.4.5. Check IDs and wording can change between versions, so pin it.

Create the folders, a virtual environment and the pinned scanner. The -q flags keep uv quiet.

Terminal
mkdir -p iac-lab/stack && cd iac-lab
uv venv -q --python 3.12 .venv
uv pip install -q --python .venv/bin/python checkov==3.4.5
.venv/bin/checkov --version
Expected output
3.4.5

02. Step 1: The misconfigured stack

Save the stack below as stack/main.tf. It has five faults on purpose: a bucket for customer exports with ACLs (access control lists) switched back on, a public-read ACL and a public access block that is switched off; a security group open to the whole internet on SSH port 22; a database with encryption at rest switched off; and a password written straight into the code. Settings like these appear in many real cloud breaches.

HCL · iac-lab/stack/main.tf
# Deliberately misconfigured demo stack. Scanned, not deployed. Do not use as a base.
terraform {
  required_providers {
    aws = {
      source  = "hashicorp/aws"
      version = "~> 5.0"
    }
  }
}

provider "aws" {
  region = "eu-west-1"
}

resource "aws_s3_bucket" "exports" {
  bucket = "shop-customer-exports-demo"
}

resource "aws_s3_bucket_public_access_block" "exports" {
  bucket                  = aws_s3_bucket.exports.id
  block_public_acls       = false
  block_public_policy     = false
  ignore_public_acls      = false
  restrict_public_buckets = false
}

# New buckets have ACLs disabled; this setting turns them back on.
resource "aws_s3_bucket_ownership_controls" "exports" {
  bucket = aws_s3_bucket.exports.id
  rule {
    object_ownership = "BucketOwnerPreferred"
  }
}

resource "aws_s3_bucket_acl" "exports" {
  depends_on = [aws_s3_bucket_ownership_controls.exports]
  bucket     = aws_s3_bucket.exports.id
  acl        = "public-read"
}

resource "aws_security_group" "web" {
  name        = "web-sg"
  description = "web server"

  ingress {
    description = "ssh from anywhere"
    from_port   = 22
    to_port     = 22
    protocol    = "tcp"
    cidr_blocks = ["0.0.0.0/0"]
  }

  egress {
    from_port   = 0
    to_port     = 0
    protocol    = "-1"
    cidr_blocks = ["0.0.0.0/0"]
  }
}

resource "aws_db_instance" "orders" {
  identifier          = "orders"
  engine              = "postgres"
  instance_class      = "db.t3.micro"
  allocated_storage   = 20
  username            = "app"
  password            = "change-me-please"
  storage_encrypted   = false
  skip_final_snapshot = true
}

Since April 2023, new S3 buckets have ACLs disabled (the Object Ownership setting "Bucket owner enforced") and the public access block on. Setting an ACL such as public-read then fails with AccessControlListNotSupported, so the stack first sets ownership to BucketOwnerPreferred, which turns ACLs back on. On a bucket, public-read gives everyone the READ permission, which lets anyone on the internet list every object name. Reading the object data also needs a public object ACL or a public bucket policy, and nothing here stops an upload from setting one. A public access block is an S3 feature that overrides public ACLs and policies; here all four of its switches are false, so it blocks nothing. The security group allows 0.0.0.0/0 (every address) to reach port 22, the SSH port, which invites internet-wide password guessing. The database sets storage_encrypted = false, so its data on disk is not encrypted.

03. Step 2: Scan and rank by exposure

Run Checkov once and you will see dozens of findings, from public exposure down to a missing lifecycle rule. Treating them as one flat list wastes effort: you must fix the public customer bucket today, but missing versioning can wait. So the scan is written to JSON, and a small script keeps this lab's focus findings and ranks them by exposure. Save it as iac-lab/prioritize.py.

Python · iac-lab/prioritize.py
"""Reads a Checkov JSON report and ranks this lab's focus findings by exposure."""
import json
import sys

# check_id -> (rank, short reason). Lower rank is more urgent.
FOCUS = {
    "CKV_AWS_20": (1, "public-read ACL: anyone can list customer exports"),
    "CKV2_AWS_6": (2, "public access block is missing or switched off"),
    "CKV_AWS_24": (2, "security group allows 0.0.0.0/0 to SSH port 22"),
    "CKV_AWS_16": (3, "RDS storage is not encrypted at rest"),
    "CKV_AWS_145": (4, "default encryption is SSE-S3, not a KMS key"),
    "CKV_AWS_21": (4, "bucket has no versioning"),
}
BAND = {1: "CRITICAL", 2: "HIGH", 3: "MEDIUM", 4: "LOW"}


def failed_checks(report):
    blocks = report if isinstance(report, list) else [report]
    for block in blocks:
        for f in block.get("results", {}).get("failed_checks", []):
            yield f


def main(path):
    rows = []
    for f in failed_checks(json.load(open(path))):
        if f["check_id"] in FOCUS:
            rank, reason = FOCUS[f["check_id"]]
            rows.append((rank, f["check_id"], f["resource"], reason))
    for rank, cid, resource, reason in sorted(rows):
        res = resource.split(".")[-1]
        print(f"{BAND[rank]:9} {cid:12} {res:10} {reason}")
    print(f"focus findings: {len(rows)}")
    return 1 if rows else 0


if __name__ == "__main__":
    sys.exit(main(sys.argv[1] if len(sys.argv) > 1 else "ck.json"))
Terminal
.venv/bin/checkov -d stack -o json --quiet > ck.json
python3 prioritize.py ck.json
Expected output
CRITICAL  CKV_AWS_20   exports    public-read ACL: anyone can list customer exports
HIGH      CKV2_AWS_6   exports    public access block is missing or switched off
HIGH      CKV_AWS_24   web        security group allows 0.0.0.0/0 to SSH port 22
MEDIUM    CKV_AWS_16   orders     RDS storage is not encrypted at rest
LOW       CKV_AWS_145  exports    default encryption is SSE-S3, not a KMS key
LOW       CKV_AWS_21   exports    bucket has no versioning
focus findings: 6

The ranking puts the public-read ACL first. It opens a bucket of customer exports to the whole internet: anyone can list the file names now, and one upload with a public object ACL exposes the data. The switched-off public access block and the open SSH rule are next, because both widen exposure to the internet. The unencrypted database is medium: it matters if someone already has access to the storage or a stolen disk, a smaller set of attackers than the whole internet. The bucket is not unencrypted. Since January 2023, S3 encrypts every bucket by default with S3-managed keys (SSE-S3). CKV_AWS_145 asks for a customer-managed KMS key (adding a key policy, rotation and a log of key use), so it is low, next to missing versioning. The full scan also flags the hardcoded password (a secrets check) and CKV2_AWS_65 (ACLs not disabled); the next step removes both. The script exits non-zero when any focus finding remains, which the CI gate later relies on.

04. Step 3: Fix the findings in code

Fix the problems in stack/main.tf, highest exposure first. Remove the ACL and the ownership setting, so ACLs are disabled again, and turn the public access block fully on; set default encryption to a customer-managed KMS key (KMS is the cloud key-management service) and turn on versioning; narrow the SSH rule to an admin network; encrypt the database and let AWS manage its password instead of storing one. The full fixed stack is below.

HCL · iac-lab/stack/main.tf (fixed)
# Remediated stack: same resources, exposure removed. Scanned, not deployed.
terraform {
  required_providers {
    aws = {
      source  = "hashicorp/aws"
      version = "~> 5.0"
    }
  }
}

provider "aws" {
  region = "eu-west-1"
}

resource "aws_s3_bucket" "exports" {
  bucket = "shop-customer-exports-demo"
}

resource "aws_s3_bucket_public_access_block" "exports" {
  bucket                  = aws_s3_bucket.exports.id
  block_public_acls       = true
  block_public_policy     = true
  ignore_public_acls      = true
  restrict_public_buckets = true
}

resource "aws_s3_bucket_versioning" "exports" {
  bucket = aws_s3_bucket.exports.id
  versioning_configuration {
    status = "Enabled"
  }
}

resource "aws_s3_bucket_server_side_encryption_configuration" "exports" {
  bucket = aws_s3_bucket.exports.id
  rule {
    apply_server_side_encryption_by_default {
      sse_algorithm     = "aws:kms"
      kms_master_key_id = aws_kms_key.data.arn
    }
  }
}

resource "aws_kms_key" "data" {
  description         = "customer export encryption"
  enable_key_rotation = true
}

resource "aws_security_group" "web" {
  name        = "web-sg"
  description = "web server"

  ingress {
    description = "ssh from the admin network only"
    from_port   = 22
    to_port     = 22
    protocol    = "tcp"
    cidr_blocks = ["10.20.0.0/24"]
  }

  egress {
    description = "all outbound"
    from_port   = 0
    to_port     = 0
    protocol    = "-1"
    cidr_blocks = ["0.0.0.0/0"]
  }
}

resource "aws_db_instance" "orders" {
  identifier          = "orders"
  engine              = "postgres"
  instance_class      = "db.t3.micro"
  allocated_storage   = 20
  username            = "app"
  manage_master_user_password = true
  storage_encrypted   = true
  kms_key_id          = aws_kms_key.data.arn
  skip_final_snapshot = true
}

Re-scan the same way. Every focus finding is gone and the script exits zero.

Terminal
.venv/bin/checkov -d stack -o json --quiet > ck.json
python3 prioritize.py ck.json
Expected output
focus findings: 0

The fix is in code, so it survives: the next terraform apply keeps the bucket private. A one-off change in the console would be drift, a live resource that no longer matches its code, and the next apply would undo it. Some findings have more than one valid fix. The open SSH rule here is narrowed to an admin range; a stronger design removes inbound SSH and uses a session manager instead.

05. Step 4: A CI gate and a reintroduced bug

A scan helps only if it runs on every change. Save the gate script below as iac-lab/gate.sh. It scans a stack directory for just the focus check IDs and reuses prioritize.py, so its exit code is non-zero when any focus finding is present. A pipeline runs it on each pull request and blocks the merge on a non-zero exit.

Bash · iac-lab/gate.sh
#!/bin/bash
# CI gate: scan a stack directory for the focus checks and fail if any still apply.
set -u
DIR="${1:-stack}"
CHECKS="CKV_AWS_20,CKV2_AWS_6,CKV_AWS_24,CKV_AWS_16,CKV_AWS_145,CKV_AWS_21"
checkov -d "$DIR" --check "$CHECKS" -o json --quiet > gate.json 2>/dev/null
python3 prioritize.py gate.json

On the fixed stack the gate passes.

Terminal
export PATH="$PWD/.venv/bin:$PATH"
bash gate.sh stack
Expected output
focus findings: 0

Now reintroduce a misconfiguration: add the public-read ACL back to stack/main.tf, then run the gate again. This is the negative test. The gate must fail, because a CI gate that passes a reintroduced public bucket is giving false assurance.

HCL · add to iac-lab/stack/main.tf
resource "aws_s3_bucket_acl" "exports_bad" {
  bucket = aws_s3_bucket.exports.id
  acl    = "public-read"
}
Terminal
bash gate.sh stack
Expected output
CRITICAL  CKV_AWS_20   exports    public-read ACL: anyone can list customer exports
focus findings: 1

The gate prints the one critical finding and exits with code 1, which a pipeline reads as a failed check and uses to block the merge. On a real apply this ACL would be refused, because ACLs are disabled again, and with ACLs re-enabled the public access block would still neutralise it. The gate fails anyway, and it should: the code states public intent, and a gate must not rely on other layers staying in place (defence in depth). Remove the extra ACL block again afterwards.

06. Beyond IaC: CSPM and benchmarks

Scanning IaC catches problems before deployment, but it cannot see drift or a resource created outside Terraform. For that you need cloud security posture management (CSPM): a tool that reads the live account through its API and checks the real resources. Open-source Prowler and the providers' own services (AWS Security Hub, Microsoft Defender for Cloud, Google Security Command Center) do this. Prowler can report against frameworks such as the CIS AWS Foundations Benchmark, a community-agreed baseline of account settings; the current version is 7.1.0, and Prowler maps its checks to version 7.0 at the time of writing. Running Prowler needs real cloud credentials, so this lab does not run it; you run it against your own sandbox account in the skill project. It writes compliance reports under output/compliance/. The command and the shape of its findings look like this.

Illustrative output (shape only; needs a real account)
$ prowler aws --compliance cis_7.0_aws
FAIL ec2_securitygroup_allow_ingress_from_internet_to_tcp_port_22
     eu-west-1  sg-0abc...  Security group web-sg allows 0.0.0.0/0 to port 22
FAIL s3_bucket_public_access  shop-customer-exports  Bucket is public

The important idea is to run the same rules at two points: in CI against the code, so most problems are stopped before they reach the account, and as a CSPM scan against the live account, as a backstop for drift and anything created outside the pipeline. The IaC gate prevents; the CSPM scan detects.

07. Troubleshooting

08. Check your understanding

Practice check · 3 questions

Scanning and fixing

Three questions about the scan, the ranking and the gate.

Q1. In `prioritize.py` the open SSH rule (CKV_AWS_24) and the missing bucket versioning (CKV_AWS_21) both apply. Which prints first, and why?
Q2. On the fixed stack, a teammate adds an ingress rule that opens port 3389 (remote desktop) to `0.0.0.0/0`. A full `checkov -d stack` run reports CKV_AWS_25, but `bash gate.sh stack` still prints `focus findings: 0`. Why?
Q3. After fixing the stack, you add the public-read ACL back and run `bash gate.sh stack`. What should happen for the gate to be doing its job?
Practice only: not graded, not saved, not evidence.

09. Apply it

For the skill project, grow this into a small pipeline:

  • Add one more misconfigured resource to the stack (for example an unencrypted EBS volume) and a matching entry in FOCUS with an exposure rank and reason.
  • Fix it in code and show the before and after prioritize.py output.
  • Write the gate as a real CI step (a GitHub Actions job or a pre-commit hook) that runs on each change and blocks on a non-zero exit.
  • Run Prowler against your sandbox account and note which findings your IaC gate could not have caught.

10. Review prompt

Without looking back, explain: the difference between scanning IaC and scanning a live account; how to rank findings by exposure; what a public-read bucket ACL allows and why new buckets refuse it; what CKV_AWS_145 asks for when S3 already encrypts by default; why a fix belongs in the code rather than the console; what the CI gate checks and why a non-zero exit matters; and what CSPM and a CIS benchmark add on top of an IaC scan.

References

Your progress

Reading state

Sign in to save that you finished reading this lesson.

Sign in to mark reading complete

Prove this skill

10 questions · about 8 minutes · scored automatically. Marking a lesson as read never demonstrates a skill.
Take the skill check