kubectl exec to execute commands in a container is a powerful feature for Kubernetes. It’s especially useful for debugging applications. But, it can also be a security risk and some policies require you to disable this feature. So, how can you do it?
If we look at similar systems, for example systems that control access to ssh, we will see the need is more than an explicit deny all setup. There are cases where a person might be given temporary access and there may be automation tools given permanent access on a case by case basis.
RBAC To The Rescue
Kubernetes includes RBAC Authorization. This can be used to control access to exec.
There are two pieces you need. The first is either a Role or ClusterRole setting access and then a corresponding RoleBinding or ClusterRoleBinding to connect it to someone.
The following is an example ClusterRole:
apiVersion: rbac.authorization.k8s.io/v1 kind: ClusterRole metadata: name: no-exec rules: - apiGroups: [""] resources: ["pods"] verbs: ["get", "watch", "list", "create", "delete", "edit"]
This ClusterRole sets what one can access. They currently do not offer a deny capability. In this case the allowed verbs are all of the ones except
exec. That means anyone who has this ClusterRole set will not be able to use
exec in any namespaces.
To make this work a corresponding RoleBinding or ClusterRoleBinding needs to be created. This binds the role to users. Since a ClusterRole was used in this example, a ClusterRoleBinding is needed. To assign it to a specific user you can do something like:
apiVersion: rbac.authorization.k8s.io/v1 kind: ClusterRoleBinding metadata: name: no-exec subjects: - kind: User name: user1 apiGroup: rbac.authorization.k8s.io roleRef: kind: ClusterRole name: no-exec apiGroup: rbac.authorization.k8s.io
In this example the subject this ClusterRole affects is an individual user. There are a number of different types of subjects, including groups, that you can use to couple the role to users of the system. Different examples can be found in the Kubernetes documentation.
If you need to limit access to
exec, one of the easiest way to do that is with RBAC.