Security Context 和 Pod Security Policy

    Kubernetes 提供了三种配置 Security Context 的方法:

    • Container-level Security Context:仅应用到指定的容器
    • Pod-level Security Context:应用到 Pod 内所有容器以及 Volume
    • Pod Security Policies(PSP):应用到集群内部所有 Pod 以及 Volume

    Container-level Security Context 仅应用到指定的容器上,并且不会影响 Volume。比如设置容器运行在特权模式:

    应用到 Pod 内所有容器,并且还会影响 Volume(包括 fsGroup 和 selinuxOptions)。

    1. kind: Pod
    2. metadata:
    3. name: hello-world
    4. spec:
    5. containers:
    6. # specification of the pod's containers
    7. # ...
    8. securityContext:
    9. fsGroup: 1234
    10. supplementalGroups: [5678]
    11. seLinuxOptions:

    Pod Security Policies(PSP)是集群级的 Pod 安全策略,自动为集群内的 Pod 和 Volume 设置 Security Context。

    限制容器的 host 端口范围为 8000-8080:

    限制只允许使用 lvm 和 cifs 等 flexVolume 插件:

    1. apiVersion: extensions/v1beta1
    2. kind: PodSecurityPolicy
    3. metadata:
    4. name: allow-flex-volumes
    5. fsGroup:
    6. rule: RunAsAny
    7. runAsUser:
    8. rule: RunAsAny
    9. seLinux:
    10. rule: RunAsAny
    11. supplementalGroups:
    12. rule: RunAsAny
    13. volumes:
    14. - flexVolume
    15. allowedFlexVolumes:
    16. - driver: example/lvm
    17. - driver: example/cifs

    SELinux (Security-Enhanced Linux) 是一种强制访问控制(mandatory access control)的实现。它的作法是以最小权限原则(principle of least privilege)为基础,在 Linux 核心中使用 Linux 安全模块(Linux Security Modules)。SELinux 主要由美国国家安全局开发,并于 2000 年 12 月 22 日发行给开放源代码的开发社区。

    可以通过 runcon 来为进程设置安全策略,ls 和 ps 的 - Z 参数可以查看文件或进程的安全策略。

    • 开启:SELINUX=enforcing
    • 关闭:SELINUX=disabled

    通过命令临时修改:

    • 开启:setenforce 1
    • 关闭:setenforce 0

    查询 SELinux 状态:

    1. apiVersion: v1
    2. kind: Pod
    3. name: hello-world
    4. spec:
    5. containers:
    6. name: test-container
    7. command:
    8. - sleep
    9. - "6000"
    10. volumeMounts:
    11. - mountPath: /mounted_volume
    12. name: test-volume
    13. restartPolicy: Never
    14. hostPID: false
    15. hostIPC: false
    16. securityContext:
    17. seLinuxOptions:
    18. level: "s0:c2,c3"
    19. volumes:
    20. - name: test-volume
    21. emptyDir: {}

    这会自动给 docker 容器生成如下的 HostConfig.Binds:

    对应的 volume 也都会正确设置 SELinux:

    1. $ ls -Z /var/lib/kubelet/pods/f734678c-95de-11e6-89b0-42010a8c0002/volumes
    2. drwxr-xr-x. root root unconfined_u:object_r:svirt_sandbox_file_t:s0:c2,c3 kubernetes.io~empty-dir