Kubernetes 高级工程师教程

第27章 PodSecurity Standards与OPA Gatekeeper策略治理

从 PodSecurityPolicy 退役到 PodSecurity Standards 的范式迁移,再到 OPA Gatekeeper 的 Rego 策略引擎与 Constraint 模型,构建 K8s 准入层的纵深策略治理体系。

系列 Kubernetes 高级工程师教程 篇章 安全篇 章节 第27章 / 共46章 难度 ★★★★★ 预计阅读 60分钟 前置知识 Admission Webhook、RBAC、Pod安全上下文、Rego语言基础

1准入控制全景:从 PSP 到 PSA 再到 OPA

Kubernetes 的准入控制(Admission Control)是 API 请求在鉴权通过后、持久化到 etcd 前的最后一道关卡。它不仅能校验(Validating),还能修改请求(Mutating)。Pod 安全策略治理经历了三代演进:

1.1 三代演进

阶段机制版本状态特点
第一代PodSecurityPolicy(PSP)v1.0~v1.24已移除(1.25)集群级资源,绑定复杂,易配错导致全集群 Pod 无法创建
第二代PodSecurity Admission(PSA)v1.22+(beta 1.25)内置 GA内置准入插件,按 NS label 分级(privileged/baseline/restricted),配置极简
第三代OPA Gatekeeper / Kyverno独立项目活跃通用策略引擎,Rego/YAML 表达任意策略,可扩展但需额外部署

1.2 为什么 PSP 被移除

PSP 的核心问题是绑定模型过于复杂。一个 PSP 通过 RBAC(Role/ClusterRole 引用 PSP 资源)绑定到 SA,但多个 PSP 同时匹配时,选用策略不直观(选最宽松的),且 PSP 的 use verb 与实际 Pod 创建的授权分离,导致审计困难。社区在 1.21 弃用,1.25 移除。

迁移警告

如果你的集群仍 ≤1.24 且用 PSP,升级到 1.25+ 前必须完成迁移。用 kubectl-convert 或 psp-to-psa 工具将 PSP 转为 PSA label + 补充 OPA 策略。未迁移的集群升级后所有受 PSP 保护的 Pod 创建将无准入控制,安全降级。

1.3 PSA vs OPA Gatekeeper 定位

PodSecurity Admission(PSA)

内置 / 开箱即用 / 有限策略

内置在 kube-apiserver 的准入插件,零额外部署。覆盖 Pod 安全最核心的三个等级,配置只需 NS label。但策略固定,无法自定义。

适合:标准 Pod 安全基线,快速启用,不想维护额外组件。

OPA Gatekeeper

外置 / Rego / 任意策略

独立 Admission Webhook,用 Rego 语言表达任意策略(镜像来源、标签规范、资源配额、拓扑约束等)。功能强大但需部署运维。

适合:超出 PSA 范围的自定义策略、多团队策略治理、合规审计。

Kyverno

外置 / YAML / 策略即K8s资源

策略用 YAML 而非 Rego 表达,学习曲线更低。支持 mutate + validate + generate。适合不熟悉 Rego 的团队。

适合:偏好 YAML 策略、需要 mutate/generate 的场景。

类比

把准入控制比作"大厦门禁":PSA 是物业标配的门禁卡系统——三种权限等级(访客/员工/管理员),开箱即用,但只能管这三种。OPA Gatekeeper 是可编程的智能门禁——你可以写规则"穿工牌且非节假日且 7-19 点才能进机房",灵活但要请人写规则。Kyverno 是用填表代替写代码的智能门禁——规则用表格表达,不用学编程,但表达力略弱。

2PodSecurity Standards 三级模型深度解析

PodSecurity Standards 定义了三个预置安全等级,每个等级是一组 Pod 字段的约束集合。PSA 准入插件按 NS label 决定该 NS 执行哪个等级的审计/强制。

2.1 三个等级

等级定位关键限制典型用途
privileged无限制(最宽松)无任何限制系统组件、CSI 驱动、CNI、需 hostNetwork 的特殊工作负载
baseline阻止已知提权向量禁 privileged、hostPID、hostIPC、hostNetwork、hostPath、不允许添加大多数 Linux capabilities、seLinuxOptions、seccomp 不能设 Unconfined一般业务应用
restricted严格硬化(最严格)在 baseline 基础上:必须设 runAsNonRoot、drop ALL capabilities、seccompProfile 设 RuntimeDefault、只允许特定 volume 类型生产业务、多租户、合规要求

2.2 restricted 等级的完整约束清单

