3 min read | by Jordi Prats
To be able to audit access permissions of users un a Kubernetes cluster we might be interested in searching for Roles or ClusterRoles that grants access to a certain object:
For example, if we want to identify which Roles in a certain namespace or ClusterRoles are allowing create of ConfigMap objects.
To do so we'll need to list all the ClusterRoles and Roles within and then look at all it's rules for one that matches this criteria. We can install the golang version from the releases page in github.
Below you'll find how much of a difference would it make to implement this functionality using a bash script, python and golang.
We are going to use a bash script that uses kubectl to list all the Roles that we need to check, and then let a python script check for rules that match the criteria.
This script takes around 8 minutes to list all the matching roles:
$ time bash bash rule-lookup.sh demo-ns create configmaps ""
(...)
real 8m20.793s
user 2m13.657s
sys 2m50.060s
We can rewrite the bash script to python to improve the execution time, a pure python script takes around 2 seconds:
$ time python3 rule-lookup.py --namespace demo-ns --verb create --resource configmaps --api-group ""
(...)
real 0m2.575s
user 0m0.612s
sys 0m0.117s
$ time python3 rule-lookup.py --namespace demo-ns --verb create --resource configmaps --api-group ""
(...)
real 0m2.310s
user 0m0.737s
sys 0m0.215s
$ time python3 rule-lookup.py --namespace demo-ns --verb create --resource configmaps --api-group ""
(...)
real 0m2.053s
user 0m0.662s
sys 0m0.163s
If we use a go run to execute the golang version it takes about the same time it takes to run the python script:
$ time go run rule-lookup.go --namespace demo-ns --verb create --resource configmaps --api-group ""
(...)
real 0m2.809s
user 0m1.135s
sys 0m0.562s
$ time go run rule-lookup.go --namespace demo-ns --verb create --resource configmaps --api-group ""
(...)
real 0m1.835s
user 0m1.123s
sys 0m0.501s
$ time go run rule-lookup.go --namespace demo-ns --verb create --resource configmaps --api-group ""
(...)
real 0m1.849s
user 0m1.124s
sys 0m0.492s
If we compile this golang version with go build rule-lookup.go
we can get better results, taking somewhere between 1 second and half a second:
$ time ./rule-lookup --namespace demo-ns --verb create --resource configmaps --api-group ""
(...)
real 0m1.034s
user 0m0.115s
sys 0m0.049s
$ time ./rule-lookup --namespace demo-ns --verb create --resource configmaps --api-group ""
(...)
real 0m0.478s
user 0m0.105s
sys 0m0.028s
$ time ./rule-lookup --namespace demo-ns --verb create --resource configmaps --api-group ""
(...)
real 0m0.449s
user 0m0.100s
sys 0m0.024s
Posted on 27/02/2023