Bảo mật Pod: securityContext và Pod Security Standards
RBAC quyết định ai được tạo Pod. Nhưng bản thân Pod được phép làm gì khi chạy trên node: chạy bằng root, mount thư mục của node, dùng mạng của node? Bài này trả lời bằng hai công cụ: securityContext (bạn tự khóa quyền của từng Pod, từng container) và Pod Security Admission (cluster bắt buộc mọi Pod trong namespace đạt một mức an toàn). Bạn sẽ bật mức restricted cho namespace notes, xem notes-api cũ bị từ chối, rồi sửa notes-api, Redis và Postgres để chạy được dưới mức nghiêm ngặt nhất.
Vì sao cần
Khóa Docker đã chỉ ra: container không phải máy ảo. Tiến trình trong container chạy trực tiếp trên kernel của host; root trong container là uid 0 của chính kernel đó, chỉ bị giới hạn bởi namespaces, cgroups, capabilities và seccomp. Bỏ bớt lớp nào là mở thêm đường thoát: --privileged (mọi capability, mọi thiết bị), mount /var/run/docker.sock hoặc / của host, capability mạnh như CAP_SYS_ADMIN, hay một lỗ hổng kernel mà tiến trình root khai thác dễ hơn nhiều.
Trên Kubernetes, hậu quả lớn hơn: ai có quyền tạo Pod trong bất kỳ namespace nào (bài trước) đều có thể nộp Pod như sau.
apiVersion: v1
kind: Pod
metadata:
name: escape
spec:
hostPID: true # thấy mọi tiến trình của node
containers:
- name: shell
image: busybox:1.37
command: ["sleep", "infinity"]
securityContext:
privileged: true
volumeMounts:
- name: host
mountPath: /host
volumes:
- name: host
hostPath:
path: / # toàn bộ ổ đĩa của nodeMột lệnh kubectl exec -it escape -- chroot /host là có shell root trên node: đọc được Secret của mọi Pod trên node đó, chứng chỉ của kubelet, rồi lan sang node khác. Vì vậy cluster cần một cửa chặn những Pod như thế ngay từ lúc tạo.
Mặc định của Pod còn lỏng hơn Docker: Docker áp profile seccomp mặc định cho mọi container, còn Pod không khai báo gì thì chạy Unconfined (không lọc syscall), trừ khi admin bật tùy chọn seccompDefault của kubelet. Trước đây Kubernetes có PodSecurityPolicy để chặn Pod nguy hiểm, nhưng nó khó dùng và đã bị gỡ bỏ ở 1.25. Thay thế chính thức là Pod Security Admission tích hợp sẵn, dựa trên bộ tiêu chuẩn Pod Security Standards.
Cơ chế
securityContext: hai cấp
securityContext đặt được ở cấp Pod (spec.securityContext, áp cho mọi container) và cấp container (containers[].securityContext, ghi đè cấp Pod với trường trùng tên).
| Trường | Cấp | Ý nghĩa | Tương đương Docker |
|---|---|---|---|
runAsUser, runAsGroup | Pod, container | Chạy tiến trình với uid/gid này | --user 1000:1000 |
runAsNonRoot: true | Pod, container | Kubelet từ chối khởi động container nếu nó sẽ chạy với uid 0 | |
fsGroup | Pod | Volume hỗ trợ được đổi group sở hữu thành gid này; tiến trình có thêm group đó | |
seccompProfile.type | Pod, container | RuntimeDefault (profile mặc định của runtime), Localhost (profile riêng), Unconfined | --security-opt seccomp=... |
appArmorProfile.type | Pod, container | Tương tự cho AppArmor, trên node bật AppArmor | --security-opt apparmor=... |
allowPrivilegeEscalation: false | Container | Bật cờ no_new_privs: binary setuid không nâng quyền được | --security-opt no-new-privileges |
privileged | Container | Gần như toàn quyền trên node | --privileged |
capabilities.drop / add | Container | Bỏ / thêm capability Linux | --cap-drop ALL --cap-add ... |
readOnlyRootFilesystem: true | Container | Root filesystem của container chỉ đọc | --read-only |
Vài điểm cần hiểu kỹ:
runAsNonRootchỉ kiểm tra, không đổi user. Kubelet nhìn uid sẽ dùng (từrunAsUser, nếu không có thì từUSERcủa image). Nếu image ghiUSER node(một tên, không phải số), kubelet không biếtnodelà uid mấy và từ chối vớiCreateContainerConfigError. Đó là lý do ta đặt thêmrunAsUser: 1000.capabilities.drop: ["ALL"]bỏ cả bộ capability mặc định. Ứng dụng nghe cổng 3000 không cần capability nào; chỉ khi nghe cổng dưới 1024 mới cầnadd: ["NET_BIND_SERVICE"].readOnlyRootFilesystemchặn kẻ tấn công tải công cụ hay sửa file của ứng dụng. Chỗ nào ứng dụng thật sự cần ghi (như/tmp) thì gắn một volumeemptyDirvào đúng chỗ đó.fsGroupcần cho ổ đĩa mới format trên cloud (thư mục gốc thuộc root, quyền 755): không có nó, tiến trình uid 999 không ghi được. Với volume lớn, thêmfsGroupChangePolicy: OnRootMismatchđể kubelet không đổi quyền lại toàn bộ file mỗi lần Pod khởi động.- AppArmor xưa cấu hình bằng annotation, nay dùng trường
appArmorProfile. Các bản gần đây còn cóhostUsers: false(chạy Pod trong user namespace riêng), nhưng cần kernel và runtime hỗ trợ.
Pod Security Standards: ba mức
| Kiểm tra | privileged | baseline | restricted |
|---|---|---|---|
hostNetwork, hostPID, hostIPC | Cho phép | Cấm | Cấm |
privileged: true | Cho phép | Cấm | Cấm |
Volume hostPath, hostPort | Cho phép | Cấm | Cấm |
| Thêm capability | Cho phép | Chỉ trong bộ mặc định (CHOWN, SETUID, NET_BIND_SERVICE…) | Bắt buộc drop: ["ALL"], chỉ được thêm NET_BIND_SERVICE |
| seccomp | Mọi giá trị | Không được đặt Unconfined | Bắt buộc RuntimeDefault hoặc Localhost |
AppArmor, SELinux, procMount, sysctls | Cho phép | Không được nới lỏng | Như baseline |
| Loại volume | Mọi loại | Mọi loại trừ hostPath | Chỉ configMap, secret, emptyDir, persistentVolumeClaim, projected, downwardAPI, csi, ephemeral |
allowPrivilegeEscalation | Tùy | Tùy | Bắt buộc false |
runAsNonRoot / runAsUser | Tùy | Tùy | Bắt buộc runAsNonRoot: true, runAsUser khác 0 |
privileged dành cho thành phần hệ thống thật sự cần chạm vào node (CNI, agent giám sát, driver lưu trữ), thường ở kube-system. baseline chặn các đường leo thang đã biết nhưng chạy được hầu hết image phổ biến không sửa gì: mức tối thiểu cho mọi namespace ứng dụng. restricted đòi hỏi bạn khai báo securityContext: mục tiêu cho ứng dụng của chính bạn. restricted không bắt buộc readOnlyRootFilesystem; đó là lớp phòng thủ thêm bạn nên tự bật.
Pod Security Admission: gắn mức cho namespace
Pod Security Admission là admission controller có sẵn trong API server. Bạn chọn mức bằng label của namespace, theo ba chế độ:
| Label | Khi Pod vi phạm |
|---|---|
pod-security.kubernetes.io/enforce: <mức> | Từ chối tạo Pod |
pod-security.kubernetes.io/warn: <mức> | Trả cảnh báo về cho người dùng (kubectl in Warning:), vẫn cho tạo |
pod-security.kubernetes.io/audit: <mức> | Ghi chú vào audit log (chương 14), vẫn cho tạo |
Mỗi chế độ có label -version đi kèm (v1.34 hoặc latest) để cố định bộ quy tắc theo một phiên bản Kubernetes. Ba chế độ đặt được ở ba mức khác nhau, ví dụ enforce baseline nhưng warn restricted để chuẩn bị siết dần.
Hai chi tiết quan trọng: enforce chỉ áp cho Pod, còn warn và audit kiểm tra cả template trong Deployment, StatefulSet, Job…; và gắn label không đụng tới Pod đang chạy, chỉ áp cho Pod tạo mới.
Thực hành: đưa namespace notes lên restricted
Trạng thái xuất phát: namespace notes có Deployment notes-api và redis, StatefulSet postgres (chương 7, 8), chưa có securityContext nào.
Bước 1: thử trước bằng dry-run
--dry-run=server cho API server đánh giá mà không lưu, kèm danh sách Pod hiện có sẽ vi phạm:
kubectl label --dry-run=server --overwrite ns notes pod-security.kubernetes.io/enforce=restrictedWarning: existing pods in namespace "notes" violate the new PodSecurity enforce level "restricted:latest"
Warning: notes-api-6d8f9c7b5-2xk8p (and 4 other pods): allowPrivilegeEscalation != false, unrestricted capabilities, runAsNonRoot != true, seccompProfile
namespace/notes labeled (server dry run)Cả 5 Pod (3 notes-api, redis, postgres-0) cùng thiếu bốn thứ mà restricted đòi hỏi.
Bước 2: bật enforce, warn, audit
kubectl label --overwrite ns notes \
pod-security.kubernetes.io/enforce=restricted \
pod-security.kubernetes.io/enforce-version=latest \
pod-security.kubernetes.io/warn=restricted \
pod-security.kubernetes.io/warn-version=latest \
pod-security.kubernetes.io/audit=restricted \
pod-security.kubernetes.io/audit-version=latestBạn nhận lại đúng các cảnh báo ở bước 1, kèm namespace/notes labeled. Pod cũ vẫn chạy. Thử tạo một Pod mới:
kubectl -n notes run test --image=nginx:1.29Error from server (Forbidden): pods "test" is forbidden: violates PodSecurity "restricted:latest": allowPrivilegeEscalation != false (container "test" must set securityContext.allowPrivilegeEscalation=false), unrestricted capabilities (container "test" must set securityContext.capabilities.drop=["ALL"]), runAsNonRoot != true (pod or container "test" must set securityContext.runAsNonRoot=true), seccompProfile (pod or container "test" must set securityContext.seccompProfile.type to "RuntimeDefault" or "Localhost")Thông báo liệt kê chính xác trường nào cần đặt. Giờ khởi động lại notes-api với manifest cũ:
kubectl -n notes rollout restart deploy/notes-api
kubectl -n notes get deploy notes-api
kubectl -n notes describe rs -l app=notes-api | grep FailedCreate | tail -1Warning: would violate PodSecurity "restricted:latest": allowPrivilegeEscalation != false (container "notes-api" must set ...), ...
deployment.apps/notes-api restarted
NAME READY UP-TO-DATE AVAILABLE AGE
notes-api 3/3 0 3 6d
Warning FailedCreate 8s replicaset-controller Error creating: pods "notes-api-5f7c8d9b6-k2m4p" is forbidden: violates PodSecurity "restricted:latest": ...Deployment được cập nhật (chế độ warn chỉ cảnh báo), nhưng ReplicaSet mới không tạo được Pod nào (UP-TO-DATE 0). Ứng dụng vẫn phục vụ nhờ 3 Pod cũ, vì rolling update không xóa Pod cũ khi Pod mới chưa lên. Đây đúng là kiểu lỗi "Deployment ổn mà không có Pod" của chương 9: luôn xem event của ReplicaSet.
Bước 3: sửa notes-api
apiVersion: apps/v1
kind: Deployment
metadata:
name: notes-api
namespace: notes
labels:
app: notes-api
spec:
replicas: 3
selector:
matchLabels:
app: notes-api
template:
metadata:
labels:
app: notes-api
spec:
automountServiceAccountToken: false
enableServiceLinks: false
securityContext: # cấp Pod: áp cho mọi container
runAsNonRoot: true
runAsUser: 1000 # uid của user "node" (USER node trong Dockerfile)
runAsGroup: 1000
seccompProfile:
type: RuntimeDefault
containers:
- name: notes-api
image: notes-api:1.0
imagePullPolicy: IfNotPresent
ports:
- containerPort: 3000
envFrom:
- configMapRef:
name: notes-config
env:
- name: POSTGRES_USER
valueFrom:
secretKeyRef: { name: notes-db, key: POSTGRES_USER }
- name: POSTGRES_PASSWORD
valueFrom:
secretKeyRef: { name: notes-db, key: POSTGRES_PASSWORD }
- name: POSTGRES_DB
valueFrom:
secretKeyRef: { name: notes-db, key: POSTGRES_DB }
- name: DATABASE_URL
value: postgres://$(POSTGRES_USER):$(POSTGRES_PASSWORD)@postgres:5432/$(POSTGRES_DB)
securityContext: # cấp container
allowPrivilegeEscalation: false
readOnlyRootFilesystem: true
capabilities:
drop: ["ALL"]
volumeMounts:
- name: app-config
mountPath: /etc/notes
readOnly: true
- name: tmp
mountPath: /tmp # chỗ duy nhất được ghi
readinessProbe:
httpGet: { path: /health, port: 3000 }
periodSeconds: 5
livenessProbe:
httpGet: { path: /health, port: 3000 }
initialDelaySeconds: 10
periodSeconds: 10
volumes:
- name: app-config
configMap:
name: notes-app-config
- name: tmp
emptyDir:
sizeLimit: 64MiNếu bạn đã thêm resources ở chương 9, giữ nguyên phần đó. Áp dụng và kiểm chứng:
kubectl apply -f notes-api-deployment.yaml
kubectl -n notes rollout status deploy/notes-api
kubectl -n notes exec deploy/notes-api -- id
kubectl -n notes exec deploy/notes-api -- sh -c 'touch /x; touch /tmp/x && echo "/tmp ghi được"'
kubectl -n notes exec deploy/notes-api -- grep -E 'CapEff|NoNewPrivs|Seccomp:' /proc/1/statusdeployment.apps/notes-api configured
deployment "notes-api" successfully rolled out
uid=1000(node) gid=1000(node) groups=1000(node)
touch: cannot touch '/x': Read-only file system
/tmp ghi được
CapEff: 0000000000000000
NoNewPrivs: 1
Seccomp: 2CapEff toàn số 0: không còn capability nào. NoNewPrivs: 1: cờ chống leo thang đã bật. Seccomp: 2: đang lọc syscall bằng profile.
Bước 4: Redis
Image redis:8-alpine khởi động bằng root rồi tự hạ xuống user redis (uid 999). Chạy thẳng bằng uid 999 thì entrypoint bỏ qua bước đó. Redis ghi file snapshot vào /data, nên khi root filesystem chỉ đọc, /data phải là một volume:
spec:
automountServiceAccountToken: false
securityContext:
runAsNonRoot: true
runAsUser: 999 # user redis trong image
seccompProfile:
type: RuntimeDefault
containers:
- name: redis
image: redis:8-alpine
ports:
- containerPort: 6379
securityContext:
allowPrivilegeEscalation: false
readOnlyRootFilesystem: true
capabilities:
drop: ["ALL"]
volumeMounts:
- name: data
mountPath: /data
volumes:
- name: data
emptyDir: {}Bước 5: Postgres
Image postgres:18 (bản Debian) có user postgres uid 999, gid 999. Khi chạy thẳng bằng uid 999, entrypoint vẫn khởi tạo database bình thường, chỉ cần các thư mục nó ghi đều ghi được: dữ liệu ở /var/lib/postgresql (PVC), Unix socket và file khóa ở /var/run/postgresql.
spec:
terminationGracePeriodSeconds: 60
automountServiceAccountToken: false
securityContext:
runAsNonRoot: true
runAsUser: 999 # user postgres trong image
runAsGroup: 999
fsGroup: 999 # để ổ đĩa mới (thuộc root) ghi được
fsGroupChangePolicy: OnRootMismatch
seccompProfile:
type: RuntimeDefault
containers:
- name: postgres
image: postgres:18
# ports, envFrom, readinessProbe, resources giữ nguyên như chương 8
securityContext:
allowPrivilegeEscalation: false
readOnlyRootFilesystem: true
capabilities:
drop: ["ALL"]
volumeMounts:
- name: data
mountPath: /var/lib/postgresql
- name: run
mountPath: /var/run/postgresql
- name: tmp
mountPath: /tmp
volumes:
- name: run
emptyDir: {}
- name: tmp
emptyDir: {}Dữ liệu từ chương 8 vốn đã thuộc uid 999 (entrypoint cũ hạ quyền xuống postgres trước khi ghi), nên không cần chuyển gì. Entrypoint còn tự đặt lại quyền 0700 cho thư mục dữ liệu mỗi lần khởi động, đúng như Postgres đòi hỏi.
kubectl apply -f deps.yaml -f postgres-statefulset.yaml
kubectl -n notes rollout status deploy/redis
kubectl -n notes rollout status statefulset/postgres
kubectl -n notes exec postgres-0 -- psql -U notes -d notes -c 'SELECT current_user;'
kubectl label --dry-run=server --overwrite ns notes pod-security.kubernetes.io/enforce=restricteddeployment "redis" successfully rolled out
statefulset rolling update complete 1 pods at revision postgres-6c8d5f7b9...
current_user
--------------
notes
(1 row)
namespace/notes labeled (server dry run)Lần dry-run cuối không còn cảnh báo nào: mọi Pod trong notes đã đạt restricted.
TIP
Nếu Postgres báo Permission denied trên thư mục dữ liệu (thường do provisioner tạo thư mục thuộc root, quyền 755, mà không hỗ trợ fsGroup), đừng nới restricted cho cả namespace ứng dụng. Hoặc dùng StorageClass hỗ trợ fsGroup, hoặc tách database sang namespace riêng enforce baseline (cho phép image chạy root rồi tự hạ quyền), giữ notes ở restricted.
Vượt ra ngoài Pod Security Admission
PSA chỉ có ba mức cố định và chỉ nhìn securityContext. Nó không chặn được image tag latest, không bắt buộc label, không giới hạn registry. Khi cần chính sách riêng, có ba hướng:
| Công cụ | Viết chính sách bằng | Ghi chú |
|---|---|---|
| ValidatingAdmissionPolicy | Biểu thức CEL trong YAML | Có sẵn trong Kubernetes (GA từ 1.30), chạy ngay trong API server |
| Kyverno | YAML | Kiểm tra, sửa (mutate), sinh đối tượng, xác minh chữ ký image |
| OPA Gatekeeper | Rego | Dùng chung ngôn ngữ chính sách với hệ thống khác ngoài Kubernetes |
Ví dụ cấm image không có tag hoặc dùng tag latest trong namespace notes:
apiVersion: admissionregistration.k8s.io/v1
kind: ValidatingAdmissionPolicy
metadata:
name: no-latest-tag
spec:
failurePolicy: Fail
matchConstraints:
resourceRules:
- apiGroups: ["apps"]
apiVersions: ["v1"]
operations: ["CREATE", "UPDATE"]
resources: ["deployments"]
validations:
# đơn giản hóa: image dạng localhost:5000/app (registry có cổng, không tag) vẫn lọt
- expression: "object.spec.template.spec.containers.all(c, c.image.contains(':') && !c.image.endsWith(':latest'))"
message: "Image phải có tag cụ thể, không dùng latest"
---
apiVersion: admissionregistration.k8s.io/v1
kind: ValidatingAdmissionPolicyBinding
metadata:
name: no-latest-tag
spec:
policyName: no-latest-tag
validationActions: ["Deny"] # thử nghiệm trước với ["Warn", "Audit"]
matchResources:
namespaceSelector:
matchLabels:
kubernetes.io/metadata.name: notesSau khi apply, kubectl -n notes create deployment bad --image=nginx bị từ chối với thông báo chứa ValidatingAdmissionPolicy 'no-latest-tag' with binding 'no-latest-tag' denied request. Cùng cơ chế này bịt được lỗ hổng ở bài RBAC: giới hạn Secret hay ServiceAccount mà Pod trong một namespace được tham chiếu.
Chuỗi cung ứng image. Image từ registry riêng cần Secret loại docker-registry (kubectl create secret docker-registry ...) khai báo trong imagePullSecrets của Pod hoặc gắn vào ServiceAccount. Ghim theo digest (ghcr.io/acme/notes-api@sha256:...) để chạy đúng từng byte đã kiểm tra. Ký image trong CI bằng cosign (dự án Sigstore, có chế độ keyless dùng danh tính OIDC của CI) rồi xác minh lúc admission bằng Sigstore policy-controller hoặc verifyImages của Kyverno. Quét lỗ hổng trong CI: trivy image --severity HIGH,CRITICAL --exit-code 1 notes-api:1.0.
Phát hiện lúc chạy. Admission chỉ kiểm tra lúc tạo. Falco theo dõi syscall trên node (qua eBPF) và cảnh báo hành vi bất thường: shell được mở trong container production, tiến trình đọc /etc/shadow, kết nối ra địa chỉ lạ.
Bẫy thường gặp
1. CreateContainerConfigError với runAsNonRoot
- Thông báo:
container has runAsNonRoot and image has non-numeric user (node), cannot verify user is non-root. - Cách sửa: thêm
runAsUserdạng số, hoặc dùngUSER 1000trong Dockerfile.
2. Ứng dụng chết vì root filesystem chỉ đọc
- Triệu chứng: log có
EROFShoặcRead-only file system. - Cách sửa: gắn
emptyDirvào đúng thư mục ứng dụng cần ghi (/tmp, cache, socket), không tắtreadOnlyRootFilesystem.
3. Deployment "configured" nhưng không có Pod mới: enforce chỉ chặn Pod; lỗi nằm ở event FailedCreate của ReplicaSet (hoặc Job, StatefulSet).
4. Gắn label xong tưởng đã an toàn: Pod vi phạm đang chạy không bị đuổi; chúng chỉ "nổ" khi bị tạo lại (drain node, restart). Luôn dry-run trước. CronJob sao lưu ở chương 8 cũng sẽ thất bại ở lần chạy tới nếu chưa thêm securityContext như Postgres.
5. latest đổi nghĩa khi nâng cấp cluster: bản mới có thể siết thêm quy tắc. Production nên ghim enforce-version và để warn-version: latest để thấy trước.
6. Ai sửa được namespace thì tắt được PSA: quyền patch trên namespaces cho phép gỡ label. Chỉ admin cluster được giữ quyền này.
Tóm tắt
- Container dùng chung kernel với node; Pod privileged, hostPath
/, hostPID là đường thoát ra node. Pod mặc định còn chạy seccomp Unconfined. securityContextcấp Pod và container:runAsNonRoot+runAsUserdạng số,fsGroup,seccompProfile: RuntimeDefault,allowPrivilegeEscalation: false,capabilities.drop: ["ALL"],readOnlyRootFilesystem+emptyDircho chỗ cần ghi.- Pod Security Standards:
privileged,baseline,restricted. PodSecurityPolicy bị gỡ ở 1.25, thay bằng Pod Security Admission. - PSA bật bằng label namespace
pod-security.kubernetes.io/enforce|warn|auditvà-version. Enforce chỉ chặn Pod mới; dùngkubectl label --dry-run=serverđể tìm Pod vi phạm trước. - notes-api chạy uid 1000, Redis và Postgres chạy uid 999, cả ba đạt
restrictedvới root filesystem chỉ đọc. - Chính sách riêng: ValidatingAdmissionPolicy (CEL), Kyverno, OPA Gatekeeper. Chuỗi cung ứng:
imagePullSecrets, digest, cosign, Trivy. Lúc chạy: Falco.
Comments