restricted 是生产推荐等级。以下是它对 Pod spec 的完整约束,每条都对应一个历史安全漏洞:

约束对应字段防御的攻击
必须 runAsNonRoot: true 或 image 用户非 0spec.securityContext.runAsNonRoot / container.securityContext.runAsNonRoot容器内 root 提权 → 逃逸到节点
必须 allowPrivilegeEscalation: falsecontainer.securityContext.allowPrivilegeEscalation子进程获取比父进程更多权限(setuid)
必须 drop ALL capabilities,可选 add NET_BIND_SERVICEcontainer.securityContext.capabilities用 CAP_SYS_ADMIN 等提权
seccompProfile 必须设 RuntimeDefault 或 Localhostcontainer.securityContext.seccompProfile未限制的系统调用(如 keyctl、bpf)
禁 hostNetwork/hostPID/hostIPCspec.hostNetwork 等看到节点进程、网络命名空间
禁 hostPath volumevolumes.hostPath直接读写节点文件系统
禁 privileged: truecontainer.securityContext.privileged容器拥有几乎所有 root 能力
volume 类型白名单volumes[*]仅允许 configMap/secret/emptyDir/projected/downwardAPI/persistentVolumeClaim
禁 seLinuxOptions 自定义container.securityContext.seLinuxOptionsSELinux 策略篡改
procMount 默认 Defaultcontainer.securityContext.procMountUnmasked procMount 暴露 /proc 敏感项

2.3 PSA 准入插件配置

PSA 通过 apiserver 的 AdmissionConfiguration 配置,定义三个等级的默认行为和豁免:

yaml · /etc/kubernetes/admission-control/pod-security.yaml
apiVersion: apiserver.config.k8s.io/v1
kind: AdmissionConfiguration
plugins:
- name: PodSecurity
  configuration:
    apiVersion: pod-security.admission.config.k8s.io/v1beta1
    kind: PodSecurityConfiguration
    defaults:
      enforce: baseline          # 默认强制等级
      enforce-version: latest
      audit: restricted          # 默认审计等级(记录违规但不拒绝)
      audit-version: latest
      warn: restricted           # 默认告警等级(kubectl apply 时警告)
      warn-version: latest
    exemptions:
      usernames: []              # 豁免的用户
      runtimeClasses: []         # 豁免的 runtimeClass
      namespaces: [kube-system, kube-public, kube-node-lease]  # 豁免的 NS

2.4 NS label 级配置

每个 NS 通过 label 覆盖默认等级。这是 PSA 的核心设计——配置即 label,极简:

bash · 为 NS 设置 Pod 安全等级
# 生产 NS:强制 restricted
kubectl label ns prod \
  pod-security.kubernetes.io/enforce=restricted \
  pod-security.kubernetes.io/enforce-version=latest \
  pod-security.kubernetes.io/audit=restricted \
  pod-security.kubernetes.io/warn=restricted

# 系统 NS:允许 privileged
kubectl label ns kube-system \
  pod-security.kubernetes.io/enforce=privileged

# 开发 NS:强制 baseline(允许 root 但禁 hostPath)
kubectl label ns dev \
  pod-security.kubernetes.io/enforce=baseline \
  pod-security.kubernetes.io/audit=restricted  # 审计按 restricted,记录违规

# 查看某 NS 的有效策略
kubectl get ns prod --show-labels | grep pod-security
# pod-security.kubernetes.io/enforce=restricted,...
enforce / audit / warn 的区别

enforce:违规直接拒绝创建。audit:违规记录到审计日志但不拒绝。warn:违规在 kubectl 响应中返回警告但不拒绝。三者可独立设不同等级——典型做法:enforce=baseline(硬底线),audit=restricted(记录谁不达标),warn=restricted(提示开发者改进)。这种渐进式收紧让迁移不中断业务。

3PSA 实战:渐进式安全收紧

将一个已有集群从无准入控制渐进收紧到 restricted,是 PSA 最典型的实战场景。关键原则:先 audit 再 enforce,避免一次性拒绝导致业务中断。

Step 1:全集群 audit=baseline(发现违规)

bash
# 所有业务 NS 先开 baseline audit(只记录不拒绝)
for ns in $(kubectl get ns -o name | cut -d/ -f2 | grep -v kube-); do
  kubectl label ns $ns \
    pod-security.kubernetes.io/audit=baseline \
    pod-security.kubernetes.io/audit-version=latest --overwrite
done

