TExcelTAD
Home › Cloud & Container Security › RBAC Review: Who Can Do What

RBAC Review: Who Can Do What

Inside the cluster, Kubernetes RBAC decides what every user, group and service account may do through the API. A compromised pod's service account token, a developer's leaked kubeconfig, or a CI token are all only as dangerous as their RBAC bindings, so "who can do what" is the central question of a cluster review. It has a twist that IAM reviewers will recognise: some permissions that look modest are escalation paths, because the API lets you turn them into others. Creating a pod lets you run as any service account in the namespace and mount any Secret; bind and escalate let you grant roles you don't hold; impersonate lets you act as someone else. RBAC built a basic evaluator; this lesson adds the escalation view and compares it with a scanner.

Permissions that are worth more than they look

Permission Why it is an escalation path
create pods (or create/update any workload: deployments, jobs, daemonsets…) the pod can name any service account in the namespace and mount any Secret or ConfigMap in it, so it reaches everything those can; with weak Pod Security, also privileged and host paths
get/list/watch secrets service-account tokens of other identities (legacy long-lived ones), cloud keys, database passwords; list returns the values, not just names
create pods/exec, pods/attach, pods/portforward a shell or tunnel in any running pod, with its identity and mounted secrets
bind on roles, escalate on roles, or create/update (Cluster)RoleBindings grant yourself or others permissions you don't have (the API normally blocks that, unless you hold bind or escalate)
impersonate users, groups, service accounts act as any of them, including system:masters if not restricted
create serviceaccounts/token mint tokens for other service accounts
nodes/proxy, get nodes/proxy talk to kubelet APIs through the API server, including exec on that node
update/patch on validatingwebhookconfigurations, mutatingwebhookconfigurations switch off or subvert admission controls
* on * everything (cluster-admin)

A scanner's view

Trivy checks Role and ClusterRole definitions against a set of rules. The session writes three roles from the lab cluster and scans them; it runs in your sandbox on a local file.

bash · try it yourself
cat > rbac.yaml <<'Y'
apiVersion: rbac.authorization.k8s.io/v1
kind: Role
metadata: {name: deployer, namespace: shop}
rules:
  - apiGroups: ["apps"]
    resources: ["deployments"]
    verbs: ["get", "list", "update", "patch"]
  - apiGroups: [""]
    resources: ["pods/exec"]
    verbs: ["create"]
---
apiVersion: rbac.authorization.k8s.io/v1
kind: ClusterRole
metadata: {name: support}
rules:
  - apiGroups: [""]
    resources: ["secrets"]
    verbs: ["get", "list"]
  - apiGroups: ["rbac.authorization.k8s.io"]
    resources: ["clusterrolebindings"]
    verbs: ["create"]
  - apiGroups: [""]
    resources: ["users", "groups", "serviceaccounts"]
    verbs: ["impersonate"]
---
apiVersion: rbac.authorization.k8s.io/v1
kind: ClusterRole
metadata: {name: ops-all}
rules:
  - apiGroups: ["*"]
    resources: ["*"]
    verbs: ["*"]
Y
trivy config -q -f json . | jq -r '[.Results[].Misconfigurations[]?] | sort_by(.ID)[] | "\(.Severity) \(.ID) \(.Message)"'
CRITICAL KSV-0041 ClusterRole 'support' shouldn't have access to manage resource 'secrets'
CRITICAL KSV-0044 Role permits wildcard verb on wildcard resource
CRITICAL KSV-0046 ClusterRole 'ops-all' shouldn't manage all resources
MEDIUM KSV-0048 Role 'deployer' should not have access to resources ["pods", "deployments", "jobs", "cronjobs", "statefulsets", "daemonsets", "replicasets", "replicationcontrollers"] for verbs ["create", "update", "patch", "delete", "deletecollection", "impersonate", "*"]
HIGH KSV-0053 Role 'deployer' should not have access to resource '["pods/exec"]' for verbs ["create", "update", "patch", "delete", "deletecollection", "impersonate", "*"]

Useful findings, but look at what is missing for support: the scanner flagged its Secret access, and said nothing about create clusterrolebindings or impersonate, either of which is a direct path to cluster-admin. Scanners check roles one at a time against fixed rules; reviewers must also ask who is bound to what and what each binding can turn into.

A who-can analysis

The program loads roles and bindings, expands them per subject (RoleBindings grant within their namespace, ClusterRoleBindings everywhere), and answers two questions: who holds each sensitive permission, and which subjects can reach cluster-admin through an escalation verb.

python · try it yourself
import yaml

docs = list(yaml.safe_load_all("""
kind: Role
metadata: {name: deployer, namespace: shop}
rules:
- {apiGroups: [apps], resources: [deployments], verbs: [get, list, update, patch]}
- {apiGroups: [""], resources: [pods/exec], verbs: [create]}
---
kind: Role
metadata: {name: config-reader, namespace: shop}
rules:
- {apiGroups: [""], resources: [configmaps, secrets], verbs: [get, list]}
---
kind: ClusterRole
metadata: {name: support}
rules:
- {apiGroups: [""], resources: [secrets], verbs: [get, list]}
- {apiGroups: [rbac.authorization.k8s.io], resources: [clusterrolebindings], verbs: [create]}
- {apiGroups: [""], resources: [users, groups, serviceaccounts], verbs: [impersonate]}
---
kind: ClusterRole
metadata: {name: view-pods}
rules:
- {apiGroups: [""], resources: [pods, pods/log], verbs: [get, list, watch]}
---
kind: RoleBinding
metadata: {name: devs-deploy, namespace: shop}
subjects: [{kind: Group, name: shop-devs}]
roleRef: {kind: Role, name: deployer}
---
kind: RoleBinding
metadata: {name: app-config, namespace: shop}
subjects: [{kind: ServiceAccount, name: web, namespace: shop}]
roleRef: {kind: Role, name: config-reader}
---
kind: ClusterRoleBinding
metadata: {name: helpdesk}
subjects: [{kind: User, name: carol}]
roleRef: {kind: ClusterRole, name: support}
---
kind: ClusterRoleBinding
metadata: {name: monitoring}
subjects: [{kind: ServiceAccount, name: prometheus, namespace: monitoring}]
roleRef: {kind: ClusterRole, name: view-pods}
"""))
roles = {(d["kind"], d["metadata"]["name"], d["metadata"].get("namespace")): d["rules"] for d in docs if d["kind"] in ("Role", "ClusterRole")}

grants = []   # (subject, namespace or '*', rule)
for b in (d for d in docs if d["kind"].endswith("Binding")):
    ns = b["metadata"].get("namespace", "*")
    ref = b["roleRef"]
    rules = roles[(ref["kind"], ref["name"], ns if ref["kind"] == "Role" else None)]
    for s in b["subjects"]:
        who = f"{s['kind']}:{s.get('namespace', '') + '/' if s['kind'] == 'ServiceAccount' else ''}{s['name']}"
        grants += [(who, ns, r) for r in rules]

def can(who, verb, resource, ns):
    return any(g_who == who and g_ns in ("*", ns) and (verb in r["verbs"] or "*" in r["verbs"])
               and (resource in r["resources"] or "*" in r["resources"]) for g_who, g_ns, r in grants)

subjects = sorted({g[0] for g in grants})
SENSITIVE = [("read secrets", "list", "secrets"), ("exec into pods", "create", "pods/exec"),
             ("change workloads", "update", "deployments"), ("bind cluster roles", "create", "clusterrolebindings"),
             ("impersonate users", "impersonate", "users")]
print(f"{'in namespace shop':37}" + "".join(f"{label:>19}" for label, _, _ in SENSITIVE))
for who in subjects:
    print(f"{who:37}" + "".join(f"{('yes' if can(who, v, r, 'shop') else '-'):>19}" for _, v, r in SENSITIVE))

print()
for who in subjects:
    paths = []
    if can(who, "create", "clusterrolebindings", "*"):
        paths.append("create a ClusterRoleBinding to cluster-admin (needs bind, or holding the role, in real RBAC; check!)")
    if can(who, "impersonate", "groups", "*"):
        paths.append("impersonate group system:masters")
    if can(who, "update", "deployments", "shop") and can(who, "list", "secrets", "shop") is False:
        paths.append("change a deployment to run as another service account of 'shop' and mount its secrets")
    for p in paths:
        print(f"ESCALATION {who}: {p}")
in namespace shop                           read secrets     exec into pods   change workloads bind cluster roles  impersonate users
Group:shop-devs                                        -                yes                yes                  -                  -
ServiceAccount:monitoring/prometheus                   -                  -                  -                  -                  -
ServiceAccount:shop/web                              yes                  -                  -                  -                  -
User:carol                                           yes                  -                  -                yes                yes

ESCALATION Group:shop-devs: change a deployment to run as another service account of 'shop' and mount its secrets
ESCALATION User:carol: create a ClusterRoleBinding to cluster-admin (needs bind, or holding the role, in real RBAC; check!)
ESCALATION User:carol: impersonate group system:masters

The matrix answers the first question at a glance: one person (carol, through a cluster-wide binding) and one workload (web) can read Secrets in shop. The second part shows why carol's "support" role is the critical finding: impersonate on groups is enough to act as system:masters, which bypasses RBAC entirely. The create clusterrolebindings path is flagged with a caveat the model can't check: the API server only lets you bind a role you already hold unless you also have the bind verb, an important built-in guard. And the shop-devs path is the quiet one: updating a deployment is updating a pod template, so developers can run code as any service account in shop, including web, which can read every Secret there.

How RBAC is reviewed in a live cluster

console
# lab session (illustrative; cluster "shop" in the lab account, run by the cluster admin)
$ kubectl auth can-i --list --as=system:serviceaccount:shop:web -n shop
Resources        Non-Resource URLs   Resource Names   Verbs
configmaps       []                  []               [get list]
secrets          []                  []               [get list]
...
$ kubectl auth can-i impersonate groups --as=carol
yes
$ kubectl get clusterrolebindings -o json | jq -r '.items[] | select(.roleRef.name=="cluster-admin") | .subjects[]?.name'
system:masters
ops-breakglass
  • kubectl auth can-i --list --as … per identity; kubectl who-can-style plugins and tools (rbac-tool, KubiScan, rakkess) invert it per permission.
  • List every binding to cluster-admin, admin, edit and every role with escalation verbs.
  • Check service accounts as carefully as people: a pod's token is the first thing an attacker uses after compromising it.

How it is detected in use

Kubernetes audit logs record the user, verb, resource and response for every request: alert on impersonate (the audit event shows impersonatedUser), new ClusterRoleBindings, pods/exec by humans in production, Secret list calls by service accounts that never did it before (Audit Logs).

How it is fixed

  • Bind humans through groups from the identity provider, never individual users; give production write access through CI, not people.
  • Remove list/watch on Secrets wherever get on named Secrets is enough (resourceNames), and prefer workload identity and external secret stores so fewer Secrets exist.
  • Reserve bind, escalate, impersonate, nodes/proxy, webhook configuration and serviceaccounts/token for the platform team, with alerts on use.
  • Set automountServiceAccountToken: false for pods that don't call the API, and give each workload its own service account.
  • Enforce Pod Security so that "create pods" can't also mean "create privileged pods".

Pitfalls

  • Reading Roles without their bindings (and the reverse): risk is the product of what a role allows and who holds it.
  • Forgetting aggregated ClusterRoles (admin, edit, view grow when new CRDs add aggregation labels).
  • Treating view as harmless everywhere: it excludes Secrets, but custom resources aggregated into it may hold sensitive data.

Practice

1. Add a RoleBinding giving Group:shop-devs the config-reader role. How does the matrix change, and does the deployment escalation still matter?

shop-devs gains "read secrets: yes" and the deployment-escalation line disappears (the model only prints it for subjects who can't read Secrets directly). The deployment path still matters for anything else the service accounts can do, such as cloud access through workload identity.

2. Why is list on Secrets worse than get with resourceNames?

list returns every Secret in the namespace with its data, including ones created later; get restricted by resourceNames reaches only the named Secrets.

3. Which audit-log fields would show carol using impersonation?

user.username: carol together with impersonatedUser (for example username and groups: ["system:masters"]), plus the verb and resource of the request made as that identity.

Test yourself

Why is 'create pods' in a namespace an escalation path?

  1. Pods are expensive
  2. A pod can run as any service account in the namespace and mount any Secret there
  3. Pods bypass the API server
  4. It isn't

What did Trivy miss in the support ClusterRole?

  1. Secret access
  2. The create-clusterrolebindings and impersonate escalation paths
  3. Wildcards
  4. Nothing

What does impersonating the group system:masters give?

  1. Read-only access
  2. Full cluster-admin: the group bypasses RBAC authorization
  3. Access to one namespace
  4. Nothing without a token

What built-in guard limits creating RoleBindings?

  1. None
  2. You can only bind roles whose permissions you already hold, unless you have the bind verb
  3. Bindings need MFA
  4. Only the kubelet can create them