Communitygithub.com

審計 Kubernetes RBAC 權限提升

此技能系統化列舉 Kubernetes 中每個主體的有效 RBAC 權限,識別可能導致權限提升的危險基本元素,並提供修復證據。

審計 Kubernetes RBAC 權限提升 是什麼?

此技能專為 Kubernetes 安全性審計與授權測試設計,旨在識別並評估 RBAC 權限提升路徑。它透過系統化列舉所有 Role、ClusterRole、RoleBinding 和 ClusterRoleBinding 物件,並使用 kubectl auth can-i、kubectl-who-can、rakkess、rbac-police 等工具,分析每個主體(使用者、服務帳戶)的有效權限。該技能聚焦於 Kubernetes RBAC 中的危險基本元素,如 escalate、bind、impersonate、wildcards 等,這些元素可能導致從單一受損 pod 提升至叢集管理員層級。支援 Kubernetes 作為平台,適用於授權安全測試、漏洞評估、許可權漂移審查及生產前驗證。透過自動化掃描與 Rego 策略評估,能生成優先排序的發現報告,並提供最小權限修復建議。

相容平台~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 的研究,危險的基本元素包括:

  • 對角色使用 escalate — 賦予自己任何權限,甚至包括自身不具備的權限。
  • 對叢集角色使用 bind — 建立對 cluster-admin 的綁定。
  • 對使用者/群組/服務帳號使用 impersonate — 以任何主體身分運作,包括 system:masters。
  • 對 Pod 執行 create/update/patch — 排程特權 Pod 或掛載節點,從而逃逸至主機(T1611)。
  • 對 pods/exec、pods/attach、pods/ephemeralcontainers 執行 create — 在現有 Pod 中執行程式碼。
  • 對 Secret 執行 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 來模擬一個主體(審計身分需要擁有 impersonate 權限)。

# 服務帳號的完整存取矩陣
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 掛載了該令牌時才有意義。

# 將每個 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") |
  "FINDING cluster-admin bound to: " +
  ((.subjects // []) | map(.kind+":"+.name) | join(", "))'

修復方式:以明確的動詞/資源取代萬用字元;除非必要,否則移除 escalate/bind/impersonate;對不呼叫 API 的工作負載設定 automountServiceAccountToken: false;盡可能使用 Scope Role(命名空間層級)而非 ClusterRole;謹慎使用 aggregationRule。

工具與資源

工具用途來源
kubectl auth can-i權威即時權限檢查(--list、--as)https://kubernetes.io/zh/docs/reference/access-authn-authz/authorization/
rbac-police基於 Rego 的權限提升路徑分析https://github.com/PaloAltoNetworks/rbac-police
kubectl-who-can反向查詢:誰可以執行 Xhttps://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/zh/docs/concepts/security/rbac-good-practices/

危險 RBAC 基本元素參考

動詞 / 資源為什麼等同叢集管理員
對角色使用 escalate賦予自己任何權限
對叢集角色使用 bind將自己綁定至 cluster-admin
對使用者/群組使用 impersonate以 system:masters 身分運作
create pods(+ 節點存取)特權/hostPath Pod → 主機接管
create pods/exec、pods/attach在現有 Pod 中執行程式碼
對 Secret 執行 get/list讀取所有令牌與憑證
對 serviceaccounts/token 執行 create生成特權令牌
*/*(萬用字元)隱含的超級權限

驗證準則

  • 已盤點並匯出所有 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,

相關技能