Skip to content
Published on

Kubernetes RBAC完全ガイド:Golden Kubestronaut試験対策ハンズオン

Authors
  • Name
    Twitter

1. RBACとは

KubernetesのRBAC(Role-Based Access Control)は、クラスター内のAPIリソースへのアクセスをロールベースで制御する認可(Authorization)メカニズムである。kube-apiserver--authorization-mode=RBACフラグが設定されていると有効化される。

RBACの基本原則は**最小権限の原則(Principle of Least Privilege)**である。すべてのユーザーとサービスアカウントは、業務遂行に必要な最小限の権限のみ付与されるべきである。

1.1 RBACの4つのコアリソース

リソーススコープ用途
Roleネームスペース特定ネームスペース内のリソース権限を定義
ClusterRoleクラスター全体クラスタースコープのリソースまたは複数ネームスペース共通の権限
RoleBindingネームスペースRoleまたはClusterRoleを特定ネームスペースでSubjectにバインド
ClusterRoleBindingクラスター全体ClusterRoleをクラスター全体でSubjectにバインド

2. RoleとClusterRoleの詳細

2.1 ネームスペースRoleの作成

# dev-reader-role.yaml
apiVersion: rbac.authorization.k8s.io/v1
kind: Role
metadata:
  namespace: development
  name: pod-reader
rules:
  - apiGroups: [''] # core API group
    resources: ['pods']
    verbs: ['get', 'watch', 'list']
  - apiGroups: ['']
    resources: ['pods/log']
    verbs: ['get']
  - apiGroups: ['apps']
    resources: ['deployments']
    verbs: ['get', 'list']

2.2 ClusterRoleの作成

apiVersion: rbac.authorization.k8s.io/v1
kind: ClusterRole
metadata:
  name: node-viewer
rules:
  - apiGroups: ['']
    resources: ['nodes']
    verbs: ['get', 'list', 'watch']
  - apiGroups: ['metrics.k8s.io']
    resources: ['nodes']
    verbs: ['get', 'list']

2.3 Aggregated ClusterRole

CKS試験で頻出するAggregated ClusterRoleパターン:

apiVersion: rbac.authorization.k8s.io/v1
kind: ClusterRole
metadata:
  name: monitoring-endpoints
  labels:
    rbac.example.com/aggregate-to-monitoring: 'true'
rules:
  - apiGroups: ['']
    resources: ['services', 'endpoints', 'pods']
    verbs: ['get', 'list', 'watch']
---
apiVersion: rbac.authorization.k8s.io/v1
kind: ClusterRole
metadata:
  name: monitoring
aggregationRule:
  clusterRoleSelectors:
    - matchLabels:
        rbac.example.com/aggregate-to-monitoring: 'true'
rules: [] # 自動的に集約される

3. RoleBindingとClusterRoleBinding

3.1 RoleBinding:ネームスペース内の権限付与

apiVersion: rbac.authorization.k8s.io/v1
kind: RoleBinding
metadata:
  name: read-pods
  namespace: development
subjects:
  - kind: User
    name: jane
    apiGroup: rbac.authorization.k8s.io
  - kind: ServiceAccount
    name: ci-bot
    namespace: development
roleRef:
  kind: Role
  name: pod-reader
  apiGroup: rbac.authorization.k8s.io

3.2 ClusterRoleをRoleBindingで使用する(重要!)

ClusterRoleをRoleBindingに接続すると、そのネームスペースでのみ有効となる。共通の権限セットを複数のネームスペースで再利用する際に非常に便利である:

apiVersion: rbac.authorization.k8s.io/v1
kind: RoleBinding
metadata:
  name: read-pods-staging
  namespace: staging
subjects:
  - kind: Group
    name: dev-team
    apiGroup: rbac.authorization.k8s.io
roleRef:
  kind: ClusterRole # ClusterRoleだが
  name: pod-reader # RoleBindingなのでstagingネームスペースでのみ有効
  apiGroup: rbac.authorization.k8s.io

4. ServiceAccountとRBAC

4.1 ServiceAccountトークン(1.24+)

Kubernetes 1.24以降、SAの自動Secret生成は廃止された:

