Skip to content

Pod Security Standards

三个安全级别

K8s 1.25+ 内置 Pod Security Admission,定义三个安全级别:

级别说明适用场景
Privileged无限制系统组件、特权工具
Baseline防止已知特权提升通用应用
Restricted最严格,遵循最佳实践安全敏感应用

命名空间级别配置

yaml
apiVersion: v1
kind: Namespace
metadata:
  name: production
  labels:
    # 强制执行 restricted 级别
    pod-security.kubernetes.io/enforce: restricted
    pod-security.kubernetes.io/enforce-version: latest
    # 警告(不阻止,但显示警告)
    pod-security.kubernetes.io/warn: restricted
    pod-security.kubernetes.io/warn-version: latest
    # 审计(记录到审计日志)
    pod-security.kubernetes.io/audit: restricted
    pod-security.kubernetes.io/audit-version: latest

Restricted 级别要求

yaml
spec:
  securityContext:
    runAsNonRoot: true          # 必须以非 root 运行
    runAsUser: 1000             # 指定 UID
    seccompProfile:
      type: RuntimeDefault      # 启用 seccomp
  containers:
  - name: app
    securityContext:
      allowPrivilegeEscalation: false  # 禁止特权提升
      readOnlyRootFilesystem: true     # 只读根文件系统
      capabilities:
        drop: ["ALL"]                  # 删除所有 capabilities
        # add: ["NET_BIND_SERVICE"]    # 只在需要时添加

OPA Gatekeeper 策略

yaml
# 安装 Gatekeeper
kubectl apply -f https://raw.githubusercontent.com/open-policy-agent/gatekeeper/release-3.14/deploy/gatekeeper.yaml

# 定义约束模板
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("缺少必要标签: %v", [missing])
      }

---
# 应用约束
apiVersion: constraints.gatekeeper.sh/v1beta1
kind: K8sRequiredLabels
metadata:
  name: require-app-label
spec:
  match:
    kinds:
    - apiGroups: ["apps"]
      kinds: ["Deployment"]
    namespaces: ["production"]
  parameters:
    labels: ["app", "version", "team"]

本站内容由 褚成志 整理编写,仅供学习参考