Communitygithub.com

审计Terraform基础设施安全性

审计Terraform基础设施即代码(IaC)中的安全配置错误。

审计Terraform基础设施安全性 是什么?

此技能旨在帮助开发者和DevOps工程师在Terraform基础设施即代码(IaC)中执行安全审计。它集成了多个主流安全扫描工具(如Checkov、tfsec、Terrascan)以及OPA/Conftest定制策略引擎,支持在本地、CI/CD流水线(如GitHub Actions)中对Terraform代码、计划文件和状态文件进行全面的安全扫描与合规检查。该技能详细描述了从代码扫描到结果输出的完整工作流程,包括如何扫描Terraform模块、配置跳过特定检查、生成SARIF报告用于GitHub安全中心,以及如何编写自定义Rego策略来实现组织特有的安全规则。它还提供了常见场景(如为现有CI/CD流水线添加安全门禁)和输出示例,帮助团队在实践中落地“左移安全”理念,防范云基础设施中的安全配置错误。

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

在你喜欢的 AI 中提问

打开一个已预加载此 Agent Skill 的新对话。

文档

审计Terraform基础设施安全性 是做什么的?

何时使用

  • 将安全扫描集成到Terraform部署的CI/CD流水线中时
  • 在应用Terraform计划和模块之前,审查它们是否符合安全最佳实践时
  • 为云基础设施预配构建策略即代码(Policy-as-Code)防护措施时
  • 审计现有Terraform状态文件以识别已部署的配置错误时
  • 在多个Terraform项目中强制执行组织安全标准时

不要使用于运行时安全监控(请使用CSPM工具)、应用程序安全测试(请使用SAST/DAST工具)或云配置漂移检测(部署后请使用AWS Config或Azure Policy)。

先决条件

  • 已安装Checkov(pip install checkov)
  • 已安装tfsec(brew install tfsec 或从GitHub下载二进制文件)
  • 已安装Terrascan(brew install terrascan)
  • Terraform v1.0+(用于生成计划)
  • OPA(开放策略代理,用于定制策略执行)
  • 包含待审计Terraform代码的Git仓库

工作流程

步骤1:使用Checkov扫描Terraform代码

运行Checkov进行全面的IaC安全扫描,支持内置和自定义策略。

# 扫描Terraform目录
checkov -d ./terraform/ --framework terraform

# 按特定检查类别扫描
checkov -d ./terraform/ --check CKV_AWS_18,CKV_AWS_19,CKV_AWS_20,CKV_AWS_21

# 以JSON格式输出结果
checkov -d ./terraform/ --output json > checkov-results.json

# 为更准确的分析扫描Terraform计划文件
terraform init && terraform plan -out=tfplan
terraform show -json tfplan > tfplan.json
checkov -f tfplan.json --framework terraform_plan

# 跳过特定检查并附上理由
checkov -d ./terraform/ --skip-check CKV_AWS_145 \
  --bc-api-key $BRIDGECREW_API_KEY

# 扫描Terraform模块
checkov -d ./modules/ --framework terraform --compact

# 列出所有可用检查项
checkov --list --framework terraform | grep CKV_AWS

步骤2:使用tfsec扫描Terraform特定问题

使用tfsec进行Terraform原生安全分析,并提供详细的修复指导。

# 扫描Terraform目录
tfsec ./terraform/

# 按最低严重级别扫描
tfsec ./terraform/ --minimum-severity HIGH

# 输出JSON以便CI/CD处理
tfsec ./terraform/ --format json > tfsec-results.json

# 使用自定义检查扫描
tfsec ./terraform/ --custom-check-dir ./custom-checks/

# 排除特定规则
tfsec ./terraform/ --exclude-downloaded-modules \
  --exclude aws-s3-enable-bucket-logging

# 扫描并在特定严重级别上失败
tfsec ./terraform/ --minimum-severity CRITICAL --soft-fail

# 为GitHub安全选项卡生成SARIF输出
tfsec ./terraform/ --format sarif > tfsec.sarif

步骤3:运行Terrascan进行多框架合规检查

执行Terrascan,对照CIS、NIST和SOC 2框架进行合规检查。

# 针对CIS AWS基准扫描Terraform
terrascan scan -t aws -i terraform -d ./terraform/ \
  --policy-type aws --verbose

# 对照特定合规框架扫描
terrascan scan -t aws -i terraform -d ./terraform/ \
  --policy-type aws \
  --categories "Compliance Validation"

# 以JSON输出
terrascan scan -t aws -i terraform -d ./terraform/ \
  --output json > terrascan-results.json

# 扫描Terraform计划
terrascan scan -t aws -i terraform \
  --iac-file tfplan.json \
  --iac-type tfplan

# 列出可用策略
terrascan scan --list-policies -t aws

步骤4:为组织标准创建自定义OPA策略

编写Rego策略以满足组织特定的安全要求。

# 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存储桶 '%s' 必须启用服务端加密", [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策略 '%s' 不得使用通配符(*)动作", [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策略 '%s' 对通配符资源具有过于宽松的动作", [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("安全组规则 '%s' 允许来自 0.0.0.0/0 的SSH访问", [name])
}
# 使用OPA策略评估Terraform计划	erraform show -json tfplan | opa eval \
  --data ./policy/ \
  --input /dev/stdin \
  "data.terraform.aws" \
  --format pretty

# 使用Conftest进行更简单的OPA策略测试
conftest test tfplan.json --policy ./policy/ --output json

步骤5:将安全扫描集成到CI/CD流水线中

将IaC安全扫描作为强制性的CI/CD门禁。

# GitHub Actions: Terraform安全流水线
name: Terraform Security Scan
on:
  pull_request:
    paths: ['terraform/**']

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

      - name: 设置Terraform
        uses: hashicorp/setup-terraform@v3

      - name: Terraform初始化和计划
        run: |
          cd terraform/
          terraform init
          terraform plan -out=tfplan
          terraform show -json tfplan > tfplan.json

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

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

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

      - name: OPA策略检查
        run: |
          conftest test terraform/tfplan.json \
            --policy ./policy/ \
            --output json

步骤6:扫描Terraform状态以识别已部署的配置错误

审计当前Terraform状态以发现已部署的安全问题。

# 导出当前状态为JSON
terraform show -json > terraform-state.json

# 使用Checkov扫描状态
checkov -f terraform-state.json --framework terraform_plan

# 查询状态以查找特定安全问题
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

# 查找缺少必需标签的资源
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 "缺少标签: $resource 缺少 'Environment' 标签"
  fi
done

关键概念

术语定义
基础设施即代码 (IaC)通过声明式配置文件(Terraform、CloudFormation)而非手动控制台操作来管理云基础设施的实践
策略即代码 (Policy as Code)将安全和合规策略表达为可执行代码(Rego、Python),能够自动对基础设施定义进行评估
左移安全 (Shift Left Security)通过在部署前扫描IaC而非预配后审计,将安全检查提前到开发生命周期的早期阶段
Terraform计划 (Terraform Plan)Terraform将执行更改的预览,可在应用更改之前以JSON格式导出用于安全扫描
Checkov开源的IaC静态分析工具,支持Terraform、CloudFormation、Kubernetes和Docker,内置1000+条策略
OPA/Rego开放策略代理及其策略语言Rego,用于定义可对结构化数据输入进行评估的自定义安全规则

工具与系统

  • Checkov: 全面的IaC扫描器,拥有1000+条策略,支持Terraform、CloudFormation、Kubernetes、ARM和Dockerfile
  • tfsec: Terraform专用静态分析工具,提供详细修复指导以及SARIF输出
  • Terrascan: 多IaC扫描器,支持合规框架(CIS、NIST、SOC 2),支持策略即代码
  • OPA/Conftest: 自定义策略引擎,用于使用Rego语言定义组织特定的安全规则
  • Bridgecrew: 基于Checkov的商业平台,提供漂移检测和供应链安全功能

常见场景

场景:为现有Terraform CI/CD流水线添加安全门禁

背景:一个DevOps团队通过GitHub Actions使用Terraform部署基础设施,但没有安全扫描。最近的审计发现多个S3存储桶未加密,以及安全组允许来自互联网的SSH访问。

方法:

  1. 在GitHub Actions工作流中首先添加Checkov作为安全门禁
  2. 运行 checkov -d ./terraform/ 建立当前发现的基线
  3. 对现有发现进行分诊:修复CRITICAL问题、为HIGH问题创建工单、抑制已接受的风险
  4. 添加tfsec作为辅助扫描器,用于Terraform专用检查
  5. 编写自定义OPA策略用于组织标准(必需的标签、命名约定)
  6. 配置流水线以阻止含有CRITICAL或HIGH发现的PR
  7. 生成SARIF报告以集成到GitHub安全选项卡

陷阱:向现有项目添加安全扫描最初会产生数百个发现。应逐步实施,首先仅阻止CRITICAL级别的问题,然后扩展到HIGH级别。对于有意为之的例外情况,使用内联抑制注释 (#checkov:skip=CKV_AWS_18:用于静态网站的公共存储桶)并附上已记录的正当理由。

输出格式

Terraform安全审计报告
==================================
仓库: acme-corp/infrastructure
分支: main
扫描日期: 2026-02-23
工具: Checkov 3.x, tfsec 1.x, OPA自定义策略

扫描结果:
  Checkov检查通过:    187
  Checkov检查失败:     34
  tfsec检查通过:      156
  tfsec检查失败:       28
  OPA自定义策略:       12通过, 3失败

关键发现:
[TF-001] S3存储桶未启用加密
  文件: modules/storage/main.tf:24
  资源: aws_s3_bucket.data_lake
  检查: CKV_AWS_19
  修复: 添加 server_side_encryption_configuration 块

[TF-002] 安全组允许来自 0.0.0.0/0 的SSH访问
  文件: modules/network/security.tf:45
  资源: aws_security_group_rule.ssh_access
  检查: CKV_AWS_24
  修复: 将 cidr_blocks 限制为堡垒机子网

[TF-003] 包含通配符动作的IAM策略
  文件: modules/iam/policies.tf:12
  资源: aws_iam_policy.developer_policy
  检查: CKV_AWS_1
  修复: 将动作范围限定为所需的特定服务

按严重级别汇总:
  严重:   6 个发现
  高:    14 个发现
  中:    28 个发现
  低:    18 个发现
  信息:   12 个发现

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,

相关技能