✅ 第32课:合规审计

核心概念

合规审计:让安全可证明

用自动化手段证明系统符合安全标准——CIS Benchmark、SOC2、等保2.0等。Compliance as Code让合规持续。

常见合规框架

框架         │ 适用范围      │ 核心要求
─────────────┼──────────────┼───────────────
CIS Benchmark│ 通用基线      │ OS/K8s/Cloud安全配置
SOC2         │ SaaS企业     │ 安全/可用/机密性
等保2.0      │ 中国企业     │ 三级(金融)/二级(一般)
GDPR         │ 欧盟用户      │ 数据隐私保护
PCI-DSS      │ 支付业务      │ 卡数据安全

命令实操

1. CIS Benchmark扫描 ✅

CIS Benchmark
# kube-bench(K8s CIS Benchmark)
docker run --rm -v /etc:/etc -v /var:/var \
  aquasec/kube-bench:latest run --targets master,node

# 保存报告
docker run --rm -v /etc:/etc -v /var:/var \
  aquasec/kube-bench:latest run --json > cis-report.json

# Ubuntu OS CIS
apt install -y libopenscap8
oscap xccdf eval --profile xccdf_org.ssgproject.content_profile_cis \
  --report cis-report.html \
  /usr/share/xml/scap/ssg/content/ssg-ubuntu2204-ds.xml

2. OPA/Gatekeeper策略即代码 ✅

OPA策略
kubectl apply -f https://raw.githubusercontent.com/open-policy-agent/gatekeeper/v3.15.0/deploy/gatekeeper.yaml

# 约束模板
cat > k8s-required-labels.yaml << 'EOF'
apiVersion: templates.gatekeeper.sh/v1
kind: ConstraintTemplate
metadata: {name: k8srequiredlabels}
spec:
  crd:
    spec:
      names: {kind: K8sRequiredLabels}
      validation:
        openAPIV3Schema:
          type: object
          properties:
            labels: {type: array, items: {type: string}}
  targets:
  - target: admission.k8s.gatekeeper.sh
    rego: |
      package k8srequiredlabels
      violation[{"msg": msg}] {
        provided := {label | input.review.object.metadata.labels[label]}
        required := {label | label := input.parameters.labels[_]}
        missing := required - provided
        count(missing) > 0
        msg := sprintf("Missing required labels: %v", [missing])
      }
EOF

# 应用约束(要求所有Deployment有team+environment标签)
cat > require-team-label.yaml << 'EOF'
apiVersion: constraints.gatekeeper.sh/v1
kind: K8sRequiredLabels
metadata: {name: require-team-label}
spec:
  match: {kinds: [{apiGroups: [""], kinds: ["Deployment"]}]}
  parameters: {labels: ["team", "environment"]}
EOF
kubectl apply -f k8s-required-labels.yaml
kubectl apply -f require-team-label.yaml

3. 合规审计自动化报告 ✅

合规报告
#!/bin/bash
# compliance-report.sh
REPORT="/var/compliance/$(date +%Y-%m-%d)"
mkdir -p "$REPORT"

# CIS Benchmark
docker run --rm -v /etc:/etc -v /var:/var aquasec/kube-bench:latest run --json > "$REPORT/cis-k8s.json"

# 漏洞扫描
trivy k8s --report all cluster --format json > "$REPORT/vulns.json"

# 网络策略检查
echo "无默认拒绝策略的命名空间:" > "$REPORT/netpol-audit.txt"
for ns in $(kubectl get ns -o jsonpath='{.items[*].metadata.name}'); do
    kubectl get networkpolicy default-deny-ingress -n "$ns" &>/dev/null || echo "  ⚠️ $ns" >> "$REPORT/netpol-audit.txt"
done

# RBAC审计
kubectl get clusterrolebindings -o json | \
  jq -r '.items[] | select(.subjects[]?.name=="system:anonymous") | .metadata.name' > "$REPORT/rbac-audit.txt"

# Pod安全
kubectl get pods -A -o json | \
  jq -r '.items[] | select(.spec.containers[].securityContext==null) | .metadata.namespace + "/" + .metadata.name' > "$REPORT/pod-security.txt"

echo "报告目录: $REPORT" 

架构图

合规审计:让安全可证明架构

┌──────────────────────────────────────────┐
│           Compliance as Code             │
│  OPA策略 → CIS Benchmark → RBAC审计     │
└──────────────────┬───────────────────────┘
    ┌──────────────┼──────────────┐
    ▼              ▼              ▼
┌────────┐  ┌──────────┐  ┌──────────┐
│ 准入控制│  │ 定期扫描  │  │ 审计报告  │
│(实时)  │  │(每日/每周)│  │(季度/年度)│
│Gatekeeper│ │kube-bench│ │SOC2/等保 │
└────────┘  └──────────┘  └──────────┘

故障排查

❌ OPA策略误拦截

排查
kubectl get constraints -o yaml
# 临时排除特定命名空间
spec:
  match:
    excludedNamespaces: ["kube-system", "monitoring"]
# dry-run测试
kubectl apply --dry-run=server -f deployment.yaml
💡 合规即代码:策略自动执行、持续扫描而非年度审计、误拦截用excludedNamespaces处理。

🏆 成就解锁:合规审计专家!

掌握CIS Benchmark、OPA/Gatekeeper、自动化报告——合规是持续过程不是一次性检查

📝 合规检查清单

检查项CIS等保2.0SOC2
默认拒绝网络
RBAC最小权限
数据加密(传输+存储)
审计日志
密钥轮换
漏洞扫描
备份恢复测试
物理安全N/AN/A
💡 合规自动化:用OPA实现策略即代码、kube-bench定期CIS扫描、所有检查结果自动归档、季度Review。

🔧 CIS Benchmark自动化

CIS自动化
# kube-bench定期扫描CronJob
cat > cis-cronjob.yaml << 'EOF'
apiVersion: batch/v1
kind: CronJob
metadata: {name: cis-benchmark}
spec:
  schedule: "0 6 * * 1"  # 每周一6点
  jobTemplate:
    spec:
      template:
        spec:
          containers:
          - name: kube-bench
            image: aquasec/kube-bench:latest
            command: ["sh", "-c", "kube-bench run --json > /reports/cis-$(date +%Y%m%d).json"]
          restartPolicy: OnFailure
          volumes: [{name: reports, persistentVolumeClaim: {claimName: reports-pvc}}]
EOF

# OPA Gatekeeper合规约束
cat > require-resources.yaml << 'EOF'
apiVersion: constraints.gatekeeper.sh/v1beta1
kind: K8sRequiredLabels
metadata: {name: require-resources}
spec:
  match: {kinds: [{apiGroups: ["apps"], kinds: ["Deployment"]}]}
  parameters:
    labels: ["app.kubernetes.io/managed-by", "app.kubernetes.io/version"]
EOF
kubectl apply -f require-resources.yaml

📝 合规报告模板

检查项通过失败N/A
默认拒绝网络策略
RBAC最小权限
Pod安全标准
密钥加密存储
审计日志启用
镜像漏洞扫描
💡 合规即代码:OPA策略实时拦截、CIS定期扫描、所有结果归档、季度Review改进。
⚠️ 学习建议:每课内容都需要在实验环境中实际操作验证,只有动手才能真正掌握。建议搭建自己的实验环境反复练习。

课前准备

课后巩固

进阶方向