Skip to content
ImagineWorld

RBAC Policies and Auditing

node_idnode-book_kubernetes-an-enterprise-guide_chapter-07-rbac-policies-and-auditing
node_typechapter-node
schema_profileworld.chapter_node.v1
statusactive
entropyhigh
manifoldworld
domainimagineworld.net
authorityinforms
layercorpus
chapter_num7
chapter_titleRBAC Policies and Auditing
governed_byCORPUS
constitutional_citationCONSTITUTION
local graph

Authentication is only the first step in managing access to a cluster. Once access to a cluster is granted, it’s important to limit what accounts can do, depending on whether an account is for an automated system or a user. Authorizing access to resources is an important part of protecting against both accidental issues and bad actors looking to abuse a cluster.

In this chapter, we’re going to detail how Kubernetes authorizes access via its Role-Based Access Control (RBAC) model. The first part of this chapter will be a deep dive into how Kubernetes RBAC is configured, what options are available, and mapping the theory onto practical examples. Debugging and troubleshooting RBAC policies will be the focus of the second half.

In this chapter, we will cover the following topics:

  • Introduction to RBAC
  • Mapping enterprise identities to Kubernetes to authorize access to resources
  • Implementing namespace multi-tenancy
  • Kubernetes auditing
  • Using audit2rbac to debug policies

Once you have completed this chapter, you’ll have the tools needed to manage access to your cluster via Kubernetes’ integrated RBAC model and debug issues when they arise. Next, let’s dive into the technical requirements for this chapter.

This chapter has the following technical requirements:

RBAC stands for Role-Based Access Control. At its core is the idea of building permission sets, which are called Roles, and lists of subjects (users) that those permissions apply to. In this chapter, we’ll walk through building roles and their corresponding bindings to build out the permissions in our clusters.

In Kubernetes, a Role is a way to tie together permissions into an object standardized to a specific schema. By codifying Roles into this schema, you’re able to standardize and automate their creation and management.

Roles have rules, which are a collection of resources and verbs. Working backward, we have the following:

  • Verbs: The actions that can be taken on an API, such as reading (get), writing (create, update, patch, and delete), or listing and watching.
  • Resources: Names of APIs to apply the verbs to, such as services, endpoints, and so on. Specific sub-resources, such as logs and status, may be listed as well. Specific resources can be named to provide very specific permissions on an object.

A Role does not say who can perform the verbs on the resources—that is handled by RoleBindings and ClusterRoleBindings. We will learn more about these in the RoleBindings and ClusterRoleBindings section.

The term “role” can have multiple meanings, and RBAC is often used in other contexts. In the enterprise world, the term “role” is often associated with a business role and used to convey entitlements to that role instead of a specific person.

Diagram Description automatically generated

Figure 7.1: RBAC versus entitlement-based access control

As an example, in Figure 7.1, a user is a member of the “role” for accounts payable. Being a member of this role automatically provides the entitlement to “write checks.” If our user’s job changes to accounts receivable, their permissions will change automatically because the permissions are tied to the user’s role. In enterprise RBAC models, what ties a user to a “role” is generally some context instead of a specific group membership or attribute value. For instance, users might be located in different parts of the corporate directory based on their “role.”

This is different from how Kubernetes uses the term “Role” to mean a list of permissions, and those permissions aren’t tied together because of a business role but because of a technical requirement. As we’ll see when we get to bindings, Kubernetes Roles are tightly bound to accounts and groups, and while the permissions of a Role are grouped together for a specific function, that function is defined at a lower, technical level than “enterprise” roles.

Now that we’ve differentiated between what the “enterprise” definition of a role is from how Kubernetes defines a Role, let’s dive into how you build a Role.

Each resource that a role will be built from is identified by the following:

  • apiGroups: A list of groups the resources are a member of
  • resources: The name of the object type for the resource (and potentially sub-resources)
  • resourceNames: An optional list of specific objects to apply this rule to

Each rule must have a list of apiGroups and resources. resourceNames is optional.

Once the resource is identified in a rule, verbs can be specified. A verb is an action that can be taken on the resource, providing access to the object in Kubernetes.

If the desired access to an object should be all, you do not need to add each verb; instead, the wildcard character may be used to identify all the verbs, resources, or apiGroups.

