Skip to content
LF Cert Trainer

Lesson 68 · Section 7: Security

Lesson 68: Security introduction: who may do what in a cluster

A map of Kubernetes security before the detailed lessons: what there is to protect, the three gates every API request passes, what a Pod may do by default, and which lesson of this section tightens each part. · 12 min read · 3 min video

1/9Security
0:00 / 3:25

Narrated by the local narrator voice. Keys: Space plays and pauses, J and L step, C captions, F full screen.

Why this section exists

Until now you have worked as kubernetes-admin, the identity in the kubeconfig file that kubeadm writes. That identity may do anything, so nothing has ever been refused. A real cluster is shared: by colleagues who should only touch their own namespace, by CI pipelines, by the controllers of the control plane, and by every Pod that runs in it. Some of the applications in those Pods will have bugs that an attacker can use.

Security in Kubernetes is the set of answers to four questions:

  1. Who is making this request? (authentication)
  2. Is that identity allowed to do what it asks? (authorization, then admission)
  3. Can anyone read or change the traffic on the way? (TLS)
  4. Once a container runs, what can it reach and what can it break? (workload security)

This lesson is the map. It shows where each control sits and why it exists, so that the detailed lessons that follow have a place to land. It contains only a few commands, and all of them are for looking.

What there is to protect

What there is to protectTLSTLSTLS, client certrunsstartsUsers and toolskubectl, CI, Podskube-apiserverport 6443etcdport 2379, all dataNode (the host)SSH keys, rootkubeletport 10250Podsyour containers
What there is to protect. Four doors lead into a cluster: the API server, etcd, the kubelet on every node, and the nodes themselves. All of them listen on the network, so all of them need TLS and a check of who is calling.

Parts:

  • Users and tools (kubectl, CI, Pods)
  • kube-apiserver (port 6443)
  • etcd (port 2379, all data)
  • Node (the host) (SSH keys, root)
  • kubelet (port 10250)
  • Pods (your containers)

Connections:

  • Users and tools to kube-apiserver: TLS
  • kube-apiserver to etcd: TLS
  • kube-apiserver to kubelet: TLS, client cert
  • Node (the host) to kubelet: runs
  • kubelet to Pods: starts

A cluster has four doors, and each one listens on the network.

DoorWhy it mattersHow it is protected
kube-apiserver (port 6443)The only way to read or change cluster state. Whoever controls it controls the clusterTLS, authentication, authorization, admission
etcd (port 2379)Holds every object, including every Secret. Reading etcd bypasses all API checksReachable only from the control plane, client certificates required, optional encryption of Secrets at rest
kubelet (port 10250)Can run commands in, and read the logs of, any container on its nodeTLS, anonymous access off, every call is checked with the API server
The node itselfRoot on a node can read every Pod's files and Secrets on that machine, and the kubelet's own credentialsOutside Kubernetes: SSH with keys only, no shared root password, a patched operating system, a firewall

The last row is easy to forget. Kubernetes cannot defend a host that lets anyone log in as root. On a control plane node the stakes are highest: the folder /etc/kubernetes/pki holds the private key of the cluster's certificate authority, and whoever has it can issue themselves a certificate for any identity.

How a request is checked

Every API request passes three gatesTLSknownallowedvalidunknown: 401Requestkubectl, Pod, kubeletAuthenticationWho are you?AuthorizationMay you do this?AdmissionIs the object OK?etcdchange is storedRejected401 or 403
Every API request passes three gates. The API server asks the same three questions about every request, in this order. Only a request that passes all three is stored in etcd.

Parts:

  • Request (kubectl, Pod, kubelet)
  • Authentication (Who are you?)
  • Authorization (May you do this?)
  • Admission (Is the object OK?)
  • etcd (change is stored)
  • Rejected (401 or 403)

Connections:

  • Request to Authentication: TLS
  • Authentication to Authorization: known
  • Authorization to Admission: allowed
  • Admission to etcd: valid
  • Authentication to Rejected: unknown: 401

Every request reaches the API server over TLS, so it is encrypted and the client knows it is talking to the real server. Then three stages run in a fixed order.

