TDCTF Academy Logo TDCTF ACADEMY

IaC Scanning - Policy as Code untuk Infrastruktur

Pendahuluan

Infrastructure as Code (IaC) memungkinkan tim untuk mendefinisikan dan mengelola infrastruktur melalui kode - Terraform, CloudFormation, Kubernetes manifests, ARM templates, dan Pulumi. Namun, kode infrastruktur juga rentan terhadap kesalahan konfigurasi yang dapat menyebabkan celah keamanan serius: S3 bucket yang terbuka untuk publik, security group yang terlalu permisif, atau database tanpa enkripsi.

IaC Scanning adalah praktik menganalisis kode infrastruktur secara otomatis untuk mendeteksi security misconfigurations sebelum infrastruktur di-deploy. Pendekatan ini disebut policy-as-code - kebijakan keamanan ditulis sebagai kode yang dapat dieksekusi oleh tool scanning.

Artikel ini membahas tool utama IaC Scanning (Checkov, tfsec, Terrascan, KICS), integrasi dengan pipeline CI/CD, kebijakan berbasis CIS benchmarks, drift detection, dan penulisan custom policies dengan Rego (OPA).

Tools IaC Scanning

1. Checkov

Checkov adalah tool static analysis untuk IaC yang dikembangkan oleh Bridgecrew (sekarang bagian dari Prisma Cloud). Checkov mendukung Terraform, CloudFormation, Kubernetes, ARM, Serverless, dan Dockerfile.

Instalasi:

# Via pip
pip install checkov

# Via pipx (recommended)
pipx install checkov

# Verifikasi
checkov --version

Scanning dasar:

# Scan direktori Terraform
checkov --directory ./terraform/

# Scan file spesifik
checkov --file ./terraform/main.tf

# Output dalam format yang berbeda
checkov --directory ./terraform/ --output json
checkov --directory ./terraform/ --output junitxml > checkov-report.xml
checkov --directory ./terraform/ --output sarif > checkov-report.sarif

Contoh output Checkov:

checkov --directory ./terraform/

# Output:
#
# _ _
# ___| |__ ___ ___| | _______ __
# / __| '_ \ / _ \/ __| |/ / _ \ \ / /
# | (__| | | | __/ (__| < (_) \ V /
# \___|_| |_|\___|\___|_|\_\___/ \_/
#
# By Bridgecrew
#
# terraform scan results:
#
# Passed checks: 15, Failed checks: 3, Skipped: 0
#
# Check: CKV_AWS_53: "Ensure S3 bucket has block public access"
# FAILED for resource: aws_s3_bucket.data_bucket
# File: /terraform/s3.tf:1-12
# Guide: https://docs.prismacloud.io/en/enterprise-edition/policy-reference/aws-policies/s3-policies/s3-2-block-public-access
#
# Check: CKV_AWS_21: "Ensure all data stored in S3 bucket is encrypted"
# FAILED for resource: aws_s3_bucket.data_bucket
# File: /terraform/s3.tf:1-12
#
# Check: CKV_AWS_20: "Ensure S3 bucket has ACL defined"
# PASSED for resource: aws_s3_bucket.data_bucket

Skip check tertentu:

# Di kode Terraform - skip check dengan justifikasi
# checkov:skip=CKV_AWS_53:Bucket ini hanya untuk development sementara
resource "aws_s3_bucket" "dev_bucket" {
bucket = "dev-data-123"
}

2. tfsec

tfsec adalah tool scanning khusus untuk Terraform yang dikembangkan oleh Aqua Security. tfsec menggunakan aturan berbasis pola untuk mendeteksi misconfigurations di kode Terraform.

Instalasi:

# Via binary
curl -sL https://github.com/aquasecurity/tfsec/releases/latest/download/tfsec-linux-amd64 -o /usr/local/bin/tfsec
chmod +x /usr/local/bin/tfsec

# Via Homebrew
brew install tfsec

# Via Go
go install github.com/aquasecurity/tfsec/cmd/tfsec@latest

Scanning dasar:

