mcpField
A
auditing-kubernetes-cluster-rbac

auditing-kubernetes-cluster-rbac

github.com/mukul975セキュリティ35.2k264 回インストール8 週間前に更新
リポジトリ

auditing-kubernetes-cluster-rbac について

Kubernetes管理者やセキュリティ監査担当者向けのRBAC監査スキルです。複数のコマンドラインツールを使い、ロール、バインディング、サービスアカウント、危険な権限を確認する手順を示します。

主な機能

  1. 01ロールと権限バインディングの一覧化
  2. 02ワイルドカードや危険な権限の検出
  3. 03主体ごとに可能な操作の照会
  4. 04リスクのあるサービスアカウントの特定
  5. 05トークン自動マウントの確認
  6. 06監査ログとの照合

活用シーン

  1. 01クラスターの最小権限ポリシーの評価
  2. 02横展開や権限昇格リスクの調査
  3. 03コンプライアンス向けアクセス制御の記録
  4. 04共有クラスターの権限設計

インストール

コマンドをコピーしてターミナルで実行します。

$npx skills add https://github.com/mukul975/anthropic-cybersecurity-skills --skill auditing-kubernetes-cluster-rbac

インストール後、Claude Code で/auditing-kubernetes-cluster-rbacを入力して読み込まれたか確認します。

同梱ファイル

SKILL.md と一緒にインストールされる参考資料やスクリプト。

LICENSE
references/
api-reference.md
scripts/
agent.py

詳細

Kubernetes クラスター RBAC の監査

使用する場面

  • Kubernetes クラスター(EKS、GKE、AKS、またはセルフマネージド)のセキュリティ評価を実施するとき
  • RBAC ポリシーによって、ユーザーとサービスアカウントに最小権限が適用されていることを検証するとき
  • Kubernetes クラスター内での潜在的なラテラルムーブメントや権限昇格を調査するとき
  • コンプライアンス監査で、アクセス制御と権限の文書化が必要なとき
  • 共有クラスターに新しいチームを迎え入れ、適切な RBAC ポリシーを定義するとき

使用しないでください:ネットワークポリシーの監査(Cilium または Calico のネットワークポリシーツールを使用してください)、コンテナイメージのスキャン(Trivy または Grype を使用してください)、またはランタイムセキュリティの監視(Falco または Sysdig Secure を使用してください)。

前提条件

  • 対象クラスターに対する cluster-admin または同等の読み取り権限を持つように kubectl が設定されていること
  • rbac-tool がインストールされていること(kubectl krew install rbac-tool または GitHub からバイナリを取得)
  • KubiScan がインストールされていること(pip install kubiscan)
  • Kubeaudit がインストールされていること(brew install kubeaudit または GitHub リリースから取得)
  • RBAC の検出結果と実際の API アクセスを照合するために、クラスターの監査ログにアクセスできること

ワークフロー

ステップ 1:危険な権限を持つ ClusterRole と Role を列挙する

ワイルドカード権限、シークレットへのアクセス、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:ClusterRoleBinding と RoleBinding を監査する

バインディングを確認して、誰が昇格されたアクセス権を持つかを特定し、範囲が広すぎるグループ割り当てを検出します。

# 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 を使用して、who-can クエリやポリシー生成を含む 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

主な概念

用語定義
RBACKubernetes におけるロールベースのアクセス制御。個々のユーザーまたはサービスアカウントのロールに基づいて、クラスターリソースへのアクセスを制御する方法です
ClusterRoleすべての名前空間に適用される権限(リソースに対する動詞)を指定する、クラスター全体のロール定義です
ClusterRoleBindingクラスターのスコープで ClusterRole と主体(ユーザー、グループ、サービスアカウント)を関連付けます
Service AccountKubernetes API サーバーへの認証に使用される、Pod に関連付けられた ID です。無効化されていない限り、自動的にマウントされます
automountServiceAccountTokenサービスアカウントトークンを Pod のファイルシステムに自動的にマウントするかどうかを制御する Pod 仕様のフィールドです
Privilege Escalationユーザー自身または他のユーザーに昇格された権限を付与できる RBAC の動詞(bind、escalate、impersonate)です

ツールとシステム

  • kubectl:Kubernetes RBAC リソース(ロール、バインディング、サービスアカウント)を照会するための主要な CLI です
  • rbac-tool:who-can クエリ、可視化、ポリシー生成などの RBAC 分析を行う kubectl プラグインです
  • KubiScan:Kubernetes RBAC をスキャンし、リスクのある権限や権限昇格経路を検出する Python ツールです
  • Kubeaudit:RBAC の問題を含むセキュリティ上のアンチパターンがないか、Pod とワークロードをチェックするセキュリティ監査ツールです
  • rakkess:すべてのリソースタイプについて、現在のユーザーのアクセスマトリックスを表示する kubectl プラグインです

よくあるシナリオ

シナリオ:複数の開発チームが共有する EKS クラスターの監査

背景:共有 EKS クラスターを 4 つの開発チームが使用しています。初期設定時に RBAC が構成されましたが、過去 12 か月間見直されていません。各チームから、他のチームの名前空間にアクセスできてしまうという報告があります。

アプローチ:

  1. すべての ClusterRoleBindings を一覧表示し、認証済みユーザーに広範なアクセスを許可するバインディングを特定します
  2. kubectl rbac-tool who-can get secrets を実行して、名前空間をまたいでシークレットを読み取れるサブジェクトを確認します
  3. ClusterRoleBinding が system:authenticated に edit を付与しており、すべてのユーザーにクラスター全体への書き込みアクセスを許可していることを発見します
  4. KubiScan を実行し、リスクのある権限を持つサービスアカウントと、権限が昇格したサービスアカウントで実行されているポッドを特定します
  5. ClusterRoleBinding を、各チームを対象とする名前空間スコープの RoleBindings に置き換えます
  6. API アクセスを必要としないワークロードでは、automountServiceAccountToken を無効にします
  7. チーム間の名前空間トラフィックを分離する NetworkPolicy を作成します

注意点:ClusterRoleBindings を削除すると、クラスター全体へのアクセスに依存する CI/CD パイプラインやオペレーターが動作しなくなる可能性があります。削除する前に、どのワークロードがバインディングを使用しているかを必ず監査してください。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

コメント