StageQuestionTypical mechanismsWhen it says no
AuthenticationWho are you?Client certificates, ServiceAccount tokens, OpenID Connect tokens401 Unauthorized
AuthorizationMay this identity do this verb on this resource?Node and RBAC authorizers (the kubeadm default is --authorization-mode=Node,RBAC)403 Forbidden, with the user, verb and resource in the message
AdmissionIs the object itself acceptable?Admission controllers such as NodeRestriction and Pod Security, plus webhooks and policies403 Forbidden, with the name of the plugin or policy in the message

A few properties of this pipeline explain a lot of what you will see later:

  • Authentication produces a name and groups, nothing more. The result is a username such as jane and a list of groups such as developers. No permissions are attached at this stage.
  • Kubernetes has no user objects. There is no kubectl create user. A human is whoever holds a certificate signed by the cluster's CA (the username is the certificate's common name, the groups are its organisations), or a token from an identity provider the API server trusts. Only ServiceAccounts, the identities for Pods, are objects in the API.
  • Authorization is deny by default. With RBAC, an identity may do only what some Role or ClusterRole grants it. There are no "deny" rules to write; you simply do not grant.
  • Admission only runs for requests that create, change or delete something (and for exec and similar connections). A get or list stops after authorization. You met admission controllers in the Scheduling section; here they return as the place where Pod security rules are enforced.
Under the hood · What happens to a request with no credentials?

On a kubeadm cluster a request without any credentials is not rejected at the first gate. It is given the username system:anonymous and the group system:unauthenticated, and passed on to authorization. RBAC then refuses almost everything, which is why you see 403 Forbidden and not 401:

"message": "pods is forbidden: User \"system:anonymous\" cannot list resource \"pods\" in API group \"\" at the cluster scope"

A small set of paths is deliberately open to anonymous callers, such as /healthz, /livez, /readyz and /version, so that load balancers and probes can check the server. A request that does present credentials, but wrong ones (an expired certificate, a token that does not verify), gets 401 Unauthorized.

Anonymous access is controlled by the API server flag --anonymous-auth, or more precisely by an AuthenticationConfiguration file that can limit it to the health paths only.

The components authenticate too

The gates are not only for people. The scheduler, the controller manager, every kubelet and kube-proxy are clients of the API server, and each has its own certificate and its own identity: system:kube-scheduler, system:kube-controller-manager, system:node:<node name>. Each is granted just the permissions its job needs. The Node authorizer and the NodeRestriction admission plugin together make sure a kubelet can only read the Secrets of Pods scheduled to its own node and only modify its own Node object, so one compromised node does not expose the whole cluster.

In the other direction, the API server is itself a client of etcd and of each kubelet, again with a client certificate. That is why a kubeadm cluster carries a whole folder of certificates, and why five lessons of this section are about TLS.

What a Pod may do by default

A request that passes the gates can start a Pod. What that Pod is then allowed to do is a separate question, and the defaults are generous.

What a Pod may do by default, and what limits itidentityopenshared kernellimitslimitslimitsNew Podno settings at allAPI servertoken is mountedOther Podsany Pod, any portNode kerneloften runs as rootRBACServiceAccount rightsNetworkPolicyallowed trafficsecurityContextuser, capabilities
What a Pod may do by default, and what limits it. A new Pod gets an identity for the API, an open network and, unless the image says otherwise, a root process. Each default has its own control in this section.

Parts:

  • New Pod (no settings at all)
  • API server (token is mounted)
  • Other Pods (any Pod, any port)
  • Node kernel (often runs as root)
  • RBAC (ServiceAccount rights)
  • NetworkPolicy (allowed traffic)
  • securityContext (user, capabilities)

Connections:

  • New Pod to API server: identity
  • New Pod to Other Pods: open
  • New Pod to Node kernel: shared kernel
  • RBAC to API server: limits
  • NetworkPolicy to Other Pods: limits
  • securityContext to Node kernel: limits
