「Kubernetes Objects」- PodSecurityPolicy

加强 Pod 安全

如何在Pod级别为应用定义安全上下文环境?例如,以非特权进程运行该应用,或者限制该应用可以访问的卷的类别

在Pod的spec中使用securityContext字段。

例如以非root用户运行一个应用:

kind: Pod
apiVersion: v1
metadata:
  name: secpod
spec:
  containers:
  - name: shell
    image: centos:7
    command:
      - "sh"
      - "-c"
      - "whatever"
    securityContext:
      runAsUser: 5000

spec.securityContext

Configure a Security Context for a Pod or Container | Kubernetes
Kubernetes API Reference Docs/SecurityContext v1 core

runAsUser:指定运行进程的用户(UID);

runAsGroup:指定运行进程的组(GID,Primary);如果未指定该参数,则默认属于 root 组(GID==0);

fsGroup:指定运行进程的附属组(GID,Supplementary);在 Volume 中已创建的文件也将属于该组,同时组内用户具有 rw 权限;

cat > security-context-demo.yaml <<EOF
---
apiVersion: v1
kind: PersistentVolumeClaim
metadata:
  name: security-context-demo
spec:
  accessModes:
  - ReadWriteOnce
  resources:
    requests:
      storage: 10Gi
  storageClassName: nfs-client
---
apiVersion: apps/v1
kind: Deployment
metadata:
  name: security-context-demo
  labels:
    app: security-context-demo
spec:
  replicas: 1
  selector:
    matchLabels:
      app: security-context-demo
  template:
    metadata:
      labels:
        app: security-context-demo
    spec:
      securityContext:
        runAsUser: 1000
        runAsGroup: 1000
        fsGroup: 1000
      volumes:
      - name: sec-ctx-vol
        persistentVolumeClaim:
          claimName: security-context-demo
      containers:
      - name: sec-ctx-demo
        image: busybox:1.28
        command: [ "sh", "-c", "sleep 1h" ]
        volumeMounts:
        - name: sec-ctx-vol
          mountPath: /data/demo
EOF

kubectl apply -f security-context-demo.yaml

SecurityContext vs. PodSecurityContext

虽然 container 也能够配置 securityContext 属性,但是其为 SecurityContext 对象,而非 PodSecurityContext 对象;
并且 SecurityContext 属性并不能对 Volume 进行修改;

已知问题及限制

部分文件系统无法支持 SecurityContext 特性,例如:
1)在 NFS 中,fsGroup 无法修改文件系统的属组;
2)在 Ceph 中,SecurityContext 能够正常工作;

PodSecurityPolicy

另外一个加强安全级别的方法是使用更强大的「Pod安全策略」(PSP, Pod Security Policies)。可以定义一系列策略,包括一些与上述类似的操作,以及与存储和网络相关的限制。

Removed feature: PodSecurityPolicy was deprecated in Kubernetes v1.21, and removed from Kubernetes in v1.25.

相关链接

Secure A Kubernetes Cluster With Pod Security Policies
Kubernetes/Concepts/Pod Security Policies