如何用OPA Gatekeeper强制限制容器必须以非root身份运行?
解读
在国内金融、运营商、政务云等等保2.0三级以上场景中,“容器禁止以uid 0启动”是基线红线,也是CIS Kubernetes Benchmark的必测项。面试官问Gatekeeper,不是考“写一条Rego”,而是验证候选人能否把政策即代码(Policy-as-Code)落地到DevSecOps流水线,并兼顾灰度发布、审计溯源、性能影响与应急逃生。回答必须体现:
- 政策模型(ConstraintTemplate + Constraint)
- 参数化与版本管理
- 与华为云CCE、阿里云ACK、腾讯云TKE等托管K8s的Admission Webhook兼容性
- 失败时的审计日志与Prometheus告警对接方式
知识点
- OPA Gatekeeper v3架构:Admission Webhook + Audit + Sync + Controller
- ConstraintTemplate:定义Rego逻辑与输入schema,复用性高
- Constraint:实例化模板,指定匹配范围(namespace、label、镜像仓库等)
- Kubernetes安全上下文:
securityContext.runAsNonRoot、runAsUser、runAsGroup、fsGroup - 等保2.0控制点:安全计算环境—入侵防范—最小权限;安全区域边界—恶意代码防范
- CIS 5.2.7:“Ensure that containers do not run as root”
- 灰度策略:使用
parameters.excludeNamespaces或namespaceSelector让kube-system、monitoring、istio-system先豁免 - 审计回溯:Gatekeeper Audit每60秒扫描集群,把违规写入
status.violations,可通过kube-state-metrics暴露为Grafana大盘 - 性能调优:
--enable-generator=false关闭证书自转;--audit-match-kind-only=true减少List压力 - 应急逃生:给SRE组创建
gatekeeper-exempt标签的Namespace,绑定RBAC仅ClusterAdmin可写,防止误锁集群
答案
步骤一:安装Gatekeeper(国内镜像加速)
helm repo add gatekeeper https://open-policy-agent.github.io/gatekeeper/charts
helm install gatekeeper/gatekeeper --generate-name \
--set controllerManager.exemptNamespaces={"kube-system","monitoring"} \
--set controllerManager.image.repository=registry.cn-hangzhou.aliyuncs.com/acs/gatekeeper \
--set audit.image.repository=registry.cn-hangzhou.aliyuncs.com/acs/gatekeeper-audit
步骤二:定义ConstraintTemplate(mustrunasnonroot-template.yaml)
apiVersion: templates.gatekeeper.sh/v1beta1
kind: ConstraintTemplate
metadata:
name: k8spsphostnonroot
spec:
crd:
spec:
names:
kind: K8sPSPHostNonRoot
validation:
openAPIV3Schema:
type: object
properties:
exemptImages:
type: array
items:
type: string
pattern: "^[a-z0-9.-]+(:[0-9]+)?/[a-z0-9/-]+(:.+)?$"
targets:
- target: admission.k8s.gatekeeper.sh
rego: |
package k8spsphostnonroot
violation[{"msg": msg}] {
container := input.review.object.spec.containers[_]
not container.securityContext.runAsNonRoot == true
not exempt_image(container.image)
msg := sprintf("Container <%v> in Pod <%v/%v> is attempting to run as root, which is prohibited by policy.", [container.name, input.review.object.metadata.namespace, input.review.object.metadata.name])
}
exempt_image(img) {
exempt := input.parameters.exemptImages[_]
startswith(img, exempt)
}
步骤三:下发全局Constraint(nonroot-policy.yaml)
apiVersion: constraints.gatekeeper.sh/v1beta1
kind: K8sPSPHostNonRoot
metadata:
name: pods-must-run-as-non-root
spec:
match:
kinds:
- apiGroups: [""]
kinds: ["Pod"]
namespaces: ["prod","staging"] # 灰度范围
parameters:
exemptImages:
- "registry.k8s.io/pause:"
- "registry.cn-hangzhou.aliyuncs.com/acs/csi-plugin:"
步骤四:验证
kubectl apply -f - <<EOF
apiVersion: v1
kind: Pod
metadata:
name: bad-root
namespace: prod
spec:
containers:
- name: app
image: nginx:1.25
EOF
# 期望返回:Error from server (Forbidden): admission webhook "validation.gatekeeper.sh" denied the request: Container <app> in Pod <prod/bad-root> is attempting to run as root...
步骤五:审计与告警
kubectl get k8spsphostnonroot pods-must-run-as-non-root -o jsonpath='{.status.violations[*].name}'
通过阿里云日志服务SLS或腾讯云CLS采集gatekeeper-audit容器stdout,配置告警规则:
- 近5分钟新增违规>5即@值班群
- 每周生成等保测评报告PDF,自动上传堡垒机
拓展思考
-
多租户场景:如何给不同BU(事业群)分配自助Constraint权限?
答:使用OPA Gatekeeper v3.11的Config Sync把Constraints和ConstraintTemplates放到各BU的GitLab子组,通过ArgoCD ApplicationSet做Namespace级RBAC,只允许修改match.namespaceSelector字段,防止越权。 -
镜像构建阶段提前拦截:把同一条Rego编译成conftest策略,嵌入Harbor的Webhook或阿里云ACR云原生构建,镜像push时即扫描
config.User字段,如果为0直接拒绝,左移减少运行时Admission压力。 -
与PodSecurity Standards冲突:K8s 1.25+内置PodSecurity admission,restricted模式也要求
runAsNonRoot。此时应关闭内置控制器或把Gatekeeper enforce级别设为warn,避免双重拒绝导致CI流水线无法调试。 -
性能兜底:在双11、春晚红包等大促前,通过Gatekeeper Profiler(
--enable-profiling)采集P99延迟,若Admission Review>30 ms,临时把policy降级为dryrun并切入Falco做行为检测,形成纵深防御弹性策略。