# 部署一些测试 Pod,观察 audit log 中的违规
kubectl run test --image=nginx -n prod --restart=Never
# Warning: would violate PodSecurity "baseline:latest": hostPath volumes (volume "data")
# (audit 模式下 Pod 仍创建成功,但 audit log 记录违规)

Step 2:分析 audit log,修复违规 Pod

bash · 扫描 audit log 中的 PSA 违规
# 查 audit log 中 PSA 拒绝/警告记录
grep "pod-security.admission.config" /var/log/kube-audit.log | \
  jq -r 'select(.annotations["pod-security.admission.config.k8s.io/audit-violations"]) |
    "\(.user.username) \(.namespace) \(.annotations["pod-security.admission.config.k8s.io/audit-violations"])"'
# 输出示例:
# system:serviceaccount:default:app1  default  hostPath volume "data"
# system:serviceaccount:default:app2  default  privileged containers: "c1"

# 逐个修复:去掉 hostPath(改 PVC)、去 privileged、加 runAsNonRoot

Step 3:enforce=baseline(硬底线)

bash
# 确认无违规后,升级为 enforce
kubectl label ns prod \
  pod-security.kubernetes.io/enforce=baseline \
  pod-security.kubernetes.io/enforce-version=latest --overwrite

# 验证:尝试创建违规 Pod 应被拒
kubectl run evil --image=nginx -n prod --privileged --restart=Never
# Error from server (Forbidden): pods "evil" is forbidden:
# violates PodSecurity "baseline:latest": privileged (container "evil")

Step 4:audit=restricted → 修复 → enforce=restricted

重复 Step 1-3 但等级升到 restricted。restricted 要求 runAsNonRoot、drop ALL capabilities、seccomp=RuntimeDefault——需要改所有 Deployment 的 securityContext。用 kubectl set env 或批量 patch 自动化。

3.1 批量加 securityContext 的脚本

bash · 批量给 Deployment 加 restricted 安全上下文
for dep in $(kubectl get deploy -n prod -o name | cut -d/ -f2); do
  kubectl patch deploy $dep -n prod --type=json -p='[
    {"op":"add","path":"/spec/template/spec/securityContext","value":{
      "runAsNonRoot":true,"seccompProfile":{"type":"RuntimeDefault"}
    }},
    {"op":"add","path":"/spec/template/spec/containers/0/securityContext","value":{
      "allowPrivilegeEscalation":false,
      "capabilities":{"drop":["ALL"]},
      "runAsNonRoot":true,
      "seccompProfile":{"type":"RuntimeDefault"}
    }}
  ]'
done
# 注意:op add 要求原路径不存在;若已有 securityContext 需用 replace

4OPA Gatekeeper 架构深度剖析

OPA(Open Policy Agent)是 CNCF 毕业项目,Gatekeeper 是 OPA 的 K8s 集成。它将 Rego 策略包装为 K8s Admission Webhook,用 CRD 管理策略,实现"策略即代码、策略即 K8s 资源"。

4.1 架构组件

kube-apiserver Admission Webhook Gatekeeper Controller 监听 ConstraintTemplate/Constraint 编译 Rego → OPA 引擎 Gatekeeper Audit 定期扫描全集群 输出 ConstraintViolation OPA 引擎 Rego 策略求值 data.inventory 缓存 ConstraintTemplate CRD Rego 源码 + schema Constraint CRD 参数 + 匹配规则 Config CRD 豁免 / 数据源同步
图 27-1 Gatekeeper 架构:Controller 编译策略,OPA 引擎求值,Audit 定期扫描

4.2 ConstraintTemplate 与 Constraint 的关系

这是 Gatekeeper 的核心抽象,理解它才能写策略:

类比

ConstraintTemplate 是"法律条文模板"(如"禁止使用未批准的镜像,批准列表由参数提供"),Constraint 是"具体法律"(如"在 prod NS,批准列表 = [registry.corp.com/*]")。一个模板可实例化出多条法律(prod 严格、dev 宽松)。

4.3 请求处理流程

apiserver 发起 Admission webhook

用户 create/update 一个资源,apiserver 鉴权通过后,向 Gatekeeper 的 webhook 发送 AdmissionReview 请求(含资源完整 spec)。

Gatekeeper 匹配 Constraint

根据资源的 kind/NS/label 匹配所有 Constraint,筛选出适用的策略。

OPA 引擎求值 Rego

对每个匹配 Constraint,用其 Template 的 Rego 代码对请求资源求值。Rego 查询 violation 集合——若非空则违规。

返回 AdmissionReview 响应

若有违规,返回 allowed: false + 违规消息,apiserver 拒绝请求。无违规则 allowed: true。

5Rego 语言与策略编写实战

Rego 是 OPA 的策略语言,声明式、基于逻辑编程。掌握几个核心概念就能写绝大多数 K8s 策略。

5.1 Rego 核心概念

概念语法含义
包package k8srequiredlabels策略的命名空间
规则violation[msg] { ... }定义违规条件,msg 为违规消息
引用input.review.kind.kind访问 AdmissionReview 输入
集合labels := {label | label := input.review.object.metadata.labels[_]}集合推导
全称量词some k; required[k]; not labels[k]对所有 required k,若 labels 中无 k 则...
否定即失败not has_keyRego 的 not 是"无法证明",非逻辑非

5.2 实战策略 1:强制标签

yaml · ConstraintTemplate:强制必须有指定 label
apiVersion: templates.gatekeeper.sh/v1
kind: ConstraintTemplate
metadata:
  name: k8srequiredlabels
spec:
  crd:
    spec:
      names:
        kind: K8sRequiredLabels
      validation:
        openAPIV3Schema:
          type: object
          properties:
            labels:           # 参数:要求的 label 列表
              type: array
              items:
                type: string
  targets:
  - target: admission.k8s.gatekeeper.sh
    rego: |
      package k8srequiredlabels

      violation[{"msg": msg, "details": {"missing_labels": missing}}] {
        # 1. 获取对象的所有 label key
        provided := {label | label := input.review.object.metadata.labels[label]}
        # 2. 获取参数要求的 label 列表
        required := {label | label := input.parameters.labels[_]}
        # 3. 计算缺失的 label
        missing := required - provided
        # 4. 若缺失非空则违规
        count(missing) > 0
        msg := sprintf("你缺少了必需的 label: %v", [missing])
      }
yaml · Constraint:所有 Deployment 必须有 app、env、team 标签
apiVersion: constraints.gatekeeper.sh/v1beta1
kind: K8sRequiredLabels
metadata:
  name: require-deployment-labels
spec:
  match:
    kinds:
    - apiGroups: ["apps"]
      kinds: ["Deployment"]
    namespaces: ["prod", "staging"]   # 仅这两个 NS 生效
  parameters:
    labels: ["app", "env", "team"]    # 必须有这三个 label
测试:缺 label 的 Deployment 被拒 $ kubectl create deploy test --image=nginx -n prod Error from server (Forbidden): admission webhook "validation.gatekeeper.sh" denied the request: [K8sRequiredLabels] 你缺少了必需的 label: {"app", "env", "team"}

5.3 实战策略 2:镜像来源限制

yaml · ConstraintTemplate:只允许批准的镜像 registry
apiVersion: templates.gatekeeper.sh/v1
kind: ConstraintTemplate
metadata:
  name: k8sallowedrepos
spec:
  crd:
    spec:
      names:
        kind: K8sAllowedRepos
      validation:
        openAPIV3Schema:
          type: object
          properties:
            repos:
              type: array
              items: {type: string}
  targets:
  - target: admission.k8s.gatekeeper.sh
    rego: |
      package k8sallowedrepos

      violation[{"msg": msg}] {
        # 遍历所有 container
        container := input.review.object.spec.containers[_]
        # 取镜像名
        image := container.image
        # 检查是否以任一批准的 repo 开头
        not startswith_any(image, input.parameters.repos)
        msg := sprintf("镜像 %v 不在批准的 registry 列表中: %v", [image, input.parameters.repos])
      }

      # 辅助规则:image 是否以 repos 中任一开头
      startswith_any(image, repos) {
        repo := repos[_]
        startswith(image, repo)
      }

      # 也检查 initContainers
      violation[{"msg": msg}] {
        container := input.review.object.spec.initContainers[_]
        image := container.image
        not startswith_any(image, input.parameters.repos)
        msg := sprintf("initContainer 镜像 %v 不在批准列表中", [image])
      }
yaml · Constraint:prod 只允许公司 registry
apiVersion: constraints.gatekeeper.sh/v1beta1
kind: K8sAllowedRepos
metadata:
  name: prod-registry-only
spec:
  match:
    kinds:
    - apiGroups: [""]
      kinds: ["Pod"]
    - apiGroups: ["apps"]
      kinds: ["Deployment","StatefulSet","DaemonSet"]
    namespaces: ["prod"]
  parameters:
    repos:
    - "registry.corp.com/"
    - "docker.io/library/"   # 允许官方镜像

