Communitygithub.com

Terraform-Infrastruktur-Sicherheitsprüfung

Prüft Terraform Infrastructure-as-Code auf Sicherheitsfehlkonfigurationen

Was ist Terraform-Infrastruktur-Sicherheitsprüfung?

Diese Fähigkeit dient der umfassenden Sicherheitsprüfung von Terraform-Infrastruktur (IaC) vor der Bereitstellung. Sie integriert mehrere führende Open-Source-Tools wie Checkov, tfsec und Terrascan, um Hunderte von vordefinierten Sicherheitsregeln (CIS, NIST, SOC 2) automatisch zu evaluieren. Darüber hinaus ermöglicht sie die Erstellung individueller Sicherheitsrichtlinien mit OPA (Open Policy Agent) und Rego, um organisationsspezifische Compliance-Anforderungen durchzusetzen. Der Workflow führt den Benutzer Schritt für Schritt vom ersten Scan über die Plan-Validierung bis zur Integration in CI/CD-Pipelines und zur Prüfung bereits deployter Terraform-Zustände. Die Fähigkeit ist plattformunabhängig und funktioniert mit jeder Terraform-basierten Cloud-Umgebung (AWS, Azure, GCP) und kann direkt in GitHub Actions, GitLab CI oder andere CI/CD-Systeme eingebunden werden. Sie ist ideal für DevOps-Teams, die Sicherheit früh im Entwicklungszyklus (Shift Left) verankern und Security-Gates für Pull-Requests etablieren möchten.

Funktioniert mit~Claude Code~Codex CLI~Cursor
npx skills add https://github.com/mukul975/Anthropic-Cybersecurity-Skills/tree/main/skills/auditing-terraform-infrastructure-for-security

In Ihrer bevorzugten KI fragen

Öffnet einen neuen Chat, in dem dieser Agent-Skill bereits geladen ist.

Dokumentation

Was macht Terraform-Infrastruktur-Sicherheitsprüfung?

Wann verwenden

  • Beim Integrieren von Sicherheitsscans in CI/CD-Pipelines für Terraform-Deployments
  • Beim Überprüfen von Terraform-Plänen und -Modulen auf Sicherheitsbest Practices vor dem Anwenden
  • Beim Einrichten von Policy-as-Code-Schranken für die Cloud-Infrastrukturbereitstellung
  • Beim Prüfen vorhandener Terraform-Statusdateien, um bereits deployte Fehlkonfigurationen zu identifizieren
  • Beim Durchsetzen organisatorischer Sicherheitsstandards über mehrere Terraform-Projekte hinweg

Nicht verwenden für Runtime-Sicherheitsüberwachung (CSPM-Tools verwenden), für Anwendungssicherheitstests (SAST/DAST-Tools verwenden) oder für Erkennung von Cloud-Konfigurationsabweichungen (AWS Config oder Azure Policy nach dem Deployment verwenden).

Voraussetzungen

  • Checkov installiert (pip install checkov)
  • tfsec installiert (brew install tfsec oder Binary von GitHub)
  • Terrascan installiert (brew install terrascan)
  • Terraform v1.0+ für Plan-Erstellung
  • OPA (Open Policy Agent) für benutzerdefinierte Richtliniendurchsetzung
  • Git-Repository mit Terraform-Code zur Prüfung

Arbeitsablauf

Schritt 1: Terraform-Code mit Checkov scannen

Führen Sie Checkov für umfassende IaC-Sicherheitsscans mit integrierten und benutzerdefinierten Richtlinien aus.

# Ein Terraform-Verzeichnis scannen
checkov -d ./terraform/ --framework terraform

# Mit bestimmten Prüfkategorien scannen
checkov -d ./terraform/ --check CKV_AWS_18,CKV_AWS_19,CKV_AWS_20,CKV_AWS_21

# Ergebnisse als JSON ausgeben
checkov -d ./terraform/ --output json > checkov-results.json

# Eine Terraform-Plan-Datei für genauere Analyse scannen
terraform init && terraform plan -out=tfplan
terraform show -json tfplan > tfplan.json
checkov -f tfplan.json --framework terraform_plan

# Bestimmte Prüfungen mit Begründung überspringen
checkov -d ./terraform/ --skip-check CKV_AWS_145 \
  --bc-api-key $BRIDGECREW_API_KEY

# Terraform-Module scannen
checkov -d ./modules/ --framework terraform --compact

# Alle verfügbaren Prüfungen auflisten
checkov --list --framework terraform | grep CKV_AWS

Schritt 2: Mit tfsec auf terraformspezifische Probleme scannen

Verwenden Sie tfsec für eine Terraform-native Sicherheitsanalyse mit detaillierter Behebungsanleitung.

# Ein Terraform-Verzeichnis scannen
tfsec ./terraform/

# Mit minimalem Schweregradschwellwert scannen
tfsec ./terraform/ --minimum-severity HIGH

# Ausgabe im JSON-Format für CI/CD-Verarbeitung
tfsec ./terraform/ --format json > tfsec-results.json

# Mit benutzerdefinierten Prüfungen scannen
tfsec ./terraform/ --custom-check-dir ./custom-checks/

# Bestimmte Regeln ausschließen
tfsec ./terraform/ --exclude-downloaded-modules \
  --exclude aws-s3-enable-bucket-logging

# Scannen und bei bestimmten Schweregrad fehlschlagen lassen
tfsec ./terraform/ --minimum-severity CRITICAL --soft-fail

# SARIF-Ausgabe für den GitHub-Sicherheitstab generieren
tfsec ./terraform/ --format sarif > tfsec.sarif

Schritt 3: Terrascan für Multi-Framework-Compliance ausführen

Führen Sie Terrascan zur Compliance-Prüfung gegen CIS-, NIST- und SOC-2-Frameworks aus.

# Terraform gegen den CIS-AWS-Benchmark scannen
terrascan scan -t aws -i terraform -d ./terraform/ \
  --policy-type aws --verbose

# Gegen bestimmte Compliance-Frameworks scannen
terrascan scan -t aws -i terraform -d ./terraform/ \
  --policy-type aws \
  --categories "Compliance Validation"

# Ausgabe im JSON-Format
terrascan scan -t aws -i terraform -d ./terraform/ \
  --output json > terrascan-results.json

# Einen Terraform-Plan scannen
terrascan scan -t aws -i terraform \
  --iac-file tfplan.json \
  --iac-type tfplan

# Verfügbare Richtlinien auflisten
terrascan scan --list-policies -t aws

Schritt 4: Benutzerdefinierte OPA-Richtlinien für Organisationsstandards erstellen

Schreiben Sie Rego-Richtlinien für organisatorische Sicherheitsanforderungen.

# policy/aws_s3_encryption.rego
package terraform.aws.s3

deny[msg] {
    resource := input.resource.aws_s3_bucket[name]
    not resource.server_side_encryption_configuration
    msg := sprintf("S3-Bucket '%s' muss serverseitige Verschlüsselung aktiviert haben", [name])
}

# policy/aws_iam_no_wildcards.rego
package terraform.aws.iam

deny[msg] {
    resource := input.resource.aws_iam_policy[name]
    statement := resource.policy.Statement[_]
    statement.Action == "*"
    statement.Effect == "Allow"
    msg := sprintf("IAM-Richtlinie '%s' darf keine Wildcard-Aktionen (*) verwenden", [name])
}

deny[msg] {
    resource := input.resource.aws_iam_policy[name]
    statement := resource.policy.Statement[_]
    statement.Resource == "*"
    statement.Effect == "Allow"
    contains(statement.Action[_], "*")
    msg := sprintf("IAM-Richtlinie '%s' hat zu freizügige Aktionen auf Wildcard-Ressourcen", [name])
}

# policy/aws_no_public_ingress.rego
package terraform.aws.security_group

deny[msg] {
    resource := input.resource.aws_security_group_rule[name]
    resource.type == "ingress"
    resource.cidr_blocks[_] == "0.0.0.0/0"
    resource.from_port <= 22
    resource.to_port >= 22
    msg := sprintf("Security Group Regel '%s' erlaubt SSH von 0.0.0.0/0", [name])
}
# Terraform-Plan gegen OPA-Richtlinien auswerten
terraform show -json tfplan | opa eval \
  --data ./policy/ \
  --input /dev/stdin \
  "data.terraform.aws" \
  --format pretty

