<!-- Copyright (c) 2026 defconxt. All rights reserved. -->
<!-- Licensed under AGPL-3.0 — see LICENSE file for details. -->
---
name: implementing-infrastructure-as-code-scanning
description: >-
  Scan Terraform, CloudFormation, Kubernetes manifests, and Helm charts for
  misconfigurations using Checkov, tfsec, and KICS. Enforce compliance policies
  as code and block deployments that violate security baselines.
domain: cybersecurity
subdomain: devsecops
tags:
  - iac-scanning
  - checkov
  - tfsec
  - kics
  - terraform
  - cloudformation
  - kubernetes
  - compliance-as-code
version: "1.0"
author: defconxt
license: AGPL-3.0
metadata:
  mitre-attack: ["T1195.002"]
---

# Implementing Infrastructure as Code Scanning

## Overview

Infrastructure as Code (IaC) scanning detects misconfigurations, compliance violations,
and insecure defaults in infrastructure definitions before provisioning. This skill
covers integrating Checkov, tfsec, and KICS into CI/CD pipelines with custom policies
and drift detection. Targets CIS Benchmarks, SOC 2, and NIST 800-53 controls.

Mode: `[MODE: BLUE]` — Shift-left infrastructure security through policy-as-code.

## Prerequisites

| Requirement | Details |
|---|---|
| Checkov (`pip install checkov`) or tfsec CLI | Required |
| Terraform, CloudFormation, or Kubernetes manifests | Required |
| CI/CD platform | GitHub Actions, GitLab CI, or Jenkins |
| Python 3.10+ for custom check authoring | Required |

## Key Concepts

### Checkov in GitHub Actions

```yaml
name: IaC Security Scan
on:
  pull_request:
    paths:
      - 'terraform/**'
      - 'k8s/**'
      - 'cloudformation/**'

jobs:
  checkov:
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v4
      - name: Run Checkov
        uses: bridgecrewio/checkov-action@v12
        with:
          directory: terraform/
          framework: terraform
          output_format: cli,sarif
          output_file_path: console,results.sarif
          soft_fail: false
          check: CKV_AWS_18,CKV_AWS_21,CKV_AWS_145
      - name: Upload SARIF
        if: always()
        uses: github/codeql-action/upload-sarif@v3
        with:
          sarif_file: results.sarif
```

### tfsec Pipeline Integration

```yaml
name: tfsec Scan
on:
  pull_request:
    paths: ['terraform/**']

jobs:
  tfsec:
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v4
      - name: tfsec
        uses: aquasecurity/tfsec-action@v1.0.3
        with:
          working_directory: terraform/
          format: sarif
          soft_fail: false
          additional_args: --minimum-severity HIGH
```

### Custom Checkov Policy

```python
# custom_checks/s3_versioning.py
from checkov.terraform.checks.resource.base_resource_check import BaseResourceCheck
from checkov.common.models.enums import CheckCategories, CheckResult


class S3VersioningEnabled(BaseResourceCheck):
    def __init__(self) -> None:
        name = "Ensure S3 bucket has versioning enabled"
        id = "CKV_CUSTOM_1"
        supported = ["aws_s3_bucket"]
        categories = [CheckCategories.BACKUP_AND_RECOVERY]
        super().__init__(name=name, id=id, categories=categories,
                         supported_resources=supported)

    def scan_resource_conf(self, conf: dict) -> CheckResult:
        versioning = conf.get("versioning", [{}])
        if isinstance(versioning, list) and versioning:
            enabled = versioning[0].get("enabled", [False])
            if enabled is True or enabled == [True]:
                return CheckResult.PASSED
        return CheckResult.FAILED


check = S3VersioningEnabled()
```

### Kubernetes Manifest Scanning

```yaml
name: K8s Security Scan
on:
  pull_request:
    paths: ['k8s/**', 'helm/**']

jobs:
  kics:
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v4
      - name: KICS Scan
        uses: checkmarx/kics-github-action@v2.1.0
        with:
          path: k8s/
          output_path: kics-results/
          output_formats: json,sarif
          fail_on: high,medium
          exclude_queries: "b9c83569-459b-4110-8f79-6305aa33cb37"
```

### Policy-as-Code with OPA

```rego
# policy/terraform/s3.rego
package terraform.s3

deny[msg] {
    resource := input.resource.aws_s3_bucket[name]
    not resource.server_side_encryption_configuration
    msg := sprintf("S3 bucket '%s' missing encryption configuration", [name])
}

deny[msg] {
    resource := input.resource.aws_s3_bucket[name]
    resource.acl == "public-read"
    msg := sprintf("S3 bucket '%s' has public-read ACL", [name])
}
```

## Workflow

### Step 1: Scan Terraform Directory

```bash
node scripts/agent.js --action scan --framework terraform --source-dir ./terraform/ --output /tmp/iac-results.json
```

### Step 2: Scan Kubernetes Manifests

```bash
node scripts/agent.js --action scan --framework kubernetes --source-dir ./k8s/ --output /tmp/k8s-results.json
```

### Step 3: Evaluate Custom Policies

```bash
node scripts/agent.js --action policy --source-dir ./terraform/ --policy-dir ./policies/ --output /tmp/policy-results.json
```

## Detection

```yaml
title: Infrastructure As Code Scanning Detection
id: 5c8772df-704c-45e0-925d-48f073c99533
status: experimental
description: Detects suspicious activity related to implementing infrastructure as code scanning techniques in devsecops context
logsource:
  category: process_creation
  product: linux
detection:
  selection:
    CommandLine: "*implementing*infrastructure*"
  condition: selection
level: medium
tags:
  - attack.t1195.002
  - attack.execution
falsepositives:
  - CI/CD pipeline executing authorized security scanning tools
```


**Detection Opportunities**

| Indicator | Source | Detection Logic |
|---|---|---|
| Infrastructure As Code Scanning Detection | linux/process_creation | Sigma rule (medium) |
| ATT&CK Coverage | MITRE ATT&CK | T1195.002 |

## Verification

- [ ] IaC scans run on every PR touching infrastructure files
- [ ] Custom policies enforce organization security baselines
- [ ] High/critical misconfigurations block merge
- [ ] SARIF results appear in GitHub Security tab
- [ ] Drift detection runs on scheduled basis
- [ ] CIS Benchmark compliance tracked per environment

## References

- [Checkov Documentation](https://www.checkov.io/1.Welcome/Quick%20Start.html)
- [tfsec Documentation](https://aquasecurity.github.io/tfsec/)
- [KICS Documentation](https://docs.kics.io/)
- [CIS Benchmarks](https://www.cisecurity.org/cis-benchmarks)