# ServiceAccountの作成
kubectl create serviceaccount monitoring-sa -n monitoring

# 短期トークンの生成(1時間)
kubectl create token monitoring-sa -n monitoring --duration=3600s

# 長期トークン(レガシー互換用)
cat <<EOF | kubectl apply -f -
apiVersion: v1
kind: Secret
metadata:
  name: monitoring-sa-token
  namespace: monitoring
  annotations:
    kubernetes.io/service-account.name: monitoring-sa
type: kubernetes.io/service-account-token
EOF

4.2 PodでのSAトークンマウントの無効化

apiVersion: v1
kind: Pod
metadata:
  name: secure-pod
spec:
  automountServiceAccountToken: false
  containers:
    - name: app
      image: nginx:1.27

5. ハンズオン:マルチテナントRBAC構成

5.1 シナリオ

  • frontend-teamfrontend NS — Deployment、Service、ConfigMapの管理
  • backend-teambackend NS — すべてのワークロード + Secretsの読み取り
  • platform-team:クラスター全体 — 読み取り専用 + Node/PVの管理

5.2 実装

kubectl create ns frontend
kubectl create ns backend

# 1) frontend-team
cat <<'EOF' | kubectl apply -f -
apiVersion: rbac.authorization.k8s.io/v1
kind: Role
metadata:
  namespace: frontend
  name: frontend-developer
rules:
- apiGroups: ["", "apps"]
  resources: ["deployments", "services", "configmaps", "pods"]
  verbs: ["get", "list", "watch", "create", "update", "patch", "delete"]
- apiGroups: [""]
  resources: ["pods/log", "pods/exec"]
  verbs: ["get", "create"]
---
apiVersion: rbac.authorization.k8s.io/v1
kind: RoleBinding
metadata:
  namespace: frontend
  name: frontend-team-binding
subjects:
- kind: Group
  name: frontend-team
  apiGroup: rbac.authorization.k8s.io
roleRef:
  kind: Role
  name: frontend-developer
  apiGroup: rbac.authorization.k8s.io
EOF

# 2) backend-team
cat <<'EOF' | kubectl apply -f -
apiVersion: rbac.authorization.k8s.io/v1
kind: Role
metadata:
  namespace: backend
  name: backend-developer
rules:
- apiGroups: ["", "apps", "batch"]
  resources: ["*"]
  verbs: ["*"]
- apiGroups: [""]
  resources: ["secrets"]
  verbs: ["get", "list"]
---
apiVersion: rbac.authorization.k8s.io/v1
kind: RoleBinding
metadata:
  namespace: backend
  name: backend-team-binding
subjects:
- kind: Group
  name: backend-team
  apiGroup: rbac.authorization.k8s.io
roleRef:
  kind: Role
  name: backend-developer
  apiGroup: rbac.authorization.k8s.io
EOF

# 3) platform-team
cat <<'EOF' | kubectl apply -f -
apiVersion: rbac.authorization.k8s.io/v1
kind: ClusterRole
metadata:
  name: platform-admin
rules:
- apiGroups: [""]
  resources: ["nodes", "persistentvolumes"]
  verbs: ["*"]
- apiGroups: ["", "apps", "batch", "networking.k8s.io"]
  resources: ["*"]
  verbs: ["get", "list", "watch"]
---
apiVersion: rbac.authorization.k8s.io/v1
kind: ClusterRoleBinding
metadata:
  name: platform-team-binding
subjects:
- kind: Group
  name: platform-team
  apiGroup: rbac.authorization.k8s.io
roleRef:
  kind: ClusterRole
  name: platform-admin
  apiGroup: rbac.authorization.k8s.io
EOF

5.3 権限検証

# frontend-teamはfrontend NSでPodの一覧を取得できるか?
kubectl auth can-i list pods --namespace=frontend --as=jane --as-group=frontend-team
# yes

# frontend-teamはbackend NSでPodを削除できるか?
kubectl auth can-i delete pods --namespace=backend --as=jane --as-group=frontend-team
# no

# 全権限一覧(CKS試験のコツ!)
kubectl auth can-i --list --as=jane --as-group=frontend-team -n frontend

6. CKS試験頻出RBACシナリオ

6.1 危険な権限の検出

# cluster-adminバインディングの検索
kubectl get clusterrolebindings -o json | jq -r '
  .items[] |
  select(.roleRef.name == "cluster-admin") |
  .metadata.name + " -> " +
  (.subjects[]? | .kind + "/" + .name)'

# ワイルドカード(*)権限を持つRoleの検索
kubectl get roles,clusterroles -A -o json | jq -r '
  .items[] |
  select(.rules[]?.verbs[]? == "*" or .rules[]?.resources[]? == "*") |
  .metadata.namespace + "/" + .metadata.name'

6.2 Secret アクセス監査

kubectl get roles,clusterroles -A -o json | jq -r '
  .items[] |
  select(.rules[]? | .resources[]? == "secrets") |
  "\(.metadata.namespace // "cluster")/\(.metadata.name)"'

6.3 Pod Security Standards + RBAC の組み合わせ

apiVersion: v1
kind: Namespace
metadata:
  name: secure-ns
  labels:
    pod-security.kubernetes.io/enforce: restricted
    pod-security.kubernetes.io/audit: restricted
    pod-security.kubernetes.io/warn: restricted

7. RBACベストプラクティス

  1. 最小権限の原則:ワイルドカード(*)の使用禁止、必要なverbのみ明示
  2. ClusterRoleBindingの最小化:可能な限りRoleBinding + ClusterRoleの組み合わせを使用
  3. ServiceAccountの分離:Pod毎に専用SAを作成、default SAの使用禁止
  4. トークンマウントの無効化automountServiceAccountToken: falseをデフォルト設定に
  5. 定期監査kubectl auth can-i --listで定期的な権限レビュー
  6. Aggregated ClusterRoleの活用:モジュール化された権限管理
  7. Impersonationの活用--asフラグで権限テスト後に適用

8. よくある間違いと解決策

間違い問題解決策
ClusterRole + RoleBinding vs ClusterRoleBindingの混同スコープの不一致Bindingのタイプがスコープを決定
apiGroups: [""]の欠落coreリソースにアクセス不可core API = 空文字列
サブリソース未包含pods/logpods/execにアクセス不可別途明示が必要
SAトークン期限切れの認識不足1.24+は短期トークンがデフォルト--durationを設定

9. クイズ

Q1. RoleとClusterRoleの最大の違いは?

Roleは特定のネームスペース内でのみ有効で、ClusterRoleはクラスター全体スコープの権限を定義する。ClusterRoleはNode、PVのような非ネームスペースリソースにも権限を付与できる。

Q2. ClusterRoleをRoleBindingに接続するとどうなるか?

ClusterRoleに定義された権限が、RoleBindingが属するネームスペースでのみ有効となる。

Q3. Kubernetes 1.24+以降のServiceAccountトークン関連の変更点は?

自動Secret生成が廃止された。kubectl create tokenで短期トークン(デフォルト1時間)を生成するか、kubernetes.io/service-account-token Secretを手動で作成する必要がある。

Q4. automountServiceAccountToken: falseを設定する理由は?

Pod内の不要なSAトークンマウントを防止し、コンテナ侵害時に攻撃者のK8s APIへのアクセスを遮断する。最小権限の原則の一環である。

Q5. kubectl auth can-i delete pods --as=jane -n productionは何をするか?

Impersonation機能を使用して、janeユーザーがproductionネームスペースでPodの削除権限を持っているか確認する。

Q6. Aggregated ClusterRoleの動作原理は?

aggregationRuleのラベルセレクターに一致する他のClusterRoleのrulesが自動的に集約される。新しいClusterRoleの追加時に自動反映される。

Q7. 過剰な権限(cluster-admin)バインディングを見つける方法は?

kubectl get clusterrolebindings -o json | jqroleRef.name == "cluster-admin"のバインディングをフィルタリングする。

Q8. KCSA試験のRBAC主要出題ポイント3つは?

(1) 最小権限の原則 — ワイルドカードの回避 (2) SAセキュリティ — トークンマウント無効化、default SA未使用 (3) 定期監査 — can-i --list、過剰なClusterRoleBindingの検出