
Auditing Kubernetes Cluster Rbac
- 224 installs
- 27.3k repo stars
- Updated August 2, 2026
- mukul975/anthropic-cybersecurity-skills
Auditing Kubernetes Cluster RBAC is an agent skill that guides systematic review of Kubernetes roles, cluster roles, and bindings to catch over-privileged access.
About
Auditing Kubernetes Cluster RBAC is an agent skill aimed at solo and indie builders who run apps on Kubernetes and need repeatable role-and-binding reviews without hiring a dedicated platform security team. It instructs your coding agent to walk cluster RBAC configuration—who can create secrets, exec into pods, or escalate privileges—and surface excessive grants before they become incidents. Use it when you are shipping a new service account layout, onboarding a contractor, or responding to a leaked kubeconfig. The skill fits the Ship and Operate phases as a checker-style ritual you invoke against kube-apiserver context you already trust. It complements generic linting by focusing on authorization graphs rather than container image CVEs. Pair it with your existing kubectl or cloud-console workflow; the agent structures questions and findings you can paste into tickets or policy docs. Because the published SKILL body in-repo is minimal beyond licensing, treat outputs as advisory and validate every recommendation against your org’s least-privilege baseline and live `kubectl auth can-i` checks.
- Guides agent-assisted review of Kubernetes RBAC bindings and effective permissions
- Fits pre-ship hardening and post-deploy access-change checks on live clusters
- Aligns with Anthropic cybersecurity skill patterns for infrastructure assurance
- Supports solo builders operating their own EKS, GKE, or self-managed clusters
- Apache 2.0 licensed skill package from a cybersecurity-focused skills collection
Auditing Kubernetes Cluster Rbac by the numbers
- 224 all-time installs (skills.sh)
- +12 installs in the week ending Aug 4, 2026 (Skillselion tracking)
- Ranked #728 of 2,203 Security skills by installs in the Skillselion catalog
- Security screen: LOW risk (skills.sh audit)
- Data as of Aug 5, 2026 (Skillselion catalog sync)
npx skills add https://github.com/mukul975/anthropic-cybersecurity-skills --skill auditing-kubernetes-cluster-rbacAdd your badge
Show developers this skill is listed on Skillselion. Paste this into your README.
| Installs | 224 |
|---|---|
| repo stars | ★ 27.3k |
| Security audit | 3 / 3 scanners passed |
| Last updated | August 2, 2026 |
| Repository | mukul975/anthropic-cybersecurity-skills ↗ |
What it does
Run a structured Kubernetes RBAC review before release or during production access changes so cluster roles and bindings do not over-privilege workloads or humans.
Who is it for?
Best when you're on managed or self-hosted Kubernetes and change RBAC infrequently and want agent-guided review checkpoints.
Skip if: Skip if you already enforce RBAC exclusively via GitOps policy engines with mandatory CI gates and no manual cluster drift.
When should I use this skill?
Before production Kubernetes deploys or when cluster roles, bindings, or service account permissions change.
What you get
You get a structured RBAC audit narrative and remediation-oriented notes you can apply before merge, release, or after an access-model change.
- RBAC findings summary
- prioritized binding and role remediation notes
Files
Auditing Kubernetes Cluster RBAC
When to Use
- When performing security assessments of Kubernetes clusters (EKS, GKE, AKS, or self-managed)
- When validating that RBAC policies enforce least privilege for users and service accounts
- When investigating potential lateral movement or privilege escalation within a Kubernetes cluster
- When compliance audits require documentation of access controls and permissions
- When onboarding new teams to a shared cluster and defining appropriate RBAC policies
Do not use for network policy auditing (use Cilium or Calico network policy tools), for container image scanning (use Trivy or Grype), or for runtime security monitoring (use Falco or Sysdig Secure).
Prerequisites
- kubectl configured with cluster-admin or equivalent read permissions to the target cluster
- rbac-tool installed (
kubectl krew install rbac-toolor binary from GitHub) - KubiScan installed (
pip install kubiscan) - Kubeaudit installed (
brew install kubeauditor from GitHub releases) - Access to the cluster's audit logs for correlating RBAC findings with actual API access
Workflow
Step 1: Enumerate ClusterRoles and Roles with Dangerous Permissions
Identify roles with wildcard permissions, secret access, pod exec, or escalation capabilities.
# 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')
"Step 2: Audit ClusterRoleBindings and RoleBindings
Review bindings to identify who has elevated access and detect overly broad group assignments.
# 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']}\")
"Step 3: Scan with rbac-tool for Comprehensive Analysis
Use rbac-tool for automated RBAC analysis including who-can queries and policy generation.
# 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.pngStep 4: Run KubiScan for Risky Permissions Detection
Use KubiScan to automatically identify risky service accounts, pods, and RBAC configurations.
# 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 checksStep 5: Audit Service Account Token Mounting and Usage
Check for unnecessary service account token mounts that could enable lateral movement from compromised pods.
# 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}')
"Step 6: Run Kubeaudit for RBAC and Security Policy Validation
Execute Kubeaudit for comprehensive security checks including RBAC-related findings.
# 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.jsonKey Concepts
| Term | Definition |
|---|---|
| RBAC | Role-Based Access Control in Kubernetes, a method for regulating access to cluster resources based on the roles of individual users or service accounts |
| ClusterRole | Cluster-wide role definition that specifies permissions (verbs on resources) applicable across all namespaces |
| ClusterRoleBinding | Associates a ClusterRole with subjects (users, groups, service accounts) at the cluster scope |
| Service Account | Identity associated with pods for authenticating to the Kubernetes API server, automatically mounted unless disabled |
| automountServiceAccountToken | Pod spec field controlling whether the service account token is automatically mounted into the pod filesystem |
| Privilege Escalation | RBAC verbs (bind, escalate, impersonate) that allow a user to grant themselves or others elevated permissions |
Tools & Systems
- kubectl: Primary CLI for querying Kubernetes RBAC resources (roles, bindings, service accounts)
- rbac-tool: kubectl plugin for RBAC analysis including who-can queries, visualization, and policy generation
- KubiScan: Python tool for scanning Kubernetes RBAC for risky permissions and privilege escalation paths
- Kubeaudit: Security auditing tool that checks pods and workloads for security anti-patterns including RBAC issues
- rakkess: kubectl plugin showing access matrix for the current user across all resource types
Common Scenarios
Scenario: Auditing an EKS Cluster Shared by Multiple Development Teams
Context: A shared EKS cluster serves four development teams. RBAC was configured during initial setup but has not been reviewed in 12 months. Teams report being able to access other teams' namespaces.
Approach: 1. List all ClusterRoleBindings to identify bindings granting broad access to authenticated users 2. Run kubectl rbac-tool who-can get secrets to find subjects that can read secrets across namespaces 3. Discover that a ClusterRoleBinding grants edit to system:authenticated, giving all users write access cluster-wide 4. Run KubiScan to identify service accounts with risky permissions and pods running with elevated service accounts 5. Replace the ClusterRoleBinding with namespace-scoped RoleBindings for each team 6. Disable automountServiceAccountToken for workloads that do not need API access 7. Create a NetworkPolicy to isolate namespace traffic between teams
Pitfalls: Removing ClusterRoleBindings can break CI/CD pipelines and operators that rely on cluster-wide access. Always audit which workloads use the bindings before removing them. EKS maps IAM roles to Kubernetes groups via aws-auth ConfigMap, so RBAC changes must be coordinated with IAM role mappings.
Output Format
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
Apache License
Version 2.0, January 2004
http://www.apache.org/licenses/
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
1. Definitions.
"License" shall mean the terms and conditions for use, reproduction,
and distribution as defined by Sections 1 through 9 of this document.
"Licensor" shall mean the copyright owner or entity authorized by
the copyright owner that is granting the License.
"Legal Entity" shall mean the union of the acting entity and all
other entities that control, are controlled by, or are under common
control with that entity. For the purposes of this definition,
"control" means (i) the power, direct or indirect, to cause the
direction or management of such entity, whether by contract or
otherwise, or (ii) ownership of fifty percent (50%) or more of the
outstanding shares, or (iii) beneficial ownership of such entity.
"You" (or "Your") shall mean an individual or Legal Entity
exercising permissions granted by this License.
"Source" form shall mean the preferred form for making modifications,
including but not limited to software source code, documentation
source, and configuration files.
"Object" form shall mean any form resulting from mechanical
transformation or translation of a Source form, including but
not limited to compiled object code, generated documentation,
and conversions to other media types.
"Work" shall mean the work of authorship, whether in Source or
Object form, made available under the License, as indicated by a
copyright notice that is included in or attached to the work
(an example is provided in the Appendix below).
"Derivative Works" shall mean any work, whether in Source or Object
form, that is based on (or derived from) the Work and for which the
editorial revisions, annotations, elaborations, or other modifications
represent, as a whole, an original work of authorship. For the purposes
of this License, Derivative Works shall not include works that remain
separable from, or merely link (or bind by name) to the interfaces of,
the Work and Derivative Works thereof.
"Contribution" shall mean any work of authorship, including
the original version of the Work and any modifications or additions
to that Work or Derivative Works thereof, that is intentionally
submitted to the Licensor for inclusion in the Work by the copyright owner
or by an individual or Legal Entity authorized to submit on behalf of
the copyright owner. For the purposes of this definition, "submitted"
means any form of electronic, verbal, or written communication sent
to the Licensor or its representatives, including but not limited to
communication on electronic mailing lists, source code control systems,
and issue tracking systems that are managed by, or on behalf of, the
Licensor for the purpose of discussing and improving the Work, but
excluding communication that is conspicuously marked or otherwise
designated in writing by the copyright owner as "Not a Contribution."
"Contributor" shall mean Licensor and any individual or Legal Entity
on behalf of whom a Contribution has been received by the Licensor and
subsequently incorporated within the Work.
2. Grant of Copyright License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
copyright license to reproduce, prepare Derivative Works of,
publicly display, publicly perform, sublicense, and distribute the
Work and such Derivative Works in Source or Object form.
3. Grant of Patent License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
(except as stated in this section) patent license to make, have made,
use, offer to sell, sell, import, and otherwise transfer the Work,
where such license applies only to those patent claims licensable
by such Contributor that are necessarily infringed by their
Contribution(s) alone or by combination of their Contribution(s)
with the Work to which such Contribution(s) was submitted. If You
institute patent litigation against any entity (including a
cross-claim or counterclaim in a lawsuit) alleging that the Work
or a Contribution incorporated within the Work constitutes direct
or contributory patent infringement, then any patent licenses
granted to You under this License for that Work shall terminate
as of the date such litigation is filed.
4. Redistribution. You may reproduce and distribute copies of the
Work or Derivative Works thereof in any medium, with or without
modifications, and in Source or Object form, provided that You
meet the following conditions:
(a) You must give any other recipients of the Work or
Derivative Works a copy of this License; and
(b) You must cause any modified files to carry prominent notices
stating that You changed the files; and
(c) You must retain, in the Source form of any Derivative Works
that You distribute, all copyright, patent, trademark, and
attribution notices from the Source form of the Work,
excluding those notices that do not pertain to any part of
the Derivative Works; and
(d) If the Work includes a "NOTICE" text file as part of its
distribution, then any Derivative Works that You distribute must
include a readable copy of the attribution notices contained
within such NOTICE file, excluding any notices that do not
pertain to any part of the Derivative Works, in at least one
of the following places: within a NOTICE text file distributed
as part of the Derivative Works; within the Source form or
documentation, if provided along with the Derivative Works; or,
within a display generated by the Derivative Works, if and
wherever such third-party notices normally appear. The contents
of the NOTICE file are for informational purposes only and
do not modify the License. You may add Your own attribution
notices within Derivative Works that You distribute, alongside
or as an addendum to the NOTICE text from the Work, provided
that such additional attribution notices cannot be construed
as modifying the License.
You may add Your own copyright statement to Your modifications and
may provide additional or different license terms and conditions
for use, reproduction, or distribution of Your modifications, or
for any such Derivative Works as a whole, provided Your use,
reproduction, and distribution of the Work otherwise complies with
the conditions stated in this License.
5. Submission of Contributions. Unless You explicitly state otherwise,
any Contribution intentionally submitted for inclusion in the Work
by You to the Licensor shall be under the terms and conditions of
this License, without any additional terms or conditions.
Notwithstanding the above, nothing herein shall supersede or modify
the terms of any separate license agreement you may have executed
with Licensor regarding such Contributions.
6. Trademarks. This License does not grant permission to use the trade
names, trademarks, service marks, or product names of the Licensor,
except as required for reasonable and customary use in describing the
origin of the Work and reproducing the content of the NOTICE file.
7. Disclaimer of Warranty. Unless required by applicable law or
agreed to in writing, Licensor provides the Work (and each
Contributor provides its Contributions) on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
implied, including, without limitation, any warranties or conditions
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
PARTICULAR PURPOSE. You are solely responsible for determining the
appropriateness of using or redistributing the Work and assume any
risks associated with Your exercise of permissions under this License.
8. Limitation of Liability. In no event and under no legal theory,
whether in tort (including negligence), contract, or otherwise,
unless required by applicable law (such as deliberate and grossly
negligent acts) or agreed to in writing, shall any Contributor be
liable to You for damages, including any direct, indirect, special,
incidental, or consequential damages of any character arising as a
result of this License or out of the use or inability to use the
Work (including but not limited to damages for loss of goodwill,
work stoppage, computer failure or malfunction, or any and all
other commercial damages or losses), even if such Contributor
has been advised of the possibility of such damages.
9. Accepting Warranty or Additional Liability. While redistributing
the Work or Derivative Works thereof, You may choose to offer,
and charge a fee for, acceptance of support, warranty, indemnity,
or other liability obligations and/or rights consistent with this
License. However, in accepting such obligations, You may act only
on Your own behalf and on Your sole responsibility, not on behalf
of any other Contributor, and only if You agree to indemnify,
defend, and hold each Contributor harmless for any liability
incurred by, or claims asserted against, such Contributor by reason
of your accepting any such warranty or additional liability.
END OF TERMS AND CONDITIONS
APPENDIX: How to apply the Apache License to your work.
To apply the Apache License to your work, attach the following
boilerplate notice, with the fields enclosed by brackets "[]"
replaced with your own identifying information. (Don't include
the brackets!) The text should be enclosed in the appropriate
comment syntax for the file format. Please do not remove or change
the license header comment from a contributed file except when
necessary.
Copyright 2026 mukul975
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
API Reference: Auditing Kubernetes Cluster RBAC
kubernetes (Python Client)
Configuration
from kubernetes import client, config
config.load_kube_config() # From ~/.kube/config
# or
config.load_incluster_config() # Inside a podList ClusterRoles
rbac = client.RbacAuthorizationV1Api()
roles = rbac.list_cluster_role()
for role in roles.items:
print(role.metadata.name)
for rule in role.rules or []:
print(f" verbs={rule.verbs} resources={rule.resources}")List ClusterRoleBindings
bindings = rbac.list_cluster_role_binding()
for b in bindings.items:
print(b.metadata.name, "->", b.role_ref.name)
for s in b.subjects or []:
print(f" {s.kind}: {s.name}")List Pods (Security Context)
v1 = client.CoreV1Api()
pods = v1.list_pod_for_all_namespaces()
for pod in pods.items:
for c in pod.spec.containers:
sc = c.security_context
if sc and sc.privileged:
print(f"PRIVILEGED: {pod.metadata.namespace}/{pod.metadata.name}")Key RBAC Resources
| Resource | API | Description |
|---|---|---|
| ClusterRole | rbac.list_cluster_role() | Cluster-wide permission definitions |
| ClusterRoleBinding | rbac.list_cluster_role_binding() | Binds roles to subjects cluster-wide |
| Role | rbac.list_namespaced_role(ns) | Namespace-scoped permissions |
| RoleBinding | rbac.list_namespaced_role_binding(ns) | Namespace-scoped binding |
| ServiceAccount | v1.list_service_account_for_all_namespaces() | Pod identities |
Dangerous RBAC Patterns to Detect
| Pattern | Risk |
|---|---|
verbs: ["*"], resources: ["*"] | Equivalent to cluster-admin |
resources: ["secrets"], verbs: ["get"] | Can read all secrets |
resources: ["pods/exec"] | Can exec into containers |
subjects: system:authenticated | All users get this role |
automountServiceAccountToken: true | Token available in pod |
References
- kubernetes Python client: https://pypi.org/project/kubernetes/
- K8s RBAC docs: https://kubernetes.io/docs/reference/access-authn-authz/rbac/
- KubiScan: https://github.com/cyberark/KubiScan
#!/usr/bin/env python3
"""Agent for auditing Kubernetes cluster RBAC configurations."""
import os
import json
import argparse
from datetime import datetime
from kubernetes import client, config
def load_kube_config(kubeconfig=None, context=None):
"""Load Kubernetes configuration."""
if kubeconfig:
config.load_kube_config(config_file=kubeconfig, context=context)
else:
try:
config.load_incluster_config()
except config.ConfigException:
config.load_kube_config(context=context)
def list_cluster_roles_with_wildcards():
"""Find ClusterRoles with wildcard verb or resource permissions."""
rbac = client.RbacAuthorizationV1Api()
roles = rbac.list_cluster_role()
risky = []
for role in roles.items:
for rule in role.rules or []:
verbs = rule.verbs or []
resources = rule.resources or []
if "*" in verbs or "*" in resources:
risky.append({
"name": role.metadata.name,
"verbs": verbs,
"resources": resources,
"api_groups": rule.api_groups or [],
})
return risky
def list_secret_access_roles():
"""Find ClusterRoles that can read secrets."""
rbac = client.RbacAuthorizationV1Api()
roles = rbac.list_cluster_role()
results = []
for role in roles.items:
for rule in role.rules or []:
resources = rule.resources or []
verbs = rule.verbs or []
if ("secrets" in resources or "*" in resources) and \
("get" in verbs or "list" in verbs or "*" in verbs):
if not role.metadata.name.startswith("system:"):
results.append({
"role": role.metadata.name,
"verbs": verbs,
"resources": resources,
})
return results
def list_cluster_admin_bindings():
"""Find all ClusterRoleBindings that grant cluster-admin."""
rbac = client.RbacAuthorizationV1Api()
bindings = rbac.list_cluster_role_binding()
results = []
for binding in bindings.items:
if binding.role_ref.name == "cluster-admin":
subjects = []
for s in binding.subjects or []:
subjects.append({
"kind": s.kind,
"name": s.name,
"namespace": s.namespace or "cluster-wide",
})
results.append({
"binding": binding.metadata.name,
"subjects": subjects,
})
return results
def find_dangerous_bindings():
"""Find bindings granting access to system:authenticated or system:unauthenticated."""
rbac = client.RbacAuthorizationV1Api()
bindings = rbac.list_cluster_role_binding()
dangerous = []
for binding in bindings.items:
for s in binding.subjects or []:
if s.name in ("system:authenticated", "system:unauthenticated"):
dangerous.append({
"binding": binding.metadata.name,
"role": binding.role_ref.name,
"subject": s.name,
})
return dangerous
def audit_service_account_tokens():
"""Find pods with automounted service account tokens."""
v1 = client.CoreV1Api()
pods = v1.list_pod_for_all_namespaces()
risky_pods = []
for pod in pods.items:
spec = pod.spec
sa = spec.service_account_name or "default"
automount = spec.automount_service_account_token
if automount is not False and sa != "default":
risky_pods.append({
"namespace": pod.metadata.namespace,
"pod": pod.metadata.name,
"service_account": sa,
"automount": True,
})
return risky_pods
def find_privileged_containers():
"""Find containers running as privileged or root."""
v1 = client.CoreV1Api()
pods = v1.list_pod_for_all_namespaces()
privileged = []
for pod in pods.items:
for container in pod.spec.containers or []:
sc = container.security_context
if sc:
is_privileged = getattr(sc, "privileged", False)
run_as_root = getattr(sc, "run_as_user", None) == 0
if is_privileged or run_as_root:
privileged.append({
"namespace": pod.metadata.namespace,
"pod": pod.metadata.name,
"container": container.name,
"privileged": is_privileged,
"run_as_root": run_as_root,
})
return privileged
def main():
parser = argparse.ArgumentParser(description="Kubernetes RBAC Audit Agent")
parser.add_argument("--kubeconfig", default=os.getenv("KUBECONFIG"))
parser.add_argument("--context", help="Kubernetes context to use")
parser.add_argument("--output", default="k8s_rbac_audit.json")
parser.add_argument("--action", choices=[
"wildcards", "secrets", "cluster_admin", "dangerous",
"tokens", "privileged", "full_audit"
], default="full_audit")
args = parser.parse_args()
load_kube_config(args.kubeconfig, args.context)
report = {"audit_date": datetime.utcnow().isoformat(), "findings": {}}
if args.action in ("wildcards", "full_audit"):
wildcards = list_cluster_roles_with_wildcards()
report["findings"]["wildcard_roles"] = wildcards
print(f"[+] Wildcard ClusterRoles: {len(wildcards)}")
if args.action in ("secrets", "full_audit"):
secret_roles = list_secret_access_roles()
report["findings"]["secret_access_roles"] = secret_roles
print(f"[+] Roles with secret access: {len(secret_roles)}")
if args.action in ("cluster_admin", "full_audit"):
admins = list_cluster_admin_bindings()
report["findings"]["cluster_admin_bindings"] = admins
total_subjects = sum(len(a["subjects"]) for a in admins)
print(f"[+] cluster-admin bindings: {len(admins)} ({total_subjects} subjects)")
if args.action in ("dangerous", "full_audit"):
danger = find_dangerous_bindings()
report["findings"]["dangerous_bindings"] = danger
print(f"[+] Dangerous bindings: {len(danger)}")
if args.action in ("tokens", "full_audit"):
tokens = audit_service_account_tokens()
report["findings"]["automounted_tokens"] = tokens
print(f"[+] Pods with automounted tokens: {len(tokens)}")
if args.action in ("privileged", "full_audit"):
priv = find_privileged_containers()
report["findings"]["privileged_containers"] = priv
print(f"[+] Privileged containers: {len(priv)}")
with open(args.output, "w") as f:
json.dump(report, f, indent=2, default=str)
print(f"[+] Report saved to {args.output}")
if __name__ == "__main__":
main()
Related skills
How it compares
Use for Kubernetes authorization review, not as a substitute for container image vulnerability scanning or network policy design.
FAQ
Who is auditing-kubernetes-cluster-rbac for?
Developers and small teams running workloads on Kubernetes who need help reviewing RoleBindings and ClusterRoleBindings before ship or after access changes.
When should I use auditing-kubernetes-cluster-rbac?
During Ship security prep before production cutover, when validating a new namespace layout in Validate-style prototypes on cluster, and during Operate when you rotate credentials or onboard users.
Is auditing-kubernetes-cluster-rbac safe to install?
Review the Security Audits panel on this Prism page for published audit results; the skill may instruct cluster API access—use least-privilege kube contexts and never paste production credentials into untrusted sessions.