Kubernetes: Search the specific rule granting a given permission

kubernetes role clusterrole rule search kubectl

2 min read | by Jordi Prats

Sometimes might be difficult to tell how some subject (User, ServiceAccount, ...) is able to perform a certain task: What's the Role or ClusterRole granting some permission?

For this we can use the searchrule plugin.

First we'll have to download the latest version available from the release page. Once we have it we just need to copy it somewhere in our $PATH so that we can use it as kubectl searchrule:

$ sudo cp ./kubectl-searchrule /usr/local/bin/

With the following options we can search Roles and ClusterRoles matching a specific criteria:

  • --api-group or -g: API group to search
  • --namespace or -n: Namespace search (Role). If not specified it will only search for ClusterRole rules.
  • --resource or -r: For a specific resource
  • --verb or -v: Verb to search. If not specified searches for *. In case we look for some specific verb, if the role is set to * will match it anyway since it is included.

So, for example, to search which ClusterRoles grant all privileges to namespaces we can use it as follows:

$ kubectl searchrule -v '*' -r namespaces  -n pet2cattle-gitops
clusterrole/backplane-srep-admins-cluster
clusterrole/cluster-image-registry-operator
clusterrole/pet2cattle-dns-operator
clusterrole/pet2cattle-argocd-application-controller
clusterrole/pet2cattle-ingress-operator

If we retrieve the ClusterRole we'll be able to see the matching rule:

$ kubectl get clusterrole/pet2cattle-argocd-application-controller
NAME                                       CREATED AT
pet2cattle-argocd-application-controller   2020-01-22T19:30:38Z
$ kubectl get clusterrole/pet2cattle-argocd-application-controller -o yaml
(...)
- apiGroups:
  - ""
  resources:
  - namespaces
  - persistentvolumeclaims
  - persistentvolumes
  - configmaps
  verbs:
  - '*'

If we specify some specific verb instead of * we can see how we get all the ClusterRoles granting this verb, including the ones granting all the verbs:

$ kubectl searchrule -v '*' -r namespaces  -n pet2cattle-gitops | wc -l
       5
$ kubectl searchrule -v 'create' -r namespaces  -n pet2cattle-gitops | wc -l
      13

Posted on 25/07/2023

Categories