# Scan direktori
tfsec ./terraform/

# Scan dengan output detail
tfsec ./terraform/ --verbose

# Output JSON
tfsec ./terraform/ --format json > tfsec-report.json

# Output SARIF (untuk GitHub Security)
tfsec ./terraform/ --format sarif > tfsec-report.sarif

# Hanya error severity
tfsec ./terraform/ --minimum-severity CRITICAL

Contoh output tfsec:

tfsec ./terraform/

# Output:
# __ _ ___ ___ ___ ___
# / _\ /_\ / __/ __| __| _ \
# \ \ / _ \\__ \__ \ _|| /
# _\ \/ _ \/___/___/___|_|_\
#
# by Aqua Security
#
# Result 1
# Result 2
#
# 8 passed, 2 failed
#
# FAIL: azure-open-blob-container
# Container is open to public access.
# File: /terraform/storage.tf:10-14
#
# FAIL: aws-sqs-queue-encryption-at-rest
# Queue is not encrypted at rest.
# File: /terraform/queue.tf:5-12
#
# 2 problems (0 ignored)

Konfigurasi tfsec dengan tfsec.yaml:

# tfsec.yaml
minimum_severity: MEDIUM
exclude:
- aws-s3-enable-bucket-logging
include:
- aws-*
no_color: true
format: json
output: tfsec-report.json

Menjalankan dengan konfigurasi:

tfsec ./terraform/ --config-file tfsec.yaml

3. Terrascan

Terrascan adalah tool IaC scanning yang dikembangkan oleh Accurics (Tenable). Terrascan mendukung Terraform, Kubernetes, Helm, Kustomize, dan Docker.

Instalasi:

# Via script
curl -sL https://raw.githubusercontent.com/tenable/terrascan/master/install.sh | bash

# Via Homebrew
brew install terrascan

Scanning dasar:

# Scan direktori
terrascan scan -d ./terraform/

# Scan dengan policy tertentu
terrascan scan -d ./terraform/ --policy-type aws

# Output JSON
terrascan scan -d ./terraform/ -o json > terrascan-report.json

# Output human-readable
terrascan scan -d ./terraform/ -o human

Contoh output Terrascan:

terrascan scan -d ./terraform/

# Output:
# Results Summary:
# Violation: 3
# Low: 0
# Medium: 2
# High: 1
#
# Resource: aws_security_group_rule.ssh_from_all
# Rule: AWS.SecurityGroup.NS.MEDIUM.1016
# Severity: MEDIUM
# File: /terraform/network.tf:15
# Desc: SSH access should not be allowed from all IPs

4. KICS (Keeping Infrastructure as Code Secure)

KICS adalah tool open-source dari Checkmarx yang mendukung banyak format IaC: Terraform, CloudFormation, Kubernetes, Docker, Ansible, dan lainnya.

Instalasi:

# Via script
curl -sL https://raw.githubusercontent.com/Checkmarx/kics/master/install.sh | bash

# Via Docker
docker pull checkmarx/kics:latest

Scanning dasar:

# Scan dengan binary
./kics scan -p ./terraform/ --report-formats json,sarif

# Scan dengan Docker
docker run -v $(pwd):/path checkmarx/kics:latest scan \
-p /path/terraform \
--report-formats json \
-o /path/reports/

Kelebihan KICS:

  • Mendukung lebih dari 1.600 query.
  • Deteksi misconfigurations untuk 15+ platform.
  • Output format yang kaya (JSON, SARIF, HTML, PDF).

5. ScoutSuite dan Prowler

Kedua tool ini berbeda dari yang di atas - mereka memindai infrastruktur yang sudah berjalan, bukan kode IaC. Namun, hasilnya dapat digunakan sebagai feedback loop untuk memperbaiki kode IaC.

ScoutSuite:

# Instalasi
pip install scoutsuite

# Scan AWS
scout aws --report-dir ./reports/

# Scan dengan profile tertentu
scout aws --profile production --report-dir ./reports/

Prowler:

# Instalasi
pip install prowler

