Zum Inhalt springen

Checkov Cheat Sheet

Überblick

Checkov ist ein statisches Code-Analyse-Tool für Infrastructure as Code (IaC), das Cloud-Infrastruktur scannt, die mit Terraform, CloudFormation, Kubernetes, Helm, ARM Templates und Serverless Framework bereitgestellt wird. Es erkennt Sicherheits- und Compliance-Fehlkonfigurationen und bietet Behebungshinweise.

⚠️ Hinweis: Kostenloses und Open-Source-Tool. Premium-Funktionen verfügbar über die Bridgecrew/Prisma Cloud-Plattform.

Installation

Python-Paket

# Install via pip
pip install checkov

# Install specific version
pip install checkov==2.5.0

# Upgrade to latest version
pip install --upgrade checkov

# Install with additional dependencies
pip install checkov[secrets]

Docker

# Run with Docker
docker run --rm -it \
  -v $(pwd):/tf \
  bridgecrew/checkov:latest \
  -d /tf

# Docker with specific version
docker run --rm -it \
  -v $(pwd):/tf \
  bridgecrew/checkov:2.5.0 \
  -d /tf

Homebrew (macOS)

# Install via Homebrew
brew install checkov

# Upgrade
brew upgrade checkov

Binäre Herunterladen

# Download binary (Linux)
wget https://github.com/bridgecrewio/checkov/releases/latest/download/checkov-linux
chmod +x checkov-linux
sudo mv checkov-linux /usr/local/bin/checkov

# Download binary (macOS)
wget https://github.com/bridgecrewio/checkov/releases/latest/download/checkov-darwin
chmod +x checkov-darwin
sudo mv checkov-darwin /usr/local/bin/checkov

Grundlegende Nutzung

Scan-Befehle

# Scan current directory
checkov -d .

# Scan specific file
checkov -f main.tf

# Scan multiple files
checkov -f main.tf -f variables.tf

# Scan with specific framework
checkov -d . --framework terraform

# Scan multiple frameworks
checkov -d . --framework terraform,kubernetes

Ausgabeformate

# JSON output
checkov -d . -o json

# JUnit XML output
checkov -d . -o junitxml

# SARIF output
checkov -d . -o sarif

# CSV output
checkov -d . -o csv

# Multiple output formats
checkov -d . -o cli,json,junitxml

In Datei ausgeben

# Save results to file
checkov -d . -o json --output-file-path results.json

# Save with timestamp
checkov -d . -o json --output-file-path "results-$(date +%Y%m%d-%H%M%S).json"

# Multiple formats to different files
checkov -d . -o json --output-file-path results.json -o junitxml --output-file-path results.xml

Framework-spezifisches Scannen

Terraform

# Scan Terraform files
checkov -d . --framework terraform

# Scan specific Terraform file
checkov -f main.tf

# Scan with Terraform plan
terraform plan -out=tfplan.binary
terraform show -json tfplan.binary > tfplan.json
checkov -f tfplan.json --framework terraform_plan

# Skip Terraform parsing errors
checkov -d . --framework terraform --skip-parsing-errors

CloudFormation

# Scan CloudFormation templates
checkov -d . --framework cloudformation

# Scan specific template
checkov -f template.yaml --framework cloudformation

# Scan with parameters
checkov -f template.yaml --framework cloudformation --var-file parameters.json

Kubernetes

# Scan Kubernetes manifests
checkov -d . --framework kubernetes

# Scan specific manifest
checkov -f deployment.yaml --framework kubernetes

# Scan Helm charts
checkov -d ./charts --framework helm

# Scan with Helm values
helm template myapp ./chart | checkov -f - --framework kubernetes

Docker

# Scan Dockerfile
checkov -f Dockerfile --framework dockerfile

# Scan Docker Compose
checkov -f docker-compose.yml --framework docker_compose

# Scan all Docker files
checkov -d . --framework dockerfile,docker_compose

Check-Verwaltung

Bestimmte Checks überspringen

# Skip single check
checkov -d . --skip-check CKV_AWS_20

# Skip multiple checks
checkov -d . --skip-check CKV_AWS_20,CKV_AWS_21

# Skip check categories
checkov -d . --skip-check CKV_AWS_*

# Skip using file
echo "CKV_AWS_20" > .checkov.skip
echo "CKV_AWS_21" >> .checkov.skip
checkov -d . --skip-check-file .checkov.skip

Bestimmte Checks ausführen

# Run only specific checks
checkov -d . --check CKV_AWS_20

# Run multiple specific checks
checkov -d . --check CKV_AWS_20,CKV_AWS_21

# Run checks by severity
checkov -d . --check HIGH,CRITICAL

Check-Informationen

# List all available checks
checkov --list

# List checks for specific framework
checkov --list --framework terraform

# Get check details
checkov --check CKV_AWS_20 --list

# Search for checks
checkov --list | grep -i "encryption"

Konfigurationsdateien

.checkov.yml

# .checkov.yml configuration file
branch: main
check:
  - CKV_AWS_20
  - CKV_AWS_21
skip-check:
  - CKV_AWS_52
framework:
  - terraform
  - kubernetes
output: json
quiet: true
compact: true
directory:
  - ./terraform
  - ./k8s
file:
  - ./main.tf
download-external-modules: true
evaluate-variables: true

.checkov.yaml (Alternative)

# Alternative YAML configuration
checkov:
  framework:
    - terraform
    - cloudformation
  directory:
    - ./infrastructure
  skip-check:
    - CKV_AWS_79  # S3 bucket encryption
    - CKV_AWS_144 # S3 bucket replication
  check:
    - HIGH
    - CRITICAL
  output:
    - cli
    - json
  output-file-path: ./checkov-results.json
  quiet: false
  compact: true

Umgebungsvariablen

# Set configuration via environment variables
export CHECKOV_FRAMEWORK=terraform,kubernetes
export CHECKOV_SKIP_CHECK=CKV_AWS_20,CKV_AWS_21
export CHECKOV_CHECK=HIGH,CRITICAL
export CHECKOV_OUTPUT=json
export CHECKOV_OUTPUT_FILE_PATH=results.json
export CHECKOV_QUIET=true
export CHECKOV_COMPACT=true

# Run with environment configuration
checkov -d .

Inline-Unterdrückungen

Terraform-Unterdrückungen

# Suppress specific check
resource "aws_s3_bucket" "example" {
  #checkov:skip=CKV_AWS_20:Reason for skipping
  bucket = "my-bucket"
}

# Suppress multiple checks
resource "aws_instance" "example" {
  #checkov:skip=CKV_AWS_79:Skip encryption check
  #checkov:skip=CKV_AWS_8:Skip security group check
  ami           = "ami-12345678"
  instance_type = "t2.micro"
}

# Suppress with detailed reason
resource "aws_db_instance" "example" {
  #checkov:skip=CKV_AWS_16:Database encryption not required for test environment
  engine         = "mysql"
  instance_class = "db.t2.micro"
}

CloudFormation-Unterdrückungen

Would you like me to continue with the remaining sections?```yaml

CloudFormation suppression

Resources: MyBucket: Type: AWS::S3::Bucket Metadata: checkov: skip: - id: CKV_AWS_20 comment: “Encryption not required for public assets” Properties: BucketName: my-public-bucket


### Kubernetes Suppressions
```yaml
# Kubernetes suppression
apiVersion: apps/v1
kind: Deployment
metadata:
  name: nginx
  annotations:
    checkov.io/skip1: CKV_K8S_20=Allow privilege escalation for system pods
    checkov.io/skip2: CKV_K8S_23=Root user required for nginx
spec:
  template:
    spec:
      containers:
      - name: nginx
        image: nginx:latest

CI/CD Integration

GitHub Actions

# .github/workflows/checkov.yml
name: Checkov Security Scan

on:
  push:
    branches: [ main, develop ]
  pull_request:
    branches: [ main ]

jobs:
  checkov:
    runs-on: ubuntu-latest
    steps:
    - uses: actions/checkout@v3
    
    - name: Set up Python
      uses: actions/setup-python@v4
      with:
        python-version: '3.9'
    
    - name: Install Checkov
      run: pip install checkov
    
    - name: Run Checkov
      run: |
        checkov -d . \
          --framework terraform,kubernetes \
          --output cli,sarif \
          --output-file-path checkov-results.sarif \
          --soft-fail
    
    - name: Upload SARIF results
      uses: github/codeql-action/upload-sarif@v2
      if: always()
      with:
        sarif_file: checkov-results.sarif

GitLab CI

# .gitlab-ci.yml
checkov:
  stage: security
  image: bridgecrew/checkov:latest
  script:
    - checkov -d . --framework terraform --output cli,json --output-file-path checkov-results.json
  artifacts:
    reports:
      junit: checkov-results.json
    paths:
      - checkov-results.json
    expire_in: 1 week
  allow_failure: true

Jenkins Pipeline

pipeline {
    agent any
    
    stages {
        stage('Checkout') {
            steps {
                checkout scm
            }
        }
        
        stage('Checkov Scan') {
            steps {
                script {
                    docker.image('bridgecrew/checkov:latest').inside {
                        sh '''
                            checkov -d . \
                                --framework terraform,kubernetes \
                                --output cli,junitxml \
                                --output-file-path checkov-results.xml \
                                --soft-fail
                        '''
                    }
                }
            }
            post {
                always {
                    publishTestResults testResultsPattern: 'checkov-results.xml'
                    archiveArtifacts artifacts: 'checkov-results.xml', fingerprint: true
                }
            }
        }
    }
}

Azure DevOps

# azure-pipelines.yml
trigger:
- main

pool:
  vmImage: 'ubuntu-latest'

steps:
- task: UsePythonVersion@0
  inputs:
    versionSpec: '3.9'

- script: |
    pip install checkov
  displayName: 'Install Checkov'

- script: |
    checkov -d . \
      --framework terraform \
      --output cli,junitxml \
      --output-file-path $(Agent.TempDirectory)/checkov-results.xml
  displayName: 'Run Checkov Scan'
  continueOnError: true

- task: PublishTestResults@2
  inputs:
    testResultsFormat: 'JUnit'
    testResultsFiles: '$(Agent.TempDirectory)/checkov-results.xml'
    testRunTitle: 'Checkov Security Scan'
  condition: always()

Custom Checks

Python Custom Check

# custom_checks/MyCustomCheck.py
from checkov.common.models.enums import CheckResult
from checkov.terraform.checks.resource.base_resource_check import BaseResourceCheck

class MyCustomCheck(BaseResourceCheck):
    def __init__(self):
        name = "Ensure S3 bucket has custom tag"
        id = "CKV_CUSTOM_1"
        supported_resources = ['aws_s3_bucket']
        categories = ['GENERAL_SECURITY']
        super().__init__(name=name, id=id, categories=categories, supported_resources=supported_resources)

    def scan_resource_conf(self, conf):
        """
        Looks for custom tag on S3 bucket
        """
        if 'tags' in conf:
            tags = conf['tags'][0]
            if isinstance(tags, dict) and 'Environment' in tags:
                return CheckResult.PASSED
        return CheckResult.FAILED

check = MyCustomCheck()

YAML Custom Check

# custom_checks/s3_custom.yaml
metadata:
  id: "CKV_CUSTOM_2"
  name: "Ensure S3 bucket has versioning enabled"
  category: "BACKUP_AND_RECOVERY"
scope:
  provider: "aws"
definition:
  and:
    - cond_type: "attribute"
      resource_types: ["aws_s3_bucket"]
      attribute: "versioning.enabled"
      operator: "equals"
      value: true

Running Custom Checks

# Run with custom check directory
checkov -d . --external-checks-dir ./custom_checks

# Run specific custom check
checkov -d . --check CKV_CUSTOM_1

# Combine built-in and custom checks
checkov -d . --external-checks-dir ./custom_checks --framework terraform

Advanced Features

Variable Evaluation

# Enable variable evaluation
checkov -d . --evaluate-variables

# With variable files
checkov -d . --var-file terraform.tfvars --evaluate-variables

# Multiple variable files
checkov -d . --var-file prod.tfvars --var-file common.tfvars --evaluate-variables

External Module Download

# Download external modules
checkov -d . --download-external-modules true

# Specify module download directory
checkov -d . --download-external-modules true --external-modules-download-path ./modules

Baseline Creation

# Create baseline from current scan
checkov -d . --create-baseline

# Use existing baseline
checkov -d . --baseline baseline.json

# Update baseline
checkov -d . --create-baseline --baseline baseline.json

Policy as Code

# Use custom policy repository
checkov -d . --external-checks-git https://github.com/myorg/custom-policies.git

# Specify branch or tag
checkov -d . --external-checks-git https://github.com/myorg/custom-policies.git --external-checks-git-branch main

# Use multiple policy sources
checkov -d . \
  --external-checks-dir ./local-policies \
  --external-checks-git https://github.com/myorg/shared-policies.git

Reporting and Integration

SARIF Integration

# Generate SARIF report
checkov -d . -o sarif --output-file-path results.sarif

# Upload to GitHub Security tab
# (automatically done with GitHub Actions SARIF upload)

SonarQube Integration

# Generate SonarQube external issues format
checkov -d . -o json | jq '[.results.failed_checks[] | {
  engineId: "checkov",
  ruleId: .check_id,
  severity: "MAJOR",
  type: "VULNERABILITY",
  primaryLocation: {
    message: .check_name,
    filePath: .file_path,
    textRange: {
      startLine: .file_line_range[0]
    }
  }
}]' > sonarqube-issues.json

Slack Notifications

# Send results to Slack webhook
checkov -d . -o json | \
  jq -r '"Checkov scan completed. Failed checks: " + (.summary.failed | tostring)' | \
  curl -X POST -H 'Content-type: application/json' \
    --data '{"text":"'"$(cat)"'"}' \
    YOUR_SLACK_WEBHOOK_URL

Performance Optimization

Parallel Execution

# Enable parallel execution
checkov -d . --framework terraform --parallel

# Specify number of workers
export CHECKOV_MAX_WORKERS=4
checkov -d . --parallel

Caching

# Enable caching
export CHECKOV_CACHE_DIR=~/.checkov_cache
checkov -d . --framework terraform

# Clear cache
rm -rf ~/.checkov_cache

Selective Scanning

# Scan only changed files (with git)
git diff --name-only HEAD~1 HEAD | grep '\.tf$' | xargs checkov -f

# Scan specific directories only
checkov -d ./terraform/modules/security --framework terraform

# Exclude large directories
checkov -d . --framework terraform --skip-path .terraform/

Troubleshooting

Common Issues

# Debug mode
checkov -d . --framework terraform --debug

# Verbose output
checkov -d . --framework terraform -v

# Skip parsing errors
checkov -d . --framework terraform --skip-parsing-errors

# Check version
checkov --version

# Update to latest
pip install --upgrade checkov

Error Resolution

# Module not found errors
pip install --upgrade checkov[secrets]

# Permission errors
sudo chown -R $USER:$USER ~/.checkov_cache

# Memory issues with large codebases
export CHECKOV_MAX_WORKERS=2
checkov -d . --compact --quiet
```### Logging-Konfiguration
```bash
# Set log level
export CHECKOV_LOG_LEVEL=DEBUG
checkov -d . --framework terraform

# Log to file
checkov -d . --framework terraform --debug 2> checkov.log
```## Best Practices

### Sicherheits-Scanning-Strategie
```bash
# 1. Start with high and critical checks
checkov -d . --check HIGH,CRITICAL

# 2. Gradually include medium severity
checkov -d . --check HIGH,CRITICAL,MEDIUM

# 3. Implement baseline for existing code
checkov -d . --create-baseline

# 4. Use soft-fail in CI initially
checkov -d . --soft-fail

# 5. Gradually remove soft-fail
checkov -d . # Hard fail on issues
```### Konfigurationsmanagement
```bash
# Use configuration files for consistency
# .checkov.yml in repository root
# Team-specific skip lists
# Framework-specific configurations
# Output format standardization
```### Integrations-Workflow
```bash
# 1. Pre-commit hooks for developers
# 2. CI/CD pipeline integration
# 3. Pull request checks
# 4. Scheduled full scans
# 5. Security dashboard reporting
```## Ressourcen

### Dokumentation
- [Checkov-Dokumentation](https://www.checkov.io/1.Welcome/Quick%20Start.html)
- [Check-Referenz](https://www.checkov.io/5.Policy%20Index/all.html)
- [Benutzerdefinierte Richtlinien](https://www.checkov.io/3.Custom%20Policies/Custom%20Policies%20Overview.html)

### Community
- [GitHub-Repository](https://github.com/bridgecrewio/checkov)
- [Slack-Community](https://slack.bridgecrew.io/)
- [Stack Overflow](https://stackoverflow.com/questions/tagged/checkov)

### Training
- [Bridgecrew Academy](https://bridgecrew.io/resource-center/)
- [DevSecOps Best Practices](https://www.checkov.io/6.Scans/resource-scans.html)
- [Policy as Code Leitfaden](https://www.checkov.io/3.Custom%20Policies/YAML%20Custom%20Policies.html)