IaC-beveiliging: Checkov, Trivy en OPA Policy-as-Code
Integreer beveiligingsscans in de Terraform-lus: Checkov voor controles statistieken over meer dan 1000 beleidsregels, Trivy als opvolger van tfsec en OPA/conftest voor aangepast beleid van de organisatie in de pre-apply-poort.
Waarom IaC-beveiliging cruciaal is
In 2023 documenteerde Palo Alto Networks dat 65% van de cloudinbreuken plaatsvonden komt voort uit IaC-misconfiguraties: openbare S3-buckets, ook beveiligingsgroepen permissief, loggen uitgeschakeld, encryptie niet geconfigureerd. De functie verwoestende van deze fouten is dat ja ze schalen: een Terraform-module onveilig gebruikt in 50 omgevingen creëert tegelijkertijd 50 kwetsbaarheden.
De oplossing is het Shift Links Beveiliging: Beweeg de bedieningselementen beveiliging zo vroeg mogelijk in de workflow, voordat er verkeerde configuraties optreden de wolk bereiken. In dit artikel integreren we drie complementaire tools: Checkov voor brede dekking, Trivy voor het vinden van kwetsbaarheden en OPA voor aangepast organisatiebeleid.
De drie instrumenten en hun rollen
- Controle: Meer dan 1000 ingebouwde beleidsregels voor AWS/Azure/GCP/K8's. Gespecialiseerd in IaC. Onderhouden door Bridgecrew (overgenomen door Palo Alto).
- Trivia: Opvolger van tfsec (Aqua Security). Uniforme scanner: IaC, containers, afhankelijkheden, geheimen. tfsec → Trivy-migratie voltooid in 2024.
- OPA + wedstrijdtest: Generieke beleidsengine. Schrijf beleid in Rego voor aangepaste organisatieregels (naamgevingsconventies, verplichte tags, toegestane regio's).
Checkov: beveiligingsscans met meer dan 1000 beleidsregels
Checkov parseert Terraform-bestanden (.tf) statisch, zonder init of plan uit te voeren. Dekt veelvoorkomende kwetsbaarheden af: niet-versleutelde opslag, onbedoelde openbare toegang, loggen uitgeschakeld, IAM te toegeeflijk.
# Installazione
pip install checkov
# Oppure con Docker (raccomandato per CI)
docker pull bridgecrew/checkov:latest
# Scansione base di una directory Terraform
checkov -d ./environments/production --framework terraform
# Solo errori HIGH e CRITICAL (ignora LOW e MEDIUM)
checkov -d . --check HIGH,CRITICAL
# Output SARIF per integrare con GitHub Code Scanning
checkov -d . --output sarif --output-file checkov.sarif
# Skip di check specifici (con motivazione documentata)
checkov -d . --skip-check CKV_AWS_20,CKV_AWS_57
# CKV_AWS_20: bucket S3 public read - skippiamo solo se il bucket è intenzionalmente pubblico
# Esempio: codice Terraform con vulnerabilità e relativo fix
# VULNERABILE - Checkov alert: CKV_AWS_18, CKV_AWS_52, CKV_AWS_144
resource "aws_s3_bucket" "logs" {
bucket = "my-app-logs"
# MANCA: server_side_encryption_configuration
# MANCA: versioning
# MANCA: replication_configuration per disaster recovery
}
# SICURO - Tutti i check Checkov superati
resource "aws_s3_bucket" "logs" {
bucket = "my-app-logs"
}
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" # CKV_AWS_19: usa KMS, non AES256
}
bucket_key_enabled = true
}
}
resource "aws_s3_bucket_versioning" "logs" {
bucket = aws_s3_bucket.logs.id
versioning_configuration {
status = "Enabled" # CKV_AWS_21
}
}
resource "aws_s3_bucket_public_access_block" "logs" {
bucket = aws_s3_bucket.logs.id
block_public_acls = true # CKV_AWS_53
block_public_policy = true # CKV_AWS_54
ignore_public_acls = true # CKV_AWS_55
restrict_public_buckets = true # CKV_AWS_56
}
resource "aws_s3_bucket_logging" "logs" {
bucket = aws_s3_bucket.logs.id
target_bucket = aws_s3_bucket.access_logs.id # CKV_AWS_18
target_prefix = "s3-access-logs/"
}
# checkov.yaml - Configurazione progetto (in root del repo)
# Skippa check non applicabili con motivazione documentata
skip-check:
- CKV_AWS_144 # S3 cross-region replication: non richiesto per log bucket interni
# Controlla solo risorse dei moduli custom (escludi moduli registry)
directory:
- modules/
# Severity minima da riportare
soft-fail-on: LOW,MEDIUM # Non fallisce la pipeline per LOW/MEDIUM
# Abilita output colorato
compact: false
Trivy: Unified IaC-scanner
Trivy is de opvolger van tfsec (migratie voltooid in 2024). Het voordeel ten opzichte van Checkov is dat Trivy ook containerimages scant, applicatie-afhankelijkheden en -geheimen in dezelfde pijplijn, waardoor het aantal tools wordt verminderd.
# Installazione
brew install trivy # macOS
# oppure:
curl -sfL https://raw.githubusercontent.com/aquasecurity/trivy/main/contrib/install.sh | sh
# Scansione Terraform
trivy config ./environments/production
# Con severity filter
trivy config --severity HIGH,CRITICAL ./
# Output JSON per parsing
trivy config --format json --output trivy-results.json ./
# Template Terraform specifico con maggiore dettaglio
trivy config --tf-vars ./environments/production/terraform.tfvars ./environments/production
# Scansione tutto il repo: IaC + dipendenze + segreti
trivy fs ./
# Esempio output Trivy (semplificato)
# trivy config ./environments/production
2024-01-15T10:30:00Z INFO Misconfiguration Types: terraform
environments/production/main.tf (terraform)
HIGH: Resource 'aws_security_group.app' has a wide open egress rule
------------------------------------------
Via: environments/production/main.tf:45
egress {
from_port = 0
to_port = 0
protocol = "-1"
cidr_blocks = ["0.0.0.0/0"] # VULN: egress completamente aperto
}
Fix: Limita l'egress solo alle porte e destinazioni necessarie.
MEDIUM: Resource 'aws_db_instance.main' has no deletion protection
Via: environments/production/main.tf:78
deletion_protection = false # VULN: in production deve essere true
# .trivyignore - Ignora check specifici con motivazione
# Formato: CHECK_ID # Commento obbligatorio con motivazione
AVD-AWS-0025 # S3: CORS permissivo necessario per CDN pubblica
AVD-AWS-0168 # CloudFront: TLS 1.0 permesso per client legacy pre-2022
OPA en conftest: beleid op maat met Rego
Beleidsagent openen (OPA) is een generieke beleidsengine die wordt gebruikt door Kubernetes, Istio en Terraform. betwist het is de CLI die van toepassing is OPA-beleid voor configuratiebestanden (inclusief Terraform-plan JSON). Met OPA kan dat implementeer organisatiebeleid dat niet bestaat in Checkov of Trivy: naamgevingsconventie, verplichte tags, toegestane regio's, kostenlimieten.
# Installazione conftest
brew install conftest
# oppure:
curl -L https://github.com/open-policy-agent/conftest/releases/download/v0.49.0/conftest_0.49.0_linux_amd64.tar.gz | tar xz
# policy/terraform/naming.rego
# Policy: tutte le risorse AWS devono seguire la naming convention aziendale
package main
import future.keywords.in
# Regex per naming convention: {team}-{environment}-{name}
naming_pattern := `^[a-z]+-(?:dev|staging|production)-[a-z0-9-]+
06 - IaC-beveiliging: Checkov, Trivy en OPA Policy-as-Code | Federico Calò
06 - IaC-beveiliging: Checkov, Trivy en OPA Policy-as-Code | Federico Calò
Salta al contenuto principaleHallo! Ik ben
Federico Calò
Sviluppatore Software | Divulgatore Tecnico
Creo applicazioni web moderne e strumenti digitali personalizzati per aiutare le attività a crescere attraverso l'innovazione tecnologica. La mia passione è unire informatica ed economia per generare valore reale.
Over Mij
La mia passione per l'informatica è nata tra i banchi dell'Istituto Tecnico Commerciale di Maglie, dove ho scoperto il potere della programmazione e il fascino di creare soluzioni digitali. Fin da subito, ho capito che l'informatica non era solo codice, ma uno strumento straordinario per trasformare idee in realtà.
Durante gli studi superiori in Sistemi Informativi Aziendali, ho iniziato a intrecciare informatica ed economia, comprendendo come la tecnologia possa essere il motore della crescita per qualsiasi attività. Questa visione mi ha accompagnato all'Università degli Studi di Bari, dove ho conseguito la Laurea in Informatica, approfondendo le mie competenze tecniche e la mia passione per lo sviluppo software.
Oggi metto questa esperienza al servizio di imprese, professionisti e startup, creando soluzioni digitali su misura che automatizzano processi, ottimizzano risorse e aprono nuove opportunità di business. Perché la vera innovazione inizia quando la tecnologia incontra le esigenze reali delle persone.
Mijn Vaardigheden
Analisi Dati & Modelli Previsionali
Trasformo i dati in insights strategici con analisi approfondite e modelli predittivi per decisioni informate
Procesautomatisering
Creo strumenti personalizzati che automatizzano operazioni ripetitive e liberano tempo per attività a valore aggiunto
Maatwerksystemen
Sviluppo sistemi software su misura, dalle integrazioni tra piattaforme alle dashboard personalizzate
const federico = {
nome: "Federico Calò",
ruolo: "Sviluppatore Software",
città: "Bari, Italia",
missione: "Aiutare attraverso l'informatica",
passioni: [
"Codice Pulito",
"Innovazione",
"Crescita Continua"
]
};
Mijn Missie
Credo fermamente che l'informatica sia lo strumento più potente per trasformare le idee in realtà e migliorare la vita delle persone.
Technologie Democratiseren
La mia missione è rendere l'informatica accessibile a tutti: dalle piccole imprese locali alle startup innovative, fino ai professionisti che vogliono digitalizzare la propria attività. Ogni realtà merita di sfruttare le potenzialità del digitale.
IT en Business Verenigen
Non è solo questione di scrivere codice: è capire come la tecnologia possa generare valore reale. Intrecciando competenze informatiche e visione economica, aiuto le attività a crescere, ottimizzare processi e raggiungere nuovi traguardi di efficienza e redditività.
Maatwerkoplossingen Creëren
Ogni attività è unica, e così devono esserlo le soluzioni. Sviluppo strumenti personalizzati che rispondono alle esigenze specifiche di ciascun cliente, automatizzando processi ripetitivi e liberando tempo per ciò che conta davvero: far crescere il business.
Transformeer Uw Bedrijf met Technologie
Che tu gestisca un negozio, uno studio professionale o un'azienda, posso aiutarti a sfruttare le potenzialità dell'informatica per lavorare meglio, più velocemente e in modo più intelligente.
Laten We Praten →Unisciti alla Community
Entra nella community di sviluppatori dove discutiamo di software, AI, architettura e DevOps. Condividi idee, fai domande e cresci insieme a noi.
CanaleFC Dev Blog
Ricevi notifiche su nuovi articoli, serie complete, tips settimanali e tool in evidenza. Contenuti bilingui IT/EN direttamente nel tuo Telegram.
Nuovi articoli appena pubblicati Tips e code snippets settimanali Sondaggi sugli argomenti futuri
Iscriviti al CanaleGruppoFC Dev Community
Una community bilingue IT/EN per sviluppatori. Discussioni, Q&A, aiuto reciproco e networking con altri professionisti del settore.
Discussioni su articoli e tecnologie Help coding e code review Opportunità di lavoro e collaborazione
Unisciti al GruppoTopic di Discussione
#general #articles #help-coding #ai-ml #devops-cloud #architecture #tools #jobs-opportunitiesFormazione & Competenze
Il mio percorso accademico e le tecnologie che padroneggio
Certificazioni Professionali
8 certificazioni conseguite
Linguaggi & Tecnologie
Java Python JavaScript Angular React TypeScript SQL PHP CSS/SCSS Node.js Docker GitNeem Contact Op
Heeft u een project in gedachten? Laten we praten! Vul het formulier in en ik reageer snel.
* Campi obbligatori. I tuoi dati saranno utilizzati solo per rispondere alla tua richiesta.
# Risorse che richiedono naming convention
resources_requiring_naming := {
"aws_s3_bucket",
"aws_rds_instance",
"aws_elasticache_cluster",
"aws_eks_cluster",
}
# Deny se il nome non segue la convention
deny[msg] {
resource := input.resource[resource_type][resource_name]
resource_type in resources_requiring_naming
name := resource.config.bucket[0].constant_value # per S3
not regex.match(naming_pattern, name)
msg := sprintf(
"POLICY VIOLATION: %s '%s' ha nome '%s' che non rispetta la naming convention '%s'",
[resource_type, resource_name, name, naming_pattern]
)
}
# policy/terraform/tags.rego
# Policy: tag obbligatori su tutte le risorse AWS
package main
# Tag obbligatori per compliance e cost allocation
required_tags := {
"Team",
"Environment",
"CostCenter",
"ManagedBy",
}
# Risorse che devono avere tag
taggable_resources := {
"aws_instance",
"aws_s3_bucket",
"aws_rds_instance",
"aws_eks_cluster",
"aws_lambda_function",
}
deny[msg] {
resource := input.resource[resource_type][resource_name]
resource_type in taggable_resources
# Ottieni i tag dalla configurazione Terraform (formato piano JSON)
tags := resource.config.tags[0].constant_value
# Verifica che ogni tag obbligatorio sia presente
required_tag := required_tags[_]
not tags[required_tag]
msg := sprintf(
"POLICY VIOLATION: %s '%s' manca il tag obbligatorio '%s'",
[resource_type, resource_name, required_tag]
)
}
# Policy: il tag 'Environment' deve avere un valore valido
deny[msg] {
resource := input.resource[resource_type][resource_name]
resource_type in taggable_resources
tags := resource.config.tags[0].constant_value
env := tags.Environment
not env in {"dev", "staging", "production"}
msg := sprintf(
"POLICY VIOLATION: %s '%s' tag Environment='%s' non valido. Deve essere dev|staging|production",
[resource_type, resource_name, env]
)
}
# policy/terraform/regions.rego
# Policy: deploy permesso solo nelle regioni EU (GDPR compliance)
package main
allowed_regions := {"eu-west-1", "eu-west-2", "eu-central-1", "eu-south-1"}
deny[msg] {
resource := input.resource[resource_type][resource_name]
region := resource.config.region[0].constant_value
not region in allowed_regions
msg := sprintf(
"POLICY VIOLATION: %s '%s' usa la regione '%s' non permessa per compliance GDPR. Regioni ammesse: %v",
[resource_type, resource_name, region, allowed_regions]
)
}
# Uso di conftest con piano Terraform in JSON
# 1. Genera il piano Terraform in formato JSON
terraform init
terraform plan -out=tfplan
terraform show -json tfplan > tfplan.json
# 2. Esegui conftest con le policy
conftest test tfplan.json --policy policy/terraform/
# Output esempio:
# FAIL - tfplan.json - main - POLICY VIOLATION: aws_s3_bucket 'logs' manca il tag obbligatorio 'CostCenter'
# FAIL - tfplan.json - main - POLICY VIOLATION: aws_s3_bucket 'data' usa la regione 'us-east-1' non permessa per compliance GDPR
# 2 tests, 2 failures
# Test con output strutturato JSON
conftest test tfplan.json --policy policy/ --output json
# Test con namespace specifico
conftest test tfplan.json --policy policy/ --namespace main
CI Pipeline geïntegreerd met alle tools
# .github/workflows/security-scan.yml
name: IaC Security Scan
on:
pull_request:
paths:
- '**.tf'
- '**.tfvars'
jobs:
checkov:
name: Checkov Scan
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
- name: Run Checkov
uses: bridgecrewio/checkov-action@v12
with:
directory: .
framework: terraform
output_format: sarif
output_file_path: reports/checkov.sarif
soft_fail: true # Non blocca la pipeline su LOW/MEDIUM
- name: Upload SARIF to GitHub Code Scanning
uses: github/codeql-action/upload-sarif@v3
if: always()
with:
sarif_file: reports/checkov.sarif
trivy:
name: Trivy Scan
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
- name: Run Trivy
uses: aquasecurity/trivy-action@master
with:
scan-type: 'config'
scan-ref: '.'
format: 'sarif'
output: 'trivy.sarif'
severity: 'HIGH,CRITICAL'
exit-code: '1' # Blocca la pipeline su HIGH/CRITICAL
- name: Upload Trivy SARIF
uses: github/codeql-action/upload-sarif@v3
if: always()
with:
sarif_file: trivy.sarif
opa-policy:
name: OPA Policy Check
runs-on: ubuntu-latest
needs: [checkov, trivy]
steps:
- uses: actions/checkout@v4
- name: Setup Terraform
uses: hashicorp/setup-terraform@v3
with:
terraform_version: '1.7.5'
- name: Configure AWS Credentials
uses: aws-actions/configure-aws-credentials@v4
with:
role-to-assume: ${{ secrets.TERRAFORM_PLAN_ROLE }}
aws-region: eu-west-1
- name: Generate Terraform Plan JSON
run: |
cd environments/production
terraform init -no-color
terraform plan -out=tfplan -no-color
terraform show -json tfplan > ../../tfplan.json
- name: Install conftest
run: |
curl -L https://github.com/open-policy-agent/conftest/releases/download/v0.49.0/conftest_0.49.0_linux_amd64.tar.gz | tar xz
sudo mv conftest /usr/local/bin/
- name: Run OPA Policies
run: |
conftest test tfplan.json --policy policy/terraform/ --output json | tee opa-results.json
# Fallisce se ci sono violation
jq -e '.[] | select(.failures | length > 0)' opa-results.json && exit 1 || exit 0
Dekkingsmatrix: welke hulpmiddelen voor welke risico's
| Risico | Checkov | Trivia | OPA |
|---|---|---|---|
| S3 openbare toegang | Ja (CKV_AWS_20) | Si | Aangepast |
| Versleuteling in rust ontbreekt | Ja (veel controles) | Si | No |
| Beveiligingsgroep te tolerant | Si | Si | No |
| Er ontbreken verplichte tags | Gedeeltelijk | No | Ja (aangepaste Rego) |
| Naamgevingsconventie | No | No | Ja (aangepaste Rego) |
| Regio's die niet zijn toegestaan (AVG) | No | No | Ja (aangepaste Rego) |
| Geheimen in de code | Gedeeltelijk | Ja (geheim scannen) | No |
| Kwetsbaarheden in containers | No | Si | No |
| Kwetsbare verslavingen | No | Si | No |
Conclusies en volgende stappen
De combinatie van Checkov (ingebouwde brede dekking), Trivy (unified scanner) en OPA (aangepast organisatiebeleid) vormt een gelaagde verdediging die het meeste dekt onderdeel van de veiligheidsrisico’s in IaC. Het belangrijkste principe is dat deze instrumenten moeten PR-samenvoeging blokkeren en mogen geen afwijsbare waarschuwingen zijn.
Volgende artikelen in de serie
- Artikel 7: Terraform Multi-Cloud — AWS + Azure + GCP met Gedeelde modules: bouw een abstractielaag om meerdere providers te beheren met een uniforme interface.
- Artikel 8: GitOps voor Terraform — Flux TF-controller e Driftdetectie: brengt Terraform in het GitOps-paradigma met voortdurende afstemming.







