如何優(yōu)雅的給 Kubernetes Pod 啟用安全策略
文中的演示和示例均在 v1.18.17 集群中通過驗證。
Pod Security Policies
Pod Security Policies (下文簡稱 psp 或 pod 安全策略)是一種集群級別的全局資源,能夠對 pod 的創(chuàng)建和更新進行細粒度的授權控制。具體來說,一個 psp 對象定義了一組安全性條件,一個 pod 的 spec 字段必須滿足這些條件以及適用相關字段的默認值,其創(chuàng)建或更新請求才會被 apiserver 所接受。
具體的 pod 字段和安全條件可見文檔 what-is-a-pod-security-policy[1] 。
啟用 Pod Security Policies
Kubernetes 默認不開啟 pod 安全策略功能,在集群中啟用 pod 安全策略的步驟大體上分為三步:
- 授予用戶訪問安全策略資源的權限,通常會授權給整個命名空間的 service account。
- 在集群中創(chuàng)建指定的安全策略資源。
- 啟用 apiserver 的 admission-controller 插件。
注意步驟 1、2 的順序不重要,因為它們不會產(chǎn)生實際影響。
但步驟 3 推薦在最后一步執(zhí)行,否則一旦啟用 admission-controller 插件,如果集群中沒有可用的 pod 安全策略或者未對安全策略資源預先授權,所有 pod 的創(chuàng)建都會被拒絕,包括 kube-system 命名空間下的系統(tǒng)管理組件如 apiserver(但由于是受 kubelet 管理的靜態(tài) pod 實際上容器依然會運行)。
RBAC 身份認證
- 創(chuàng)建可訪問所有安全策略資源的 ClusterRole:
apiVersion: rbac.authorization.k8s.io/v1
kind: ClusterRole
metadata:
name: all-psp
rules:
- apiGroups: ['policy']
resources: ['podsecuritypolicies']
verbs: ['use']
- 通過 ClusterRoleBinding 將創(chuàng)建的角色綁定到指定命名空間下的所有 service account(也可以授權給指定的 sa 或者用戶):
apiVersion: rbac.authorization.k8s.io/v1
kind: ClusterRoleBinding
metadata:
name: cluster-psp-bind
roleRef:
kind: ClusterRole
name: all-psp
apiGroup: rbac.authorization.k8s.io
subjects:
# 授權給指定命名空間下的所有 service account(推薦做法):
- kind: Group
apiGroup: rbac.authorization.k8s.io
name: system:nodes
namespace: kube-system
- kind: Group
apiGroup: rbac.authorization.k8s.io
name: system:serviceaccounts:kube-system
- kind: Group
apiGroup: rbac.authorization.k8s.io
name: system:serviceaccounts:security-test
# 也可授權給指定的 service account 或者用戶(不推薦):
- kind: ServiceAccount
name: <authorized service account name>
namespace: <authorized pod namespace>
- kind: User
apiGroup: rbac.authorization.k8s.io
name: <authorized user name>
# 授權給所有的 service accounts:
- kind: Group
apiGroup: rbac.authorization.k8s.io
name: system:serviceaccounts
# 授權給所有已認證的用戶:
- kind: Group
apiGroup: rbac.authorization.k8s.io
name: system:authenticated
創(chuàng)建安全策略資源
- 在集群中創(chuàng)建一個 PodSecurityPolicy 資源。寬松權限版本:
apiVersion: policy/v1beta1
kind: PodSecurityPolicy
metadata:
name: privileged
annotations:
seccomp.security.alpha.kubernetes.io/allowedProfileNames: '*'
spec:
privileged: true
allowPrivilegeEscalation: true
allowedCapabilities:
- '*'
volumes:
- '*'
hostNetwork: true
hostPorts:
- min: 0
max: 65535
hostIPC: true
hostPID: true
runAsUser:
rule: 'RunAsAny'
seLinux:
rule: 'RunAsAny'
supplementalGroups:
rule: 'RunAsAny'
fsGroup:
rule: 'RunAsAny'
- 嚴格權限版本:
apiVersion: policy/v1beta1
kind: PodSecurityPolicy
metadata:
name: restricted
annotations:
seccomp.security.alpha.kubernetes.io/allowedProfileNames: 'docker/default,runtime/default'
apparmor.security.beta.kubernetes.io/allowedProfileNames: 'runtime/default'
apparmor.security.beta.kubernetes.io/defaultProfileName: 'runtime/default'
spec:
privileged: false
# Required to prevent escalations to root.
allowPrivilegeEscalation: false
requiredDropCapabilities:
- ALL
# Allow core volume types.
volumes:
- 'configMap'
- 'emptyDir'
- 'projected'
- 'secret'
- 'downwardAPI'
# Assume that ephemeral CSI drivers & persistentVolumes set up by the cluster admin are safe to use.
- 'csi'
- 'persistentVolumeClaim'
- 'ephemeral'
hostNetwork: false
hostIPC: false
hostPID: false
runAsUser:
# Require the container to run without root privileges.
rule: 'MustRunAsNonRoot'
seLinux:
# This policy assumes the nodes are using AppArmor rather than SELinux.
rule: 'RunAsAny'
supplementalGroups:
rule: 'MustRunAs'
ranges:
# Forbid adding the root group.
- min: 1
max: 65535
fsGroup:
rule: 'MustRunAs'
ranges:
# Forbid adding the root group.
- min: 1
max: 65535
readOnlyRootFilesystem: false
啟用 admission controller 插件
啟用 admission controller 的 psp 插件有兩種方式:
- 在已存在的集群中通過修改 apiserver 的靜態(tài) manifest 文件,為 apiserver 增加啟動參數(shù) enable-admission-plugins=PodSecurityPolicy。kubelet 會自動檢測到變更并重啟 apiserver。下面的示例使用 sed 對原有參數(shù)進行了替換:
$ sed -i 's/enable-admission-plugins=NodeRestriction/enable-admission-plugins=NodeRestriction,PodSecurityPolicy/' /etc/kubernetes/manifests/kube-apiserver.yaml
- 或者在初始化集群時,在 kubeadm 配置文件中添加額外參數(shù)。
apiVersion: kubeadm.k8s.io/v1beta2
kind: ClusterConfiguration
apiServer:
extraArgs:
enable-admission-plugins: "PodSecurityPolicy"
驗證 psp 的安全限制
我們在上文授權過的 security-test 命名空間進行測試,驗證 psp 對 pod 的限制條件。
首先確保在集群中應用了嚴格版本的 psp 資源,然后嘗試通過 deployment 創(chuàng)建一個需要使用 hostNetwork 的 pod:
apiVersion: apps/v1
kind: Deployment
metadata:
name: nginx-hostnetwork
spec:
selector:
matchLabels:
run: nginx
template:
metadata:
labels:
run: nginx
spec:
hostNetwork: true
containers:
- image: nginx
imagePullPolicy: Always
name: nginx-privileged
創(chuàng)建并查看結果:
$ kubectl create -f hostnetwork-pod.yaml -n security-test
deployment.apps/nginx-hostnetwork created
$ kubectl get deploy -n security-test nginx-hostnetwork
NAME READY UP-TO-DATE AVAILABLE AGE
nginx-hostnetwork 0/1 0 0 17s
$ kubectl -n security-test get event | grep "pod security policy"
103s Warning FailedCreate deployment/nginx-hostnetwork Error creating: pods "nginx-hostnetwork-" is forbidden: unable to validate against any pod security policy: [spec.securityContext.hostNetwork: Invalid value: true: Host network is not allowed to be used]
局限性
如果有 pod 違反了安全策略,解決方案是要么調(diào)整 pod 的規(guī)格,要么修改 pod 安全策略資源。psp 資源是全局生效的,不能針對不同的命名空間設置不同的安全策略級別,這是一個很明顯的局限性。
另外對 psp 的授權機制也比較復雜。如果沒有授權或者未創(chuàng)建安全策略,結果是所有 pod 被拒絕,這也導致在集群中默認開啟該功能的操作難度很大。
從 Kubernetes v1.21 開始,Pod Security Policy 將被棄用,并將在 v1.25 中刪除。Kubernetes 引入了 Pod Security Admission 作為其替代者,我們將在下文中詳細解析。
Pod Security Admission
為什么要替換 psp
KEP-2579[2] 詳細闡述了使用 Pod Security Admission 替代 Pod Security Policy 的三點主要理由:
- 將策略與用戶或 service account 綁定的模型削弱了安全性。
- 功能無法流暢切換,在沒有安全策略的情況下無法關閉。
- API 不一致且缺乏靈活性。
新的 Pod Security Admission 機制在易用性和靈活性上都有了很大提升,從使用角度有以下四點顯著不同:
- 可以在集群中默認開啟,只要不添加約束條件就不會觸發(fā)對 pod 的校驗。
- 只在命名空間級別生效,可以為不同命名空間通過添加標簽的方式設置不同的安全限制。
- 可以為特定的用戶、命名空間或者運行時設置豁免規(guī)則。
- 根據(jù)實踐預設了三種安全等級,不需要由用戶單獨去設置每一個安全條件。
工作方式
Pod Security Admission 將原來 Pod Security Policy 的安全條件劃分成三種預設的安全等級:
- privileged: 不受限,向 pod 提供所有可用的權限。
- baseline:最低限度的限制策略,防止已知的特權升級。
- restricted:嚴格限制策略,遵循當前 Pod 加固的最佳實踐。
三種等級從寬松到嚴格遞增,各自包含了不同限度的安全條件[3],適用于不同的 pod 工作場景。此外還可以將安全等級設置為固定的 Kubernetes 版本,這樣即使集群升級到了新的版本且新版本的安全等級定義發(fā)生變化,依然可以按舊版本的安全條件對 pod 進行約束。
當 pod 與安全等級沖突時,我們可通過三種模式來選擇不同的處理方式:
- enforce:只允許符合安全等級要求的 pod,拒絕與安全等級沖突的 pod。
- audit:只將安全等級沖突記錄在集群 event 中,不會拒絕 pod。
- warn:與安全等級沖突時會向用戶返回一個警告信息,但不會拒絕 pod。
audit 和 warn 模式是獨立的,如果同時需要兩者的功能必須分別設置兩種模式。
應用安全策略不再需要創(chuàng)建單獨的集群資源,只需要為命名空間設置控制標簽:
pod-security.kubernetes.io/<mode>: <level>
pod-security.kubernetes.io/<mode>-version: <version>
下文會有更完整的示例。
在舊版本啟用 psa
雖然 Pod Security Admission 是一個在 Kubernetes v1.22 引入的功能,但舊版本可以通過安裝 PodSecurity admission webhook 來啟用該功能,具體步驟如下:
$ git clone https://github.com/kubernetes/pod-security-admission.git
$ cd pod-security-admission/webhook
$ make certs
$ kubectl apply -k .
以上來自官方文檔的步驟在 v1.18.17 會有兩個兼容性問題,具體問題和解決方案如下:
- kubectl 內(nèi)置的 kustomize 版本不支持 "replacements" 字段:
$ kubectl apply -k .
error: json: unknown field "replacements"
解決方案:安裝最新版本的 kusomize 然后在同一目錄執(zhí)行
$ kustomize build . | kubectl apply -f -
- manifest/50-deployment.yaml 文件中定義的 Deployment.spec.template.spec.containers[0].securityContext 字段在 v1.19 版本才開始引入,因此 v1.18 需要將該字段修改為對應的 annotation 版本,詳見 Seccomp[4]:
error: error validating "STDIN": error validating data: ValidationError(Deployment.spec.template.spec.containers[0].securityContext): unknown field "seccompProfile" in io.k8s.api.core.v1.SecurityContext; if you choose to ignore these errors, turn validation off with --validate=false
驗證 psa 的安全限制
首先創(chuàng)建一個新的命名空間 psa-test 用于測試,并將其定義強制應用 baseline 安全等級,并對 restricted 等級進行警告和審計:
apiVersion: v1
kind: Namespace
metadata:
name: psa-test
labels:
pod-security.kubernetes.io/enforce: baseline
pod-security.kubernetes.io/enforce-version: v1.18
# We are setting these to our _desired_ `enforce` level.
pod-security.kubernetes.io/audit: restricted
pod-security.kubernetes.io/audit-version: v1.18
pod-security.kubernetes.io/warn: restricted
pod-security.kubernetes.io/warn-version: v1.18
接著在該命名空間中創(chuàng)建上文示例中用過的 deployment:
$ kubectl create -f hostnetwork-pod.yaml -n psa-test
deployment.apps/nginx-hostnetwork created
$ kubectl get deploy -n psa-test nginx-hostnetwork
NAME READY UP-TO-DATE AVAILABLE AGE
nginx-hostnetwork 0/1 0 0 17s
$ kubectl -n psa-test get event | grep PodSecurity
104s Warning FailedCreate replicaset/nginx-hostnetwork-644cdd6598 Error creating: