从 PodSecurityPolicy 退役到 PodSecurity Standards 的范式迁移,再到 OPA Gatekeeper 的 Rego 策略引擎与 Constraint 模型,构建 K8s 准入层的纵深策略治理体系。
Kubernetes 的准入控制(Admission Control)是 API 请求在鉴权通过后、持久化到 etcd 前的最后一道关卡。它不仅能校验(Validating),还能修改请求(Mutating)。Pod 安全策略治理经历了三代演进:
| 阶段 | 机制 | 版本 | 状态 | 特点 |
|---|---|---|---|---|
| 第一代 | 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 表达任意策略,可扩展但需额外部署 |
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 创建将无准入控制,安全降级。
内置在 kube-apiserver 的准入插件,零额外部署。覆盖 Pod 安全最核心的三个等级,配置只需 NS label。但策略固定,无法自定义。
适合:标准 Pod 安全基线,快速启用,不想维护额外组件。
独立 Admission Webhook,用 Rego 语言表达任意策略(镜像来源、标签规范、资源配额、拓扑约束等)。功能强大但需部署运维。
适合:超出 PSA 范围的自定义策略、多团队策略治理、合规审计。
策略用 YAML 而非 Rego 表达,学习曲线更低。支持 mutate + validate + generate。适合不熟悉 Rego 的团队。
适合:偏好 YAML 策略、需要 mutate/generate 的场景。
把准入控制比作"大厦门禁":PSA 是物业标配的门禁卡系统——三种权限等级(访客/员工/管理员),开箱即用,但只能管这三种。OPA Gatekeeper 是可编程的智能门禁——你可以写规则"穿工牌且非节假日且 7-19 点才能进机房",灵活但要请人写规则。Kyverno 是用填表代替写代码的智能门禁——规则用表格表达,不用学编程,但表达力略弱。
PodSecurity Standards 定义了三个预置安全等级,每个等级是一组 Pod 字段的约束集合。PSA 准入插件按 NS label 决定该 NS 执行哪个等级的审计/强制。
| 等级 | 定位 | 关键限制 | 典型用途 |
|---|---|---|---|
privileged | 无限制(最宽松) | 无任何限制 | 系统组件、CSI 驱动、CNI、需 hostNetwork 的特殊工作负载 |
baseline | 阻止已知提权向量 | 禁 privileged、hostPID、hostIPC、hostNetwork、hostPath、不允许添加大多数 Linux capabilities、seLinuxOptions、seccomp 不能设 Unconfined | 一般业务应用 |
restricted | 严格硬化(最严格) | 在 baseline 基础上:必须设 runAsNonRoot、drop ALL capabilities、seccompProfile 设 RuntimeDefault、只允许特定 volume 类型 | 生产业务、多租户、合规要求 |
restricted 是生产推荐等级。以下是它对 Pod spec 的完整约束,每条都对应一个历史安全漏洞:
| 约束 | 对应字段 | 防御的攻击 |
|---|---|---|
必须 runAsNonRoot: true 或 image 用户非 0 | spec.securityContext.runAsNonRoot / container.securityContext.runAsNonRoot | 容器内 root 提权 → 逃逸到节点 |
必须 allowPrivilegeEscalation: false | container.securityContext.allowPrivilegeEscalation | 子进程获取比父进程更多权限(setuid) |
| 必须 drop ALL capabilities,可选 add NET_BIND_SERVICE | container.securityContext.capabilities | 用 CAP_SYS_ADMIN 等提权 |
seccompProfile 必须设 RuntimeDefault 或 Localhost | container.securityContext.seccompProfile | 未限制的系统调用(如 keyctl、bpf) |
| 禁 hostNetwork/hostPID/hostIPC | spec.hostNetwork 等 | 看到节点进程、网络命名空间 |
| 禁 hostPath volume | volumes.hostPath | 直接读写节点文件系统 |
| 禁 privileged: true | container.securityContext.privileged | 容器拥有几乎所有 root 能力 |
| volume 类型白名单 | volumes[*] | 仅允许 configMap/secret/emptyDir/projected/downwardAPI/persistentVolumeClaim |
| 禁 seLinuxOptions 自定义 | container.securityContext.seLinuxOptions | SELinux 策略篡改 |
| procMount 默认 Default | container.securityContext.procMount | Unmasked procMount 暴露 /proc 敏感项 |
PSA 通过 apiserver 的 AdmissionConfiguration 配置,定义三个等级的默认行为和豁免:
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
每个 NS 通过 label 覆盖默认等级。这是 PSA 的核心设计——配置即 label,极简:
# 生产 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:违规在 kubectl 响应中返回警告但不拒绝。三者可独立设不同等级——典型做法:enforce=baseline(硬底线),audit=restricted(记录谁不达标),warn=restricted(提示开发者改进)。这种渐进式收紧让迁移不中断业务。
将一个已有集群从无准入控制渐进收紧到 restricted,是 PSA 最典型的实战场景。关键原则:先 audit 再 enforce,避免一次性拒绝导致业务中断。
# 所有业务 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 记录违规)
# 查 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
# 确认无违规后,升级为 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 1-3 但等级升到 restricted。restricted 要求 runAsNonRoot、drop ALL capabilities、seccomp=RuntimeDefault——需要改所有 Deployment 的 securityContext。用 kubectl set env 或批量 patch 自动化。
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
OPA(Open Policy Agent)是 CNCF 毕业项目,Gatekeeper 是 OPA 的 K8s 集成。它将 Rego 策略包装为 K8s Admission Webhook,用 CRD 管理策略,实现"策略即代码、策略即 K8s 资源"。
这是 Gatekeeper 的核心抽象,理解它才能写策略:
ConstraintTemplate 是"法律条文模板"(如"禁止使用未批准的镜像,批准列表由参数提供"),Constraint 是"具体法律"(如"在 prod NS,批准列表 = [registry.corp.com/*]")。一个模板可实例化出多条法律(prod 严格、dev 宽松)。
用户 create/update 一个资源,apiserver 鉴权通过后,向 Gatekeeper 的 webhook 发送 AdmissionReview 请求(含资源完整 spec)。
根据资源的 kind/NS/label 匹配所有 Constraint,筛选出适用的策略。
对每个匹配 Constraint,用其 Template 的 Rego 代码对请求资源求值。Rego 查询 violation 集合——若非空则违规。
若有违规,返回 allowed: false + 违规消息,apiserver 拒绝请求。无违规则 allowed: true。
Rego 是 OPA 的策略语言,声明式、基于逻辑编程。掌握几个核心概念就能写绝大多数 K8s 策略。
| 概念 | 语法 | 含义 |
|---|---|---|
| 包 | 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_key | Rego 的 not 是"无法证明",非逻辑非 |
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])
}
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
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])
}
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/" # 允许官方镜像
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])
}
有些策略需要引用集群中其他对象的信息。例如"每个 NS 最多 10 个 Deployment"需要知道当前 NS 有多少 Deployment。Gatekeeper 通过 Config CRD 的 sync 配置将指定资源复制到 OPA 的 data.inventory 中供 Rego 查询。
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"] 访问
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])
}
Gatekeeper 支持多级豁免,避免策略误伤系统组件:
| 豁免级别 | 配置位置 | 示例 |
|---|---|---|
| 全局豁免 | Config CRD match.excludedNamespaces | kube-system 永不检查 |
| Constraint 级 | Constraint spec.match.excludedNamespaces | 某策略豁免 monitoring NS |
| 对象级豁免注解 | 对象加 gatekeeper.sh/ignore 注解 | 特定 Pod 豁免某策略 |
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"]
# 用 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
# 应用 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
# 缺 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
# 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 发现了它
# 把 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 ← 不再被拒
# 适合渐进式上线策略
PSA 和 Gatekeeper 不是二选一——它们互补。最佳实践是PSA 管标准 Pod 安全基线,Gatekeeper 管自定义业务策略。
| 策略类型 | 用 PSA | 用 Gatekeeper | 理由 |
|---|---|---|---|
| Pod 安全上下文(privileged/hostPath/capabilities) | ✓ | ✗ | PSA 内置、零开销、K8s 原生 |
| 镜像来源限制 | ✗ | ✓ | PSA 无法表达 |
| 标签/注解规范 | ✗ | ✓ | PSA 无法表达 |
| 资源配额/限制 | ✗ | 可但 ResourceQuota 更合适 | ResourceQuota 是 K8s 原生 |
| 命名规范 | ✗ | ✓ | PSA 无法表达 |
| 拓扑约束(如每节点最多 N Pod) | ✗ | ✓ | 需 inventory 查询 |
| 跨资源一致性(如 Service 必须有对应 Deployment) | ✗ | ✓ | 需数据复制 |
| NS 级配额 | ✗ | 可但 LimitRange/Quota 更合适 | 原生资源更高效 |
# 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 只做原生无法表达的自定义策略。这样既保证安全又最小化准入延迟。
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 避免长超时。
运维误将 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 确保豁免。
镜像来源限制策略只检查 spec.containers,攻击者在 initContainers 用未批准镜像拉取恶意代码到 emptyDir,主 container 读取执行,绕过策略。
根因:Rego 只遍历 containers,漏了 initContainers 和 ephemeralContainers。
解决:所有镜像相关策略必须同时检查三类 container。用 Gatekeeper 的 containment.all_containers 辅助规则或手写三段 violation 规则。代码审查清单加入"是否覆盖 initContainers"。
| 现象 | 诊断步骤 | 常见根因 | 解决 |
|---|---|---|---|
| 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 Pod | webhook 不可用 + failurePolicy: Fail | 恢复 webhook Pod;临时改 failurePolicy: Ignore |
| ConstraintTemplate 状态 error | kubectl get constrainttemplate <name> -o yaml 看 status | Rego 语法错误 / 编译失败 | 用 opa check policy.rego 本地验证语法 |
| 策略未生效(违规资源存在但未被拒) | 检查 Constraint 的 match 是否覆盖该资源;检查 enforcementAction | match 不匹配 / 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-audit | audit Pod 异常 / auditInterval 过长 | 重启 audit Pod;调 auditInterval |
| 第一步 | 命令 |
|---|---|
| 看错误消息 | kubectl 输出已含策略名和违规原因 |
| 查 PSA 等级 | kubectl get ns <ns> --show-labels | grep pod-security |
| 查 Constraint | kubectl get constraint -o yaml | grep -A10 violations |
| 查 webhook 健康 | kubectl get pods -n gatekeeper-system |
| 本地测 Rego | opa eval -i input.json -d policy.rego "data.k8srequiredlabels.violation" |
策略本身也是 K8s 资源(ConstraintTemplate/Constraint),应纳入 Git 管理,通过 GitOps(ArgoCD/Flux)部署。这带来版本控制、审计、回滚等好处。
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
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
}
# 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/
| 阶段 | enforcementAction | 目的 |
|---|---|---|
| 1. 开发测试 | —(本地 opa test) | 验证 Rego 逻辑正确 |
| 2. dryrun 上线 | dryrun | 生产环境观察违规但不拒绝 |
| 3. warn 上线 | warn | kubectl 返回警告,开发者感知 |
| 4. enforce | deny(默认) | 硬拒绝,正式生效 |
failurePolicy: Fail 和 failurePolicy: Ignore 各有什么安全影响?生产环境应如何选择?| 知识点 | 掌握程度(自评 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 |