DefaultWhat it meansThe controlLesson
A ServiceAccount token is mounted in every PodCode in the Pod can call the API server as system:serviceaccount:<namespace>:defaultGive ServiceAccounts only the RBAC rights they need; turn the mount off where the API is not usedService Accounts, Role Based Access Controls
All Pods can reach all PodsOne compromised Pod can connect to every database in the clusterNetworkPolicyNetwork Policy, Developing Network Policies
The container runs as the image's user, often rootRoot in a container shares the node's kernel; with extra privileges it can reach the hostsecurityContext: run as a non-root user, drop capabilitiesSecurity in Docker, Security Contexts
Any image from any registry is pulledYou run whatever the image name points toPrivate registries with pull SecretsImage Security
Secrets are only base64 encoded in etcdAnyone who can read etcd or get secrets reads themRBAC on Secrets, encryption at rest (covered in the Application Lifecycle section)Authorization

The principle behind every row is least privilege: give each user, each component and each Pod exactly what it needs for its job. Then a stolen credential or a hacked container is worth as little as possible.

The road through this section

LessonsTopicThe question it answers
Kubernetes Security Primitives, AuthenticationIdentitiesWho can call the API server, and how do they prove it?
TLS Introduction, TLS Basics, TLS in Kubernetes, Certificate Creation, View Certificate Details, Certificates APIEncryption and certificatesHow do components trust each other, where are the certificates, and how do you issue or renew one?
KubeConfigClient configurationHow does kubectl know which cluster, user and namespace to use?
Persistent Key/Value Store, API GroupsBackgroundWhere is the cluster's state kept, and how is the API organised into the groups that permissions refer to?
Authorization, Role Based Access Controls, Cluster Roles, Service AccountsPermissionsWhat may each user and each Pod do, in a namespace and across the cluster?
Image Security, Security in Docker, Security ContextsWorkloadsWhich images run, as which user, with which kernel privileges?
Network Policy, Developing Network PoliciesNetworkWhich Pods may talk to which?
Kubectx and KubensToolsHow do you switch contexts and namespaces quickly?
Custom Resource Definition, Custom Controllers, Operator FrameworkExtending the APIHow do you add your own resource types, and software that acts on them?

In the CKA curriculum these topics appear as "Manage role based access control (RBAC)", "Define and enforce Network Policies" and "Understand CRDs, install and configure operators". Certificates and kubeconfig files are not named there, but they sit underneath troubleshooting a control plane: an expired certificate or a wrong path in a kubeconfig is a common reason for a component that cannot reach the API server.

Using it

Nothing here changes the cluster. These are the commands for finding out how its security is set up.

Example · Ask the API server who you are and what you may do

kubectl auth whoami shows the result of the first gate: the username and groups the API server derived from your credentials.

kubectl auth whoami
ATTRIBUTE   VALUE
Username    kubernetes-admin
Groups      [kubeadm:cluster-admins system:authenticated]

kubectl auth can-i asks the second gate about one action. With --as you ask on behalf of someone else, which needs no password: your own right to impersonate is what is checked.

kubectl auth can-i delete nodes                                # yes
kubectl auth can-i create deployments --as jane -n dev         # no
kubectl auth can-i list secrets -n dev \
  --as system:serviceaccount:dev:default                       # no
kubectl auth can-i --list -n dev --as jane                     # everything jane may do in dev

A ServiceAccount's full username is system:serviceaccount:<namespace>:<name>. You will type it often.

Example · Watch each gate say no

Call the API server without credentials. The request passes authentication as system:anonymous and is stopped by authorization:

curl -k https://localhost:6443/api/v1/pods
"message": "pods is forbidden: User \"system:anonymous\" cannot list resource \"pods\" in API group \"\" at the cluster scope",
"reason": "Forbidden",
"code": 403

Now present a credential that cannot be verified. This time authentication itself fails:

curl -k -H "Authorization: Bearer not-a-real-token" https://localhost:6443/api/v1/pods
"message": "Unauthorized",
"reason": "Unauthorized",
"code": 401

The third gate also answers Forbidden, but the message names a policy and not a user. Here a namespace enforces the restricted Pod Security Standard, and a plain Pod does not meet it:

kubectl create namespace locked
kubectl label namespace locked pod-security.kubernetes.io/enforce=restricted
kubectl -n locked run web --image=nginx:1.29-alpine
Error from server (Forbidden): pods "web" is forbidden: violates PodSecurity "restricted:latest":
allowPrivilegeEscalation != false (container "web" must set securityContext.allowPrivilegeEscalation=false), ...

You were authenticated and authorized to create Pods there. Admission refused the object. Clean up with kubectl delete namespace locked.

Example · Read the security settings of a kubeadm cluster

The API server is a static Pod, and its flags are the cluster's security configuration. On the control plane node:

grep -E 'authorization-mode|client-ca-file|enable-admission|tls-cert-file|etcd-cafile|anonymous' \
  /etc/kubernetes/manifests/kube-apiserver.yaml
    - --authorization-mode=Node,RBAC
    - --client-ca-file=/etc/kubernetes/pki/ca.crt
    - --enable-admission-plugins=NodeRestriction
    - --etcd-cafile=/etc/kubernetes/pki/etcd/ca.crt
    - --tls-cert-file=/etc/kubernetes/pki/apiserver.crt

Read it as the three gates. --client-ca-file is authentication: a client certificate signed by this CA is accepted as proof of identity. --authorization-mode is authorization. --enable-admission-plugins adds to the admission controllers that are on by default. The certificates themselves are in one folder:

ls /etc/kubernetes/pki
kubeadm certs check-expiration

Example · See what a default Pod is given

Start a Pod with no security settings and look around inside it:

kubectl run probe --image=busybox:1.37 --command -- sleep 3600
kubectl exec probe -- id
kubectl exec probe -- ls /var/run/secrets/kubernetes.io/serviceaccount
kubectl auth can-i --list --as system:serviceaccount:default:default | head -n 5
uid=0(root) gid=0(root) groups=0(root),10(wheel)
ca.crt
namespace
token

The process is root, and a token for the default ServiceAccount is mounted next to the CA certificate it needs to call the API server. The last command shows that this identity can do little more than discover the API. From inside the Pod you could also connect to the IP of any other Pod in the cluster: until a NetworkPolicy selects a Pod, nothing filters its traffic. Clean up with kubectl delete pod probe.

Tricks

Common mistakes

  • Mixing up authentication and authorization. A valid certificate proves who you are and grants nothing. A new user with a perfect certificate still gets Forbidden on everything until a role is bound.
  • Looking for a User object. kubectl get users does not exist. Humans live in certificates or an external identity provider; only ServiceAccounts are stored in the cluster.
  • Reading every Forbidden as an RBAC problem. Check whether the message names a user and a verb (authorization) or a policy (admission) before you start writing Roles.
  • Assuming Pods are isolated from each other. Namespaces separate names and permissions, not network traffic. Without a NetworkPolicy, a Pod in dev can reach a Pod in prod.
  • Treating a Secret as encrypted. Base64 is an encoding. Anyone allowed to get the Secret, or to read etcd, has the value.
  • Securing the API and forgetting the node. Root on a control plane node can read the CA key and admin.conf. No RBAC rule protects against that.

Recap

  • Everything goes through the API server, and every request passes authentication, authorization and admission, in that order. 401 means the first gate, 403 the second or third.
  • Kubernetes stores no human users. Identity comes from certificates or tokens; ServiceAccounts are the identities of Pods.
  • Every connection between components uses TLS with certificates, kept in /etc/kubernetes/pki on a kubeadm cluster.
  • A Pod starts with an API token, an open network and often root. RBAC, NetworkPolicy and securityContext limit each of them.
  • Least privilege is the rule throughout, and kubectl auth whoami and kubectl auth can-i show what the cluster actually decided.

Official docs

Quiz: check what you learned

5 questions on this lesson · about 3 min · instant feedback. Missed questions come back in your review queue.

Sign in to take the quiz and keep your score.

Discussion

Learners ask and answer questions here. Sign in to read and join the discussion.