# Conftest für einfachere OPA-Richtlinientests ausführen
conftest test tfplan.json --policy ./policy/ --output json

Schritt 5: Sicherheitsscan in CI/CD-Pipeline integrieren

Fügen Sie IaC-Sicherheitsscans als obligatorisches CI/CD-Gate hinzu.

# GitHub Actions: Terraform-Sicherheitspipeline
name: Terraform Security Scan
on:
  pull_request:
    paths: ['terraform/**']

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

      - name: Setup Terraform
        uses: hashicorp/setup-terraform@v3

      - name: Terraform Init & Plan
        run: |
          cd terraform/
          terraform init
          terraform plan -out=tfplan
          terraform show -json tfplan > tfplan.json

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

      - name: tfsec Scan
        uses: aquasecurity/[email protected]
        with:
          working_directory: terraform/
          soft_fail: false

      - name: Upload SARIF
        uses: github/codeql-action/upload-sarif@v2
        with:
          sarif_file: checkov.sarif

      - name: OPA Policy Check
        run: |
          conftest test terraform/tfplan.json \
            --policy ./policy/ \
            --output json

Schritt 6: Terraform-Status auf bereits deployte Fehlkonfigurationen scannen

Prüfen Sie den aktuellen Terraform-Status auf bereits deployte Sicherheitsprobleme.

# Aktuellen Status als JSON exportieren
terraform show -json > terraform-state.json

# Status mit Checkov scannen
checkov -f terraform-state.json --framework terraform_plan

# Status nach bestimmten Sicherheitsproblemen durchsuchen
terraform state list | while read resource; do
  terraform state show "$resource" 2>/dev/null | grep -i "public\|0.0.0.0\|encrypt.*false\|password"
done

# Ressourcen ohne erforderliche Tags finden
terraform state list | grep aws_instance | while read resource; do
  tags=$(terraform state show "$resource" | grep -A20 "tags")
  if ! echo "$tags" | grep -q "Environment"; then
    echo "FEHLENDER TAG: $resource besitzt keinen 'Environment'-Tag"
  fi
done

Schlüsselkonzepte

BegriffDefinition
Infrastructure as CodePraxis der Verwaltung von Cloud-Infrastruktur durch deklarative Konfigurationsdateien (Terraform, CloudFormation) anstatt manueller Konsolenoperationen
Policy as CodeAusdrücken von Sicherheits- und Compliance-Richtlinien als ausführbarer Code (Rego, Python), der automatisch gegen Infrastrukturdefinitionen ausgewertet werden kann
Shift Left SecuritySicherheitsprüfungen früher im Entwicklungslebenszyklus durchführen, indem IaC vor dem Deployment gescannt wird, anstatt nach der Bereitstellung zu prüfen
Terraform PlanVorschau der Änderungen, die Terraform vornehmen wird; kann als JSON für Sicherheitsscans vor dem Anwenden exportiert werden
CheckovOpen-Source-Statikanalysewerkzeug für IaC mit Unterstützung für Terraform, CloudFormation, Kubernetes und Docker mit über 1.000 integrierten Richtlinien
OPA/RegoOpen Policy Agent und seine Richtliniensprache Rego zum Definieren benutzerdefinierter Sicherheitsregeln, die gegen strukturierte Dateneingaben ausgewertet werden

Werkzeuge und Systeme

  • Checkov: Umfassender IaC-Scanner mit über 1.000 Richtlinien für Terraform, CloudFormation, Kubernetes, ARM und Dockerfile
  • tfsec: Terraform-spezifisches Statikanalysewerkzeug mit detaillierter Behebungsanleitung und SARIF-Ausgabe
  • Terrascan: Multi-IaC-Scanner mit Unterstützung für Compliance-Frameworks (CIS, NIST, SOC 2) und Policy-as-Code
  • OPA/Conftest: Benutzerdefinierte Richtlinien-Engine zum Definieren organisationsspezifischer Sicherheitsregeln mit der Rego-Sprache
  • Bridgecrew: Kommerzielle Plattform auf Basis von Checkov mit Abweichungserkennung und Supply-Chain-Sicherheit