5.4 实战策略 3:禁止 latest 标签

yaml · ConstraintTemplate:禁止使用 :latest 标签
apiVersion: templates.gatekeeper.sh/v1
kind: ConstraintTemplate
metadata:
  name: k8snolatesttag
spec:
  crd:
    spec:
      names:
        kind: K8sNoLatestTag
  targets:
  - target: admission.k8s.gatekeeper.sh
    rego: |
      package k8snolatesttag

      violation[{"msg": msg}] {
        container := input.review.object.spec.containers[_]
        image := container.image
        # 镜像以 :latest 结尾,或没有 tag(默认 latest)
        endswith(image, ":latest")
        msg := sprintf("镜像 %v 使用了 :latest 标签,请使用具体版本号", [image])
      }

      violation[{"msg": msg}] {
        container := input.review.object.spec.containers[_]
        image := container.image
        # 无 tag(不含 :)则默认 latest
        not contains(image, ":")
        msg := sprintf("镜像 %v 未指定 tag(默认 latest),请用具体版本", [image])
      }

6Gatekeeper 高级特性:数据复制与豁免

6.1 数据复制(Data Replication)

有些策略需要引用集群中其他对象的信息。例如"每个 NS 最多 10 个 Deployment"需要知道当前 NS 有多少 Deployment。Gatekeeper 通过 Config CRD 的 sync 配置将指定资源复制到 OPA 的 data.inventory 中供 Rego 查询。

yaml · Config:同步 Namespace 和 Ingress 到 OPA
apiVersion: config.gatekeeper.sh/v1
kind: Config
metadata:
  name: config
spec:
  sync:
    syncOnly:
    - group: ""
      version: "v1"
      kind: "Namespace"
    - group: "networking.k8s.io"
      version: "v1"
      kind: "Ingress"
    # 同步后 Rego 可通过 data.inventory.namespace["prod"] 访问
rego · 用 inventory 实现"每 NS 最多 N 个 Deployment"
package nsdeploymentlimit

violation[{"msg": msg}] {
  ns := input.review.object.metadata.namespace
  # 从 inventory 统计该 NS 现有 Deployment 数
  count([d | d := data.inventory.cluster["apps"]["v1"]["Deployment"][ns][_]]) > input.parameters.max
  msg := sprintf("NS %v 的 Deployment 数超过上限 %v", [ns, input.parameters.max])
}

6.2 豁免机制

Gatekeeper 支持多级豁免,避免策略误伤系统组件:

豁免级别配置位置示例
全局豁免Config CRD match.excludedNamespaceskube-system 永不检查
Constraint 级Constraint spec.match.excludedNamespaces某策略豁免 monitoring NS
对象级豁免注解对象加 gatekeeper.sh/ignore 注解特定 Pod 豁免某策略
yaml · Constraint 级豁免
apiVersion: constraints.gatekeeper.sh/v1beta1
kind: K8sRequiredLabels
metadata:
  name: require-labels
spec:
  match:
    kinds:
    - apiGroups: ["apps"]
      kinds: ["Deployment"]
    excludedNamespaces:      # 这些 NS 不检查
    - "kube-system"
    - "gatekeeper-system"
    - "ingress-nginx"
  parameters:
    labels: ["app", "env"]

7动手实验:部署 Gatekeeper 并实施策略

Step 1:部署 Gatekeeper

bash
# 用 Helm 部署
helm repo add gatekeeper https://open-policy-agent.github.io/gatekeeper/charts
helm install gatekeeper gatekeeper/gatekeeper \
  --namespace gatekeeper-system --create-namespace \
  --set auditInterval=60 \
  --set auditFromCache=true

# 确认组件就绪
kubectl get pods -n gatekeeper-system
# gatekeeper-controller-manager-xxx  1/1  Running
# gatekeeper-audit-xxx               1/1  Running

Step 2:部署标签策略

bash
# 应用 ConstraintTemplate(5.2 的 k8srequiredlabels)
kubectl apply -f k8srequiredlabels-template.yaml
# 应用 Constraint
kubectl apply -f require-deployment-labels-constraint.yaml

# 验证 Template 被编译
kubectl get constrainttemplate k8srequiredlabels
# NAME               STATUS
# k8srequiredlabels  OK

Step 3:测试策略

bash
# 缺 label → 被拒
kubectl create deploy test --image=nginx -n prod
# Error: [K8sRequiredLabels] 你缺少了必需的 label: {"app","env","team"}

# 有 label → 通过
kubectl create deploy valid --image=nginx -n prod \
  -l app=valid,env=prod,team=backend
