容器安全性-為容器配置安全上下文
安全上下文(Security Context)定義 Pod 或 Container 的特權與訪問控制設置。 安全上下文包括但不限於:
-
自主訪問控制(Discretionary Access Control):基於 用戶 ID(UID)和組 ID(GID). 來判定對對象(例如文件)的訪問權限。
-
安全性增強 Linux(SELinux): 為對象賦予安全性標簽,需要用戶自行開啟Selinux模塊。
-
以特權模式或者非特權模式運行。
-
Linux Capabilities: 為進程賦予 root 用戶的部分特權而非全部特權。
-
AllowPrivilegeEscalation:控制進程是否可以獲得超出其父進程的特權。 此布爾值直接控制是否為容器進程設置
no_new_privs
標志。 當容器以特權模式運行或者具有CAP_SYS_ADMIN
權能時,AllowPrivilegeEscalation 總是為 true。 -
readOnlyRootFilesystem:以只讀方式加載容器的根文件系統。
這里主要演示:Discretionary Access Control
,Linux Capabilities
設置Discretionary Access Control
yaml示例:
apiVersion: v1
kind: Pod
metadata:
name: security-context-demo
spec:
securityContext:
runAsUser: 1000
runAsGroup: 3000
fsGroup: 2000
volumes:
- name: sec-ctx-vol
emptyDir: {}
containers:
- name: sec-ctx-demo
image: registry.acs.env26.shuguang-ops.com/acs/nginx:1.16
command: [ "sh", "-c", "sleep 1h" ]
volumeMounts:
- name: sec-ctx-vol
mountPath: /data/demo
securityContext:
allowPrivilegeEscalation: false
在配置文件中,runAsUser 字段指定 Pod 中的所有容器內的進程都使用用戶 ID 1000 來運行。runAsGroup 字段指定所有容器中的進程都以主組 ID 3000 來運行。 如果忽略此字段,則容器的主組 ID 將是 root(0)。
當 runAsGroup 被設置時,所有創建的文件也會划歸用戶 1000 和組 3000。 由於 fsGroup 被設置,容器中所有進程也會是附組 ID 2000 的一部分。 卷 /data/demo 及在該卷中創建的任何文件的屬主都會是組 ID 2000。
驗證:
kubectl exec -it security-context-demo -- /bin/bash
$ id
# 可以看到,容器使用的用戶不在是root(id=0),而是我們設置的值
uid=1000 gid=3000 groups=3000,2000
為容器設置Linux Capabilities
使用 Linux Capabilities,你可以 賦予進程 root 用戶所擁有的某些特權,但不必賦予其全部特權。 要為 Container 添加或移除 Linux 權能,可以在 Container 清單的 securityContext
節 包含 capabilities
字段。
首先,查看不包含 capabilities
字段時候會發生什么。 下面是一個配置文件,其中沒有添加或移除容器的權能:
apiVersion: v1
kind: Pod
metadata:
name: security-context-demo-1
spec:
containers:
- name: sec-ctx-1
image: gcr.io/google-samples/node-hello:1.0
通過控制台創建pod,然后登錄到容器中kubectl exec -it security-context-demo-1 -- /bin/bash
查看進程1的狀態:
# cd /proc/1 && cat status
輸出Capality位圖:
CapPrm: 00000000a80425fb
CapEff: 00000000a80425fb
然后,運行一個設置了Capality的容器:
apiVersion: v1
kind: Pod
metadata:
name: security-context-demo-2
spec:
containers:
- name: sec-ctx-2
image: registry.acs.env26.shuguang-ops.com/acs/nginx:1.16
securityContext:
capabilities:
add: ["NET_ADMIN", "SYS_TIME"]
通過控制台創建pod,然后登錄到容器中kubectl exec -it security-context-demo-2 -- /bin/bash
查看進程1的狀態:
# cd /proc/1 && cat status
輸出Capality位圖:
...
CapPrm: 00000000aa0435fb
CapEff: 00000000aa0435fb
...
對比發現:在第一個容器的權能位圖中,位 12 和 25 是沒有設置的。在第二個容器中,位 12 和 25 是設置了的。位 12 是 CAP_NET_ADMIN
而位 25 則是 CAP_SYS_TIME
。 參見 capability.h 了解權能常數的定義。
設置Selinux
若要給 Container 設置 SELinux 標簽,可以在 Pod 或 Container 清單的 securityContext
節包含 seLinuxOptions
字段。 seLinuxOptions
字段的取值是一個 SELinuxOptions 對象。下面是一個應用 SELinux 標簽的例子:
apiVersion: v1
kind: Pod
metadata:
name: security-context-demo-3
spec:
containers:
- name: sec-ctx-3
image: registry.acs.env26.shuguang-ops.com/acs/nginx:1.16
securityContext:
seLinuxOptions:
level: "s0:c123,c456"
說明: 要指定 SELinux,需要在宿主操作系統中裝載 SELinux 安全性模塊。
文章參考:官方文章