Häufige Szenarien

Szenario: Sicherheitsgates zu einer bestehenden Terraform-CI/CD-Pipeline hinzufügen

Kontext: Ein DevOps-Team stellt Infrastruktur über Terraform in GitHub Actions bereit, hat aber keine Sicherheitsscans. Aktuelle Audit-Ergebnisse zeigen mehrere S3-Buckets ohne Verschlüsselung und Security Groups, die SSH aus dem Internet erlauben.

Vorgehen:

  1. Checkov als erstes Sicherheitsgate im GitHub Actions-Workflow hinzufügen
  2. checkov -d ./terraform/ ausführen, um die aktuelle Basis an Fundstellen zu ermitteln
  3. Vorhandene Fundstellen priorisieren: KRITISCHE Probleme beheben, Tickets für HOHE erstellen, akzeptierte Risiken unterdrücken
  4. tfsec als sekundären Scanner für terraformspezifische Prüfungen hinzufügen
  5. Benutzerdefinierte OPA-Richtlinien für Organisationsstandards schreiben (erforderliche Tags, Namenskonventionen)
  6. Pipeline so konfigurieren, dass sie PRs mit KRITISCHEN oder HOHEN Fundstellen blockiert
  7. SARIF-Berichte für die Integration in den GitHub-Sicherheitstab erstellen