# deployment.apps/valid created

Step 4:查看审计结果

bash
# Audit 定期扫描已有资源,输出违规
kubectl get k8srequiredlabels require-deployment-labels -o yaml | \
  grep -A20 status
# status:
#   auditTimestamp: "2026-10-29T10:00:00Z"
#   violations:
#   - enforcementAction: deny
#     kind: Deployment
#     message: 你缺少了必需的 label: {"app"}
#     name: old-app
#     namespace: prod

# 说明 old-app 是策略部署前就存在的违规资源,audit 发现了它

Step 5:dry-run 模式(只审计不拒绝)

bash
# 把 Constraint 改为 dryrun,只记录不拒绝(类似 PSA 的 audit)
kubectl patch k8srequiredlabels require-deployment-labels \
  --type=merge -p '{"spec":{"enforcementAction":"dryrun"}}'

# 现在缺 label 的 Deployment 能创建,但 audit 会记录违规
kubectl create deploy test2 --image=nginx -n prod
# deployment.apps/test2 created   ← 不再被拒

# 适合渐进式上线策略

8PSA 与 Gatekeeper 的协同策略

PSA 和 Gatekeeper 不是二选一——它们互补。最佳实践是PSA 管标准 Pod 安全基线,Gatekeeper 管自定义业务策略。

8.1 职责划分

策略类型用 PSA用 Gatekeeper理由
Pod 安全上下文(privileged/hostPath/capabilities)✓✗PSA 内置、零开销、K8s 原生
镜像来源限制✗✓PSA 无法表达
标签/注解规范✗✓PSA 无法表达
资源配额/限制✗可但 ResourceQuota 更合适ResourceQuota 是 K8s 原生
命名规范✗✓PSA 无法表达
拓扑约束(如每节点最多 N Pod)✗✓需 inventory 查询
跨资源一致性(如 Service 必须有对应 Deployment)✗✓需数据复制
NS 级配额✗可但 LimitRange/Quota 更合适原生资源更高效

8.2 协同配置示例

bash · 生产 NS 的完整准入配置
# 1. PSA:强制 restricted(Pod 安全基线)
kubectl label ns prod \
  pod-security.kubernetes.io/enforce=restricted \
  pod-security.kubernetes.io/enforce-version=latest

# 2. Gatekeeper:业务策略(镜像来源、标签、命名等)
kubectl apply -f - <<'EOF'
apiVersion: constraints.gatekeeper.sh/v1beta1
kind: K8sAllowedRepos
metadata: {name: prod-repo}
spec:
  match:
    kinds: [{apiGroups: [""], kinds: ["Pod"]}]
    namespaces: ["prod"]
  parameters:
    repos: ["registry.corp.com/"]
EOF

kubectl apply -f - <<'EOF'
apiVersion: constraints.gatekeeper.sh/v1beta1
kind: K8sRequiredLabels
metadata: {name: prod-labels}
spec:
  match:
    kinds: [{apiGroups: ["apps"], kinds: ["Deployment"]}]
    namespaces: ["prod"]
  parameters:
    labels: ["app","env","team","cost-center"]
EOF

# 3. ResourceQuota:资源配额(原生)
kubectl apply -f - <<'EOF'
apiVersion: v1
kind: ResourceQuota
metadata: {name: prod-quota, namespace: prod}
spec:
  hard:
    requests.cpu: "100"
    requests.memory: 200Gi
    persistentvolumeclaims: "20"
EOF

# 三层协同:PSA 管安全上下文,Gatekeeper 管业务策略,Quota 管资源
分层原则

策略放在最合适的层:能用 K8s 原生(PSA/ResourceQuota/LimitRange)就不用 Gatekeeper(原生更高效、无额外 webhook 延迟);Gatekeeper 只做原生无法表达的自定义策略。这样既保证安全又最小化准入延迟。

9生产案例:策略治理的真实教训

案例 A:Gatekeeper webhook 不可用导致全集群写停

现象

Gatekeeper controller Pod 因 OOM 被杀,apiserver 的 admission webhook 调用超时。由于 webhook 配置为 failurePolicy: Fail,所有需准入的资源创建全部超时失败,集群写操作停摆 8 分钟。

根因:failurePolicy: Fail 意味着 webhook 不可用时拒绝请求。Gatekeeper OOM 是因为同步了过多资源到 inventory(配了 syncAll: true)。