# Scan AWS dengan CIS benchmark
prowler aws --compliance cis_1.4_aws

# Output JSON
prowler aws --compliance cis_2.0_aws -M json -o ./reports/

Scanning Policies - CIS Benchmarks

CIS (Center for Internet Security) Benchmarks adalah standar industri untuk konfigurasi keamanan. Tool IaC Scanning dapat menggunakan CIS benchmarks sebagai basis kebijakan.

Contoh CIS Benchmark untuk AWS

Beberapa aturan CIS yang umum:

ID CIS Deskripsi Resource
CIS 2.1 S3 bucket public access block aws_s3_bucket
CIS 3.1 CloudTrail enabled aws_cloudtrail
CIS 4.1 Security group change detection aws_security_group
CIS 5.1 IAM password policy aws_iam_account_password_policy

Checkov dengan CIS benchmark:

# Gunakan framework CIS
checkov --directory ./terraform/ --framework terraform --check CKV_AWS_*

# Framework spesifik
checkov --directory ./terraform/ --framework terraform --output cli

tfsec dengan custom severity:

# Sesuaikan threshold severity
tfsec ./terraform/ --minimum-severity HIGH

# Ignore low-severity issues
tfsec ./terraform/ --exclude aws-s3-enable-logging

Integrasi CI/CD

IaC Scanning paling efektif ketika diintegrasikan ke dalam pipeline CI/CD. Dengan integrasi ini, setiap perubahan kode infrastruktur akan dipindai sebelum di-apply.

GitHub Actions - Checkov

name: IaC Security Scan

on:
pull_request:
paths:
- 'terraform/**'
- 'kubernetes/**'

jobs:
checkov-scan:
runs-on: ubuntu-latest
permissions:
contents: read
security-events: write
steps:
- uses: actions/checkout@v4
- name: Run Checkov
id: checkov
uses: bridgecrewio/checkov-action@master
with:
directory: terraform/
framework: terraform
output_format: sarif
output_file_path: checkov-results.sarif
soft_fail: false
- name: Upload SARIF
uses: github/codeql-action/upload-sarif@v3
with:
sarif_file: checkov-results.sarif
category: checkov

GitHub Actions - tfsec

name: tfsec Scan

on:
pull_request:
paths:
- 'terraform/**'

jobs:
tfsec:
runs-on: ubuntu-latest
permissions:
contents: read
security-events: write
steps:
- uses: actions/checkout@v4
- name: Run tfsec
uses: aquasecurity/tfsec-[email protected]
with:
working_directory: terraform/
soft_fail: false
format: sarif
output: tfsec-results.sarif
- name: Upload SARIF
uses: github/codeql-action/upload-sarif@v3
with:
sarif_file: tfsec-results.sarif
category: tfsec

GitLab CI - Checkov

# .gitlab-ci.yml
stages:
- validate
- security

checkov-scan:
stage: security
image: bridgecrew/checkov:latest
script:
- checkov --directory terraform/ --framework terraform
- checkov --directory terraform/ --framework terraform --output json > checkov-report.json
artifacts:
reports:
junit: checkov-report.xml
paths:
- checkov-report.json
only:
changes:
- terraform/**/*

GitLab CI - Multi-Tool Scan

iac-scan:
stage: security
image: alpine:latest
before_script:
- apk add --no-cache python3 py3-pip curl
- pip3 install checkov
- curl -sL https://github.com/aquasecurity/tfsec/releases/latest/download/tfsec-linux-amd64 -o /usr/local/bin/tfsec
- chmod +x /usr/local/bin/tfsec
script:
- echo "=== Checkov Scan ==="
- checkov --directory terraform/ --framework terraform --quiet
- echo "=== tfsec Scan ==="
- tfsec ./terraform/ --no-color --minimum-severity HIGH
artifacts:
paths:
- checkov-report.json
- tfsec-report.json
only:
changes:
- terraform/**/*

Drift Detection

Drift detection adalah proses mendeteksi perbedaan antara konfigurasi infrastruktur yang didefinisikan di kode dengan konfigurasi yang sebenarnya berjalan. Drift dapat terjadi karena perubahan manual, auto-scaling events, atau perubahan dari tool lain.