Fallstricke: Das Hinzufügen von Sicherheitsscans zu einem bestehenden Projekt wird anfangs Hunderte von Fundstellen erzeugen. Graduell implementieren, indem zunächst nur KRITISCHE Fundstellen blockiert werden, dann auf HOHE erweitern. Inline-Unterdrückungskommentare (#checkov:skip=CKV_AWS_18:Öffentlicher Bucket für statische Website) für beabsichtigte Ausnahmen mit dokumentierter Begründung verwenden.

Ausgabeformat

Terraform Security Audit Report
==================================
Repository: acme-corp/infrastructure
Branch: main
Scan-Datum: 2026-02-23
Werkzeuge: Checkov 3.x, tfsec 1.x, OPA benutzerdefinierte Richtlinien

SCAN-ERGEBNISSE:
  Checkov-Prüfungen bestanden:    187
  Checkov-Prüfungen fehlgeschlagen: 34
  tfsec-Prüfungen bestanden:      156
  tfsec-Prüfungen fehlgeschlagen: 28
  OPA benutzerdefinierte Richtlinien: 12 bestanden, 3 fehlgeschlagen

KRITISCHE FUNDSTELLEN:
[TF-001] S3-Bucket ohne Verschlüsselung
  Datei: modules/storage/main.tf:24
  Ressource: aws_s3_bucket.data_lake
  Prüfung: CKV_AWS_19
  Behebung: server_side_encryption_configuration-Block hinzufügen

[TF-002] Security Group erlaubt SSH von 0.0.0.0/0
  Datei: modules/network/security.tf:45
  Ressource: aws_security_group_rule.ssh_access
  Prüfung: CKV_AWS_24
  Behebung: cidr_blocks auf Bastion-Subnetz einschränken

[TF-003] IAM-Richtlinie mit Wildcard-Aktionen
  Datei: modules/iam/policies.tf:12
  Ressource: aws_iam_policy.developer_policy
  Prüfung: CKV_AWS_1
  Behebung: Aktionen auf die erforderlichen spezifischen Dienste eingrenzen

ZUSAMMENFASSUNG NACH SCHWEREGRAD:
  Kritisch:  6 Fundstellen
  Hoch:     14 Fundstellen
  Mittel:   28 Fundstellen
  Niedrig:  18 Fundstellen
  Info:     12 Fundstellen

Individual skills in this repo

This repo contains 20 individual skills — each has its own dedicated page.

abusing-dpapi-for-credential-access

Extract and decrypt Windows DPAPI-protected secrets (Credential Manager, browser logins/cookies, Wi-Fi credentials, KeePass keys) online or offline using SharpDPAPI, SharpChrome, Mimikatz, or Impacket

abusing-shadow-credentials-for-privesc

Take over Active Directory accounts by writing attacker-controlled public keys to msDS-KeyCredentialLink (Shadow Credentials) with pyWhisker, Whisker, or Certipy, then authenticate via PKINIT to recover the target

achieving-cmmc-level-2-compliance

>-

acquiring-disk-image-with-dd-and-dcfldd

Create forensically sound bit-for-bit disk images with dd or dcfldd on a Linux forensic workstation, preserving evidence integrity through hash verification (MD5/SHA) during acquisition. Use when imaging a suspect drive, USB device, or memory card for investigation, preserving volatile disk evidence during incident response, or producing a verified copy for legal or law-enforcement proceedings before any destructive analysis.

analyzing-active-directory-acl-abuse

Detect dangerous ACL misconfigurations in Active Directory using ldap3

analyzing-android-malware-with-apktool

Perform static analysis of Android APK malware using apktool for resource decompilation, jadx for Java source recovery, and androguard for manifest inspection, dangerous permission-combination detection, and identification of obfuscated code, dynamic code loading, and reflection-based API calls. Use to statically triage a suspicious APK without executing it or to build mobile malware detection rules.

analyzing-api-gateway-access-logs

Parses API Gateway access logs (AWS API Gateway, Kong, Nginx) to detect

analyzing-apt-group-with-mitre-navigator

Query ATT&CK data with attackcti, mitreattack-python, and stix2, then build MITRE ATT&CK Navigator layers and multi-layer heatmap overlays mapping one or more APT groups

analyzing-azure-activity-logs-for-threats

Queries Azure Monitor activity logs and sign-in logs via azure-monitor-query

analyzing-bootkit-and-rootkit-samples

Analyzes bootkit and advanced rootkit malware infecting the Master

analyzing-browser-forensics-with-hindsight

Parse Chromium-based browser databases with Hindsight to extract and correlate browsing history, downloads, cookies, cached content, autofill data, saved passwords, and extensions from Chrome, Edge, Brave, Opera, and Vivaldi into a unified timeline (XLSX, JSON, or SQLite output). Use during incident response, insider-threat investigations, or criminal cases when you need to reconstruct a user

analyzing-campaign-attribution-evidence

Systematically evaluate cyber-campaign evidence to attribute an operation to a threat actor, using the Diamond Model and Analysis of Competing Hypotheses (ACH) to weigh infrastructure overlaps, TTP consistency, malware code similarity, and timing/language artifacts into confidence-weighted attribution assessments. Use when an incident investigation needs a defensible attribution confidence level.

analyzing-certificate-transparency-for-phishing

Monitor Certificate Transparency logs using crt.sh and Certstream to

analyzing-cloud-storage-access-patterns

Detect abnormal access in AWS S3, GCS, and Azure Blob Storage by analyzing CloudTrail Data Events, GCS audit logs, and Azure Storage Analytics for after-hours bulk downloads, new-IP access, and API-call spikes (e.g. GetObject) via statistical baselines and time-series anomaly detection. Use when investigating suspected cloud data exfiltration or building related detection rules.

analyzing-cobalt-strike-beacon-configuration

Extract and analyze Cobalt Strike beacon configuration from PE files

analyzing-cobaltstrike-malleable-c2-profiles

Parse and analyze Cobalt Strike Malleable C2 profiles with dissect.cobaltstrike (profiles and beacon-payload configs) and pyMalleableC2 (AST parsing) to extract HTTP/DNS transforms, URIs, headers, sleep/jitter, and injection behavior, then generate network detection signatures. Use when reverse-engineering a captured malleable profile or building detections against Cobalt Strike Beacon traffic.

analyzing-command-and-control-communication

Analyzes malware C2 communication over HTTP, HTTPS, DNS, and custom

analyzing-cyber-kill-chain

Analyzes intrusion activity against the Lockheed Martin Cyber Kill Chain

analyzing-disk-image-with-autopsy

Perform comprehensive forensic analysis of raw (dd), E01, or AFF disk images with Autopsy and The Sleuth Kit, recovering deleted files, examining metadata and embedded artifacts, keyword searching, and building investigation timelines with visual reports. Use for structured analysis of a forensic disk image or when stakeholders need visual reports from evidence.

analyzing-dns-logs-for-exfiltration

Analyzes DNS query logs to detect data exfiltration via DNS tunneling,

Verwandte Skills