解决:(1) 给 Gatekeeper controller 调大 memory limit;(2) syncOnly 只同步策略需要的资源,不 syncAll;(3) 关键集群考虑 failurePolicy: Ignore + 依赖 audit 事后发现违规(牺牲实时性换可用性);(4) 配 timeoutSeconds: 3 避免长超时。

案例 B:PSA enforce=restricted 导致系统组件无法启动

现象

运维误将 pod-security.kubernetes.io/enforce=restricted 加到所有 NS(含 kube-system),CSI 驱动、CNI、kube-proxy 等系统组件因需 hostPath/privileged 全部无法创建,集群瘫痪。

根因:系统 NS 未加入 PSA 豁免列表。

解决:PSA 配置的 exemptions.namespaces 必须含 kube-system, kube-public, kube-node-lease 及所有系统组件 NS(ingress-nginx、cert-manager、longhorn-system 等)。用脚本检查所有含 system label 的 NS 确保豁免。

案例 C:Rego 策略未覆盖 initContainers 导致绕过

现象

镜像来源限制策略只检查 spec.containers,攻击者在 initContainers 用未批准镜像拉取恶意代码到 emptyDir,主 container 读取执行,绕过策略。

根因:Rego 只遍历 containers,漏了 initContainers 和 ephemeralContainers。

解决:所有镜像相关策略必须同时检查三类 container。用 Gatekeeper 的 containment.all_containers 辅助规则或手写三段 violation 规则。代码审查清单加入"是否覆盖 initContainers"。

10排障指南:准入策略诊断矩阵

现象诊断步骤常见根因解决
Pod 创建被拒 "violates PodSecurity"看错误消息中的等级和字段;kubectl label ns <ns> --show-labels 确认 enforce 等级Pod spec 不满足 PSA 等级(如 restricted 要求 runAsNonRoot)加 securityContext 或降 NS 等级
Pod 创建被拒 "admission webhook denied"kubectl get constraint -o yaml 看 violations;看 Gatekeeper controller 日志Gatekeeper Constraint 拒绝修正资源使其满足策略,或调整策略
所有资源创建超时kubectl get validatingwebhookconfiguration 看 webhook 状态;检查 Gatekeeper Podwebhook 不可用 + failurePolicy: Fail恢复 webhook Pod;临时改 failurePolicy: Ignore
ConstraintTemplate 状态 errorkubectl get constrainttemplate <name> -o yaml 看 statusRego 语法错误 / 编译失败用 opa check policy.rego 本地验证语法
策略未生效(违规资源存在但未被拒)检查 Constraint 的 match 是否覆盖该资源;检查 enforcementActionmatch 不匹配 / enforcementAction=dryrun / 豁免修正 match;改 enforcementAction: deny
PSA warn 但不拒绝确认 NS 是否有 enforce label(可能只有 warn/audit)只配了 warn/audit 未配 enforce加 enforce label
Gatekeeper audit 不更新kubectl logs -n gatekeeper-system -l app=gatekeeper-auditaudit Pod 异常 / auditInterval 过长重启 audit Pod;调 auditInterval
准入排障速查
第一步命令
看错误消息kubectl 输出已含策略名和违规原因
查 PSA 等级kubectl get ns <ns> --show-labels | grep pod-security
查 Constraintkubectl get constraint -o yaml | grep -A10 violations
查 webhook 健康kubectl get pods -n gatekeeper-system
本地测 Regoopa eval -i input.json -d policy.rego "data.k8srequiredlabels.violation"

11策略即代码:GitOps 与策略生命周期管理

策略本身也是 K8s 资源(ConstraintTemplate/Constraint),应纳入 Git 管理,通过 GitOps(ArgoCD/Flux)部署。这带来版本控制、审计、回滚等好处。

11.1 策略仓库结构

text · 推荐的策略仓库结构
policies-repo/
├── templates/                    # ConstraintTemplate(策略逻辑)
│   ├── k8srequiredlabels.yaml
│   ├── k8sallowedrepos.yaml
│   └── k8snolatesttag.yaml
├── constraints/                  # Constraint(策略实例)
│   ├── prod/
│   │   ├── require-labels.yaml
│   │   ├── registry-only.yaml
│   │   └── no-latest-tag.yaml
│   ├── staging/
│   │   └── require-labels.yaml   # staging 可能放宽某些策略
│   └── dev/
│       └── no-latest-tag.yaml    # dev 只保留最关键策略
├── tests/                        # Rego 单元测试
│   ├── k8srequiredlabels_test.rego
│   └── k8sallowedrepos_test.rego
└── .github/workflows/
    └── policy-ci.yaml            # CI:opa check + opa test

