Managing rights and access to Kubernetes
- Several authentication methods, from a simple text file to an enterprise directory.
- Generating a key and obtaining a certificate.
- Using the kubectl configuration file.
- Roles and permissions; protecting your private keys and configuration file.
Introduction
Access to a Kubernetes cluster is via an API, which is managed by the kube-apiserver component hosted on a control plane node.
Of course, interaction with this API is subject to authentication.
Kubernetes supports several methods for this: from using a simple text file to querying an enterprise directory.
By default, authentication to a cluster is done through a combination of private key/certificate. This system is used in many other scenarios and provides an interesting level of security as long as you have proper management of your private keys and configuration file.
When you deploy a Kubernetes cluster, especially with kubeadm, the component called kube-controller-manager is configured to include a Certificate Authority (CA), thus enabling certificate issuance.
If you look at, for example, the deployment manifest of a controller manager on a control plane, you will find something like this:
cat /etc/kubernetes/manifests/kube-controller-manager.yaml
Click the image to enlarge.
Of course, a third-party CA can be used and other configurations may be encountered.
In the following sections of this article, we will focus on using the Certificate Authority deployed by default. It is recommended to have some knowledge of certificate and private key usage to feel comfortable with the topic. I will nevertheless try to be as clear as possible.
My objectives are:
- To create a new private key associated with a new user in my cluster.
- To submit a certificate request generated from this key to the Certificate Authority present in my cluster.
- To use my cluster administrator account to validate this certificate request.
- To retrieve the generated certificate.
- Declare the certificate and this private key in my configuration file used by kubectl on my machine.
- Create a role specific to this user on my cluster.
- Connect to my cluster with this user.
This will allow us to see the basic logic behind authentication and permission management within Kubernetes.
The diagram below summarizes the elements we will cover in this article. Feel free to refer to it as you follow the explanations.
Click the image to enlarge.
Generating the key and obtaining the certificate
Generating the private key
The first step is to generate your private key. This is completely independent of Kubernetes. You can simply use openssl for this (for example, under Windows with WSL).
openssl genrsa -out mon_user.key 4096
Click the image to enlarge.
I would like to draw your attention to the criticality of the generated key. It must be protected and not shared. It "represents" you and identifies you uniquely. You could secure it with a password, but I have not been able to use a key of this type, and I haven't found any information about it.
Generating the Certificate Signing Request (CSR)
We will stick to a classic certificate usage pattern by creating a CSR (Certificate Signing Request) from the private key and specifying the user's name as the CN (canonical name). Depending on the elements you specify in your CSR, Kubernetes can translate different needs, such as the groups to which the user must belong. But we will keep it basic and only use the CN. The user will be referenced by this name within Kubernetes.
openssl req -new -key mon_user.key -subj "/CN=mon_user" -out mon_user.csr
Click the image to enlarge.
Submitting the request and retrieving the certificate
Once the CSR is obtained, you need to submit it to the cluster's CA Kubernetes. As always in Kubernetes, this is done through an object, here a CertificateSigningRequest. The corresponding YAML is as follows:
apiVersion: certificates.k8s.io/v1
kind: CertificateSigningRequest
metadata:
name: mon_user
spec:
request: csr_en_base_64
signerName: kubernetes.io/kube-apiserver-client
#expirationSeconds: 157680000 # 5 ans (A partir de k8s 1.22)
usages:
- client auth
The content is quite simple. The username, which corresponds to the CN in the certificate request and is specified in the metadata section.
The most important element is in the spec section, the request option. This is the value of the CSR obtained previously, but in base 64.
To obtain it, there's nothing simpler, for example, under Linux or via WSL under Windows.
cat mon_user.csr | base64 | tr -d "\n"
Click the image to enlarge.
Click the image to enlarge.
Once retrieved and entered into the YAML, you can apply the object using the command kubectl apply -f mon_path\user.yaml.
Click the image to enlarge.
The subtlety is that this command requires you to already have access to the cluster, since we are using kubectl to apply a CertificateSigningRequest object to the cluster.
We can imagine several possible scenarios, such as providing the CSR to a cluster administrator who already has sufficient access to submit the file.
In my example, I am using my default credentials obtained during cluster initialization to allow me to run the command.
In an enterprise environment, there is usually a group of people authorized to validate certificate requests, and these individuals are not necessarily administrators. As we will see later, the concept of roles in Kubernetes allows you to assign permissions to perform certain actions.
We query the cluster to check if any certificate requests are currently pending
kubectl get csr
Click the image to enlarge.
We can indeed see my request. We could also find details about it by examining the properties of the associated object.
We will now approve the request
kubectl certificate approve mon_user
Click the image to enlarge.
Now that the request has been approved, it should contain a certificate.
kubectl get csr mon_user -o yaml
Click the image to enlarge.
It is possible to access this certificate directly by extracting it from the object and converting its content from its base 64 format.
kubectl get csr mon_user -o jsonpath='{.status.certificate}'| base64 -d > mon_user.crt
Click the image to enlarge.
(The command is executed on a Linux server or WSL).
It is important to understand that at this stage, the user is "known" to the cluster; at least, their certificate is stored in the internal PKI (Public Key Infrastructure) of the cluster.
If a connection is submitted to the API using the certificate and the associated private key, then the connection will be recognized by the API. The identity of the user will be that specified in the CN (Common Name) of the certificate.
Using the kubectl configuration file
Now that we have the certificate and the private key, it is possible to use them in the config file, which is usually located in the .kube directory of the user profile.
Click the image to enlarge.
This file is read by kubectl to find authentication and connection information.
By itself, it allows you to manage different clusters using different identities.
Its location may vary depending on the operating system, but it will always have the same logic.
The file uses the syntax of a k8s object with specific sections.
Click the image to enlarge.
- The "clusters" section contains all the clusters to which you can connect. For each cluster, you will find its name, the URL for accessing its API, and the base64 encoded certificate of the associated CA (Certificate Authority).
- The "users" section contains all the users for whom you can assume an identity. For each user, you will find their name and connection identifiers. These identifiers either refer to external files or directly contain the information in base64 format.
- The "contexts" section: a context is the association of a cluster and a user. You can create as many combinations, and therefore contexts, as there are possible associations between a user and a cluster. The name of a context is given in the format user@cluster. This allows you to present yourself not only to multiple clusters, but also within the same cluster, you can present yourself with a different user (and therefore different permissions). The concept of current-context is also included. This is simply the "default" context in which you will be when launching kubectl. Another important point is that you can override your context with a namespace, allowing you to run all your commands within a specific namespace without having to specify its name.
Another small detail: the order of sections in the configuration file does not matter. The user section can be before, in the middle, or at the end of the file, as is the case here, and the same applies to other sections.
A very important point: the criticality of your configuration file. It contains the elements necessary for accessing your clusters. Pay close attention to its content and exposure.
In the example below, this is the configuration file obtained after deploying a cluster. By default, it contains connection information for full admin access to the cluster.
The private key and associated certificate are directly provided in their base64 format.
This means that anyone who can retrieve this file is able to connect to the cluster with the highest level of privilege (subject to network access to the API).
You will understand that it is essential that this file is secured and accessible only to a limited number of people.
In the case of creating a new user and the private key/certificate combination mentioned previously, we will proceed differently.
We will not directly provide the value of these elements in base64 format, but rather refer to them as files.
This involves adding an additional user to the 'users' section of the existing configuration file and creating a new context that associates this new user with the cluster that is already defined.
Adding to the 'context' section
- context:
cluster: nom_cluster
user: nom_user
name: nom_user@nom_cluster
Adding to the 'user' section
- name: nom_user
user:
client-certificate: emplacement du certificat
client-key: emplacement de la clef
Click the image to enlarge.
With this approach, connection information is no longer directly present in the configuration file, and the file is no longer self-contained because the private key and certificate must also be available.
(To do it properly in my example, I should also remove references to the default admin account, but I will keep it for explanation purposes later).
Ultimately, what remains critical is the file containing the private key.
Now that the config has two connection contexts, I can switch to the context of the user who was just created on the cluster.
Simply use the following command:
kubectl config use-context user@cluster
Click the image to enlarge.
All subsequent actions will therefore be performed under the identity of the user I just created, and not with the default administrator account.
If we try a simple kubectl get nod
We get an error message indicating that the user is not authorized to list the requested resource.
Click the image to enlarge.
This is perfectly normal, because even though the user now exists within the cluster, they have no permissions assigned.
Roles and permissions
Kubernetes uses the concept of RBAC (Role-based access control). This is a very common resource management method that is also found in major public cloud providers and in many software applications.
The principle is to associate actions with roles, and then associate these roles with users (or groups of users).
A role can contain a whole set of actions, some of which may grant significant permissions over part of the cluster's objects, while others are more restrictive (such as read-only access for example).
Combined with the concept of K8S objects, it is possible to offer a very fine-grained access policy, with granularity per object (e.g., listing pods but not secrets).
The list of possible actions, including their level of interaction with the objects, constitutes a list of rules (rules) contained within the role.
Kubernetes offers two types of roles:
- The standard roles (kind: Role): these roles are applied to a namespace. All the actions described here are only valid within that namespace. These roles are often reserved for standard users or specific teams. It all depends on the logic used when adopting namespaces in the cluster. For example, you could have a "developer" role that can only act on namespaces involving development applications. Be aware that if the applications are in multiple namespaces, there will be a role per namespace, and an individual user can have multiple roles.
- Cluster roles (kind: ClusterRole): As their name suggests, these roles are applicable across all namespaces. They are typically reserved for administrative tasks and involve rules that define possible actions on the entire cluster or on resources that are independent of the concept of a namespace.
Standard roles (kind: Role)
You can start by creating a role object.
This simply involves defining the types of actions that are permitted, on which types of objects, and within which namespace. In the example below, we allow the 'get' (query), 'watch' (monitor), and 'list' actions for pods with the role 'pod-reader' in the namespace inf-velero-lan.
apiVersion: rbac.authorization.k8s.io/v1
kind: Role
metadata:
namespace: mon-namespace
name: role-pod-reader
rules:
- apiGroups: [""] #
resources: ["pods"]
verbs: ["get", "watch", "list"]
Click the image to enlarge.
At the rule level, we specify:
- apiGroups: The API branch that contains the objects on which we want to allow actions.
- resources: These are the objects within the API branch.
- verbs: These are the actions that are allowed.
The asterisk (*) character can be used to generalize actions to all objects in a branch.
Similarly, several rules can be declared within a role, but always for the same namespace.
Applying the role is equivalent to performing a kubectl apply -f mon-role.yaml.
However, I need to switch back to an administrator context if I want the API to accept my role object.
To do this, there's nothing simpler: I return to the default context of my configuration file.
kubectl config use-context kubernetes-admin@kub
Click the image to enlarge.
I can then apply the role: kubectl apply -f role-pod-reader.yml.
Click the image to enlarge.
Once the role has been created, it needs to be associated with the new user. This is done using a RoleBinding object. This object simply allows you to associate a role with a user within a namespace.
In this specific example, my user "vburgun" will be associated with my role "pod-reader" within the namespace "inf-velero-lan" .
apiVersion: rbac.authorization.k8s.io/v1
kind: RoleBinding
metadata:
name: read-pods
namespace: mon-namespace
subjects:
- kind: User
name: mon-user
apiGroup: rbac.authorization.k8s.io
roleRef:
kind: Role
name: pod-reader
apiGroup: rbac.authorization.k8s.io
Click the image to enlarge.
We apply the RoleBinding object using the command kubectl apply -f mon-role-binding.yaml.
Click the image to enlarge.
I can now switch back to my user's context.
kubectl config use-context vburgun@kub
Click the image to enlarge.
If I run my kubectl get node command again, I still get an error.
Click the image to enlarge.
This is normal, since the role I created only allows listing the pods in the namespace inf-velero-lan.
Let's see if this is possible with the following command:
kubectl get pod -n inf-velero-lan
This time, I get a response from the API.
Click the image to enlarge.
Cluster roles (kind: ClusterRole)
If I want to authorize my command kubectl get node for my user vburgun, I need to use a ClusterRole instead of a regular role, because nodes are resources that are global to the cluster and not specific to a namespace.
I'll switch back to an administrator context first.
kubectl config use-context kubernetes-admin@kub
Click the image to enlarge.
Note that there are some default ClusterRoles. Others are added automatically when you deploy third-party applications or addons for the cluster (such as cert-manager, for example).
You can list the clusterroles with the following command:
kubectl get clusterrole
Click the image to enlarge.
The most well-known (and most critical) ClusterRole is the cluster-admin. This is the role you get by default when you install the cluster. The access credentials for the default super administrator associated with this ClusterRole are stored in the config file generated at the end of the installation.
Let's start by creating a cluster role called clusterrole-list-nodes in a YAML file named clusterrole-list-nodes.yml:
apiVersion: rbac.authorization.k8s.io/v1
kind: ClusterRole
metadata:
name: clusterrole-list-nodes
rules:
- apiGroups: [""]
resources: ["nodes"]
verbs: ["get", "list", "watch"]
Unlike a regular role, there is no reference to a namespace.
In the rule, I simply authorize the get, list, and watch actions on node resources from the default API group.
I apply it with kubectl apply -f clusterrole-list-nodes.yml.
Click the image to enlarge.
Now I need to associate it with my user vburgun, but this time using a ClusterRoleBinding object that I define in the file clusterrolebinding-list-node.yml.
apiVersion: rbac.authorization.k8s.io/v1
kind: ClusterRoleBinding
metadata:
name: clusterrolebinding-list-node
roleRef:
apiGroup: rbac.authorization.k8s.io
kind: ClusterRole
name: clusterrole-list-nodes
subjects:
- kind: User
name: vburgun
apiGroup: rbac.authorization.k8s.io
I associate my ClusterRole clusterrole-list-nodes with my user vburgun.
I apply the file using the command: kubectl apply -f clusterrolebinding-list-node.yml
Click the image to enlarge.
Let's try now, by switching back to my user's context (using the command kubectl config use-context vburgun@kub), to see if I can finally list the nodes.
Click the image to enlarge.
Conclusion
Defining an access policy for a Kubernetes cluster is very important.
It is necessary to understand the authentication mechanism used and the principles associated with it, especially the RBAC (Role-based access control) logic.
It is also important to understand the distinction between permissions granted for a namespace and permissions granted for the entire cluster.
The best practice is always to try to grant the least privilege necessary when creating Role and ClusterRole objects that closely match the needs of users who will interact with the cluster. No more, no less.
However, this is not always simple, and it's easy to be tempted to use the default ClusterRoles, especially the cluster-admin. This is clearly not the best approach.
Be careful of excessive zeal. In my experience, going too far in defining roles with an overly aggressive policy can lead to frustration within teams and encourage backdoors.
It is necessary to consider the context of use and adapt best practices to the size and level of your teams. Of course, you should also consider the criticality of the assets hosted and the activity of the company for which the cluster runs applications.
Therefore, it is important to find the right balance between segregating permissions and maintaining operational efficiency, in order to avoid unnecessary complexity, which is often one of the drawbacks of an RBAC system with a proliferation of roles.
A review of access to the cluster is a good thing. Periodically checking the roles in place and the intervention needs of teams on the cluster helps maintain an up-to-date reference and avoids accumulating unnecessary or outdated roles.
Also, be aware of the configuration file read by kubetcl. This file can contain very sensitive data with significant privilege levels. It allows actions to be performed under different identities and for different clusters. A single configuration file can contain authentication information for many architectures, both on-premises and cloud.
This is an extremely powerful and practical operating logic thanks to the ability to switch between contexts, but it is also a prime target for malicious individuals.
I have also seen, through experience, configuration files being shared on network shares, resulting in many users using the same local account on the cluster through the use of the same kubectl configuration file.
That is why, as an improvement, it is preferable to map your cluster to external authentication solutions, which can simplify things, especially with a corporate directory. An example of integration with Microsoft Entra ID is available here.
In general, and from a personal point of view, when dealing with security:
prioritize training on how to prevent issues
Click the image to enlarge.
and simplifying things often enhances security.
Click the image to enlarge.