Checkov Documentation

repository·main·Indexed 27 days ago

https://github.com/bridgecrewio/checkov

Checkov is a static code analysis tool for Infrastructure as Code (IaC) and a Software Composition Analysis (SCA) tool. It detects security and compliance misconfigurations in Terraform, CloudFormation, Kubernetes, and Dockerfiles using graph-based scanning. It supports installation via pip, Homebrew, and Docker, and can be deployed as a Kubernetes Job for runtime scanning. The tool provides a CLI for directory and file scanning, programmatic access via the Checkov class, and integration with Bridgecrew/Prisma Cloud.

Tokens
110.1K
Snippets
196
Records
446
Agent score
91%

What's inside Checkov

  1. Overview of Checkov capabilities

    main

    Checkov is a static code analysis tool designed to scan Infrastructure as Code (IaC) files for security and compliance misconfigurations. It includes over 750 predefined policies and supports the creation of custom policies using Python or YAML.

    Key capabilities include:

    • Compliance Scanning: Checks against industry standards like CIS and AWS Foundations Benchmark.
    • Custom Policies: Allows checking cloud resources based on configuration attributes or connection states.
    • Prisma Cloud Integration: Extends Checkov with runtime scanning, drift detection, and automated Pull Request annotations.
  2. CloudFormation Graph and Attribute References

    main

    Checkov uses a graph to resolve CloudFormation attribute references (like !Ref, !GetAtt, or !Sub). This allows Checkov to analyze the final state of a resource by connecting different CFN elements.

    For example, if a Lambda function's Tracing_config uses !Ref ParamTracingConfig, Checkov computes the relationship in a graph to determine if the resulting configuration complies with best practices based on the parameter's value.

  3. Understand Checkov core concepts

    main

    To use Checkov effectively, understand the following core terminology:

    • Policy: A security rule defining the required state for a cloud configuration (e.g., requiring MFA for a root account). If a resource does not meet this state, it is marked as non-compliant.
    • Composite Policy: A policy that evaluates the relationship or connection state between resources (e.g., ensuring a resource is connected to a specific security group). Checkov uses a virtual connection graph to evaluate these.
    • Incident: A specific instance of non-conformance to a Policy identified during a scan.
    • Resource: A Cloud Platform entity being scanned, such as an Amazon EC2 instance, a CloudFormation stack, or an Amazon S3 bucket.
    • Suppression: The process of marking an Incident as non-problematic. You can suppress an Incident for all relevant resources or target specific resources.
  4. Run Checkov scans

    main

    Checkov can be used to scan repositories, branches, folders, or individual files to identify attribute-based misconfigurations or connection state errors.

    Key capabilities include:

    • Reviewing scan results
    • Suppressing or skipping specific policies
    • Scanning for credentials and secrets
    • Scanning Kubernetes clusters
    • Scanning Terraform plan output and 3rd party modules
  5. Key Terminology for Checkov Runners and Checks

    main

    Understanding these core concepts is essential for contributing to Checkov:

    • Runner: A unit of code that plugs into the Checkov engine to handle parsing and formatting of a specific IaC language, translating it into internal 'definitions'.
    • Registry: A data structure that collects code objects. There are separate registries for Checks and Runners.
    • Resource: A single unit within an IaC file (e.g., a specific job in a GitHub Actions YAML) that a check can be run against.
    • Definition/Entity: An internal abstraction of an IaC resource into a Checkov data structure.
    • Check: Autonomous logic that traverses a resource's schema to apply security or best-practice rules.
    • Report: A data structure that summarizes check results before they are output in formats like JSON, CLI text, or CycloneDX.
  6. Scan a Terraform Plan JSON file

    main

    To scan a Terraform plan, you must first generate a JSON representation of the plan.

    Warning: If you use terraform show -json tf.plan > tf.json, the resulting file is a single line, which causes Checkov to report all findings at line number 0. To get readable line numbers in scan results, use jq to format the JSON output.

    # Standard method (results will show line 0)
    terraform init
    terraform plan -out tf.plan
    terraform show -json tf.plan > tf.json 
    checkov -f tf.json
    
    # Recommended method for readable line numbers (requires jq)
    terraform init
    terraform plan -out tf.plan
    terraform show -json tf.plan | jq '.' > tf.json
    checkov -f tf.json
  7. Integrate Checkov with Prisma Cloud

    main

    You can integrate Checkov with Prisma Cloud to visualize scan results within the Prisma Cloud platform. This requires a Prisma Cloud issued Access Key and Secret Key token.

    To execute a scan that sends results to Prisma Cloud, use the --bc-api-key flag with the format ACCESS_KEY::SECRET_KEY, along with the --prisma-api-url, --repo-id, and --branch flags.

  8. Add Provider-Level Checks for a New Terraform Provider

    main

    To add checks that validate the provider configuration itself (e.g., preventing hardcoded secrets in a provider block):

    1. Create a Test: Create tests/terraform/checks/provider/<provider_name>/test_<check_name>.py. Use check.scan_provider_conf(conf=provider_conf) to verify the CheckResult.
    2. Implement the Provider Check: Create checkov/terraform/checks/provider/<provider_name>/<check_name>.py. Implement a class inheriting from BaseProviderCheck.
      • Define name, id, supported_provider, and categories in __init__.
      • Implement scan_provider_conf(self, conf: Dict[str, List[Any]]) -> CheckResult to perform the validation logic.
    3. Define Security Patterns: If the check relies on a new regex pattern (like a secret token), add the pattern to checkov/common/models/consts.py.
    4. Register the Provider Check: Add an __init__.py in your provider's check directory to export modules. Then, update checkov/terraform/checks/provider/__init__.py by adding from checkov.terraform.checks.provider.<provider_name> import *.
    # Example implementation of a provider check
    import re
    from typing import Dict, List, Any, Pattern
    from checkov.common.models.enums import CheckResult, CheckCategories
    from checkov.terraform.checks.provider.base_check import BaseProviderCheck
    
    class LinodeCredentials(BaseProviderCheck):
        def __init__(self):
            name = "Ensure no hard coded Linode tokens exist in provider"
            id = "CKV_LIN_1"
            supported_provider = ("linode",)
            categories = (CheckCategories.SECRETS,)
            super().__init__(name=name, id=id, categories=categories, supported_provider=supported_provider)
    
        def scan_provider_conf(self, conf: Dict[str, List[Any]]) -> CheckResult:
            # Logic to check for secrets using a pattern
            if self.secret_found(conf, "token", linode_token_pattern):
                return CheckResult.FAILED
            return CheckResult.PASSED
    
        @staticmethod
        def secret_found(conf: Dict[str, List[Any]], field: str, pattern: Pattern[str]) -> bool:
            if field in conf.keys():
                value = conf[field][0]
                if re.match(pattern, value) is not None:
                    return True
            return False
    
    check = LinodeCredentials()
  9. Set up Checkov as a pre-commit hook

    main

    To automatically run Checkov on Git changes, install the pre-commit binary and add a .pre-commit-config.yaml file to your project root. You must set the rev: field to a specific git commit SHA or tag that contains .pre-commit-hooks.yaml.

    Requirements:

    • For python hooks: pre-commit 3.x is recommended.
    • For container hooks: The Docker CLI and a container runtime must be available.

    Note: Local environment variables apply when using these hooks. You can skip hooks during a commit using the --no-verify flag.

    - repo: https://github.com/bridgecrewio/checkov.git
      rev: '' # change to tag or sha
      hooks:
        - id: checkov
  10. Scan Helm charts with Checkov

    main

    Checkov automatically detects Helm charts by looking for a Chart.yaml file. When detected, Checkov uses the helm binary to template the chart (using its default values) into Kubernetes manifests, which are then scanned against Kubernetes policies.

    Requirement: A helm binary version greater than v3 must be available in your $PATH. If the binary is missing, Checkov will automatically disable the helm framework and issue the following warning: The following frameworks will automatically be disabled due to missing system dependencies: helm

    checkov -d ./testdir/gocd --framework helm