Drift Detection dengan Terraform

# Deteksi drift
terraform plan -detailed-exitcode

# Exit code 0: Tidak ada perubahan
# Exit code 1: Error
# Exit code 2: Ada perubahan (drift detected)

Drift Detection dengan Checkov

Checkov memiliki fitur drift detection untuk membandingkan state IaC dengan infrastruktur aktual:

# Drift detection dengan Checkov
checkov --directory ./terraform/ --framework terraform --check CKV_DRIFT

Drift Detection Automation

# GitHub Actions - scheduled drift detection
name: IaC Drift Detection

on:
schedule:
- cron: '0 6 * * *' # Setiap hari jam 6 pagi
workflow_dispatch: # Bisa dijalankan manual

jobs:
detect-drift:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
- name: Setup Terraform
uses: hashicorp/setup-terraform@v2
with:
terraform_version: 1.6.0
- name: Terraform Init
run: terraform init
working-directory: terraform/
- name: Detect Drift
id: drift
run: |
terraform plan -detailed-exitcode -out=tfplan
echo "exit_code=$?" >> $GITHUB_OUTPUT
working-directory: terraform/
- name: Create Issue if Drift Found
if: steps.drift.outputs.exit_code == 2
uses: actions/github-script@v7
with:
script: |
const fs = require('fs');
const planOutput = fs.readFileSync('terraform/tfplan', 'utf8');
github.rest.issues.create({
owner: context.repo.owner,
repo: context.repo.repo,
title: 'IaC Drift Detected',
body: `Drift terdeteksi di infrastruktur pada ${new Date().toISOString()}.\\n\\nDetail perubahan:\\n\\`\\`\\`\\n${planOutput}\\n\\`\\`\\``
});

Custom Policy dengan Rego (OPA)

OPA (Open Policy Agent) adalah policy engine yang menggunakan bahasa kebijakan Rego. Checkov dan tfsec mendukung custom policies menggunakan Rego.

Struktur Dasar Rego

# policy.rego
package terraform

# Definisikan aturan
deny[msg] {
resource := input.resource.aws_s3_bucket[_]
not resource.config.server_side_encryption_configuration
msg := sprintf("S3 bucket %v tidak memiliki enkripsi", [resource.config.bucket])
}

allow {
count(deny) == 0
}

Custom Policy Checkov dengan Rego

Checkov mendukung custom policies melalui framework YAML dan Python, serta OPA/Rego untuk aturan yang lebih kompleks:

# checkov-policy.yaml
metadata:
id: CUSTOM_S3_001
name: "S3 bucket must have versioning enabled"
category: "S3"
definition:
and:
- cond: exists
resource_types:
- aws_s3_bucket
- cond: not
conditions:
- cond: attribute_exists
resource_types:
- aws_s3_bucket
attribute: versioning.enabled

Contoh Rego Policy untuk tfsec

# custom-tfsec-policy.rego
package tfsec.rules

# Aturan: EC2 instances harus menggunakan tipe instance yang diizinkan
deny[msg] {
instance := input.aws_instance[name]
not instance.instance_type in ["t3.medium", "t3.large", "m5.large"]
msg := sprintf("EC2 instance %v menggunakan tipe yang tidak diizinkan: %v", [name, instance.instance_type])
}

# Aturan: Security group tidak boleh membuka port 22 ke 0.0.0.0/0
deny[msg] {
sg := input.aws_security_group[name]
rule := sg.ingress[_]
rule.from_port <= 22
rule.to_port >= 22
rule.cidr_blocks[_] == "0.0.0.0/0"
msg := sprintf("Security group %v membuka SSH ke publik", [name])
}

# Aturan: RDS harus terenkripsi
deny[msg] {
rds := input.aws_db_instance[name]
not rds.storage_encrypted
msg := sprintf("RDS instance %v tidak memiliki storage encryption", [name])
}

Menjalankan tfsec dengan custom Rego policy:

# Lokasi custom policy
tfsec ./terraform/ --custom-policy-dir ./policies/

OPA dan Terraform

OPA juga dapat diintegrasikan langsung dengan Terraform melalui OPA provider atau sebagai external policy check:

# opa-terraform-policy.rego
package terraform

# Larang penggunaan t3.nano untuk production
deny[msg] {
instance := input.aws_instance[name]
instance.instance_type == "t3.nano"
msg := sprintf("Instance %v menggunakan t3.nano - terlalu kecil", [name])
}

# Larang S3 bucket tanpa block public access
deny[msg] {
bucket := input.aws_s3_bucket[name]
not bucket.block_public_access
msg := sprintf("S3 bucket %v tidak memiliki block public access", [name])
}

Integrasi dengan pipeline:

# GitHub Actions - custom OPA policy check
jobs:
opa-check:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
- name: OPA Policy Check
run: |
# Generate JSON dari Terraform
terraform show -json > tfstate.json

# Evaluasi dengan OPA
opa eval --data policies/ --input tfstate.json "data.terraform.deny"

Contoh: Pipeline IaC Scanning Lengkap

Berikut adalah contoh pipeline CI/CD yang mengintegrasikan tiga tool IaC scanning dan custom OPA policies:

name: Comprehensive IaC Security

on:
pull_request:
paths:
- 'terraform/**'
- 'kubernetes/**'
- '*.tf'

permissions:
contents: read
security-events: write

jobs:
iac-scan:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4

# 1. Checkov scan
- name: Checkov IaC Scan
uses: bridgecrewio/checkov-action@master
with:
directory: terraform/
framework: terraform
output_format: sarif
output_file_path: checkov-results.sarif
soft_fail: false

# 2. tfsec scan
- name: tfsec Scan
uses: aquasecurity/tfsec-[email protected]
with:
working_directory: terraform/
soft_fail: false
format: sarif
output: tfsec-results.sarif

# 3. KICS scan
- name: KICS Scan
uses: checkmarx/kics-github-[email protected]
with:
path: terraform/
fail_on: high
output_path: kics-results.sarif
output_formats: sarif

# 4. OPA custom policy check
- name: OPA Policy Check
run: |
# Install OPA
curl -sL -o opa https://openpolicyagent.org/downloads/latest/opa_linux_amd64_static
chmod +x opa

# Evaluasi custom policies
./opa eval \
--data policies/ \
--input <(cat terraform/*.tf) \
"data.terraform.deny"

# Upload all SARIF results
- name: Upload Checkov results
uses: github/codeql-action/upload-sarif@v3
with:
sarif_file: checkov-results.sarif
category: checkov

- name: Upload tfsec results
uses: github/codeql-action/upload-sarif@v3
with:
sarif_file: tfsec-results.sarif
category: tfsec

- name: Upload KICS results
uses: github/codeql-action/upload-sarif@v3
with:
sarif_file: kics-results.sarif
category: kics

# Job terpisah untuk drift detection (scheduled)
drift-detection:
if: github.event_name == 'schedule'
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
- name: Setup Terraform
uses: hashicorp/setup-terraform@v2
- name: Drift Check
run: |
cd terraform/
terraform init
terraform plan -detailed-exitcode

Kesimpulan

IaC Scanning adalah komponen kritis dari DevSecOps modern. Dengan menggunakan tool seperti Checkov, tfsec, Terrascan, dan KICS, tim dapat mendeteksi security misconfigurations sebelum infrastruktur di-deploy. Integrasi dengan pipeline CI/CD memastikan bahwa setiap perubahan kode infrastruktur melewati security gate. CIS benchmarks memberikan baseline keamanan yang terstandarisasi. Custom policies dengan Rego/OPA memungkinkan organisasi mendefinisikan kebijakan keamanan yang spesifik. Drift detection melengkapi siklus keamanan dengan memastikan infrastruktur yang berjalan tetap sesuai dengan kode. Kombinasi semua elemen ini menciptakan pertahanan berlapis untuk infrastruktur sebagai kode.

PADA HALAMAN INI