11.2 Rego 策略单元测试

rego · k8srequiredlabels_test.rego
package k8srequiredlabels

# 测试:有所有必需 label → 无违规
test_no_violation_when_all_labels_present {
  input_review := {"object": {"metadata": {"labels": {"app": "x", "env": "y", "team": "z"}}}}
  input := {"review": input_review, "parameters": {"labels": ["app", "env", "team"]}}
  count(violation_with_input(input)) == 0
}

# 测试:缺 label → 有违规
test_violation_when_label_missing {
  input_review := {"object": {"metadata": {"labels": {"app": "x"}}}}
  input := {"review": input_review, "parameters": {"labels": ["app", "env", "team"]}}
  count(violation_with_input(input)) == 1
}

# 辅助:用指定 input 求值 violation
violation_with_input(i) = v {
  v := violation with input as i
}
bash · CI 中跑策略测试
# opa test 跑所有 _test.rego
opa test templates/ tests/
# PASS: 2/2

# opa check 语法检查
opa check templates/k8srequiredlabels.yaml
# OK

# CI pipeline 示例
# .github/workflows/policy-ci.yaml
# - name: Validate Rego
#   run: |
#     opa check templates/
#     opa test templates/ tests/
# - name: Dry-run against cluster
#   run: |
#     # 用 gator(Gatekeeper 的 CLI)对 staging 集群 dry-run
#     gator test --filename=templates/ --filename=constraints/staging/

11.3 策略上线流程

阶段enforcementAction目的
1. 开发测试—(本地 opa test)验证 Rego 逻辑正确
2. dryrun 上线dryrun生产环境观察违规但不拒绝
3. warn 上线warnkubectl 返回警告,开发者感知
4. enforcedeny(默认)硬拒绝,正式生效

12思考题与知识点检查

思考题

  1. 原理题:PSA 的 enforce/audit/warn 三个级别各有什么作用?为什么推荐 audit 等级比 enforce 高一级?设计一个渐进式收紧的迁移方案。
  2. 设计题:为一个多租户集群设计完整的准入策略体系。租户 A(高安全)、租户 B(一般业务)、系统 NS 各应配什么 PSA 等级和 Gatekeeper 策略?用表格列出。
  3. 实操题:写一个 Gatekeeper ConstraintTemplate,策略为"所有 PVC 必须来自指定 StorageClass 列表"。给出 Rego 代码、Constraint YAML 和测试用例。
  4. 安全题:为什么镜像来源策略必须同时检查 containers、initContainers 和 ephemeralContainers?只检查 containers 会怎样?构造一个绕过场景。
  5. 故障题:Gatekeeper webhook 超时导致所有 Pod 创建失败。failurePolicy: Fail 和 failurePolicy: Ignore 各有什么安全影响?生产环境应如何选择?
  6. 进阶题:用 Gatekeeper 的数据复制实现"每个 NS 的 Ingress host 不能重复"策略。写出 Config sync 配置和 Rego 策略。
  7. 原理题:PSA 是内置准入插件,Gatekeeper 是外部 webhook。从延迟、可用性、功能三个维度对比两者的优劣。什么策略适合 PSA,什么适合 Gatekeeper?
  8. 实操题:为你的策略仓库写一个 CI pipeline,包含 Rego 语法检查、单元测试、对 staging 集群的 dry-run。给出 GitHub Actions YAML。

知识点检查表

知识点掌握程度(自评 1-5)
PSP→PSA→OPA 三代演进与各自定位□ 1 □ 2 □ 3 □ 4 □ 5
PodSecurity Standards 三等级约束□ 1 □ 2 □ 3 □ 4 □ 5
PSA enforce/audit/warn 与渐进式收紧□ 1 □ 2 □ 3 □ 4 □ 5
OPA Gatekeeper 架构(Controller/Audit/OPA引擎)□ 1 □ 2 □ 3 □ 4 □ 5
ConstraintTemplate 与 Constraint 模型□ 1 □ 2 □ 3 □ 4 □ 5
Rego 语言与策略编写□ 1 □ 2 □ 3 □ 4 □ 5
数据复制与豁免机制□ 1 □ 2 □ 3 □ 4 □ 5
PSA 与 Gatekeeper 协同设计□ 1 □ 2 □ 3 □ 4 □ 5
策略即代码与 GitOps 生命周期□ 1 □ 2 □ 3 □ 4 □ 5
准入排障与 webhook 可用性□ 1 □ 2 □ 3 □ 4 □ 5