Dev.to Security 🔐 Cybersecurity 👁 0 📖 6 min read

Catch Risky AWS Settings Before terraform apply: Checkov in GitLab CI

In an earlier post (Japanese) I set up a self-hosted GitLab with a Runner. This time I used it to stop risky Terraform settings before apply. The tool is Checkov. It statically analyzes Terraform, CloudFormation, Kubern

Catch Risky AWS Settings Before terraform apply: Checkov in GitLab CI

In an earlier post (Japanese) I set up a self-hosted GitLab with a Runner. This time I used it to stop risky Terraform settings before apply.

The tool is Checkov. It statically analyzes Terraform, CloudFormation, Kubernetes YAML and more, and tells you things like "this S3 bucket isn't encrypted" or "SSH is open to the world".

Two things I want to get across:

  1. Running it in CI and blocking the MR saves a lot of review back-and-forth
  2. You won't fix everything, so when you skip a check, keep the reason in the code

All screenshots are real checkov runs on my Linux box. Account IDs and bucket names are dummies.

Environment

Item Version
OS Ubuntu 24.04
Checkov 3.4.14
GitLab self-hosted + GitLab Runner
pip install checkov

Checkov reads the Terraform code directly — no terraform init, no AWS credentials.

The flow

Flow: push .tf, checkov job, fail and fix or skip, then terraform plan and apply

Step 1: Write some deliberately risky Terraform

The kind of code you write when "it just needs to work":

# before/main.tf
provider "aws" {
  region = "ap-northeast-1"
}

resource "aws_s3_bucket" "logs" {
  bucket = "example-app-logs-111122223333"
}

resource "aws_security_group" "web" {
  name   = "web-sg"
  vpc_id = var.vpc_id

  ingress {
    description = "ssh"
    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_instance" "web" {
  ami                    = var.ami_id
  instance_type          = "t3.micro"
  subnet_id              = var.subnet_id
  vpc_security_group_ids = [aws_security_group.web.id]
}

variable "vpc_id" {}
variable "subnet_id" {}
variable "ami_id" {}

Step 2: Run Checkov

checkov -d before --framework terraform --compact --quiet

Checkov: 15 failed checks, exit code 1

15 failed checks, exit code 1 — in CI the pipeline stops here.

The orange ones are the ones I'd call "must fix":

ID Finding Fix
CKV_AWS_24 SSH (22) open to 0.0.0.0/0 remove the ingress; use Session Manager
CKV_AWS_79 IMDSv1 enabled http_tokens = "required"
CKV_AWS_8 unencrypted EBS root_block_device.encrypted = true
CKV2_AWS_6 no S3 public access block aws_s3_bucket_public_access_block
CKV_AWS_145 S3 not encrypted with KMS SSE-KMS + key rotation

I also fixed open egress, the missing IAM role, versioning and lifecycle rules.

Step 3: Decide what to fix and what to skip

Fixing every finding isn't realistic, so I used this rule:

Decision: fix if risky, otherwise skip with a reason in code and review skipped checks

Skips go inside the resource as comments:

resource "aws_s3_bucket" "logs" {
  #checkov:skip=CKV_AWS_144:Log bucket - cross-region replication not required
  #checkov:skip=CKV2_AWS_62:No consumer for event notifications
  #checkov:skip=CKV_AWS_18:This bucket IS the access-log destination
  bucket = "example-app-logs-111122223333"
}

Gotcha: the KMS key policy gets flagged

While fixing things, the KMS key policy (data "aws_iam_policy_document") triggered:

  • CKV_AWS_111 (write access without constraints)
  • CKV_AWS_356 (Resource: "*")
  • CKV_AWS_109 (permissions management without constraints)

But inside a key policy, Resource: "*" means "this key", which is not what it means in an IAM policy. I skipped these with a reason:

data "aws_iam_policy_document" "kms_logs" {
  # In a key policy, Resource "*" means "this key", so IAM-policy checks do not apply
  #checkov:skip=CKV_AWS_111:In a key policy "*" means this key only
  #checkov:skip=CKV_AWS_356:In a key policy "*" means this key only
  #checkov:skip=CKV_AWS_109:In a key policy "*" means this key only
  statement {
    ...
  }
}

Granting kms:* to the account root matches AWS's default key policy. It means "let IAM policies control access to this key", so the real restriction has to happen on the IAM side — written with least privilege, as in my previous post (Policy Sentry + Parliament).

The fixed main.tf (full)
provider "aws" {
  region = "ap-northeast-1"
}

# ---------- S3 (app log bucket) ----------
resource "aws_s3_bucket" "logs" {
  #checkov:skip=CKV_AWS_144:Log bucket - cross-region replication not required
  #checkov:skip=CKV2_AWS_62:No consumer for event notifications
  #checkov:skip=CKV_AWS_18:This bucket IS the access-log destination
  bucket = "example-app-logs-111122223333"
}

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

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

resource "aws_kms_key" "logs" {
  description             = "key for app logs bucket"
  enable_key_rotation     = true
  deletion_window_in_days = 30
  policy                  = data.aws_iam_policy_document.kms_logs.json
}

data "aws_iam_policy_document" "kms_logs" {
  # In a key policy, Resource "*" means "this key", so IAM-policy checks do not apply
  #checkov:skip=CKV_AWS_111:In a key policy "*" means this key only
  #checkov:skip=CKV_AWS_356:In a key policy "*" means this key only
  #checkov:skip=CKV_AWS_109:In a key policy "*" means this key only
  statement {
    sid       = "AllowAccountAdmin"
    actions   = ["kms:*"]
    resources = ["*"]
    principals {
      type        = "AWS"
      identifiers = ["arn:aws:iam::111122223333:root"]
    }
  }
}

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

resource "aws_s3_bucket_lifecycle_configuration" "logs" {
  bucket = aws_s3_bucket.logs.id
  rule {
    id     = "expire-90d"
    status = "Enabled"
    filter {}
    expiration {
      days = 90
    }
    noncurrent_version_expiration {
      noncurrent_days = 30
    }
    abort_incomplete_multipart_upload {
      days_after_initiation = 7
    }
  }
}

# ---------- EC2 ----------
resource "aws_security_group" "web" {
  name        = "web-sg"
  description = "web server"
  vpc_id      = var.vpc_id

  # No SSH - use Session Manager instead
  egress {
    description = "https to vpc endpoints"
    from_port   = 443
    to_port     = 443
    protocol    = "tcp"
    cidr_blocks = [var.vpc_cidr]
  }
}

resource "aws_iam_role" "web" {
  name = "web-ec2-role"
  assume_role_policy = jsonencode({
    Version = "2012-10-17"
    Statement = [{
      Effect    = "Allow"
      Principal = { Service = "ec2.amazonaws.com" }
      Action    = "sts:AssumeRole"
    }]
  })
}

resource "aws_iam_role_policy_attachment" "ssm" {
  role       = aws_iam_role.web.name
  policy_arn = "arn:aws:iam::aws:policy/AmazonSSMManagedInstanceCore"
}

resource "aws_iam_instance_profile" "web" {
  name = "web-ec2-profile"
  role = aws_iam_role.web.name
}

resource "aws_instance" "web" {
  #checkov:skip=CKV_AWS_126:Detailed monitoring not needed in this sandbox (cost)
  ami                    = var.ami_id
  instance_type          = "t3.micro"
  subnet_id              = var.subnet_id
  vpc_security_group_ids = [aws_security_group.web.id]
  iam_instance_profile   = aws_iam_instance_profile.web.name
  ebs_optimized          = true

  metadata_options {
    http_tokens   = "required" # IMDSv2 only
    http_endpoint = "enabled"
  }

  root_block_device {
    encrypted = true
  }
}

variable "vpc_id" {}
variable "vpc_cidr" {}
variable "subnet_id" {}
variable "ami_id" {}

Step 4: Run it again

After fixes: 46 passed, 0 failed, 7 skipped, plus the list of skip reasons

  • 46 passed / 0 failed / 7 skipped, exit code 0
  • pulling skipped_checks out of -o json with jq gives you a list of every skip and its reason

Reviewing that list now and then ("is this reason still true?") is the key to keeping skips honest. I'd also reject any skip without a reason (#checkov:skip=CKV_AWS_xx alone) in review.

Step 5: Wire it into GitLab CI

stages:
  - security
  - plan

checkov:
  stage: security
  image:
    name: bridgecrew/checkov:3.4.14
    entrypoint: [""]
  script:
    - checkov -d . --framework terraform --compact --quiet
        -o cli -o junitxml
        --output-file-path console,checkov-junit.xml
  artifacts:
    when: always
    reports:
      junit: checkov-junit.xml
  rules:
    - changes:
        - "**/*.tf"

terraform-plan:
  stage: plan
  image:
    name: hashicorp/terraform:1.9
    entrypoint: [""]
  needs: ["checkov"]
  script:
    - terraform init -input=false
    - terraform plan -input=false
  rules:
    - changes:
        - "**/*.tf"

Notes:

  • pin the bridgecrew/checkov version so new checks don't suddenly break your pipeline
  • without entrypoint: [""], GitLab's script won't run
  • -o cli -o junitxml prints to the log and writes JUnit XML
  • passing it to artifacts:reports:junit shows findings as test results in the MR
  • needs: ["checkov"] means terraform plan doesn't run until Checkov passes

--output-file-path console,checkov-junit.xml maps to the -o flags in order: the first output (cli) goes to the console, the second (junitxml) to that file.

Takeaways

  • Checkov analyzes Terraform without init or credentials
  • you'll get lots of findings at first — fix the genuinely risky ones first
  • for the rest, use #checkov:skip=ID:reason and keep the reason in code
  • a KMS key policy's "*" doesn't mean what it means in IAM, so some checks don't fit
  • in GitLab CI, JUnit output puts findings right in the MR

Next up: AWS networking — restricting traffic between accounts with Transit Gateway.

References

📰 Read the original article on Dev.to Security

Originally published by Dev.to Security. Aggregated on AIWithGhost for educational purposes — full credit and traffic to the original publisher.