
云原生时代,Kubernetes 已成为容器编排的事实标准,但默认配置下的容器往往存在安全隐患。通过 SecurityContext 实现 Kubernetes 容器安全加固,并提供实际应用场景和代码示例。
SecurityContext 是 Kubernetes 免费的原生安全机制,通过 YAML 字段即可实现:
无需额外 CRD,即可将攻击面降低 90% 以上。
问题:默认镜像监听 80,需 root 身份;容器逃逸后获得主机 root。
方案:使用官方非 root 镜像(监听 8080),并加 runAsNonRoot: true。
# 01-run-as-non-root.yaml
apiVersion: v1
kind: Pod
metadata:
name: non-root-pod
namespace: default
spec:
securityContext:
runAsNonRoot: true
runAsUser: 1000
runAsGroup: 1000
fsGroup: 1000
containers:
- name: app
image: nginxinc/nginx-unprivileged:1.27
ports:
- containerPort: 8080注意:
USER 1000 并暴露 8080fsGroup 保证卷文件属组正确问题:攻击者修改 /etc/passwd、crontab 等持久化文件。
方案:readOnlyRootFilesystem: true,可写目录通过 emptyDir 提供。
# 02-read-only-root-fs.yaml
apiVersion: v1
kind: Pod
metadata:
name: read-only-pod
namespace: default
spec:
containers:
- name: app
image: nginxinc/nginx-unprivileged:1.27
securityContext:
readOnlyRootFilesystem: true
allowPrivilegeEscalation: false
volumeMounts:
- name: tmp-volume
mountPath: /tmp
- name: cache-volume
mountPath: /var/cache/nginx
- name: run-volume
mountPath: /var/run
volumes:
- name: tmp-volume
emptyDir: {}
- name: cache-volume
emptyDir: {}
- name: run-volume
emptyDir: {}问题:默认拥有 CHOWN、DAC_OVERRIDE、FSETID 等 14 项能力,攻击面大。
方案:drop: ["ALL"],再按需添加。
# 03-minimal-capabilities.yaml
apiVersion: v1
kind: Pod
metadata:
name: minimal-capabilities
namespace: default
spec:
containers:
- name: app
image: nginxinc/nginx-unprivileged:1.27
securityContext:
capabilities:
drop: ["ALL"]
add: ["NET_BIND_SERVICE"] # 监听 8080 可去掉
allowPrivilegeEscalation: false问题:容器内 setuid 程序可提升权限。
方案:allowPrivilegeEscalation: false 与 runAsNonRoot 组合使用。
# 04-allow-privilege-escalation-false.yaml
apiVersion: v1
kind: Pod
metadata:
name: no-priv-esc
namespace: default
spec:
containers:
- name: app
image: nginxinc/nginx-unprivileged:1.27
securityContext:
allowPrivilegeEscalation: false问题:恶意程序通过 ptrace、mount 等调用逃逸。
方案:启用 RuntimeDefault 策略(Kubernetes 1.27+ 默认自动开启,但建议显式声明)。
# 05-seccomp-runtime-default.yaml
apiVersion: v1
kind: Pod
metadata:
name: seccomp-pod
namespace: default
spec:
securityContext:
seccompProfile:
type: RuntimeDefault
containers:
- name: app
image: nginxinc/nginx-unprivileged:1.27
securityContext:
allowPrivilegeEscalation: false问题:多容器 Pod 写同一卷出现 Permission denied。
方案:Pod 级 fsGroup 统一文件属组。
# 06-fsgroup-shared-volume.yaml
apiVersion: v1
kind: Pod
metadata:
name: shared-volume-pod
namespace: default
spec:
securityContext:
fsGroup: 2000
containers:
- name: writer
image: busybox:1.36
command: ["sh","-c","echo hello > /data/msg && sleep 3600"]
volumeMounts:
- name: shared-data
mountPath: /data
- name: reader
image: busybox:1.36
command: ["sh","-c","cat /data/msg && sleep 3600"]
volumeMounts:
- name: shared-data
mountPath: /data
volumes:
- name: shared-data
emptyDir: {}1、Pod Security Admission(PSA):命名空间打标签 pod-security.kubernetes.io/enforce: restricted 即可强制基线。
2、OPA Gatekeeper / Kyverno:以下 Gatekeeper v1 策略强制所有容器必须定义 securityContext。
# 07-gatekeeper-v1-constraint.yaml
apiVersion: templates.gatekeeper.sh/v1
kind: ConstraintTemplate
metadata:
name: k8srequiredsecuritycontext
spec:
crd:
spec:
names:
kind: K8sRequiredSecurityContext
targets:
- target: admission.k8s.gatekeeper.sh
rego: |
package k8srequiredsecuritycontext
violation[{"msg": msg}] {
container := input.review.object.spec.containers[_]
not container.securityContext
msg := sprintf("Container <%v> must define securityContext", [container.name])
}
---
apiVersion: constraints.gatekeeper.sh/v1
kind: K8sRequiredSecurityContext
metadata:
name: all-must-have-sec-ctx
spec:
match:
kinds:
- apiGroups: [""]
kinds: ["Pod"]
enforcementAction: deny现象 | 根因 | 快速处理 |
|---|---|---|
CrashLoopBackOff | 镜像监听 80,非 root 无法绑定 | 改用 8080 或 add NET_BIND_SERVICE |
mkdir /var/cache/nginx failed | 根文件系统只读 | 增加 emptyDir 挂载对应目录 |
Permission denied 写卷 | 属组/权限不足 | 加 fsGroup 或 runAsUser + runAsGroup |
无法 apply YAML | 字段层级错误 | securityContext 容器级 vs Pod 级 |
GitLab CI 自动扫描 YAML 是否包含 runAsNonRoot: true:
# .gitlab-ci.yml
stages: [validate]
check-sec-ctx:
stage: validate
image: mikefarah/yq:4
script:
- yq eval 'select(.kind == "Pod") | .spec.securityContext.runAsNonRoot'
k8s/*.yaml | grep -q 'true' || (echo "missing runAsNonRoot" && exit 1)Kubernetes SecurityContext 是实现容器安全的关键机制。通过合理配置:
可以显著降低容器运行风险,构建更安全的 Kubernetes 环境。可以将这些实践纳入 CI/CD 流程,并配合策略执行工具确保一致性。
如果你觉得这篇文章有用,欢迎点赞、转发、收藏、留言、推荐❤!
本文分享自 Nicholas与Pypi 微信公众号,前往查看
如有侵权,请联系 cloudcommunity@tencent.com 删除。
本文参与 腾讯云自媒体同步曝光计划 ,欢迎热爱写作的你一起参与!