Skip to content
ImagineWorld

Integrating Authentication into Your Cluster

node_idnode-book_kubernetes-an-enterprise-guide_chapter-06-integrating-authentication-into-your-cluster
node_typechapter-node
schema_profileworld.chapter_node.v1
statusactive
entropyhigh
manifoldworld
domainimagineworld.net
authorityinforms
layercorpus
chapter_num6
chapter_titleIntegrating Authentication into Your Cluster
governed_byCORPUS
constitutional_citationCONSTITUTION
local graph

Chapter 6 — Integrating Authentication into Your Cluster

Section titled “Chapter 6 — Integrating Authentication into Your Cluster”

Once a cluster has been built, users will need to interact with it securely. For most enterprises, this means authenticating individual users and pipelines, making sure they can only access what they need in order to do their jobs. This is known as least privileged access. The principle of least privilege is a security practice that centers on providing users, systems, applications, or processes with only the essential access and permissions required to execute their tasks. With Kubernetes, this can be challenging because a cluster is a collection of APIs, not an application with a frontend that can prompt for authentication, nor does it provide a secure way to manage credentials on its own.

Failing to create an authentication strategy can lead to your cluster being taken over. Once a cluster is potentially compromised, it’s almost impossible to determine if an attacker has been purged, and you’ll need to start over. A breached cluster can also lead to breaches in other systems too, such as a database your applications may be accessing. Authentication is the first step to make sure this doesn’t happen.

In this chapter, you’ll learn how to integrate enterprise authentication into your cluster using the OpenID Connect protocol and Kubernetes impersonation. We’ll also cover several anti-patterns and explain why you should avoid using them. To close out the chapter, you’ll also learn how to integrate your pipelines into your clusters securely.

In this chapter, we will cover the following topics:

  • Understanding how Kubernetes knows who you are
  • Understanding OpenID Connect
  • Configuring KinD for OpenID Connect
  • Introducing impersonation to integrate authentication with cloud-managed clusters
  • Configuring your cluster for impersonation
  • Configuring impersonation without OpenUnison
  • Authenticating from pipelines

Let’s get started!

To complete the exercises in this chapter, you will require the following:

  • An Ubuntu 22.04 server with 8 GB of RAM
  • A fresh KinD cluster running with the configuration from Chapter 2, Deploying Kubernetes Using KinD

You can access the code for this chapter at the following GitHub repository: https://github.com/PacktPublishing/Kubernetes-An-Enterprise-Guide-Third-Edition/tree/main/chapter6.

We do our best to test everything, but there are sometimes half a dozen systems or more in our integration labs. Given the fluid nature of technology, sometimes things that work in our environment don’t work in yours. Don’t worry – we’re here to help! Open an issue on our GitHub repo at https://github.com/PacktPublishing/Kubernetes-An-Enterprise-Guide-Third-Edition/issues, and we’ll be happy to help you out!

Understanding how Kubernetes knows who you are

Section titled “Understanding how Kubernetes knows who you are”

In the 1999 sci-fi film The Matrix, Neo talks to a child about the Matrix as he waits to see the Oracle. The child explains to him that the trick to manipulating the Matrix is to realize that “ There is no spoon.”

This is a great way to look at users in Kubernetes because they don’t exist. With the exception of service accounts, which we’ll talk about later, there are no objects in Kubernetes called “User” or “Group.” Every API interaction must include enough information to tell the API server who the user is and what groups the user is a member of. This assertion can take different forms, depending on how you plan to integrate authentication into your cluster.

In this section, we will get into the details of the different ways Kubernetes can associate a user with a cluster.

Users who access the Kubernetes API from outside the cluster will usually do so using one of two authentication methods:

  • Certificate: You can assert who you are by using a client certificate that has information about you, such as your username and groups. The certificate is used as part of the TLS negotiation process.
  • Bearer token: Embedded in each request, a bearer token can either be a self-contained token that contains all the information needed to verify itself, or a token that can be exchanged by a webhook in the API server for that information.

There is a third method that can be used for authentication, using a service account. However, using service accounts to access the API server outside the cluster is strongly discouraged. We’ll cover the risks and concerns around using service accounts in the Other authentication options section.

Different users can be assigned the same permissions without creating RoleBinding objects for each user individually via groups. Kubernetes includes two types of groups:

  • System assigned: These groups start with the system: prefix and are assigned by the API server. An example group is system:authenticated, which is assigned to all authenticated users. Another example of system-assigned groups is the system:serviceaccounts:namespace group, where Namespace is the name of the namespace that contains all the service accounts for the namespace named in the group.
  • User-asserted groups: These groups are asserted by the authentication system, either in the token provided to the API server or via the authentication webhook. There are no standards or requirements for how these groups are named. Just as with users, groups don’t exist as objects in the API server. Groups are asserted at authentication time by external users and tracked locally for system-generated groups. When asserting a user’s groups, the primary difference between a user’s unique ID and groups is that the unique ID is expected to be unique, whereas groups are not.

While you may be authorized for access by groups, all access is still tracked and audited based on your user’s unique ID.

Service accounts are objects that exist in the API server to track which pods can access the various APIs. Service account tokens are called JSON Web Tokens, or JWTs, and depending on how the token was generated, there are two ways to obtain a service account:

  • The first is from a secret that can be generated by Kubernetes when a ServiceAccount is created.
  • The second is via the TokenRequest API, which is used to inject a secret into pods via a mount point or externally from the cluster. All service accounts are used by injecting the token as a header in the request into the API server. The API server recognizes it as a service account and validates it internally.

We will cover how to create these tokens in a specific context later in the chapter.

Unlike users, service accounts CANNOT be assigned to arbitrary groups. Service accounts are members of pre-built groups only; you can’t create a group of specific service accounts to assign roles.

Now that we have explored the fundamentals of how Kubernetes identifies users, we’ll explore how this framework fits into the OpenID Connect (OIDC) protocol. OIDC provides the security most enterprises require and is standards-based, but Kubernetes doesn’t use it in a way that is typical of many web applications. Understanding these differences and why Kubernetes needs them is an important step in integrating a cluster into an enterprise security environment.

OpenID Connect is a standard identity federation protocol. It’s built on the OAuth2 specification and has some very powerful features that make it the preferred choice to interact with Kubernetes clusters.

The main benefits of OpenID Connect are as follows:

  • Short-lived tokens: If a token is leaked, such as via a log message or breach, you want the token to expire as quickly as possible. With OIDC, you’re able to specify tokens that can live for 1–2 minutes, which means the token will likely have expired by the time an attacker attempts to use it.
  • User and group memberships: When we start discussing authorization in Chapter 7, RBAC Policies and Auditing, we’ll see immediately that it’s important to manage access by group instead of managing access by referencing users directly. OIDC tokens can embed both the user’s identifier and their groups, leading to easier access management.
  • Refresh tokens scoped to timeout policies: With short-lived tokens, you need to be able to refresh them as needed. The time that a refresh token remains valid can be scoped to your enterprise’s web application idle timeout policy, keeping your cluster in compliance with other web-based applications.
  • No plugins required for kubectl: The kubectl binary supports OpenID Connect natively, so there’s no need for any additional plugins. This is especially useful if you need to access your cluster from a jump box or VM because you’re unable to install the Command-Line Interface (CLI) tools directly onto your workstation. There are convenient plugins though, which we will discuss later in the chapter.
  • More multi-factor authentication options: Many of the strongest multi-factor authentication options require a web browser. Examples include FIDO and WebAuthn, which use hardware tokens.

OIDC is a peer-reviewed standard that has been in use for several years and is quickly becoming the preferred standard for identity federation. Using an existing standard, over something custom-developed, means that Kubernetes leverages the existing expertise of those peer reviews, instead of creating a new authentication protocol where that experience hasn’t been tested.

Identity federation is the term used to describe the assertion of identity data and authentication without sharing a user’s confidential secret or password. A classic example of identity federation is logging into your employee website and being able to access your benefits provider without having to log in again. Your employee website doesn’t share your password with your benefits provider. Instead, your employee website asserts that you logged in at a certain date and time and provides some information about you. This way, your account is federated across two silos (your employee website and benefits portal), without your benefits portal knowing your employee website password.

As you can see, there are multiple components to OIDC. To fully understand how OIDC works, let’s begin by understanding the OpenID Connect protocol.

The two aspects of the OIDC protocol we will focus on are:

  • Using tokens with kubectl and the API server
  • Refreshing tokens to keep your tokens up to date

We won’t focus too much on obtaining tokens. While the protocol to get a token does follow a standard, the login process does not. How you obtain tokens from an identity provider will vary, and it’s based on how you choose to implement your OIDC Identity Provider (IdP).

Three tokens are generated from the OIDC login process:

  • access_token: This token is used to make authenticated requests to web services your identity provider may provide, such as obtaining user information. It is NOT used by Kubernetes and can be discarded. This token does not have a standard form. It may be a JWT, or it may not.
  • id_token: This token is a JWT that encapsulates your identity, including your unique identifier, groups, and expiration information about you that the API server can use to authorize your access. The JWT is signed by your identity provider’s certificate and can be verified by Kubernetes, simply by checking the JWT’s signature. This is the token you pass to Kubernetes for each request to authenticate yourself.
  • refresh_token: kubectl knows how to refresh your id_token for you automatically once it expires. To do this, it makes a call to your IdP’s token endpoint using a refresh_token to obtain a new id_token. A refresh_token should only be used once and is opaque, meaning that you, as the holder of the token, have no visibility into its format, and it really doesn’t matter to you. It either works, or it doesn’t. The refresh_token never goes to Kubernetes (or any other application). It is only used in communications with the IdP.

The refresh_token ‘s ability to be used multiple times can be allowed in specific circumstances. There are well-known issues with the Kubernetes Go SDK when multiple processes attempt to refresh a token from the same kubectl configuration file at nearly the same time, causing the user’s session to be lost and forcing the user to log in again to obtain a new set of tokens. Many identity providers handle this process differently. Some allow refresh_tokens to be reused for varying amounts of time. When reviewing your choice for an identity provider, it’s important to review this part of the functionality because it’s often left more “open” by default to give a better user experience. Allowing the long-lived reuse of a refresh_token invalidates much of the security provided by a refresh_token and should be used very carefully.

Once you have your tokens, you can use them to authenticate with the API server. The easiest way to use your tokens is to add them to the kubectl configuration, using command-line parameters:

kubectl config set-credentials username --auth-provider=oidc --auth-provider-arg=idp-issuer-url=https://host/uri --auth-provider-arg=client-id=kubernetes --auth-provider-arg=refresh-token=$REFRESH_TOKEN --auth-provider-arg=id-token=$ID_TOKEN

config set-credentials has a few options that need to be provided. We have already explained id-token and refresh-token, but there are two additional options:

  • idp-issuer-url: This is the same URL we will use to configure the API server and points to the base URL used for the IdP’s discovery URL.
  • client-id: This is used by your IdP to identify your configuration. This is unique to a Kubernetes deployment and is not considered secret information.

The OpenID Connect protocol has an optional element, known as a client_secret, that is shared between an OIDC client and the IdP. It is used to “authenticate” the client before making any requests, such as refreshing a token. While it’s supported by Kubernetes as an option, it’s recommended to not use it and instead configure your IdP to use a public endpoint (which doesn’t use a secret at all).

The client secret has no practical value, since you’d need to share it with every potential user, and since it’s a password, your enterprise’s compliance framework will likely require that it is rotated regularly, causing support headaches. Overall, it’s just not worth any potential downsides in terms of security.

Instead of using a client secret, you should make sure your endpoint leverages the Proof Key for Code Exchange (PKCE) protocol. This protocol was originally created to add a layer of randomness to OIDC requests that don’t have client secrets. While this is not something that would be leveraged by the kubectl command during the refresh process, you’re likely to integrate multiple applications from your cluster into your identity provider (such as dashboards) that may have CLI components and won’t be able to use a client secret either. ArgoCD, which we will integrate in the last two chapters, is a great example. Its CLI utility works with SSO, but unlike kubectl, it will initiate SSO for you. When it does, it includes PKCE because you won’t have a client_secret on each user’s workstation.

Kubernetes requires that your identity provider supports the discovery URL endpoint, which is a URL that provides some JSON to tell you where you can get keys to verify JWTs and the various endpoints available. To access the discovery endpoint, take any issuer URL and add /.well-known/openid-configuration, which will provide the OIDC endpoint information.

Having worked through how the OpenID Connect protocol and tokens work with Kubernetes, let’s next walk through how the various components in Kubernetes and kubectl interact with each other.

Following OIDC and the API’s interaction

Section titled “Following OIDC and the API’s interaction”

Once kubectl has been configured, all of your API interactions will follow the following sequence:

Figure 7.1 – Kubernetes/kubectl OpenID Connect sequence diagram

Figure 6.1: Kubernetes/kubectl OpenID Connect sequence diagram

The preceding diagram is from Kubernetes’ authentication page at https://kubernetes.io/docs/reference/access-authn-authz/authentication/#openid-connect-tokens. Authenticating a request involves the following:

  1. Log into your IdP: This will be different for each IdP. This could involve providing a username and password to a form in a web browser, a multi-factor token, or a certificate. This will be specific to every implementation.
  2. Provide tokens to the user: Once authenticated, the user needs a way to generate the tokens needed by kubectl to access the Kubernetes APIs. This can take the form of an application that makes it easy for the user to copy and paste them into the configuration file, or it can be a new file to download.
  3. This step is where id_token and refresh_token are added to the kubectl configuration. If the tokens were presented to the user in the browser, they can be manually added to the configuration. Alternatively, some solutions provide a new kubectl configuration to download at this step. There are also kubectl plugins that will launch a web browser to start the authentication process and, once completed, generate your configuration for you.
  4. Inject id_token: Once the kubectl command has been called, each API call includes an additional header, called the Authorization header, that includes id_token.
  5. JWT signature validation: Once the API server receives id_token from the API call, it validates the signature against the public key provided by the identity provider. The API server will also validate whether the issuer matches the issuer for the API server configuration, and also that the recipient matches the client ID from the API server configuration.
  6. Check the JWT’s expiration: Tokens are only good for a limited amount of time. The API server ensures that the token hasn’t expired. If it has expired, the API server will return with a 401 error code.
  7. Authorization check: Now that the user has been authenticated, the API server will determine whether the user identified by the provided id_token is able to perform the requested action by matching the user’s identifier and asserted groups to internal policies.
  8. Execute the API: All checks are complete, and the API server executes the request, generating a response that will be sent back to kubectl.
  9. Format the response for the user: Once the API call (or a series of API calls) is complete, the response in JSON is formatted and presented to the user by kubectl.

In general terms, authentication is the process of validating that you are you. Most of us encounter this when we put our username and password into a website; we’re proving who we are. In the enterprise world, authorization then becomes the decision of whether we’re allowed to do something. First, we authenticate, and then we authorize.

The standards built around API security don’t assume authentication and go straight to authorization, based on some sort of token. It’s not assumed that the caller has to be identified. For instance, when you use a physical key to open a door, the door doesn’t know who you are, only that you have the right key. This terminology can become very confusing, so don’t feel bad if you get a bit lost. You’re in good company!

The id_token is self-contained; everything the API server needs to know about you is in that token. The API server verifies the id_token using the certificate provided by the identity provider and verifies that the token hasn’t expired. As long as that all lines up, the API server will move on to authorizing your request based on its own RBAC configuration. We’ll cover the details of that process later. Finally, assuming you’re authorized, the API server provides a response.

Note that Kubernetes never sees your password or any other secret information that you, and only you, know. The only thing that’s shared is the id_token, and that’s ephemeral. This leads to several important points:

  • Since Kubernetes never sees your password or other credentials, it can’t compromise them. This can save you a tremendous amount of time working with your security team, as all the tasks and controls related to securing passwords can be skipped!
  • The id_token is self-contained, which means that if it’s compromised, there is nothing you can do, short of rekeying your identity provider, to stop it from being abused. This is why it’s so important for your id_token to have a short lifespan. At 1–2 minutes, the likelihood that an attacker will be able to obtain an id_token, realize what it is, and abuse it is very low.

If, while performing its calls, kubectl finds that id_token has expired, it will attempt to refresh it by calling the IdP’s token endpoint using refresh_token. If the user’s session is still valid, the IdP will generate a new id_token and refresh_token, which kubectl will store for you in the kubectl configuration. This happens automatically with no user intervention. Additionally, a refresh_token has a one-time use, so if someone tries to use a previously used refresh_token, your IdP will fail the refresh process.

A sudden security event is bound to happen. Someone may need to be locked out immediately; it may be that they’re being walked out or that their session has been compromised. Revocation of tokens is dependent on your IdP, so when choosing an IdP, make sure it supports some form of session revocation.

Finally, if the refresh_token has expired or the session has been revoked, the API server will return a 401 Unauthorized message to indicate that it will no longer support the token.

We’ve spent a considerable amount of time examining the OIDC protocol. Now, let’s take an in-depth look at the id_token.

An id_token is a JSON web token that is base64-encoded and digitally signed. The JSON contains a series of attributes, known as claims, in OIDC. There are some standard claims in the id_token, but for the most part, the claims you will be most concerned with are as follows:

  • iss: The issuer, which MUST line up with the issuer in your kubectl configuration
  • aud: Your client ID
  • sub: Your unique identifier
  • groups: Not a standard claim, but it should be populated with groups specifically related to your Kubernetes deployment

Many deployments attempt to identify you by your email address. This is an anti-pattern, as your email address is generally based on your name, and names can change. The sub claim is supposed to be a unique identifier that is immutable and will never change. This way, it doesn’t matter if your email changes because your name changes. While this can make it harder to debug “who is cd25d24d-74b8-4cc4-8b8c-116bf4abbd26?”, it will provide a cleaner and easier-to-maintain cluster.

There are several other claims that indicate when an id_token should no longer be accepted. These claims are all measured in seconds from epoch (January 1, 1970) UTC time:

  • exp: When the id_token expires
  • iat: When the id_token was created
  • nbf: The absolute earliest an id_token should be allowed

Why doesn’t a token just have a single expiration time?

It’s unlikely that the clock on the system that created the id_token has the exact same time as the system that evaluates it. There’s often a skew and, depending on how the clock is set, it may be a few minutes. Having a not-before in addition to an expiration gives some room for standard time deviation.

There are other claims in an id_token that don’t really matter but are there for additional context. Examples include your name, contact information, organization, and so on.

While the primary use for tokens is to interact with the Kubernetes API server, they are not limited to only API interaction. In addition to going to the API server, webhook calls may also receive your id_token.

You may have deployed OPA as a validating webhook on a cluster. When someone submits a pod creation request, the webhook will receive the user’s id_token, which can be used to make decisions. Open Policy Agent (OPA), is a tool to validate and authorize requests. It’s often deployed in Kubernetes as an admission controller webhook. If you haven’t worked with OPA or admission controllers, we cover both in depth, starting in Chapter 11, Extending Security Using Open Policy Agent.

One example of when an admission controller would inspect the user’s id_token is that you want to ensure that the PVCs are mapped to specific PVs based on the submitter’s organization. The organization is included in the id_token, which is passed to Kubernetes, and then onto the OPA webhook. Since the token has been passed to the webhook, the information can then be used in your OPA policies.

We’ve spent an extensive amount of time on OpenID Connect and how it’s used to authenticate API calls to your Kubernetes cluster. While it may be the best overall option, it’s not the only one. In the next section, we’ll look at other options and when they would be appropriate.

In this section, we focused on OIDC and presented reasons why it’s the best mechanism for authentication. It is certainly not the only option, and we will cover the other options in this section and when they’re appropriate.

This is generally everyone’s first experience authenticating to a Kubernetes cluster.

Once a Kubernetes installation is complete, a pre-built kubectl config file that contains a certificate and private key is created and ready to be used. Where this file is created is dependent on the distribution. This file should only be used in “break glass in case of emergency” scenarios, where all other forms of authentication are not available. It should be controlled by your organization’s standards for privileged access. When this configuration file is used, it doesn’t identify the user and can easily be abused, since it doesn’t allow for an easy audit trail.

While this is a standard use case for certificate authentication, it’s not the only use case for certificate authentication. Certificate authentication, when done correctly, is one of the strongest recognized credentials in the industry.

Certificate authentication is used by the US Federal Government for its most important tasks. At a high level, certificate authentication involves using a client key and certificate to negotiate your HTTPS connection to the API server. The API server can get the certificate you used to establish the connection and validate it against a Certificate Authority (CA) certificate. Once verified, it maps attributes from the certificate to a user and groups the API server can recognize.

To get the security benefits of certificate authentication, the private key needs to be generated on isolated hardware, usually in the form of a smartcard, and never leave that hardware. A certificate signing request is generated and submitted to a CA that signs the public key, thus creating a certificate that is then installed on the dedicated hardware. At no point does the CA get the private key, so even if the CA were compromised, you couldn’t gain the user’s private key. If a certificate needs to be revoked, it’s added to a revocation list that can either be pulled from an LDAP directory or a file, or it can be checked using the OCSP protocol.

This may look like an attractive option, so why shouldn’t you use certificates with Kubernetes?

  • Smartcard integration uses a standard called PKCS11, which is not supported by either kubectl or the API server.
  • The API server has no way of checking certificate revocation lists or using OCSP, so once a certificate has been minted, there’s no way to revoke it. Since the API server can’t revoke it, anyone who has it can continue to use it until it expires.

Additionally, the process to correctly generate a key pair is rarely used. It requires a complex interface to be built that is difficult for users to use, combined with command-line tools that need to be run. To get around this, the certificate and key pair are generated for you, and you download them or they’re emailed to you, negating the security of the process.

The other reason you shouldn’t use certificate authentication for users is that it’s difficult to leverage groups. While you can embed groups into the subject of the certificate, you can’t revoke a certificate. So if a user’s role changes, you can give them a new certificate, but you can’t keep them from using the old one. While you could reference users directly in your RoleBindings and ClusterRoleBindings, this is an anti-pattern that will make it difficult to keep track of access across even small clusters.

As stated in the introduction to this section, using a certificate to authenticate in “break glass in case of emergency” situations is a good use of certificate authentication. It may be the only way to get into a cluster if all other authentication methods experience issues.

After certificates, the next most common alternative is to use ServiceAccount tokens. We’ll walk through that next and why you shouldn’t use them from outside of your cluster.

A ServiceAccount is designed to provide an identity to containers running in a cluster so that when those containers call the API server, they can be authenticated and have RBAC rules applied. Unfortunately, users began using the tokens associated with ServiceAccount objects to access the API server from outside of the cluster, which is problematic for multiple reasons:

  • Secure transmission of the token: Service accounts are self-contained and need nothing to unlock them or verify ownership, so if a token is taken in transit, you have no way of stopping its use. You could set up a system where a user logs in to download a file with the token in it, but you now have a much less secure version of OIDC.
  • No expiration: When you decode a legacy service account token, there is nothing that tells you when the token expires. That’s because the token never expires. You can revoke a token by deleting the service account and recreating it, but that means you need a system in place to do that. Again, you’ve built a less capable version of OIDC.
  • Auditing: The service account can easily be handed out by the owner once the key has been retrieved. If multiple users use a single key, it becomes very difficult to audit the use of the account.

Beginning in Kubernetes 1.24, static ServiceAccount tokens were disabled by default and replaced with short-lived tokens that are “projected” into your containers, using the TokenRequest API. We’ll cover these tokens in more detail in the next section. We’re including instructions here for how to generate static tokens as an example of an anti-pattern. While there are some narrow use cases where static tokens are useful, they should be avoided for use from outside of your cluster. They’re most often used by pipelines, and later in this chapter, we will explore alternative approaches.

Service accounts appear to provide an easy access method. Creating them is easy. The following commands create a service account object and a secret to go with it that stores the service account’s token:

kubectl create sa mysa -n default
kubectl create -n default -f - <<EOF
apiVersion: v1
kind: Secret
metadata:
name: mysa-secret
annotations:
kubernetes.io/service-account.name: mysa
type: kubernetes.io/service-account-token
EOF

The above steps:

  1. Create a ServiceAccount object
  2. Create a Secret with a token that is bound to the ServiceAccount

Next, the following command will retrieve the service account’s token in the JSON format and return only the value of the token. This token can then be used to access the API server:

kubectl get secret mysa-secret -o json | jq -r '.data.token' | base64 -d

To show an example of this, let’s call the API endpoint directly, without providing any credentials (make sure you use the port for your own local control plane):

curl -v --insecure https://0.0.0.0:6443/api

You will receive the following:

.
.
.
{
"kind": "Status",
"apiVersion": "v1",
"metadata": {
},
"status": "Failure",
"message": "forbidden: User \"system:anonymous\" cannot get path
\"/api\"",
"reason": "Forbidden",
"details": {
},
"code": 403
* Connection #0 to host 0.0.0.0 left intact

By default, most Kubernetes distributions do not allow anonymous access to the API server, so we received a 403 error because we didn’t specify a user.

Now, let’s add our service account to an API request:

export KUBE_AZ=$(kubectl get secret mysa-secret -o json | jq -r '.data.token' | base64 -d)
curl -H "Authorization: Bearer $KUBE_AZ" --insecure
https://0.0.0.0:6443/api
{
"kind": "APIVersions",
"versions": [
"v1"
],
"serverAddressByClientCIDRs": [
{
"clientCIDR": "0.0.0.0/0",
"serverAddress": "172.17.0.3:6443"
}
]
}

Success! We were able to use a static ServiceAccount token to authenticate to our API server. As we said earlier, this is an anti-pattern. In addition to the issues with the token itself that we covered, you can’t put a service account into arbitrary groups. This means that RBAC bindings have to either be direct to the service account or use one of the pre-built groups that service accounts are a member of. We’ll explore why this is an issue when we discuss authorization, but here’s an example of why this is an issue: directly binding means that in order to know if a user should have access, you need to process each binding, looking for the user instead of simply looking in an external database that has users organized into groups, which increases compliance burdens.

Finally, service accounts were never designed to be used outside of the cluster. It’s like using a hammer to drive in a screw. With enough muscle and aggravation, you will drive it in, but it won’t be pretty and no one will be happy with the result.

Now that we have covered how ServiceAccount tokens work, and that you shouldn’t use them for users, we’ll explore next why you should leverage the TokenRequest API to generate short-lived tokens for your ServiceAccounts.

The TokenRequest API is how ServiceAccount tokens are generated in Kubernetes 1.24+. This API eliminates the use of static legacy service accounts and instead projects accounts into your pods. These projected tokens are short-lived and unique for each individual pod. Finally, these tokens become invalid once the pods they’re associated with are destroyed. This makes service account tokens embedded into a pod much more secure.

This API provides another great feature: you can use it with third-party services. One example is using HashiCorp’s Vault secret management system to authenticate pods without having to do a token review API call against the API server to validate it. We’ll explore this approach when we get to Chapter 8, Managing Secrets.

This feature makes it much easier, and more secure, for your pods to call external APIs.

The TokenRequest API lets you request a short-lived service account for a specific scope. While it provides slightly better security, since it will expire and has a limited scope, it’s still bound to a service account, which means no groups, and there’s still the issue of securely getting the token to the user and auditing its use.

Starting in 1.24, all service account tokens are projected into pods via the TokenRequest API by default. The new tokens are good for a year though, so not very short-lived! That said, even if a token is set up to expire quickly, the API server won’t reject it. It will log that someone is using an expired token. This is intended to make the transition from unlimited-life tokens to short-lived tokens easier.

Some people may be tempted to use tokens for user authentication. However, tokens generated by the TokenRequest API are still built for pods to talk to your cluster or to talk to third-party APIs; they are not meant to be used by users. In order to use them, you need to create them and securely transfer them. Since they’re still bearer tokens, this could lead to a loss of the token and an eventual breach. If you’re in a situation where you need to use them because there’s no other technical option:

  1. Make the tokens as short-lived as possible
  2. Create an automated rotation process
  3. Make sure your SIEM monitors these accounts usages outside of expected scenarios

Similar to static ServiceAccount tokens, there are use cases where you may need a token that can be used from outside the cluster, such as bootstrapping integrations or simple testing. The kubectl command now includes the token sub-command that can generate a short-lived token for a ServiceAccount without having to create a static Secret:

$ export KUBE_AZ=$(kubectl create token mysa -n default)
$ curl -H "Authorization: Bearer $KUBE_AZ" --insecure \
https://0.0.0.0:6443/api
{
"kind": "APIVersions",
"versions": [
"v1"
],
"serverAddressByClientCIDRs": [
{
"clientCIDR": "0.0.0.0/0",
"serverAddress": "172.17.0.3:6443"
}
]
}

Our token from kubectl is good for an hour. This can be adjusted, but this is a much better approach for the few use cases where an external token is needed than creating a static token.

If you already have an identity platform that doesn’t use an existing standard, a custom authentication webhook will let you integrate it without having to customize the API server. This feature is commonly used by cloud providers who host managed Kubernetes instances.

You can define an authentication webhook that the API server will call with a token to validate it and get information about the user. Unless you manage a public cloud with a custom IAM token system that you are building a Kubernetes distribution for, don’t do this. Writing your own authentication is like writing your own encryption – just don’t do it. Every custom authentication system we’ve seen for Kubernetes boils down to either a pale imitation of OIDC or “pass the password.” Much like the analogy of driving a screw in with a hammer, you could do it, but it will be very painful. This is mostly because instead of driving the screw through a board, you’re more likely to drive it into your own foot.

So far, we’ve focused on the fundamentals of Kubernetes authentication, looking at both the recommended patterns and antipatterns. Next, let’s put that theory into practice by configuring authentication in a Kubernetes cluster.

For our example deployment, we will use a scenario from our customer, FooWidgets. FooWidgets has a Kubernetes cluster that they would like integrated using OIDC. The proposed solution needs to address the following requirements:

  • Kubernetes must use our central authentication system, Active Directory
  • We need to be able to map Active Directory groups into our RBAC RoleBinding objects
  • Users need access to the Kubernetes Dashboard
  • Users need to be able to use the CLI
  • All enterprise compliance requirements must be met
  • Additional cluster management applications need to be managed centrally as well

Let’s explore each of these in detail and explain how we can address the customer’s requirements.

Our enterprise’s requirements require multiple moving parts, both inside and outside our cluster. We’ll examine each of these components and how they relate to building an authenticated cluster.

Using LDAP and Active Directory with Kubernetes

Section titled “Using LDAP and Active Directory with Kubernetes”

Most enterprises today use Active Directory from Microsoft™ to store information about users and their credentials. Depending on the size of your enterprise, it’s not unusual to have multiple domains or forests where users’ data is stored.

We’ll need a solution that knows how to talk to each domain. Your enterprise may have one of many tools and products for OpenID Connect integration, or you may just want to connect via LDAP. LDAP, the Lightweight Directory Access Protocol, is a standard protocol that has been used for over 30 years and is still the standard way to talk directly to Active Directory. Using LDAP, you can look up users and validate their passwords. It’s also the simplest way to start because it doesn’t require integration with an identity provider. All you need is a service account and credentials!

For FooWidgets, we’re going to connect directly to our Active Directory for all authentication.

Don’t worry – you don’t need Active Directory ready to go to run this exercise. We’ll walk through deploying a demo directory into our KinD cluster.

Mapping Active Directory groups to RBAC RoleBindings

Section titled “Mapping Active Directory groups to RBAC RoleBindings”

This will become important when we start talking about authorization. Active Directory lists all the groups a user is a member of in the memberOf attribute. We can read this attribute directly from our logged-in user’s account to get their groups. These groups will be embedded into our id_token in the groups claim and can be referenced directly in RBAC bindings. This allows us to centralize the management of authorizations instead of having to manually manipulate RBAC bindings, simplifying management and decreasing the number of objects we need to manage and maintain in our cluster.

The Dashboard is a powerful way to quickly access information about your cluster and make quick updates. Unlike what is commonly thought about the dashboard’s security, when deployed correctly, it does not create any security issues. The proper way to deploy the dashboard is with no privileges, instead relying on the user’s own credentials. We’ll do this with a reverse proxy that injects the user’s OIDC token on each request, which the dashboard will then use when it makes calls to the API server. Using this method, we’ll be able to constrain access to our dashboard the same way we would with any other web application.

There are a few reasons why using the kubectl built-in proxy and port-forward isn’t a great strategy for accessing the dashboard. Many enterprises will not install CLI utilities locally, forcing you to use a jump box to access privileged systems such as Kubernetes, meaning port forwarding won’t work. Even if you can run kubectl locally, opening a port on loopback (127.0.0.1) means anything on your system can use it, not just you from your browser. While browsers have controls in place to keep you from accessing ports on loopback using a malicious script, that won’t stop anything else on your workstation. Finally, it’s just not a great user experience.

We’ll dig into the details of how and why this works in Chapter 10, Deploying a Secured Kubernetes Dashboard.

Most developers want to be able to access kubectl and other tools that rely on the kubectl configuration. For instance, the Visual Studio Code Kubernetes plugin doesn’t require any special configuration. It just uses the kubectl built-in configuration. Most enterprises tightly constrain what binaries you’re able to install, so we want to minimize any additional tools and plugins we want to install.

Being cloud-native doesn’t mean you can ignore your enterprise’s compliance requirements. Most enterprises have requirements such as having 20-minute idle timeouts, multi-factor authentication for privileged access, and so on. Any solution we put in place has to make it through the control spreadsheets needed to go live. Also, and this goes without saying, everything needs to be encrypted (and I do mean everything).

To fulfill these requirements, we’re going to use OpenUnison. This has prebuilt configurations to work with Kubernetes, the Dashboard, the CLI, and Active Directory.

It’s also pretty quick to deploy, so we don’t need to concentrate on provider-specific implementation details and instead can focus on Kubernetes’ configuration options. Our architecture will look like this:

Diagram Description automatically generated

Figure 6.2: Authentication architecture

Although we’re using an “Active Directory” in this instance, your enterprise might have an existing identity provider in place, such as Okta, Entra (formerly Azure Active Directory), KeyCloak, etc. In these instances, it’s still a good idea to have an identity provider in-cluster to support not only SSO in your cluster but also your cluster management applications. As we continue through this book, we’re going to be integrating monitoring systems, logging, GitOps systems, etc. It can be difficult from a management perspective to set up SSO with all of these applications, so having your own identity provider that you, as the cluster owner, control can give you greater flexibility over your clusters, making it easier to provide better security by integrating management applications with enterprise authentication, rather than relying on unauthenticated approaches like port-forwarding.

For our implementation, we’re going to use two hostnames:

  • k8s.apps.X-X-X-X.nip.io: Access to the OpenUnison portal, where we’ll initiate our login and get our tokens
  • k8sdb.apps.X-X-X-X.nip.io: Access to the Kubernetes dashboard

As a quick refresher, nip.io is a public DNS service that will return an IP address from the one embedded in your hostname. This is really useful in a lab environment where setting up DNS can be painful. In our examples, X-X-X-X is the IP of your Docker host.

When a user attempts to access https://k8s.apps.X-X-X-X.nip.io/, they’ll be asked for their username and password. After the user hits submit, OpenUnison will look up the user against Active Directory, retrieving the user’s profile information. At that point, OpenUnison will create user objects in the OpenUnison namespace to store the user’s information and create OIDC sessions.

Earlier, we described how Kubernetes doesn’t have user objects. Kubernetes lets you extend the base API with Custom Resource Definitions (CRDs). OpenUnison defines a User CRD to help with high availability and to avoid needing a database to store state in. These user objects can’t be used for RBAC.

Once the user is logged into OpenUnison, they can get their kubectl configuration to use the CLI or the Kubernetes Dashboard (https://kubernetes.io/docs/tasks/access-application-cluster/web-ui-dashboard/) to access the cluster from their browser. Once the user is ready, they can log out of OpenUnison, which will end their session and invalidate their refresh_token, making it impossible for them to use kubectl or the dashboard until after they log in again. If they walk away from their desk for lunch without logging out, when they return, their refresh_token will have expired, so they’ll no longer be able to interact with Kubernetes without logging back in.

Now that we have walked through how users will log in and interact with Kubernetes, we’ll deploy OpenUnison and integrate it into the cluster for authentication.

We’ve automated the deployment for OpenUnison, so there aren’t any manual steps. Since we want to start with a new cluster, we will delete the current cluster and execute the create-cluster.sh script in the chapter2 folder to create a fresh KinD cluster. We have also added a script to the chapter6 directory called deploy_openunison_imp_noimpersonation.sh. You can create the new cluster and integrate OIDC using the steps below:

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

This will take a few minutes, depending on your hardware. This script does several things:

  1. Creates a stand-in “Active Directory” using a project called ApacheDS. You don’t need to know anything about ApacheDS other than it’s acting as our “Active Directory.”
  2. Deploys the Kubernetes Dashboard version 2.7.
  3. Downloads the ouctl utility and the OpenUnison helm charts.
  4. Updates the values.yaml file for use with your Ubuntu VM’s IP.
  5. Deploys OpenUnison.

You can log into the OIDC provider with any machine on your network by using the assigned nip.io address. Since we will test access using the dashboard, you can use any machine with a browser.

Navigate your browser to network.openunison_host in your /tmp/openunison-values.yaml file, which was created for you by running the above scripts. When prompted, use the username mmosley and the password start123, and then click on Sign in.

There are instructions on how to add your own user accounts in the repository’s README file, located in the chapter6 directory.

Figure 6.3: OpenUnison login screen

When you do, you’ll see this screen:

Graphical user interface, application, Teams Description automatically generated

Figure 6.4: OpenUnison home screen

Let’s test the OIDC provider by clicking on the Kubernetes Dashboard link. Don’t panic when you see the initial dashboard screen – something like the following:

Graphical user interface, application Description automatically generated

Figure 6.5: Kubernetes Dashboard before SSO integration has been completed with the API server

That looks like a lot of errors! We’re in the dashboard, but nothing seems to be authorized. That’s because the API server doesn’t trust the tokens that have been generated by OpenUnison, yet. To resolve this, the next step is to tell Kubernetes to trust OpenUnison as its OpenID Connect Identity Provider.

Configuring the Kubernetes API to use OIDC

Section titled “Configuring the Kubernetes API to use OIDC”

At this point, you have deployed OpenUnison as an OIDC provider and it’s working, but your Kubernetes cluster has not been configured to use it as a provider yet.

To configure the API server to use an OIDC provider, you need to add the OIDC options to the API server and provide the OIDC certificate so that the API will trust the OIDC provider.

Since we are using KinD, we can add the required options using a few kubectl and docker commands.

To provide the OIDC certificate to the API server, we need to retrieve the certificate and copy it over to the KinD master server. We can do this using two commands on the Docker host:

  1. The first command extracts OpenUnison’s TLS certificate from its secret. This is the same secret referenced by OpenUnison’s Ingress object. We use the jq utility to extract the data from the secret and then Base64-decode it:
    kubectl get secret ou-tls-certificate -n openunison -o json | jq -r '.data["tls.crt"]' | base64 -d > ou-ca.pem
  2. The second command will copy the certificate to the master server into the /etc/kubernetes/pki directory:
    docker cp ou-ca.pem cluster01-control-plane:/etc/kubernetes/pki/ou-ca.pem
  3. As we mentioned earlier, to integrate the API server with OIDC, we need to have the OIDC values for the API options. To list the options we will use, describe the api-server-config ConfigMap in the openunison namespace:
    kubectl describe configmap api-server-config -n openunison
    Name: api-server-config
    Namespace: openunison
    Labels: <none>
    Annotations: <none>
    Data
    ====
    oidc-api-server-flags:
    ----
    --oidc-issuer-url=https://k8sou.apps.192-168-2-131.nip.io/auth/idp/k8sIdp
    --oidc-client-id=Kubernetes
    --oidc-username-claim=sub
    --oidc-groups-claim=groups
    --oidc-ca-file=/etc/kubernetes/pki/ou-ca.pem
  4. Next, edit the API server configuration. OpenID Connect is configured by changing flags on the API server. This is why managed Kubernetes generally doesn’t offer OpenID Connect as an option, but we’ll cover that later in this chapter. Every distribution handles these changes differently, so check with your vendor’s documentation. For KinD, shell into the control plane and update the manifest file:
    docker exec -it cluster01-control-plane bash
    apt-get update
    apt-get install vim -y
    vi /etc/kubernetes/manifests/kube-apiserver.yaml
  5. Add the flags from the output of the ConfigMap under command. Make sure to add spacing and a dash (-) in front. Make sure to update the URLs to match yours. It should look something like this when you’re done:
    - --kubelet-preferred-address-types=InternalIP,ExternalIP,Hostname
    - --oidc-issuer-url=https://k8sou.apps.192-168-2-131.nip.io/auth/idp/k8sIdp
    - --oidc-client-id=Kubernetes
    - --oidc-username-claim=sub
    - --oidc-groups-claim=groups
    - --oidc-ca-file=/etc/kubernetes/pki/ou-ca.pem
    - --proxy-client-cert-file=/etc/kubernetes/pki/front-proxy-client.crt
  6. Exit vim and the Docker environment (Ctrl + D), and then take a look at the api-server pod:
    kubectl get pod kube-apiserver-cluster01-control-plane -n kube-system
    NAME READY STATUS RESTARTS AGE
    kube-apiserver-cluster-auth-control-plane 1/1 Running 0 73s

Note that it’s only 73s old. That’s because KinD saw that there was a change in the manifest and restarted the API server.

The API server pod is known as a static pod. This pod can’t be changed directly; its configuration has to be changed from the manifest on disk. This gives you a process that’s managed by the API server as a container, but without giving you a situation where you need to edit pod manifests in etcd directly if something goes wrong.

Once you have updated your API server flags, the next step is to verify that you can now log in to your cluster. Let’s walk through those steps next.

Once OpenUnison and the API server have been integrated, we need to test that the connection is working:

  1. To test the integration, log back into OpenUnison and click on the Kubernetes Dashboard link again.
  2. Click on the bell in the upper right and you’ll see a different error:

A screenshot of a computer Description automatically generated

Figure 6.6: SSO enabled but the user is not authorized to access any resources

SSO between OpenUnison and Kubernetes is working! However, the new error, service is forbidden: User https://..., is an authorization error, not an authentication error. At this point, the API server knows who we are but isn’t letting us access the APIs.

  1. We’ll dive into the details of RBAC and authorizations in the next chapter, but for now, create this RBAC binding:
    kubectl create -f - <<EOF
    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
    EOF
    clusterrolebinding.rbac.authorization.k8s.io/ou-cluster-admins created
  2. Finally, go back to the Dashboard, and you’ll see that you have full access to your cluster and all the error messages are gone.

The API server and OpenUnison are now connected. Additionally, an RBAC policy has been created to enable our test user to manage the cluster as an administrator. Access was verified by logging into the Kubernetes Dashboard, but most interactions will take place using the kubectl command. The next step is to verify that we’re able to access the cluster using kubectl.

This section assumes you have a machine on your network that has a browser and kubectl running.

Using the Dashboard has its use cases, but you will likely interact with the API server using kubectl, rather than the Dashboard, for the majority of your day. In this section, we will explain how to retrieve your JWT and how to add it to your Kubernetes config file so that you can use kubectl:

  1. You can retrieve your token from the OpenUnison dashboard. Navigate to the OpenUnison home page and click on the key that says Kubernetes Tokens. You’ll see a screen that looks as follows:

Graphical user interface, text, application, email Description automatically generated

Figure 6.7: OpenUnison kubectl configuration tool

OpenUnison provides a command line that you can copy and paste into your host session that adds all the required information to your config.

  1. First, click on the double documents button next to the kubectl Command (or kubectl Windows Command if you’re on Windows) to copy your kubectl command into your buffer. Leave the web browser open in the background.
  2. You may want to back up your original config file before pasting the kubectl command from OpenUnison:
    export KUBECONFIG=$(mktemp)
    kubectl get nodes
    W0804 13:43:26.624417 3878806 loader.go:222] Config not found: /tmp/tmp.tqcXxwBh0H
    to the server localhost:8080 was refused - did you specify the right host or port?
  3. Then, go to your host console and paste the command into the console (the following output has been shortened, but your paste will start with the same output):
    export TMP_CERT=$(mktemp) && echo -e "-----BEGIN CER. . .
    Cluster "no-impersonation" set.
    Context "no-impersonation" created
    User "mmosley@no-impersonation" set.
    Switched to context "no-impersonation".
  4. Now, verify that you can view the cluster nodes using kubectl get nodes:
    kubectl get nodes
    NAME STATUS ROLES AGE VERSION
    cluster01-control-plane Ready control-plane 7m47s v1.27.3
    cluster01-worker Ready <none> 7m26s v1.27.3
  5. You’re now using your login credentials instead of the master certificate! As you work, the session will refresh. You can verify your identity using the kubectl auth whoami command:
    kubectl auth whoami
    ATTRIBUTE VALUE
    Username https://k8sou.apps.192-168-2-82.nip.io/auth/idp/k8sIdp#mmosley
    Groups [cn=group2,ou=Groups,DC=domain,DC=com cn=k8s-cluster-admins,ou=Groups,DC=domain,DC=com system:authenticated]

This command will tell you who the API server thinks you are, including your groups. This can be very handy when debugging authorizations.

When I first began working with Kubernetes in 2015, the first issue I opened was for this feature while I was debugging the integration of OpenUnison and Kubernetes. I was thrilled to see it implemented initially in 1.0.26 and for it to go GA in 1.0.28. It’s a beta feature in 1.27, and we have pre-configured our KinD cluster to support it. If you want to use this feature with other clusters, you may need to work with your vendor, since it requires a command-line argument for the API server.

  1. Log out of OpenUnison and watch the list of nodes. Within a minute or two, your token will expire and no longer work:
    kubectl get nodes
    Unable to connect to the server: failed to refresh token: oauth2: cannot fetch token: 401 Unauthorized

Congratulations! You’ve now set up your cluster so that it does the following:

  • Authenticates using LDAP, using your enterprise’s existing authentication system
  • Uses groups from your centralized authentication system to authorize access to Kubernetes (we’ll get into the details of how in the next chapter)
  • Gives user access to both the CLI and the dashboard using the centralized credentials
  • Maintains your enterprise’s compliance requirements by having short-lived tokens that provide a way to time out
  • Ensures everything uses TLS, from the user’s browser to the Ingress Controller, to OpenUnison, the Dashboard, and finally, the API server

You’ve integrated most of the advice from this chapter into your cluster. You’ve also made it easier to access because you don’t need to have a pre-configured configuration file anymore.

Next, you’ll learn how to integrate centralized authentication into your managed clusters.

Introducing impersonation to integrate authentication with cloud-managed clusters

Section titled “Introducing impersonation to integrate authentication with cloud-managed clusters”

It’s very popular to use managed Kubernetes services from cloud vendors such as Google, Amazon, Microsoft, and DigitalOcean (among many others).

When it comes to these services, they are generally very quick to get up and running, and they all share a common thread: they mostly don’t support OpenID Connect (Amazon’s EKS does support OpenID Connect now, but the cluster must be running on a public network and have a commercially signed TLS certificate).

Earlier in this chapter, we talked about how Kubernetes supports custom authentication solutions through webhooks and that you should never, ever, use this approach unless you are a public cloud provider or some other host of Kubernetes systems. It turns out that pretty much every cloud vendor has its own approach to using these webhooks that uses its own identity and access management implementations. In that case, why not just use what the vendor provides? There are several reasons why you may not want to use a cloud vendor’s IAM system:

  • Technical: You may want to support features not offered by the cloud vendor, such as the dashboard, in a secure fashion.
  • Organizational: Tightly coupling access to managed Kubernetes with that cloud’s IAM puts an additional burden on the cloud team, which means that they may not want to manage access to your clusters.
  • User experience: Your developers and admins may have to work across multiple clouds. Providing a consistent login experience makes it easier for them and requires learning fewer tools.
  • Security and compliance: The cloud implementation may not offer choices that line up with your enterprise’s security requirements, such as short-lived tokens and idle timeouts.

All that being said, there may be reasons to use the cloud vendor’s implementation. However, you’ll need to balance out the requirements. If you want to continue to use centralized authentication and authorization with hosted Kubernetes, you’ll need to learn how to work with Impersonation.

Kubernetes Impersonation is a way of telling the API server who you are without knowing your credentials or forcing the API server to trust an OpenID Connect IdP. This is useful when you can’t configure OpenID Connect, as is generally the case with managed Kubernetes offerings, or you want to support multiple access from multiple identity providers.

When you use kubectl, instead of the API server receiving your id_token directly, it will receive a service account or identifying certificate that will be authorized to impersonate users, as well as a set of headers that tell the API server who the proxy acts on behalf of:

Figure 7.11 – Diagram of how a user interacts with the API server when using Impersonation

Figure 6.8: Diagram of how a user interacts with the API server when using Impersonation

The reverse proxy is responsible for determining how to map from the id_token, which the user provides (or any other token, for that matter) to the Impersonate-User and Impersonate-Group HTTP headers. The dashboard should never be deployed with a privileged identity, which the ability to impersonate falls under.

To allow Impersonation with the 2.x dashboard, use a similar model, but instead of going to the API server, you go to the dashboard:

Figure 7.12 – Kubernetes Dashboard with Impersonation

Figure 6.9: Kubernetes Dashboard with Impersonation

The user interacts with the reverse proxy just like any web application. The reverse proxy uses its own service account and adds the impersonation headers. The dashboard passes this information through to the API server on all requests. The dashboard never has its own identity.

Now that we see what impersonation is, and how it can help us secure access to the Kubernetes Dashboard and Kubernetes APIs, we’ll walk through what you need to think about from a security perspective when implementing it.

The service account has a certain superpower: it can be used to impersonate anyone (depending on your RBAC definitions). If you’re running your reverse proxy from inside the cluster, a service account is OK, especially if combined with the TokenRequest API to keep the token short-lived.

Earlier in the chapter, we talked about the legacy tokens for ServiceAccount objects having no expiration. That’s important here because if you’re hosting your reverse proxy off-cluster, then if it were compromised, someone could use that service account to access the API service as anyone. Make sure you’re rotating that service account often. If you’re running the proxy off-cluster, it’s probably best to use a shorter-lived certificate instead of a service account.

When running the proxy on a cluster, you want to make sure it’s locked down. It should run in its own namespace at a minimum, not kube-system either. You want to minimize the number of people who have access. Using multi-factor authentication to get to that namespace is always a good idea, as is using network policies that control what pods can reach out to the reverse proxy.

Based on the concepts we’ve just learned about regarding impersonation, the next step is to update our cluster’s configuration to use impersonation instead of using OpenID Connect directly. You don’t need a cloud-managed cluster to work with impersonation.

Configuring your cluster for impersonation

Section titled “Configuring your cluster for impersonation”

Let’s deploy an impersonating proxy for our cluster. Just like integrating our cluster directly into OpenUnison using OpenID Connect, we’ve automated the deployment so that you don’t need to manually configure OpenUnison. We’ll clear out our old cluster and start afresh:

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

The differences between this script and our original script are:

  • Configuring OpenUnison to generate NetworkPolicy objects to limit access to just requests from our NGINX Ingress controller and the API server
  • Configuring OpenUnison’s ServiceAccount token to only be valid for 10 minutes instead of the typical hour or day
  • Configuring the OpenUnison values.yaml to deploy the kube-oidc-proxy to handle incoming API server requests
  • Creating the cluster-admin ClusterRoleBinding so that your user can work with your cluster

Once the script is finished running, you can log in with the same account, mmosley, as before.

The OpenUnison helm charts create NetworkPolicies and constraints the lifetime of its ServiceAccount token to line up with the security best practices we discussed above. It’s important that we keep any system that shouldn’t interact with our impersonation proxy from doing so to cut down on the potential attack surface, ensuring that any tokens that are minted with the ability to impersonate other users expire quickly.

Next, we’ll walk through testing our impersonation-based integration.

Now, let’s test our Impersonation setup. Follow these steps:

  1. In a browser, enter the URL for your OpenUnison deployment. This is the same URL you used for your initial OIDC deployment.
  2. Log into OpenUnison, and then click on the dashboard.
  3. Click on the little circular icon in the upper right-hand corner to see who you’re logged in as.
  4. Next, go back to the main OpenUnison dashboard and click on the Kubernetes Tokens badge.
  5. Note that the --server flag being passed to kubectl no longer has an IP. Instead, it has the hostname from network.api_server_host in the /tmp/openunison-values.yaml file. This is Impersonation. Instead of interacting directly with the API server, you’re now interacting with kube-oidc-proxy's reverse proxy.
  6. Finally, let’s copy and paste our kubectl command from the OpenUnison tokens screen into a shell:
    export TMP_CERT=$(mktemp) && echo -e "-----BEGIN CERTIFI...
    Cluster "impersonation" set.
    Context "impersonation" created.
    User "mmosley@impersonation" set.
    Switched to context "impersonation".
  7. To verify you have access, list the cluster nodes:
    kubectl get nodes
    NAME STATUS ROLES AGE VERSION
    cluster01-control-plane Ready control-plane 37m v1.27.3
    cluster01-worker Ready <none> 37m v1.27.3
  8. Just as with OIDC integration, you can use kubectl auth whoami to verify your identity:
    kubectl auth whoami
    ATTRIBUTE VALUE
    Username mmosley
    Groups [cn=group2,ou=Groups,DC=domain,DC=com cn=k8s-cluster-admins,ou=Groups,DC=domain,DC=com system:authenticated]

The main difference between your identity when using impersonation instead of OIDC integration is that your username doesn’t have the identity provider’s URL in the front.

  1. Just like when you integrated the original deployment of OpenID Connect, once you’ve logged out of the OpenUnison page, within a minute or two, the tokens will expire and you won’t be able to refresh them:
    kubectl get nodes
    Unable to connect to the server: failed to refresh token: oauth2: cannot fetch token: 401 Unauthorized

You’ve now validated that your cluster works correctly with Impersonation. Instead of authenticating directly to the API server, the impersonating reverse proxy (OpenUnison) forwards all requests to the API server with the correct impersonation headers. You’re still meeting your enterprise’s needs by providing both a login and logout process and integrating your Active Directory groups.

You’ll also notice that you can now access your cluster from any system on your network! This might make doing the rest of the examples throughout the book easier.

Impersonation is farmore than accessing your cluster. Next, we’ll look at how to use impersonation from kubectl get debug authorization policies.

Impersonation can be used to debug authentication and authorization configurations. This will become more useful when you begin writing RBAC policies. As an administrator, you can use impersonation from the kubectl command by adding the --as and --as-groups parameters to run a command as someone else. For instance, if you ran kubectl get nodes as a random user from your command line, it would fail:

kubectl get nodes --as somerandomuser
Error from server (Forbidden): nodes is forbidden: User "somerandomuser" cannot list resource "nodes" in API group "" at the cluster scope

However, if we add our administrative group:

kubectl get nodes --as somerandomuser --as-group=cn=k8s-cluster-admins,ou=Groups,DC=domain,DC=com
NAME STATUS ROLES AGE VERSION
cluster01-control-plane Ready control-plane 17m v1.27.3
cluster01-worker Ready <none> 17m v1.27.3

You can see that it worked. That’s because the API server interpreted our user as being a member of the group cn=k8s-cluster-admins,ou=Groups,DC=domain,DC=com, which we created an RBAC binding for. In fact, if we run kubectl auth whoami with these parameters, we’ll just see how the API server sees us:

kubectl auth whoami --as=someuser --as-group=cn=k8s-cluster-admins,ou=Groups,DC=domain,DC=com
ATTRIBUTE VALUE
Username someuser
Groups [cn=k8s-cluster-admins,ou=Groups,DC=domain,DC=com system:authenticated]
Extra: originaluser.jetstack.io-groups [cn=group2,ou=Groups,DC=domain,DC=com cn=k8s
cluster-admins,ou=Groups,DC=domain,DC=com]
Extra: originaluser.jetstack.io-user [mmosley]

In the above example, the API server sees the request as being from someuser, with the appropriate group based on the impersonation headers sent by kubectl.

The additional Extra attributes are there because while we are performing an impersonation request from kubectl -> the kube-oidc-proxy, kube-oidc-proxy does a separate impersonation with new headers, adding the extra-info headers to be included, so the audit logs show who the original user who made the request was. Before forwarding the request to the API server, the kube-oidc-proxy first performs a SubjectAccessReview to make sure that the user mmosley with their groups is allowed to impersonate someuser and the group.

We were able to quickly configure impersonation using OpenUnison, where most of the details of the implementation were hidden from you. What if you want to configure an impersonating proxy without OpenUnison?

Configuring Impersonation without OpenUnison

Section titled “Configuring Impersonation without OpenUnison”

OpenUnison automated a couple of key steps to get impersonation working. You can use any reverse proxy that can generate the correct headers. There are three critical items to understand when doing this on your own: RBAC, default groups, and inbound impersonation.

RBAC will be covered in the next chapter, but for now, the correct policy to authorize a service account for Impersonation is as follows:

apiVersion: rbac.authorization.k8s.io/v1
kind: ClusterRole
metadata:
name: impersonator
rules:
- apiGroups:
- ""
resources:
- users
- groups
verbs:
- impersonate

To constrain what accounts can be impersonated, add resourceNames to your rule. For instance, if you only want to allow the impersonation of the user mmosley:

apiVersion: rbac.authorization.k8s.io/v1
kind: ClusterRole
metadata:
name: impersonator
rules:
- apiGroups:
- ""
resources:
- users resourceNames:
- mmosley
verbs:
- impersonate

The first ClusterRole above is what tells Kubernetes that a member can impersonate all users and groups (or specific users or groups if resourceNames is specified). Be very careful as to which accounts are granted this ClusterRole, as it makes you essentially a cluster - admin because you could impersonate the system:masters group, for example, bypassing RBAC and allowing anyone who is authorized by this role to become a global administrator and compromise your cluster however they wish.

When configuring the impersonation of specific users and groups, break the ClusterRole into one ClusterRole for each. This way, you won’t have someone impersonating a group with the name of the user creating unintended consequences.

With RBAC having been configured, the next requirement is adding default groups to impersonation requests.

When impersonating a user, Kubernetes does not add the default group, system:authenticated, to the list of impersonated groups. When using a reverse proxy that doesn’t specifically know to add the header for this group, configure the proxy to add it manually. Otherwise, simple acts such as calling the /api endpoint will fail, as this will be unauthorized for anyone except cluster administrators.

We’ve focused the bulk of this chapter on authenticating users who will interact with the API server. A major advantage of Kubernetes and the APIs it provides is to automate your systems. Next, we’ll look at how you apply what we’ve learned so far to authenticating those automated systems.

We’ve shown how to use kubectl with the --as and --as-group parameters to impersonate users for debugging. If you’re using impersonation to manage access to your clusters, how does your impersonating proxy know that the user attempting to impersonate another user is, in fact, authorized to do so? In Kubernetes, you need to build a ClusterRole and a ClusterRoleBinding to enable impersonation for a specific user to a specific user, but how does your proxy know that you can impersonate someone?

In our previous example:

kubectl auth whoami --as=someuser --as-group=cn=k8s-cluster-admins,ou=Groups,DC=domain,DC=com
ATTRIBUTE VALUE
Username someuser
Groups [cn=k8s-cluster-admins,ou=Groups,DC=domain,DC=com system:authenticated]
Extra: originaluser.jetstack.io-groups [cn=group2,ou=Groups,DC=domain,DC=com cn=k8s
cluster-admins,ou=Groups,DC=domain,DC=com]
Extra: originaluser.jetstack.io-user [mmosley]

We see mmosley impersonated someuser. Kubernetes allowed this impersonation because mmosley is a member of the group cn=k8s-cluster-admins,ou=Groups,DC=domain,DC=com, which has a ClusterRoleBinding to the cluster-admin ClusterRole. However, this request went through kube-oidc-proxy, so how did kube-oidc-proxy know that the cluster would authorize the request? On each request to kube-oidc-proxy that includes impersonation headers, a SubjectAccessReview is created to check if mmosley is allowed to impersonate someuser. If this check fails, the kube-oidc-proxy denies the request.

Your impersonating proxy will need to make the same choice. There are three approaches:

  • Delete and ignore all inbound impersonation headers: Your proxy will ignore and remove all inbound headers for impersonation, making the --as and --as-group flags useless. This locks down access but limits functionality.
  • Maintain a custom authorization scheme: Before generating impersonation headers, a proxy can have its own authorization system to determine which users are allowed to impersonate other users. This means maintaining an additional authorization system, which can lead to issues with misconfiguration and, eventually, breaches.
  • Query Kubernetes for Authorization Decisions: This is what kube-oidc-proxy and Pinniped (a tool from VMware that serves a similar role to OpenUnison) use to make sure that the inbound impersonation is authorized. This is best, as it uses the same rules as your cluster to manage access, simplifying management and making it less likely a misconfiguration will lead to a breach.

Even once you’ve authorized an inbound impersonation, it’s important to log that the impersonation has occurred. The kube-oidc-proxy project does this in two places:

  • Proxy logs: Each inbound impersonation gets logged to the console (which should be captured by a log aggregator)
  • API Server Audit Logs: The extra-info headers tell the API server who the original user was which is included in the audit logs. We’ll see how to set up and inspect the audit logs in the next section.

Inbound impersonation is a very difficult process to manage. If it’s something you want to allow, you should stick with a purpose-built impersonating proxy. Otherwise, it’s best to just strip all inbound impersonation headers to avoid an account takeover.

So far, we’ve only discussed users as a whole, without adding any context. Many enterprises require that users who interact with a cluster to perform administrative work have privileges beyond their typical account. Next, we’ll look at how to implement privileged access management in Kubernetes.

In addition to managing authentication, most enterprises require a concept of “privileged access management,” where not only is access limited by the user but also by time. Most enterprises require a change control process of some kind to ensure that changes to production systems are tracked and approved. This requirement generally comes from any of the various compliance and regulatory frameworks needed in large enterprises.

There are generally three ways to manage privileged access in Kubernetes, and we’ll cover all three with their benefits and drawbacks.

It is common for enterprises to require that administrators have two accounts, one for day-to-day tasks and one to make administrative changes. This approach is generally implemented using a Privilege Access Manager (PAM) that generates a new password for the user when they’re authorized to do their work. This approach enables compliance with most frameworks because there’s a process by which someone has to approve the administrative account’s unlocking inside of the PAM. Once the admin is has completed their work, they check the account back into the PAM, which locks it. Alternatively, a time limit is usually set for how long the account can be checked out for, and when that time expires, the account is automatically locked by the PAM.

The major benefit of this approach is that the management of the privileged accounts is done outside of Kubernetes. It’s someone else’s responsibility and eliminates something that cluster owners need to manage, either via the previously mentioned PAM or some other engine. It’s important to note that as the cluster manager, you’re still responsible for authorizing access, so the same recommendations from this chapter apply.

Another reason for this approach is to protect against phishing attacks against administrators. For instance, if your cluster is integrated with your Active Directory in a way that allows desktop SSO, a bad actor could send your admins an email that runs a command as that user, without having to even know the admin’s credentials! If you are at least forcing a password, there’s an additional step an attacker needs to take.

There are arguments to be made that this isn’t the most efficient or secure approach, but it’s often what’s already in place. You will find it much easier to work within existing frameworks than trying to reinvent them.

Instead of using an external PAM to unlock users via passwords, another approach is to impersonate a privileged user using the --as command line parameter for kubectl. The idea is to simulate the Unix sudo command to escalate your privileges, to protect against accidental administrative actions.

This approach is more likely to do more harm than good. To make it work, you need at least one RBAC ClusterRole and ClusterRoleBinding for each user to maintain individual privileged accounts. If you have 100 admins, that’s 200 additional objects to create even before you authorize access to resources. In addition to creating those objects, you need to delete them when the time comes. While automation can help, the proliferation of objects makes it easier to hide misconfigurations. The fewer objects, the better.

Any security that is too complicated to be easily tracked is more likely to create security holes. In this case, you may decide you’re going to cut down on the objects created by only creating one ClusterRole for impersonation and a single ClusterRoleBinding with multiple Subjects. This doesn’t really cut down on the complexity of managing this solution because:

  • You still have to manage a Subjects list that can grow very quickly
  • Your privileged users all now look to have the same identity as the API server, losing a considerable amount of granularity and value

It’s important to note that the API server does track and log who the original requestor was, but that’s now in a different field which your systems need to look for.

This additional work provides little, if any, benefit. You can’t effectively time-box access without some kind of additional automation, and just requiring the addition of a command-line parameter to kubectl isn’t likely to stop someone from hitting the up arrow to find the previous command they ran that has the --as parameter, even if they didn’t mean to.

This approach is more trouble than it’s worth. It won’t provide any meaningful security but will complicate your cluster’s management in ways that are more likely to create security holes than plug them.

Assuming you write your RBAC policies based on groups, the only thing you really need to do to escalate privileges is temporarily assign a user to a privileged group. The workflow would look similar to using a privileged account, but instead of having an entirely separate account, you use your standard account. As an example, in our current cluster, let’s assume that mmosley was NOT a member of the AD group cn=k8s-cluster-admins,ou=Groups,DC=domain,DC=com. An external workflow engine would add them after the approval of whatever work needs to be done. Once provisioned, mmosley performs their tasks, and when completed, their membership to cn=k8s-cluster-admins,ou=Groups,DC=domain,DC=com is revoked.

This gives us the same benefits of having a privileged account, without having to have an additional account to manage. There are multiple risks associated with this approach:

  • Phishing: If you’re using your standard account that’s used for everyday tasks like email, then there’s a higher risk that your credentials will be stolen.
  • Overstaying your welcome: A long-lived credential, such as a token or a certificate, may grant access beyond when policy dictates that access has expired.

To combat these risks, it’s important that privileged users are:

  • Required to re-authenticate: Making sure that the administrator has to re-enter credentials helps protect against malicious scripts and executables.
  • Use multi-factor authentication: Requiring an admin to provide a second factor, preferably one that can’t be phished, will protect against most attacks.
  • Use short-lived tokens: What’s the point of a four-hour change window if your token is good for eight hours?

With these additional mitigations in place, privileged authorization puts the least amount of work on cluster owners because everything is externalized. Just authorize by group!

While this provides the best user experience, most large enterprises are likely to have a privileged access manager already, making that the most likely approach.

Having walked through multiple ways of authenticating users who interact with our clusters, the next step is to look at how pipelines and automation need to authenticate.

This chapter so far has focused exclusively on authentication to Kubernetes by users. Whether an operator or a developer, a user will often interact with a cluster to update objects, debug issues, view logs, and so on. However, this doesn’t quite handle all use cases. Most Kubernetes deployments are partnered with pipelines, a process by which code is moved from source to binaries to containers and, ultimately, into a running cluster. We’ll cover pipelines in more detail in Chapter 18, Provisioning a Multitenant Platform. For now, the main question is, “ How will your pipeline talk to Kubernetes securely?”

If your pipeline runs in the same cluster that is being updated, this is a simple question to answer. You would grant access to the pipeline’s service account via RBAC to do what it needs to do. This is why service accounts exist – to provide identities to processes inside the cluster.

What if your pipeline runs outside of the cluster? Kubernetes is an API, and all the options presented in this chapter apply to a pipeline as they would to a user. Legacy service account tokens don’t provide an expiration and can easily be abused. The TokenRequest API could give you a short-lived token, but you still need to be authenticated to get it. If your cluster runs on the same cloud provider as your pipeline, you may be able to use its integrated IAM system. For instance, you can generate an IAM role in Amazon CodeBuild that can talk to an EKS cluster without having a static service account. The same is true for Azure DevOps and AKS.

If a cloud’s IAM capabilities won’t cover your needs, there are three options. The first is to dynamically generate a token for a pipeline the same way you would for a user, by authenticating to an identity provider and then using the returned id_token with your API calls. The second is to generate a certificate that can be used with your API server. Finally, you can leverage impersonation to authenticate your pipeline’s token. Let’s look at all three options and see how our pipelines can use them.

Kubernetes doesn’t distinguish between an API call from a human or a pipeline. A short-lived token is a great way to interact with your API server as a pipeline, given the risks we have provided throughout this chapter of potentially losing a token. Most of the client SDKs for Kubernetes know how to refresh these tokens. The biggest issue is, how do you get a token your pipeline can use?

Most enterprises already have some kind of service account management system. Here, the term “service account” is generic and means an account used by a service of some kind, instead of being the ServiceAccount object in Kubernetes. These service account management systems often have their own way of handling tasks, such as credential rotation and authorization management. They also have their own compliance tools, making it easier to get through your security review processes!

Assuming that you have an enterprise service account for your pipeline, how do you translate that credential into a token? We generate tokens based on credentials in our OIDC integrated identity provider; it would be great to use that from our pipelines too! With OpenUnison, this is pretty easy because the page that gave us our token is just a frontend for an API. The next question to answer is how to authenticate to OpenUnison. We could write some code to simulate a browser and reverse-engineer the login process, but that’s just ugly. And if the form changes, our code will break. It would be better to configure the API to authenticate with something that is more API-friendly, such as HTTP Basic authentication.

OpenUnison can be extended by creating configuration custom resources. In fact, most of OpenUnison is configured using these custom resources. The current token service assumes you are authenticating using the default OpenUnison form login mechanism, instead of a basic authentication that would be helpful from a pipeline. In order to tell OpenUnison to support API authentication, we need to tell it to:

  • Enable authentication via HTTP Basic authentication by defining an authentication mechanism
  • Create an authentication chain that uses the basic authentication mechanism to complete the authentication process
  • Define an application that can provide the token API, authenticating using the newly created chain

We won’t go through the details of how to make this work in OpenUnison, instead focusing on the end results. The chapter6 folder contains a Helm chart that was created for you to configure this API. Run it using the same openunison-values.yaml file you used to deploy OpenUnison:

cd chapter6/pipelines
helm install orchestra-token-api token-login -n openunison -f /tmp/openunison-values.yaml
NAME: orchestra-token-api
LAST DEPLOYED: Mon Jul 24 18:47:04 2023
NAMESPACE: openunison
STATUS: deployed
REVISION: 1
TEST SUITE: None

Once deployed, we can test it using curl:

$ export KUBE_AZ=$(curl --insecure -u 'pipeline_svc_account:start123' \
https://k8sou.apps.192-168-2-114.nip.io/k8s-api-token/token/user\
| jq -r '.token.id_token')
curl --insecure -H "Authorization: Bearer $KUBE_AZ" https://k8sapi.apps.192-168-2-114.nip.io/api
{
"kind": "APIVersions",
"versions": [
"v1"
],
"serverAddressByClientCIDRs": [
{
"clientCIDR": "0.0.0.0/0",
"serverAddress": "172.18.0.2:6443"
}
]
}

If you’re using direct integration with OpenID Connect, replace k8sapi.apps.192-168-2-114.nip.io with 0.0.0.0:6443 to run the curl command directly against the API server.

Now, wait a minute or two and try the curl command again, and you’ll see that you’re not authenticated anymore. This example is great if you’re running a single command, but most pipelines run multiple steps, and a single token’s lifetime isn’t enough. We could write code to make use of the refresh_token, but most of the SDKs will do that for us. Instead of getting just the id_token, let’s generate an entire kubectl configuration:

$ export KUBECONFIG=$(mktemp)
$ kubectl get nodes
The connection to the server localhost:8080 was refused – did you specify the right host or port?
curl --insecure -u 'pipeline_svc_account:start123' https://k8sou.apps.192-168-2-114.nip.io/k8s-api-token/token/user 2>/dev/null | jq -r '.token["kubectl Command"]' | bash
Cluster "impersonation" set.
Context "impersonation" created.
User "pipelinex-95-xsvcx-95-xaccount@impersonation" set.
Switched to context "impersonation".
$ kubectl get nodes
NAME STATUS ROLES AGE VERSION
cluster01-control-plane Ready control-plane 130m v1.27.3
cluster01-worker Ready <none> 129m v1.27.3

We’re getting a short-lived token securely, while also interacting with the API server using our standard tools! This solution only works if your service accounts are stored and accessed via an LDAP directory. If that’s not the case, you can extend OpenUnison’s configuration to support any number of configuration options. To learn more, visit OpenUnison’s documentation at https://openunison.github.io/.

This solution is specific to OpenUnison because there is no standard to convert a user’s credentials into an id_token. That is a detail left to each identity provider. Your identity provider may have an API to generate an id_token easily, but it’s more likely you’ll need something to act as a broker, since an identity provider won’t know how to generate a full kubectl configuration.

The preceding process works well but requires OpenUnison or something similar. If you wanted to take a vendor-neutral approach, you could use certificates as your credential instead of trying to generate a token. Earlier in the chapter, I said that certificate authentication should be avoided for users because of Kubernetes’ lack of revocation support and the fact that most certificates aren’t deployed correctly. Both of these issues are generally easier to mitigate with pipelines because the deployment can be automated.

If your enterprise requires you to use a central store for service accounts, this approach may not be possible. Another potential issue with this approach is that you may want to use an enterprise CA to generate the certificates for service accounts, but Kubernetes doesn’t know how to trust third-party CAs. There are active discussions about enabling the feature, but it’s not there yet.

Finally, you can’t generate certificates for many managed clusters. Most managed Kubernetes distributions, such as EKS, do not make the private keys needed to sign requests via the built-in API available to clusters directly. In that case, you’ll be unable to mint certificates that will be accepted by your cluster.

With all that said, let’s walk through the process:

  1. First, we’ll generate a keypair and certificate signing request (CSR):
    $ openssl req -out sa_cert.csr \
    -new -newkey rsa:2048 -nodes -keyout sa_cert.key \
    -subj '/O=k8s/O=sa-cluster-admins/CN=sa-cert/'
    Generating a RSA private key
    ..........+++++
    .................................+++++
    writing new private key to 'sa_cert.key'
    -----
  2. Next, we’ll submit the CSR to Kubernetes:
    $ cat <<EOF | kubectl apply -f -
    apiVersion: certificates.k8s.io/v1
    kind: CertificateSigningRequest
    metadata:
    name: sa-cert
    spec:
    request: $(cat sa_cert.csr | base64 | tr -d '\n')
    signerName: kubernetes.io/kube-apiserver-client
    usages:
    - digital signature
    - key encipherment
    - client auth
    EOF
  3. Once the CSR is submitted to Kubernetes, we need to approve the submission:
    $ kubectl certificate approve sa-cert
    certificatesigningrequest.certificates.k8s.io/sa-cert approved
  4. After being approved, we download the minted certificate into a pem file:
    $ kubectl get csr sa-cert -o jsonpath='{.status.certificate}' | base64 --decode > sa_cert.crt
  5. Next, we’ll configure kubectl to use our newly approved certificate:
    $ cp ~/.kube/config ./sa-config
    $export KUBECONFIG=./sa-config
    $ kubectl config set-credentials kind-cluster01 --client-key=./sa_cert.key \
    --client-certificate=./sa_cert.crt
    $ kubectl get nodes
    Error from server (Forbidden): nodes is forbidden: User "sa-cert" cannot list resource "nodes" in API group "" at the cluster scope

The API server has accepted our certificate but has not authorized it. Our CSR had an o in the subject called sa-cluster-admins, which Kubernetes translates to “the user sa-cert is in the group sa-cluster-admins.” We need to authorize that group to be a cluster admin next:

$ export KUBECONFIG=
$ kubectl create -f chapter6/pipelines/sa-cluster-admins.yaml
$ export KUBECONFIG=./sa-config
$ kubectl get nodes
NAME STATUS ROLES AGE VERSION
cluster01-control-plane Ready control-plane 138m v1.27.3
cluster01-worker Ready <none> 138m v1.27.3

You now have a key pair that can be used from your pipelines with your cluster! Beware while automating this process. The CSR submitted to the API server can set any groups it wants, including system:masters. If a certificate is minted with system:masters as an o in the subject, it will not only be able to do anything on your cluster; it will also bypass all RBAC authorization. In fact, it will bypass all authorization!

If you’re going to go down the certificate route, think about potential alternatives, such as using certificates with your identity provider instead of going directly to the API server. This is similar to our token-based authentication, but instead of using a username and password in HTTP Basic authentication, you use a certificate. This gives you a strong credential that can be issued by your enterprise certificate authority while avoiding having to use passwords.

Next, we’ll explore how to authenticate a pipeline using its own identity.

Over the last year or two, discussions about increased supply chain security have become a front-and-center topic for Kubernetes and security professionals. Part of that discussion has led to more pipeline systems providing unique identities to workflows that can be used to interact with remote systems, such as a Kubernetes cluster. This offers the best approach because each workflow is unique, and it can have a short-lived token that doesn’t require a shared secret between the Kubernetes cluster and the workflow.

The challenge with using a workflow’s identity with a Kubernetes cluster is that a cluster can only accept a single OpenID Connect issuer, and managed clusters aren’t even capable of that. Earlier, we explored how your clusters can use impersonation to authenticate API requests to your cluster without enabling OpenID Connect directly in the API server flags. It turns out that this approach works well with CI/CD pipelines too. Instead of configuring your impersonating proxy to trust the identity provider that issues tokens for your users, you can configure it to trust the identity provider that issues tokens for your workflows.

We’ll demonstrate this using the CI/CD Proxy (https://cicd-proxy.github.io). This is a collection of Helm charts that Tremolo Security built around the kube-oidc-proxy project to simplify integration with pipelines. The kube-oidc-proxy was created by JetStack, but development ended in early 2021. Tremolo Security forked the project, adding several features, and has since kept it up to date with dependencies and bug fixes as needed. If you ran the lab to deploy authentication with impersonation earlier in this chapter, you’ve already run Tremolo’s kube-oidc-proxy. The OpenUnison Helm charts automate its integration for you.

We’re going to simulate a workflow deleting some pods in our cluster using the CI/CD Proxy. While we’ll be working with GitLab later in the book, that’s a very heavy deployment just to show how pipelines can securely authenticate. To simulate our workflow, we’re going to run a simple Job that will have a token mounted via the TokenRequest API, with our CI/CD proxy as the audience, instead of the API server. Our CI/CD proxy will then impersonate the ServiceAccount in the projected token’s sub-claim, which will be allowed to delete pods in our namespace. The CI/CD proxy will be configured to trust our cluster’s OIDC discovery URL, completing the circle of trust. Let’s walk through how these trusts come together.

Figure 6.10: Workflow authentication sequence

The above diagram shows the following sequence of events:

  1. When the CI/CD proxy starts, it reaches out to the cluster’s OIDC discovery document to pull in the correct keys to validate inbound tokens. Since we’re trusting our own cluster’s tokens, we’re using https://kubernetes.default.svc.cluster.local/ as our issuer, so we’ll pull in https://kubernetes.default.svc.cluster.local/.well-known/openid-configuration.
  2. When our workflow Job starts, it will have a token projected into it that will have our CI/CD proxy as an audience. This is in addition to the ServiceAccount token that every pod is provided by default. If we inspect this token, we’ll see how it differs from the standard token. Figure 6.11: Comparing tokens

The above image is a side-by-side comparison of the typical ServiceAccount token on the left and a token meant for the CI/CD proxy on the right. Both are bound to the specific pod, but the left-hand side is meant for the API server where whereas the right-hand token is meant for our proxy. They can’t be used interchangeably, even though they’re signed by the same set of keys and have the same issuer. If you try to use the token on the right with the API server, it will be rejected for having an invalid audience. The same would be true if you tried to use the token on the left with our proxy. The other major difference between the two tokens is that the expiration of the token on the right is only 10 minutes after creation. This means that if an attacker were to get access to this token, they’d only have 10 minutes to use it, increasing the security of the token.

  1. Once our Job makes a call using kubectl to our proxy, not directly to an API server, the proxy checks the token to make sure it was signed correctly and built correctly. The proxy then forwards the request to the API server but with its own token and the addition of the impersonation headers.
  2. Finally, the API server acts on the request as if it were made by our Job.

Throughout this transaction, there are no shared secrets that need to be distributed or rotated. There’s very little that can be compromised. Since the OIDC discovery document is controlled by our identity provider, if the keys need to be rotated, our proxy will pick it up. Having walked through the theory, let’s deploy our example.

First, start with a fresh cluster:

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

Once the cluster is created, let’s deploy the CI/CD proxy. We didn’t want to get bogged down with specific steps, so we automated the deployment:

cd ../chapter6/pipelines/cicd-proxy
./deploy-proxy.sh

This script will take a minute or two to run. It does a few things:

  1. Deploys the cert-manager project from JetStack and creates an internal CA that we’ll use to sign certificates
  2. Enables anonymous access to the API server’s OIDC discovery document
  3. Deploys the CI/CD proxy using Tremolo Security’s Helm charts
  4. Creates a target namespace and Deployment we can use to test deleting pods in
  5. Creates an RBAC binding for our impersonated user to be able to list and delete pods in our target namespace

Once everything is deployed, the next step is to create our Job and check the logs:

./run_workflow.sh
kubectl logs -l job-name=workflow -n cicd-ns
User "remote" set.
Context "remote" created.
Switched to context "remote".
pod "test-pods-777b69dc55-4bmwd" deleted

We can see that we were able to delete our pods, using the projected token!

This seems like quite a bit of work just to delete a Pod. It might have been easier to just create a ServiceAccount token and store it somewhere our workflow could access it. However, that would be a security and Kubernetes anti-pattern. It means that so long as the pod exists in the cluster’s etcd database, it could be used without restriction. You could create a rotation system, but just like with custom authentication, you’re now creating a pale imitation of OpenID Connect’s existing security. You’re also building out additional automation that also needs to be secured. So what looks like quite a bit of additional work will actually save you time and make your security team happy!

Having discussed how to properly authenticate to your cluster from your pipeline, let’s examine some anti-patterns with pipeline authentication.

It turns out most of the anti-patterns that apply to user authentication also apply to pipeline authentication. Given the nature of code which authenticates, there are some specific things to look out for.

First, don’t use a person’s account for a pipeline. It will likely violate your enterprise’s policies and can expose your account, and maybe your employer, to issues. Your enterprise account (which is assigned to everyone else in the enterprise) generally has several rules attached to it. Simply using it in code can breach these rules. The other anti-patterns we’ll discuss add to the risk.

Next, never put your service account’s credentials into Git, even when encrypted. It’s popular to include credentials directly in objects stored in Git because you now have change control, but it’s just so easy to accidentally push a Git repository out to a public space. Much of security is about protecting users from accidents that can leak sensitive information. Even encrypted credentials in Git can be abused if the encryption keys are also stored in Git. Every cloud provider has a secret management system that will synchronize your credentials into Kubernetes Secret objects. You can do this with Vault as well, which we’ll do later in this book. This is a much better approach, as these tools are specifically designed to manage sensitive data. Git is meant to make it easy to share and collaborate, which makes for poor secret management.

Finally, don’t use legacy service account tokens from outside of your cluster. I know that I’ve said this a dozen times in this chapter, but it’s incredibly important. When using a bearer token, anything that carries that token is a potential attack vector. There have been network providers that leak tokens, for example. It’s a common anti-pattern. If a vendor tells you to generate a service account token, push back – you’re putting your enterprise’s data at risk.

This chapter detailed how Kubernetes identifies users and what groups their members are in. We detailed how the API server interacts with identities and explored several options for authentication. Finally, we detailed the OpenID Connect protocol and how it’s applied to Kubernetes.

Learning how Kubernetes authenticates users and the details of the OpenID Connect protocol is an important part of building security in a cluster. Understanding the details and how they apply to common enterprise requirements will help you decide the best way to authenticate to clusters, and also provide justification regarding why the anti-patterns we explored should be avoided.

In the next chapter, we’ll apply our authentication process to authorizing access to Kubernetes resources. Knowing who somebody is isn’t enough to secure your clusters. You also need to control what they have access to.

  1. OpenID Connect is a standard protocol with extensive peer review and usage.
    1. True 2. False
  2. Which token does Kubernetes use to authorize your access to an API?
    1. access_token 2. id_token 3. refresh_token 4. certificate_token
  3. In which situation is certificate authentication a good idea?
    1. Day-to-day usage by administrators and developers 2. Access from external CI/CD pipelines and other services 3. Break glass in case of emergency, when all other authentication solutions are unavailable
  4. How should you identify users accessing your cluster?
    1. Email address 2. Unix login ID 3. Windows login ID 4. An immutable ID not based on a user’s name
  5. Where are OpenID Connect configuration options set in Kubernetes?
    1. Depends on the distribution 2. In a ConfigMap object 3. In a secret 4. Set as flags on the Kubernetes API server executable
  6. When using Impersonation with your cluster, the groups your user brings are the only ones needed.
    1. True 2. False
  7. The dashboard should have its own privileged identity to work properly.
    1. True 2. False
  1. a: True
  2. b: id_token
  3. c: Break glass in case of emergency, when all other authentication solutions are unavailable
  4. d: An immutable ID not based on a user’s name
  5. d: Set as flags on the Kubernetes API server executable
  6. b: False
  7. b: False