Aller au contenu

Feuille Cheat de Checkov

Copier toutes les commandes Générer PDF

Aperçu général

Checkov est un outil d'analyse de code statique pour Infrastructure as Code (IaC) qui scanne l'infrastructure cloud fournie à l'aide de Terraform, CloudFormation, Kubernetes, Helm, ARM Templates et Serverless framework. Il détecte les erreurs de sécurité et de conformité et fournit des conseils sur l'assainissement.

C'est pas vrai. Note: Outil libre et open-source. Fonctions haut de gamme disponibles sur la plateforme Bridgecrew/Prisma Cloud.

Installation

Python Package

# 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]

Coq

# 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
```_

### Macabre (macOS)
```bash
# Install via Homebrew
brew install checkov

# Upgrade
brew upgrade checkov
```_

### Téléchargement binaire
```bash
# 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

Utilisation de base

Commandes d'analyse

# 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

Formats de sortie

# 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

Sortie vers le fichier

# 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

Numérisation spécifique au cadre

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

NuageFormation

# 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

Coq

# 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

Gestion des vérifications

Sauter les vérifications spécifiques

# 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

Exécuter des vérifications spécifiques

# 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

Vérifier les informations

# 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"

Fichiers de configuration

.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

Variables d'environnement

# 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 .

Suppressions inline

Suppressions des formes de terre

# 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"
}

Suppressions de la formation des nuages

# 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

# 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

Intégration CI/CD

Actions GitHub

# .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()

Vérifications personnalisées

Python personnalisé Vérifier

# 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()

Vérification personnalisée YAML

# 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

Exécution des vérifications personnalisées

# 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

Caractéristiques avancées

Évaluation variable

# 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

Téléchargement du module externe

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

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

Création de référence

# 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

Politique en tant que 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

Rapports et intégration

Intégration SARIF

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

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

Intégration SonarQube

# 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

Notifications de slack

# 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

Optimisation des performances

Exécution parallèle

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

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

Cache

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

# Clear cache
rm -rf ~/.checkov_cache

Analyse sélective

# 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/

Dépannage

Questions communes

# 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

Résolution d'erreur

# 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

Configuration d'enregistrement

# Set log level
export CHECKOV_LOG_LEVEL=DEBUG
checkov -d . --framework terraform

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

Meilleures pratiques

Stratégie de numérisation de la sécurité

# 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

Gestion de la configuration

# Use configuration files for consistency
# .checkov.yml in repository root
# Team-specific skip lists
# Framework-specific configurations
# Output format standardization

Intégration Flux de travail

# 1. Pre-commit hooks for developers
# 2. CI/CD pipeline integration
# 3. Pull request checks
# 4. Scheduled full scans
# 5. Security dashboard reporting

Ressources

Documentation

Communauté

  • [Répertoire GitHub] (LINK_9)
  • [Communauté Slack] (LINK_9)
  • [Débordement de la pile] (LINK_9)

Formation