Infrastructure as Code Security
🔥 Vibe Prompt
"Scan Terraform code for security issues before apply. Enforce policy as code."
IaC Scanning with Checkov
brew install checkov
checkov -d terraform/
checkov -f cloudformation.yaml
checkov -d k8s/
checkov -d terraform/ --compact --quiet
Checkov Output
Passed checks: 45
Failed checks: 3
CKV_AWS_21: S3 bucket ACL should not be public read (s3.tf:12)
CKV_AWS_23: Ensure S3 bucket has block public access (s3.tf:8)
CKV_AWS_52: Ensure EC2 has detailed monitoring (ec2.tf:15)
Terraform Security Checks
# Good: encrypted, versioned S3
resource "aws_s3_bucket_server_side_encryption_configuration" "data" {
rule {
apply_server_side_encryption_by_default {
sse_algorithm = "AES256"
}
}
}
# Bad: public RDS
resource "aws_db_instance" "db" {
publicly_accessible = true # Never do this!
skip_final_snapshot = true # Never do this!
}
Policy as Code with OPA
package terraform
deny[msg] {
resource := input.resource.aws_s3_bucket[_]
resource.config.acl == "public-read"
msg := sprintf("S3 bucket %v has public-read ACL", [resource.config.bucket])
}
deny[msg] {
resource := input.resource.aws_security_group[_]
ingress := resource.config.ingress[_]
ingress.cidr_blocks[_] == "0.0.0.0/0"
ingress.from_port == 22
msg := sprintf("SG %v allows SSH from 0.0.0.0/0", [resource.config.name])
}
IaC Security in CI/CD
jobs:
iac-scan:
steps:
- uses: actions/checkout@v4
- uses: bridgecrewio/checkov-action@v12
with:
directory: terraform/
framework: terraform
soft_fail: false
Best Practices
- Scan IaC before every apply
- Use policy as code (OPA, Checkov)
- Store Terraform state in encrypted S3
- Use remote state with locking
- Never hardcode secrets in IaC
- Pin provider versions
- Use modules for consistency
Key Points
- Understand the core concepts thoroughly
- Practice with hands-on code examples
- Apply knowledge to real-world problems
- Review and reinforce through exercises
Further Learning
- Official documentation
- Open source projects on GitHub
- Community forums and discussions
- Related courses and tutorials
IaC 安全:你的基礎設施也有漏洞
當你用 Terraform 或 CloudFormation 管理基礎設施時,你的「基礎設施設定」變成了「程式碼」。這帶來了好處(版本控制、自動化),但也帶來了風險——錯誤的配置可能導致資料外洩。
最常見的 IaC 安全問題
| 問題 | 範例 | Checkov 規則 |
|:----|:----|:-----------|
| S3 Bucket 公開 | acl = "public-read" | CKV_AWS_53 |
| 安全群組全開 | cidr_blocks = ["0.0.0.0/0"] | CKV_AWS_24 |
| 未加密的 EBS | 未設定 encrypted = true | CKV_AWS_2 |
| 未啟用 SSL | CloudFront 未設定 SSL | CKV_AWS_89 |
| 日誌未啟用 | S3 未開啟 Access Logging | CKV_AWS_18 |
Checkov:IaC 安全掃描工具
# 掃描 Terraform 目錄中的安全問題
checkov -d terraform/
# 輸出 JSON 格式的報告
checkov -d terraform/ -o json
# 只檢查高風險問題
checkov -d terraform/ --check CKV_AWS_* --skip-check CKV_AWS_24
下一章預告:SAST 與 DAST
IaC 安全確保了你的基礎設施配置沒有漏洞。下一章回到應用程式層級的安全測試——SAST(靜態分析)和 DAST(動態分析)的比較與整合。