Skip to content

第四部分 K8s 安全进阶

安全是生产环境 Kubernetes 运维的重中之重。本部分深入讲解 Pod 安全标准、NetworkPolicy、Secret 加密、RBAC 深度实践和 OPA/Gatekeeper 策略引擎。


第 15 章 Pod 安全标准(PSS/PSA)

15.1 Pod Security Standards

Kubernetes 内置三个安全级别:

级别说明
privileged无限制,适合系统组件
baseline最小限制,阻止已知高危配置
restricted最严格,遵循 Pod 安全最佳实践

15.2 Pod Security Admission

PSA 是 K8s 1.23+ 内置的准入控制器,用于强制执行 PSS。

yaml
# 命名空间标签
apiVersion: v1
kind: Namespace
metadata:
  name: restricted-ns
  labels:
    pod-security.kubernetes.io/enforce: restricted
    pod-security.kubernetes.io/audit: restricted
    pod-security.kubernetes.io/warn: restricted

15.3 常见限制

  • 禁止 privileged 容器
  • 禁止以 root 运行
  • 禁止挂载敏感主机路径
  • 限制 capabilities
  • 要求只读根文件系统
yaml
spec:
  securityContext:
    runAsNonRoot: true
    seccompProfile:
      type: RuntimeDefault
  containers:
  - name: app
    image: nginx:1.25
    securityContext:
      allowPrivilegeEscalation: false
      readOnlyRootFilesystem: true
      capabilities:
        drop:
        - ALL

15.4 本章练习

  1. 为一个命名空间启用 restricted 策略。
  2. 创建一个违反策略的 Pod,观察报错。
  3. 修改 Pod 配置使其符合 restricted 标准。

第 16 章 Secret 与 etcd 加密

16.1 Secret 的风险

Secret 数据默认以 base64 编码存储在 etcd 中,不是加密。拥有 etcd 访问权限的人可以读取 Secret。

16.2 启用 etcd 加密

yaml
# EncryptionConfiguration
apiVersion: apiserver.config.k8s.io/v1
kind: EncryptionConfiguration
resources:
  - resources:
    - secrets
    - configmaps
    providers:
    - aescbc:
        keys:
        - name: key1
          secret: <BASE64_ENCODED_SECRET>
    - identity: {}
bash
# 修改 API Server 启动参数
--encryption-provider-config=/etc/kubernetes/encryption-config.yaml

16.3 Secret 管理最佳实践

  • 启用 etcd 加密
  • 使用外部 Secret 管理工具(Vault、External Secrets Operator)
  • 限制 Secret 的读取权限
  • 定期轮换 Secret
  • 不在环境变量中使用 Secret,优先使用 Volume 挂载

16.4 本章练习

  1. 启用 etcd Secret 加密。
  2. 验证新创建的 Secret 已加密。
  3. 部署 External Secrets Operator 或 HashiCorp Vault。

第 17 章 RBAC 深度实践

17.1 RBAC 最小权限原则

  • 只授予完成任务所需的最小权限
  • 避免使用 cluster-admin
  • 按职责划分 Role
  • 定期审计 RBAC 配置

17.2 聚合 ClusterRole

yaml
apiVersion: rbac.authorization.k8s.io/v1
kind: ClusterRole
metadata:
  name: aggregate-pod-reader
  labels:
    rbac.example.com/aggregate-to-pod-reader: "true"
rules:
- apiGroups: [""]
  resources: ["pods"]
  verbs: ["get", "list", "watch"]

17.3 模拟用户权限

bash
# 检查用户是否有权限
kubectl auth can-i create pods --as=alice -n dev

# 检查 ServiceAccount 权限
kubectl auth can-i get secrets --as=system:serviceaccount:dev:my-sa -n dev

17.4 本章练习

  1. 为开发团队设计一套 RBAC 方案。
  2. 使用 auth can-i 审计用户权限。
  3. 找出权限过大的 Role/ClusterRoleBinding。

第 18 章 OPA/Gatekeeper 策略引擎

18.1 什么是 OPA

OPA(Open Policy Agent)是通用策略引擎,K8s 中常与 Gatekeeper 结合使用。

18.2 Gatekeeper 架构

  • ConstraintTemplate:定义策略模板(Rego 语言)
  • Constraint:基于模板创建策略实例

18.3 示例:限制镜像仓库

yaml
apiVersion: templates.gatekeeper.sh/v1
kind: ConstraintTemplate
metadata:
  name: k8sallowedrepos
spec:
  crd:
    spec:
      names:
        kind: K8sAllowedRepos
  targets:
  - target: admission.k8s.gatekeeper.sh
    rego: |
      package k8sallowedrepos
      violation[{"msg": msg}] {
        container := input.review.object.spec.containers[_]
        not startswith(container.image, "harbor.example.com/")
        msg := sprintf("image '%v' is not from allowed registry", [container.image])
      }
yaml
apiVersion: constraints.gatekeeper.sh/v1beta1
kind: K8sAllowedRepos
metadata:
  name: allowed-repos
spec:
  match:
    kinds:
    - apiGroups: [""]
      kinds: ["Pod"]
  parameters: {}

18.4 本章练习

  1. 部署 Gatekeeper。
  2. 编写一个限制容器镜像来源的策略。
  3. 测试策略是否生效。

第四部分总结

完成本阶段学习后,你应该能够:

  • 使用 PSS/PSA 加固 Pod 安全
  • 启用 etcd 加密保护 Secret
  • 设计最小权限 RBAC 方案
  • 使用 OPA/Gatekeeper 实施自定义策略

进入第五部分:多集群与 GitOps