关于 auditing-kubernetes-cluster-rbac
面向 Kubernetes 管理员和安全审计人员的 RBAC 审计技能,提供检查角色、绑定、服务账户和高风险权限的步骤,并结合多个命令行工具分析访问控制。
主要功能
- 01盘点角色与权限绑定
- 02查找通配符和危险权限
- 03查询主体可执行的操作
- 04识别高风险服务账户
- 05检查令牌自动挂载
- 06结合审计日志核对访问
适用场景
- 01评估集群最小权限配置
- 02调查横向移动或提权风险
- 03记录合规审计中的访问控制
- 04为共享集群团队划分权限
安装
复制下面的命令,在终端中运行。
$
npx skills add https:/ / github.com/ mukul975/ anthropic-cybersecurity-skills --skill auditing-kubernetes-cluster-rbac安装后在 Claude Code 中输入/auditing-kubernetes-cluster-rbac确认已加载。
包含的文件
除 SKILL.md 外,安装时一起下载的参考资料和脚本。
LICENSEreferences/api-reference.mdscripts/agent.py详细介绍
审计 Kubernetes 集群 RBAC
何时使用
- 在对 Kubernetes 集群(EKS、GKE、AKS 或自管理集群)进行安全评估时
- 在验证 RBAC 策略是否为用户和服务账户强制实施最小权限时
- 在调查 Kubernetes 集群内潜在的横向移动或权限提升时
- 在合规审计要求记录访问控制和权限时
- 在将新团队加入共享集群并定义适当的 RBAC 策略时
不要使用于网络策略审计(使用 Cilium 或 Calico 网络策略工具)、容器镜像扫描(使用 Trivy 或 Grype)或运行时安全监控(使用 Falco 或 Sysdig Secure)。
前提条件
- kubectl 已配置 cluster-admin 或对目标集群具有等效的读取权限
- 已安装 rbac-tool(
kubectl krew install rbac-tool或从 GitHub 获取二进制文件) - 已安装 KubiScan(
pip install kubiscan) - 已安装 Kubeaudit(
brew install kubeaudit或从 GitHub releases 获取) - 有权访问集群的审计日志,以便将 RBAC 发现结果与实际 API 访问关联起来
工作流
步骤 1:枚举具有危险权限的 ClusterRoles 和 Roles
识别具有通配符权限、Secret 访问、Pod exec 或权限提升能力的角色。
# List all ClusterRoles with wildcard verb access
kubectl get clusterroles -o json | python3 -c "
import json, sys
data = json.load(sys.stdin)
for role in data['items']:
name = role['metadata']['name']
for rule in role.get('rules', []):
verbs = rule.get('verbs', [])
resources = rule.get('resources', [])
if '*' in verbs or '*' in resources:
print(f'ClusterRole: {name}')
print(f' Verbs: {verbs}')
print(f' Resources: {resources}')
print(f' API Groups: {rule.get(\"apiGroups\", [])}')
print()
"
# Find roles that can read secrets
kubectl get clusterroles -o json | python3 -c "
import json, sys
data = json.load(sys.stdin)
for role in data['items']:
name = role['metadata']['name']
for rule in role.get('rules', []):
resources = rule.get('resources', [])
verbs = rule.get('verbs', [])
if ('secrets' in resources or '*' in resources) and ('get' in verbs or 'list' in verbs or '*' in verbs):
if not name.startswith('system:'):
print(f'ClusterRole: {name} -> can access secrets (verbs: {verbs})')
"
# Find roles with pod/exec permissions (container escape risk)
kubectl get clusterroles -o json | python3 -c "
import json, sys
data = json.load(sys.stdin)
for role in data['items']:
name = role['metadata']['name']
for rule in role.get('rules', []):
resources = rule.get('resources', [])
if 'pods/exec' in resources or 'pods/*' in resources:
print(f'ClusterRole: {name} -> has pods/exec access')
"
步骤 2:审计 ClusterRoleBindings 和 RoleBindings
审查绑定以识别谁拥有提升的访问权限,并检测范围过宽的组分配。
# List all ClusterRoleBindings with the subjects
kubectl get clusterrolebindings -o json | python3 -c "
import json, sys
data = json.load(sys.stdin)
for binding in data['items']:
name = binding['metadata']['name']
role = binding['roleRef']['name']
subjects = binding.get('subjects', [])
for subject in subjects:
kind = subject.get('kind', '')
subj_name = subject.get('name', '')
ns = subject.get('namespace', 'cluster-wide')
print(f'{name} -> Role: {role} | {kind}: {subj_name} ({ns})')
" | sort
# Find bindings to cluster-admin
kubectl get clusterrolebindings -o json | python3 -c "
import json, sys
data = json.load(sys.stdin)
for binding in data['items']:
if binding['roleRef']['name'] == 'cluster-admin':
print(f\"Binding: {binding['metadata']['name']}\")
for subject in binding.get('subjects', []):
print(f\" {subject.get('kind')}: {subject.get('name')} (ns: {subject.get('namespace', 'N/A')})\")
"
# Find bindings granting access to all authenticated users
kubectl get clusterrolebindings -o json | python3 -c "
import json, sys
data = json.load(sys.stdin)
for binding in data['items']:
for subject in binding.get('subjects', []):
if subject.get('name') in ['system:authenticated', 'system:unauthenticated']:
print(f\"WARNING: {binding['metadata']['name']} grants {binding['roleRef']['name']} to {subject['name']}\")
"
步骤 3:使用 rbac-tool 进行全面分析扫描
使用 rbac-tool 进行自动化 RBAC 分析,包括谁可以执行的查询和策略生成。
# Who can get secrets across all namespaces
kubectl rbac-tool who-can get secrets
# Who can create pods (potential for container escape)
kubectl rbac-tool who-can create pods
# Who can exec into pods
kubectl rbac-tool who-can create pods/exec
# Who can escalate privileges (bind/escalate verbs)
kubectl rbac-tool who-can bind clusterroles
kubectl rbac-tool who-can escalate clusterroles
# Generate RBAC policy report
kubectl rbac-tool analysis
# Visualize RBAC relationships
kubectl rbac-tool viz --outformat dot > rbac-graph.dot
dot -Tpng rbac-graph.dot -o rbac-graph.png
步骤 4:运行 KubiScan 检测风险权限
使用 KubiScan 自动识别有风险的服务账户、Pod 和 RBAC 配置。
# Run KubiScan to find risky roles
python3 -m kubiscan -rroles # List risky Roles
python3 -m kubiscan -rcr # List risky ClusterRoles
python3 -m kubiscan -rrb # List risky RoleBindings
python3 -m kubiscan -rcrb # List risky ClusterRoleBindings
# Find risky service accounts
python3 -m kubiscan -rs # Risky service accounts
# Find pods running with risky service accounts
python3 -m kubiscan -rp # Risky pods
# Check for privilege escalation paths
python3 -m kubiscan -pe # Privilege escalation vectors
# Generate full report
python3 -m kubiscan -a # All checks
步骤 5:审计服务账户令牌的挂载和使用
检查是否存在不必要的服务账户令牌挂载,这些挂载可能使被入侵的 Pod 实现横向移动。
# Find pods with automounted service account tokens
kubectl get pods --all-namespaces -o json | python3 -c "
import json, sys
data = json.load(sys.stdin)
for pod in data['items']:
name = pod['metadata']['name']
ns = pod['metadata']['namespace']
sa = pod['spec'].get('serviceAccountName', 'default')
automount = pod['spec'].get('automountServiceAccountToken', True)
if automount and sa != 'default':
print(f'{ns}/{name} -> SA: {sa} (token auto-mounted)')
"
# Find service accounts with non-default token secrets
kubectl get serviceaccounts --all-namespaces -o json | python3 -c "
import json, sys
data = json.load(sys.stdin)
for sa in data['items']:
name = sa['metadata']['name']
ns = sa['metadata']['namespace']
secrets = sa.get('secrets', [])
if name != 'default' and len(secrets) > 0:
print(f'{ns}/{name}: {len(secrets)} secret(s) bound')
"
# Check for pods running as privileged or with host access
kubectl get pods --all-namespaces -o json | python3 -c "
import json, sys
data = json.load(sys.stdin)
for pod in data['items']:
name = pod['metadata']['name']
ns = pod['metadata']['namespace']
for container in pod['spec'].get('containers', []):
sc = container.get('securityContext', {})
if sc.get('privileged', False) or sc.get('runAsUser', 1) == 0:
print(f'RISK: {ns}/{name}/{container[\"name\"]} - privileged={sc.get(\"privileged\",False)} runAsRoot={sc.get(\"runAsUser\",\"not set\")==0}')
"
步骤 6:运行 Kubeaudit 进行 RBAC 和安全策略验证
执行 Kubeaudit 进行全面的安全检查,包括与 RBAC 相关的发现结果。
# Run all kubeaudit checks
kubeaudit all --kubeconfig ~/.kube/config
# Run specific RBAC-related checks
kubeaudit privesc # Check for allowPrivilegeEscalation
kubeaudit rootfs # Check for readOnlyRootFilesystem
kubeaudit nonroot # Check for runAsNonRoot
kubeaudit capabilities # Check for dangerous capabilities
# Output as JSON for processing
kubeaudit all --kubeconfig ~/.kube/config -f json > kubeaudit-results.json
关键概念
| 术语 | 定义 |
|---|---|
| RBAC | Kubernetes 中的基于角色的访问控制,一种根据单个用户或服务账户的角色来规范对集群资源访问的方法 |
| ClusterRole | 集群范围的角色定义,指定适用于所有命名空间的权限(对资源的动词) |
| ClusterRoleBinding | 在集群范围将 ClusterRole 与主体(用户、组、服务账户)关联起来 |
| 服务账户 | 与 Pod 关联的身份,用于向 Kubernetes API 服务器进行身份验证,除非禁用否则会自动挂载 |
| automountServiceAccountToken | Pod spec 字段,控制服务账户令牌是否自动挂载到 Pod 文件系统 |
| 权限提升 | 允许用户为自己或他人授予提升权限的 RBAC 动词(bind、escalate、impersonate) |
工具与系统
- kubectl:用于查询 Kubernetes RBAC 资源(角色、绑定、服务账户)的主要命令行工具
- rbac-tool:用于 RBAC 分析的 kubectl 插件,包括谁可以执行的查询、可视化和策略生成
- KubiScan:用于扫描 Kubernetes RBAC 以查找风险权限和权限提升路径的 Python 工具
- Kubeaudit:安全检查工具,检查 Pod 和工作负载是否存在安全反模式,包括 RBAC 问题
- rakkess:显示当前用户在所有资源类型上的访问矩阵的 kubectl 插件
常见场景
场景:审计多个开发团队共享的 EKS 集群
背景:一个共享的 EKS 集群为四个开发团队提供服务。RBAC 在初始设置时已配置,但已有 12 个月未审查。团队报告能够访问其他团队的命名空间。
方法:
- 列出所有 ClusterRoleBinding,以识别向已认证用户授予广泛访问权限的绑定
- 运行
kubectl rbac-tool who-can get secrets,查找可跨命名空间读取 Secret 的主体 - 发现一个 ClusterRoleBinding 向
system:authenticated授予edit,使所有用户拥有集群范围的写入权限 - 运行 KubiScan,识别具有高风险权限的服务账号,以及使用提升权限服务账号运行的 Pod
- 将该 ClusterRoleBinding 替换为每个团队的命名空间范围 RoleBinding
- 对不需要 API 访问的工作负载禁用 automountServiceAccountToken
- 创建 NetworkPolicy,隔离团队之间的命名空间流量
陷阱:移除 ClusterRoleBinding 可能会破坏依赖集群范围访问的 CI/CD 流水线和 operator。移除之前,务必审计哪些工作负载使用了这些绑定。EKS 通过 aws-auth ConfigMap 将 IAM 角色映射到 Kubernetes 组,因此 RBAC 变更必须与 IAM 角色映射协调一致。
输出格式
Kubernetes RBAC Audit Report
===============================
Cluster: production-eks (EKS 1.28)
Audit Date: 2026-02-23
Namespaces: 12
RBAC INVENTORY:
ClusterRoles: 48 (18 custom, 30 system)
ClusterRoleBindings: 32 (12 custom, 20 system)
Roles (namespaced): 24
RoleBindings (namespaced): 36
Service Accounts: 67
CRITICAL FINDINGS:
[RBAC-001] ClusterRoleBinding Grants edit to system:authenticated
Binding: authenticated-edit
Effect: ALL authenticated users have edit access across ALL namespaces
Risk: Any user can modify resources in any namespace
Remediation: Replace with namespace-scoped RoleBindings per team
[RBAC-002] Custom ClusterRole with Wildcard Permissions
ClusterRole: developer-admin
Rules: verbs=["*"], resources=["*"], apiGroups=["*"]
Bindings: 4 users via developer-admin-binding
Risk: Equivalent to cluster-admin without the name
Remediation: Scope to specific resources and verbs needed
SUMMARY:
Principals with cluster-admin: 6 (recommended: <= 3)
Roles with wildcard permissions: 4
Service accounts with secret access: 12
Pods with auto-mounted tokens: 45 / 67
Privileged containers: 8
评论
支持 Markdown