The Kubernetes authorization page (https://kubernetes.io/docs/reference/access-authn-authz/rbac/) uses the following Role as an example to allow someone to get the details of a pod and its logs:

apiVersion: rbac.authorization.k8s.io/v1
kind: Role
metadata:
namespace: default
name: pod-and-pod-logs-reader
rules:
- apiGroups: [""]
resources: ["pods", "pods/log"]
verbs: ["get", "list"]

Before defining what a Role manages, it’s important to note that Role objects are namespaced, so the namespace the Role is created in means that the permissions it defines apply only within its own namespace. In this example, the Role only applies to the default namespace.

Working backward to determine how this Role was defined, we will start with resources, since it is the easiest aspect to find. All objects in Kubernetes are represented by URLs. If you wanted to pull all the information about the pods in the default namespace, you would call the /api/v1/namespaces/default/pods URL, and if you wanted the logs for a specific pod, you would call the /api/v1/namespaces/default/pods/mypod/log URL.

The URL pattern will be true of all namespace-scoped objects. pods lines up to resources, as does pods/log. When trying to identify which resources you want to authorize, use the api-reference document from the Kubernetes API documentation at https://kubernetes.io/docs/reference/#api-reference.

If you are trying to access an additional path component after the name of the object (such as with status and logs on pods), it needs to be explicitly authorized. Authorizing Pods does not immediately authorize logs or status.

Based on the use of URL mapping to resources, your next thought may be that the verbs field is going to be HTTP verbs. This is not the case. There is no GET verb in Kubernetes. Verbs are instead defined by the schema of the object in the API server. The good news is that there’s a static mapping between HTTP verbs and RBAC verbs (https://kubernetes.io/docs/reference/access-authn-authz/authorization/#determine-the-request-verb). Looking at this URL, notice that there are verbs on top of the HTTP verbs for impersonation. That’s because the RBAC model is used beyond authorizing specific APIs and is also used to authorize who can impersonate users. The focus of this chapter is going to be on the standard HTTP verb mappings.

The final component to identify is apiGroups. APIs will be in an API group and that group will be part of their URL. You can find the group by looking at the API documentation for the object you are looking to authorize or by using the kubectl api-resources command. For instance, to get apiGroups for the Ingress object, you could run:

kubectl api-resources -o wide | grep Ingress
ingressclasses networking.k8s.io/v1 false IngressClass [create delete deletecollection get list patch update watch]
ingresses ing networking.k8s.io/v1 true Ingress [create delete deletecollection get list patch update watch]

The second result gives you what you would see in the apiVersion of a YAML version of an Ingress object. Use this for apiGroups, but without the version number. To apply a Role to an Ingress object, the apiGroups would be networking.k8s.io.

The inconsistencies in the RBAC model can make debugging difficult, to say the least. The last lab in this chapter will walk through the debugging process and take much of the guesswork out of defining your rules.

Now that we’ve defined the contents of a Role and how to define specific permissions, it’s important to note that Roles can be applied at both the namespace and cluster level.

RBAC rules can be scoped either to specific namespaces or to the entire cluster. Taking the preceding example, if we defined it as a ClusterRole instead of a Role, and removed the namespace, we would have a Role that authorizes someone to get the details and logs of all pods across the cluster. This new Role could alternatively be used in individual namespaces to assign the permissions to the pods in a specific namespace:

apiVersion: rbac.authorization.k8s.io/v1
kind: ClusterRole
metadata:
name: cluster-pod-and-pod-logs-reader
rules:
- apiGroups: [""]
resources: ["pods", "pods/log"]
verbs: ["get", "list"]

Whether this permission is applied globally across a cluster or within the scope of a specific namespace depends on how it’s bound to the subjects it applies to. This will be covered in the RoleBindings and ClusterRoleBindings section.

In addition to applying a set of rules across the cluster, ClusterRoles are used to apply rules to resources that aren’t mapped to a namespace, such as PersistentVolume and StorageClass objects.

After learning how a Role is defined, let’s explore the different ways Roles can be designed for specific purposes. In the next sections, we’ll look at different patterns for defining Roles and their application in a cluster.

One of the most common requests for authorization is “ Can I write a Role that lets me do everything EXCEPT xyz?”. In RBAC, the answer is NO. RBAC requires either every resource to be allowed or specific resources and verbs to be enumerated. There are two reasons for this in RBAC:

  • Better security through simplicity: Being able to enforce a rule that says every Secret except this one requires a much more complex evaluation engine than RBAC provides. The more complex an engine, the harder it is to test and validate, and the easier it is to break. A simpler engine is just simpler to code and keep secure.
  • Unintended consequences: Allowing someone to do everything except xyz leaves the door open for issues in unintended ways as the cluster grows and new capabilities are added.

On the first point, an engine with this capability is difficult to build and maintain. It also makes the rules much harder to keep track of. To express this type of rule, you need to not only have authorization rules but also an order to those rules. For instance, to say I want to allow everything except this Secret, you would first need a rule that says allow everything and then a rule that says deny this secret. If you switch the rules to say deny this secret then allow everything, the first rule would be overridden. You could assign priorities to different rules, but that now makes it even more complex.

There are ways to implement this pattern, either by using a custom authorization webhook or by using a controller to dynamically generate RBAC Role objects. These should both be considered security anti-patterns and so won’t be covered in this chapter.

The second point deals with unintended consequences. It’s becoming more popular to support the provisioning of infrastructure that isn’t Kubernetes using the operator pattern, where a custom controller looks for new instances of a CustomResourceDefinition (CRD) to provision infrastructure such as databases.

Amazon Web Services publishes an operator for this purpose (https://github.com/aws/aws-controllers-k8s). These operators run in their own namespaces with administrative credentials for their cloud looking for new instances of their objects to provision resources. If you have a security model that allows everything “except…”, then once deployed, anyone in your cluster can provision cloud resources that have real costs and can create security holes. Enumerating your resources, from a security perspective, is an important part of knowing what is running and who has access.

The trend in Kubernetes clusters is to provide more control over infrastructure outside of the cluster via the custom resource API. You can provision anything from VMs to additional nodes, to any kind of API-driven cloud infrastructure. There are other tools you can use besides RBAC to mitigate the risk of someone creating a resource they shouldn’t, but these should be secondary measures.

So far, we’ve looked at how to create permissions for specific use cases. What happens if you need some flexibility to be able to define permissions more dynamically than the static lists we’re providing now? Next, we’ll discover how to use aggregated ClusterRoles to provide a dynamic approach to permission lists.

ClusterRoles can become confusing quickly and be difficult to maintain. It’s best to break them up into smaller ClusterRoles that can be combined as needed. Take the admin ClusterRole, which is designed to let someone do generally anything inside of a specific namespace. When we look at the admin ClusterRole, it enumerates just about every resource there is. You may think someone wrote this ClusterRole so that it would contain all those resources, but that would be really inefficient, and what happens as new resource types get added to Kubernetes? The admin ClusterRole is an aggregated ClusterRole. Take a look at the ClusterRole:

kind: ClusterRole
apiVersion: rbac.authorization.k8s.io/v1
metadata:
name: admin
labels:
kubernetes.io/bootstrapping: rbac-defaults
annotations:
rbac.authorization.kubernetes.io/autoupdate: 'true'
rules:
.
.
.
aggregationRule:
clusterRoleSelectors:
- matchLabels:
rbac.authorization.k8s.io/aggregate-to-admin: 'true'

The key is the aggregationRule section. This section tells Kubernetes to combine the rules for all ClusterRoles where the rbac.authorization.k8s.io/aggregate-to-admin label is true. When a new CRD is created, an admin is not able to create instances of that CRD without adding a new ClusterRole that includes this label. To allow namespace admin users to create an instance of the new myapi/superwidget objects, create a new ClusterRole:

apiVersion: rbac.authorization.k8s.io/v1
kind: ClusterRole
metadata:
name: aggregate-superwidget-admin
labels:
# Add these permissions to the "admin" default role.
rbac.authorization.k8s.io/aggregate-to-admin: "true"
rules:
- apiGroups: ["myapi"]
resources: ["superwidgets"]
verbs: ["get", "list", "watch", "create", "update", "patch", "delete"]

The next time you look at the admin ClusterRole, it will include myapi/superwidgets. You can also reference this ClusterRole directly for more specific permissions.

So far, we’ve focussed on creating permission lists via Roles and ClusterRoles. Next, we’ll work on assigning those permissions to users and services.

Once a permission is defined, it needs to be assigned to something to enable it. “Something” can be a user, a group, or a service account. These options are referred to as subjects. Just as with Roles and ClusterRoles, a RoleBinding binds a Role or ClusterRole to a specific namespace, and a ClusterRoleBinding will apply a ClusterRole across the cluster. A binding can have many subjects but may only reference a single Role or ClusterRole. To assign the pod-and-pod-logs-reader Role created earlier in this chapter to a service account called mysa in the default namespace, a user named podreader, or anyone with the podreaders group, create a RoleBinding:

apiVersion: rbac.authorization.k8s.io/v1
kind: RoleBinding
metadata:
name: pod-and-pod-logs-reader
namespace: default
subjects:
- kind: ServiceAccount
name: mysa
namespace: default
apiGroup: rbac.authorization.k8s.io
- kind: User
name: podreader
- kind: Group
name: podreaders
roleRef:
kind: Role
name: pod-and-pod-logs-reader
apiGroup: rbac.authorization.k8s.io

The preceding RoleBinding lists three different subjects:

  • ServiceAccount: Any service account in the cluster can be authorized to a RoleBinding. The namespace must be included since a RoleBinding can authorize a service account in any namespace, not just the one the RoleBinding is defined in.
  • User: A user is asserted by the authentication process. Remember from Chapter 6, Integrating Authentication into Your Cluster, that there are no objects in Kubernetes that represent users.
  • Group: Just as with users, groups are asserted as part of the authentication process and have no object associated with them.

Finally, the Role we created earlier is referenced. In a similar fashion, to assign the same subjects the ability to read pods and their logs across the cluster, a ClusterRoleBinding can be created to reference the cluster-pod-and-pod-logs-reader ClusterRole created earlier in the chapter:

apiVersion: rbac.authorization.k8s.io/v1
kind: ClusterRoleBinding
metadata:
name: cluster-pod-and-pod-logs-reader
subjects:
- kind: ServiceAccount
name: mysa
namespace: default
apiGroup: rbac.authorization.k8s.io
- kind: User
name: podreader
- kind: Group
name: podreaders
roleRef:
kind: ClusterRole
name: cluster-pod-and-pod-logs-reader
apiGroup: rbac.authorization.k8s.io

The ClusterRoleBinding is bound to the same subjects but is bound to a ClusterRole instead of a namespace-bound Role. Now, instead of being able to read pod details and Pod/logs in the default namespace, these users can read all pod details and Pod/logs in all namespaces.

Till now, the focus has been on combining a Role with a RoleBinding and a ClusterRole with a ClusterRoleBinding. If you want to define the same permissions that are scoped to multiple namespaces, you’ll want a way to do that without reproducing the same Role every time. Next, we’ll cover how to simplify Role management by combining ClusterRoles and RoleBindings.

We have a use case where a log aggregator wants to pull logs from pod in multiple namespaces, but not all namespaces. A ClusterRoleBinding is too broad. While the Role could be recreated in each namespace, this is inefficient and a maintenance headache. Instead, define a ClusterRole but reference it from a RoleBinding in the applicable namespaces. This allows the reuse of permission definitions while still applying those permissions to specific namespaces. In general, note the following:

  • ClusterRole + ClusterRoleBinding = cluster-wide permission
  • ClusterRole + RoleBinding = namespace-specific permission

To apply our ClusterRoleBinding in a specific namespace, create a Role, referencing the ClusterRole instead of a namespaced Role object:

apiVersion: rbac.authorization.k8s.io/v1
kind: RoleBinding
metadata:
name: pod-and-pod-logs-reader
namespace: default
subjects:
- kind: ServiceAccount
name: mysa
namespace: default
apiGroup: rbac.authorization.k8s.io
- kind: User
name: podreader
- kind: Group
name: podreaders
roleRef:
kind: ClusterRole
name: cluster-pod-and-pod-logs-reader
apiGroup: rbac.authorization.k8s.io

The preceding RoleBinding lets us reuse the existing ClusterRole. This cuts down on the number of objects that need to be tracked in the cluster and makes it easier to update permissions across the cluster if the ClusterRole permissions need to change.

Having built our permissions and defined how to assign them, next, we’ll look at how to map enterprise identities into cluster policies.

Mapping enterprise identities to Kubernetes to authorize access to resources

Section titled “Mapping enterprise identities to Kubernetes to authorize access to resources”

One of the benefits of centralizing authentication is leveraging the enterprise’s existing identities instead of having to create new credentials that users who interact with your clusters need to remember. It’s important to know how to map your policies to these centralized users. In Chapter 6, Integrating Authentication into Your Cluster, you created a cluster and integrated it with an “enterprise Active Directory.” To finish the integration, the following ClusterRoleBinding was created:

apiVersion: rbac.authorization.k8s.io/v1
kind: ClusterRoleBinding
metadata:
name: ou-cluster-admins
subjects:
- kind: Group
name: cn=k8s-cluster-admins,ou=Groups,DC=domain,DC=com
apiGroup: rbac.authorization.k8s.io
roleRef:
kind: ClusterRole
name: cluster-admin
apiGroup: rbac.authorization.k8s.io

This binding allows all users that are members of the cn=k8s-cluster-admins,ou=Groups,DC=domain,DC=com group to have full cluster access. At the time, the focus was on authentication, so there weren’t many details provided as to why this binding was created.

What if we wanted to authorize our users directly? That way, we will have control over who has access to our cluster. Our RBAC ClusterRoleBinding would look different:

apiVersion: rbac.authorization.k8s.io/v1
kind: ClusterRoleBinding
metadata:
name: ou-cluster-admins
subjects:
- kind: User
name: https://k8sou.apps.192-168-2-131.nip.io/auth/idp/k8sIdp#mmosley
apiGroup: rbac.authorization.k8s.io
roleRef:
kind: ClusterRole
name: cluster-admin
apiGroup: rbac.authorization.k8s.io

Using the same ClusterRole as before, this ClusterRoleBinding will assign the cluster-admin privileges only to my testing user.

The first issue to point out is that the user has the URL of our OpenID Connect issuer in front of the username. When OpenID Connect was first introduced, it was thought that Kubernetes would integrate with multiple identity providers and different types of identity providers, so the developers wanted you to be able to easily distinguish between users from different identity sources. For instance, mmosley in domain 1 is a different user than mmosley in domain 2. To ensure that a user’s identity doesn’t collide with another user across identity providers, Kubernetes requires the identity provider’s issuer to be prepended to your username. This rule doesn’t apply if the username claim defined in your API server flags is mail. It also doesn’t apply if you’re using certificates or impersonation.

Beyond the inconsistent implementation requirements, this approach can cause problems in a few ways:

  • Changing your identity provider URL: Today, you’re using an identity provider at one URL, but tomorrow you decide to move it. Now, you need to go through every ClusterRoleBinding and update them.
  • Audits: You can’t query for all RoleBindings associated with a user. You need to instead enumerate every binding.
  • Large bindings: Depending on how many users you have, your bindings can become quite large and difficult to track.

While there are tools you can use to help manage these issues, it’s much easier to associate your bindings with groups instead of individual users. You could use the mail attribute to avoid the URL prefix, but that is considered an anti-pattern and will result in equally difficult changes to your cluster if an email address changes for any reason.

So far in this chapter, we have learned how to define access policies and map those policies to enterprise users. Next, we need to determine how clusters will be divided into tenants.

Clusters deployed for multiple stakeholders, or tenants, should be divided up by namespace. This is the boundary that was designed in Kubernetes from the very beginning. When deploying namespaces, there are generally two ClusterRoles that are assigned to users in the namespace:

  • admin: This aggregated ClusterRole provides access to every verb and nearly every resource that ships with Kubernetes, making the admin user the ruler of their namespace. The exception to this is any namespace-scoped object that could affect the entire cluster, such as ResourceQuotas.
  • edit: Similar to admin, but without the ability to create RBAC Roles or RoleBindings.

It’s important to note that the admin ClusterRole can’t make changes to the namespace object by itself. Namespaces are cluster-wide resources, so they can only be assigned permissions via a ClusterRoleBinding.

Depending on your strategy for multi-tenancy, the admin ClusterRole may not be appropriate. The ability to generate RBAC Role and RoleBinding objects means that a namespace admin may grant themselves the ability to change resource quotas. This is where RBAC tends to fall apart and needs some additional options:

  • Don’t grant access to Kubernetes: Many cluster owners want to keep Kubernetes out of the hands of their users and limit their interaction with external CI/CD tools. This works well with microservices but begins to fall apart on multiple lines. First, more legacy applications being moved into Kubernetes means more legacy administrators needing to directly access their namespace. Second, if the Kubernetes team keeps users out of the clusters, they are now responsible. The people who own Kubernetes may not want to be the reason things aren’t happening the way application owners want them to and, often, the application owners want to be able to control their own infrastructure to ensure they can handle any situation that impacts their own performance.
  • Treat access as privileged: Most enterprises require a privileged user to access infrastructure. This is typically done using a privileged access model where an admin has a separate account that needs to be “checked out” in order to use it and is only authorized at certain times, as approved by a “change board” or process. The use of these accounts is closely monitored. This is a good approach if you already have a system in place, especially one that integrates with your enterprise’s central authentication system.
  • Give each tenant a cluster: This model moves multi-tenancy from the cluster to the infrastructure layer. You haven’t eliminated the problem, only moved where it is addressed. This can lead to sprawl that becomes unmanageable and costs can skyrocket depending on how you are implementing Kubernetes. In Chapter 9, Building Multitenant Clusters with vClusters, we’ll explore how we can give each tenant its own cluster without having to worry about the sprawl as much.
  • Admission controllers: These augment RBAC by limiting which objects can be created. For instance, an admission controller can decide to block an RBAC policy from being created, even if RBAC explicitly allows it. This topic will be covered in Chapter 11, Extending Security Using Open Policy Agent.

In addition to authorizing access to namespaces and resources, a multi-tenant solution needs to know how to provision tenants. This topic will be covered in the final chapters – Chapter 18, Provisioning a Multitenant Platform, and Chapter 19, Building a Developer Portal.

Now that we have a strategy for implementing authorization policies, we’ll need a way to debug those policies as we create them and also to know when those policies are violated. Kubernetes provides an audit capability that will be the focus of the next section, where we will add the audit log to our KinD cluster and debug the implementation of RBAC policies.

The Kubernetes audit log is where you track what is happening in your cluster from an API perspective. It’s in JSON format, which makes reading it directly more difficult, but makes it much easier to parse using tools such as OpenSearch. In Chapter 15, Managing Clusters and Workloads, we will cover how to create a full logging system using the OpenSearch stack.

A policy file is used to control what events are recorded and where to store the logs, which can be a standard log file or a webhook. We have included an example audit policy in the chapter7 directory of the GitHub repository, and we will apply it to the KinD cluster that we have been using throughout the book.

An audit policy is a collection of rules that tell the API server which API calls to log and how. When Kubernetes parses the policy file, all rules are applied in order and only the initial matching policy event will be applied. If you have more than one rule for a certain event, you may not receive the expected data in your log files. For this reason, you need to be careful that your events are created correctly.

Policies use the audit.k8s.io API and the manifest kind of Policy. The following example shows the beginning of a policy file:

apiVersion: audit.k8s.io/v1
kind: Policy
rules:
- level: Request
userGroups: ["system:nodes"]
verbs: ["update","patch"]
resources:
- group: "" # core
resources: ["nodes/status", "pods/status"]
omitStages:
- "RequestReceived"

While a policy file may look like a standard Kubernetes manifest, you do not apply it using kubectl. A policy file is used with the --audit-policy-file API flag on the API server(s). This will be explained in the Enabling auditing on a cluster section.

To understand the rule and what it will log, we will go through each section in detail.

The first section of the rule is level, which determines the type of information that will be logged for the event. There are four levels that can be assigned to events:

Table 8.1 – Kubernetes auditing levels

Table 7.1: Kubernetes auditing levels

The userGroups, verbs, and resources values tell the API server the object and action that will trigger the auditing event. In this example, only requests from system:nodes that attempt an action of update or patch on a node/status or pod/status on the core API will create an event.

omitStages tells the API server to skip any logging events during a stage, which helps you limit the amount of data that is logged. There are four stages that an API request goes through:

Table 8.2 – Auditing stages

Table 7.2: Auditing stages

In our example, we have set the event to ignore the RequestReceived event, which tells the API server not to log any data for the incoming API request.

Every organization has its own auditing policy, and policy files can become long and complex. Don’t be afraid to set up a policy that logs everything until you get a handle on the types of events that you can create. Logging everything is not a good practice since the log files become very large. Even when pushing logs into an external system, like OpenSearch, there’s still a cost in processing and management. Fine-tuning an audit policy is a skill that is learned over time and as you learn more about the API server, you will start to learn what events are most valuable to audit.

Policy files are just the start of enabling cluster auditing, and now that we have an understanding of the policy file, let’s explain how to enable auditing on a cluster.

Enabling auditing is specific to each distribution of Kubernetes. In this section, we will enable the audit log in KinD to understand the low-level steps. As a quick refresher, the finished product of the last chapter was a KinD cluster with impersonation enabled (instead of directly integrating with OpenID Connect). The rest of the steps and examples in this chapter assume this cluster is being used. Start with a fresh cluster and deploy OpenUnison with impersonation from Chapter 6:

cd Kubernetes-An-Enterprise-Guide-Third-Edition/chapter2
kind delete cluster -n cluster01
./create-cluster.sh
cd ../chapter6/user-auth
./deploy_openunison_imp_impersonation.sh

Next, we’re going to configure the API server to send audit log data to a file. This is more complex than setting a switch because kubeadm, the installer that KinD is built on, runs the API server as a static pod(s). The API server is a container inside of Kubernetes! This means that in order for us to tell the API server where to write log data to, we first have to have storage to write it to and then configure the API server’s pod to use that location as a volume. We’re going to walk through this process manually to give you experience with modifying the API server’s context.

You can follow the steps in this section manually or you can execute the included script, enable-auditing.sh, in the chapter7 directory of the GitHub repository:

  1. First, copy the example audit policy from the chapter7 directory to the API server:
    $ cd chapter7
    $ docker exec -ti cluster01-control-plane mkdir /etc/kubernetes/audit
    $ docker cp cm/k8s-audit-policy.yaml cluster01-control-plane:/etc/kubernetes/audit/
  2. Next, create the directories to store the audit log and policy configuration on the API server. We will exec into the container since we need to modify the API server file in the next step:
    $ docker exec -ti cluster01-control-plane mkdir /var/log/k8s

At this point, you have the audit policy on the API server and you can enable the API options to use the file.

  1. On the API server, edit the kubeadm configuration file (you will need to install an editor such as vi by running apt-get update; apt-get install vim), /etc/kubernetes/manifests/kube-apiserver.yaml, which is the same file that we updated to enable OpenID Connect. To enable auditing, we need to add three values.

It’s important to note that many Kubernetes clusters may only require the file and the API options. We need the second and third steps since we are using a KinD cluster for our testing.

First, add bold command-line flags for the API server that enable the audit logs. Along with the policy file, we can add options to control the log file rotation, retention, and maximum size:

- --tls-private-key-file=/etc/kubernetes/pki/apiserver.key
- --audit-log-path=/var/log/k8s/audit.log
- --audit-log-maxage=1
- --audit-log-maxbackup=10
- --audit-log-maxsize=10
- --audit-policy-file=/etc/kubernetes/audit/k8s-audit-policy.yaml

Notice that the option is pointing to the policy file that you copied over in the previous step.

  1. Next, add the bold directories that store the policy configuration and the resulting logs to the volumeMounts section:
    - mountPath: /usr/share/ca-certificates
    name: usr-share-ca-certificates
    readOnly: true
    - mountPath: /var/log/k8s
    name: var-log-k8s
    readOnly: false
    - mountPath: /etc/kubernetes/audit
    name: etc-kubernetes-audit
    readOnly: true
  2. Finally, add the bold hostPath configurations to the volumes section so that Kubernetes knows where to mount the local paths:
    - hostPath:
    path: /usr/share/ca-certificates
    type: DirectoryOrCreate
    name: usr-share-ca-certificates
    - hostPath:
    path: /var/log/k8s
    type: DirectoryOrCreate
    name: var-log-k8s
    - hostPath:
    path: /etc/kubernetes/audit
    type: DirectoryOrCreate
    name: etc-kubernetes-audit
  3. Save and exit the file.
  4. Like all API option changes, you need to restart the API server for the changes to take effect; however, KinD will detect that the file has changed and restart the API server’s pod automatically.

Exit the attached shell and check the pods in the kube-system namespace:

$ kubectl get pod kube-apiserver-cluster01-control-plane -n kube-system
NAME READY STATUS RESTARTS AGE
kube-apiserver-cluster01-control-plane 1/1 Running 0 47s

The API server is highlighted to have been running for only 47 seconds, showing that it successfully restarted.

Having verified that the API server is running, let’s look at the audit log to verify that it’s working correctly. To check the log, you can use docker exec to tail audit.log:

$ docker exec cluster01-control-plane tail /var/log/k8s/audit.log

This command generates the following log data:

{"kind":"Event","apiVersion":"audit.k8s.io/v1","level":"Metadata","auditID":"451ddf5d-763c-4d7c-9d89-7afc6232e2dc","stage":"ResponseComplete","requestURI":"/apis/discovery.k8s.io/v1/namespaces/default/endpointslices/kubernetes","verb":"get","user":{"username":"system:apiserver","uid":"7e02462c-26d1-4349-92ec-edf46af2ab31","groups":["system:masters"]},"sourceIPs":["::1"],"userAgent":"kube-apiserver/v1.21.1 (linux/amd64) kubernetes/5e58841","objectRef":{"resource":"endpointslices","namespace":"default","name":"kubernetes","apiGroup":"discovery.k8s.io","apiVersion":"v1"},"responseStatus":{"metadata":{},"code":200},"requestReceivedTimestamp":"2021-07-12T08:53:55.345776Z","stageTimestamp":"2021-07-12T08:53:55.365609Z","annotations":{"authorization.k8s.io/decision":"allow","authorization.k8s.io/reason":""}}

There is quite a bit of information in this JSON, and it would be challenging to find a specific event by looking at a log file directly. Luckily, now that you have auditing enabled, you can forward events to a central logging server. We will do this in Chapter 15, Monitoring Clusters and Workloads with Prometheus, where we will deploy an EFK stack.

Now that we have auditing enabled, the next step is to practice debugging RBAC policies.

There is a tool called audit2rbac that can reverse-engineer errors in the audit log into RBAC policy objects. In this section, we’ll use this tool to generate an RBAC policy after discovering that one of our users can’t perform an action they need to be able to do. This is a typical RBAC debugging process and learning how to use this tool can save you hours trying to isolate RBAC issues:

  1. In the previous chapter, a generic RBAC policy was created to allow all members of the cn=k8s-cluster-admins,ou=Groups,DC=domain,DC=com group to be administrators in our cluster. If you’re logged into OpenUnison, log out.
  2. Now, log in again with the username jjackson and the password start123.
  3. Next, click on Sign In. Once you’re logged in, go to the dashboard. Just as when OpenUnison was first deployed, there won’t be any namespaces or other information because the RBAC policy for cluster administrators doesn’t apply anymore.
  4. Next, copy your kubectl configuration from the token screen, making sure to paste it into a window that isn’t your main KinD terminal so you do not overwrite your master configuration.
  5. Once your tokens are set, attempt to create a namespace called not-going-to-work:
    PS C:\Users\mlb> kubectl create ns not-going-to-work
    Error from server (Forbidden): namespaces is forbidden: User "jjackson" cannot create resource "namespaces" in API group "" at the cluster scope

There’s enough information here to reverse-engineer an RBAC policy.

  1. In order to eliminate this error message, create a ClusterRole with a resource for "namespaces", apiGroups set to "", and a verb of "create" using your KinD administrative user:
    apiVersion: rbac.authorization.k8s.io/v1
    kind: ClusterRole
    metadata:
    name: cluster-create-ns
    rules:
    - apiGroups: [""]
    resources: ["namespaces"]
    verbs: ["create"]
  2. Next, create a ClusterRoleBinding for the user and this ClusterRole:
    apiVersion: rbac.authorization.k8s.io/v1
    kind: ClusterRoleBinding
    metadata:
    name: cluster-create-ns
    subjects:
    - kind: User
    name: jjackson
    apiGroup: rbac.authorization.k8s.io
    roleRef:
    kind: ClusterRole
    name: cluster-create-ns
    apiGroup: rbac.authorization.k8s.io
  3. Once the ClusterRole and ClusterRoleBinding are created, try running the command again, and it will work:
    PS C:\Users\mlb> kubectl create ns not-going-to-work
    namespace/not-going-to-work created

Unfortunately, this is not likely how most RBAC debugging will go. Most of the time, debugging RBAC will not be this clear or simple. Typically, debugging RBAC means getting unexpected error messages between systems. For instance, if you’re deploying the kube-prometheus project for monitoring, you’ll generally want to monitor by Service objects, not by explicitly naming Pods. In order to do this, the Prometheus ServiceAccount needs to be able to list the Service objects in the namespace of the service you want to monitor. Prometheus won’t tell you this needs to happen; you just won’t see your services listed. A better way to debug is to use a tool that knows how to read the audit log and can reverse-engineer a set of roles and bindings based on the failures in the log.

The audit2rbac tool is the best way to do this. It will read the audit log and give you a set of policies that will work. It may not be the exact policy that’s needed, but it will provide a good starting point. Let’s try it out:

  1. First, attach a shell to the control-plane container of your cluster and download the tool from GitHub (https://github.com/liggitt/audit2rbac/releases):
    root@cluster01-control-plane:/# curl -L https://github.com/liggitt/audit2rbac/releases/download/v0.8.0/audit2rbac-linux-amd64.tar.gz 2>/dev/null > audit2rbac-linux-amd64.tar.gz
    root@cluster01-control-plane:/# tar -xvzf audit2rbac-linux-amd64.tar.gz
  2. Before using the tool, make sure to close the browser with the Kubernetes dashboard in it to avoid polluting the logs. Also, remove the cluster-create-ns ClusterRole and ClusterRoleBinding created previously. Finally, try creating the still-not-going-to-work namespace:
    PS C:\Users\mlb> kubectl create ns still-not-going-to-work
    Error from server (Forbidden): namespaces is forbidden: User "jjackson" cannot create resource "namespaces" in API group "" at the cluster scope
  3. Next, use the audit2rbac tool to look for any failures for your test user:
    root@cluster01-control-plane:/# ./audit2rbac --filename=/var/log/k8s/audit.log --user=jjackson
    Opening audit source...
    Loading events...
    Evaluating API calls...
    Generating roles...
    apiVersion: rbac.authorization.k8s.io/v1
    kind: ClusterRole
    metadata:
    annotations:
    audit2rbac.liggitt.net/version: v0.8.0
    labels:
    audit2rbac.liggitt.net/generated: "true" audit2rbac.liggitt.net/user: jjackson
    name: audit2rbac:jjackson
    rules:
    - apiGroups:
    - "" resources:
    - namespaces
    verbs:
    - create
    ---
    apiVersion: rbac.authorization.k8s.io/v1
    kind: ClusterRoleBinding
    metadata:
    annotations:
    audit2rbac.liggitt.net/version: v0.8.0
    labels:
    audit2rbac.liggitt.net/generated: "true" audit2rbac.liggitt.net/user: jjackson
    name: audit2rbac:jjackson
    roleRef:|
    apiGroup: rbac.authorization.k8s.io
    kind: ClusterRole|
    name: audit2rbac:jjackson
    subjects:
    - apiGroup: rbac.authorization.k8s.io
    kind: User
    name: jjackson
    Complete!
  4. This command generated a policy that will allow the test user to create namespaces. This becomes an anti-pattern, though, of explicitly authorizing access to users.
  5. In order to better leverage this policy, it would be better to use our group:
    apiVersion: rbac.authorization.k8s.io/v1
    kind: ClusterRole
    metadata:
    name: create-ns-audit2rbac
    rules:
    - apiGroups:
    - ""
    resources:
    - namespaces
    verbs:
    - create
    ---
    apiVersion: rbac.authorization.k8s.io/v1
    kind: ClusterRoleBinding
    metadata:
    name: create-ns-audit2rbac
    roleRef:
    apiGroup: rbac.authorization.k8s.io
    kind: ClusterRole
    name: create-ns-audit2rbac
    subjects:
    - apiGroup: rbac.authorization.k8s.io
    kind: Group
    name: cn=k8s-create-ns,ou=Groups,DC=domain,DC=com

The major change is highlighted. Instead of referencing the user directly, the ClusterRoleBinding is now referencing the cn=k8s-create-ns,ou=Groups,DC=domain,DC=com group so that any member of that group can now create namespaces.

This chapter’s focus was on RBAC policy creation and debugging. We explored how Kubernetes defines authorization policies and how it applies those policies to enterprise users. We also looked at how these policies can be used to enable multi-tenancy in your cluster. Finally, we enabled the audit log in our KinD cluster and learned how to use the audit2rbac tool to debug RBAC issues.

Using Kubernetes’ built-in RBAC policy management objects lets you enable access that’s needed for operational and development tasks in your clusters. Knowing how to design policies can help limit the impact of issues, providing the confidence to let users do more on their own.

In the next chapter, Chapter 8, Managing Secrets, we’ll learn how Kubernetes manages secret data and how you should integrate external secrets into your clusters using HashiCorp Vault and the External Secrets Operator.

  1. True or false – ABAC is the preferred method of authorizing access to Kubernetes clusters.
    1. True 2. False
  2. What are the three components of a Role?
    1. Subject, noun, and verb 2. Resource, action, and group 3. apiGroups, resources, and verbs 4. Group, resource, and sub-resource
  3. Where can you go to look up resource information?
    1. Kubernetes API reference 2. The library 3. Tutorials and blog posts
  4. How can you reuse Roles across namespaces?
    1. You can’t; you need to re-create them. 2. Define a ClusterRole and reference it in each namespace as a RoleBinding. 3. Reference the Role in one namespace with the RoleBindings of other namespaces. 4. None of the above.
  5. How should bindings reference users?
    1. Directly, listing every user. 2. RoleBindings should only reference service accounts. 3. Only ClusterRoleBindings should reference users. 4. Whenever possible, RoleBindings and ClusterRoleBindings should reference groups.
  6. True or false – RBAC can be used to authorize access to everything except for one resource.
    1. True 2. False
  7. True or false – RBAC is the only method of authorization in Kubernetes.
    1. True 2. False
  1. a: false
  2. b: Resource, action, and group
  3. a: Kubernetes API reference
  4. b: Define a ClusterRole and reference it in each namespace as a RoleBinding.
  5. d: Whenever possible, RoleBindings and ClusterRoleBindings should reference groups.
  6. b: False
  7. b: False

Join the book’s Discord workspace for a monthly Ask Me Anything session with the authors: