KUBERNETES · KCNA · CHAPTER 4

Orchestration Security

Who can get into the cluster, what they can do inside it, and who each pod can talk to.

15 min readKCNA domain: Container Orchestration (28%)Level: beginner

From point A to point B

Point A: you already deploy applications and know where the scheduler puts them, but anyone with access to the cluster could do anything, and any pod could talk to any other pod. Point B: by the end of this chapter you'll know how Kubernetes decides who gets in, what each person or application can do, and what traffic is allowed between pods.

Security is part of the Container Orchestration domain (28% of the KCNA exam). The exam won't ask you to configure everything by hand, but it does expect you to recognize each piece and what it's for.

What you'll cover
  1. Authentication, TLS certificates and kubeconfig
  2. Authorization with RBAC and ClusterRoles
  3. Service accounts for applications
  4. Private images and security contexts
  5. Network Policies for traffic between pods

The security primitives

Everything in Kubernetes goes through the kube-apiserver: kubectl, the scheduler, the controllers and every node's kubelet all talk to it. That's why the first line of defense is protecting it, and that comes down to two questions:

  • Who can get in? That's authentication: users with certificates, tokens or an external identity provider, and service accounts for machines.
  • What can they do? That's authorization: RBAC, Node mode, ABAC or an external webhook.

Two more layers add to that: all communication between components is encrypted with TLS, and traffic between pods can be restricted with Network Policies. Before all of this come the basics: you protect nodes like any other server, with no password access and SSH keys only.

How kube-apiserver checks a request A request from a user, kubectl or a service account reaches kube-apiserver. It goes through authentication (who are you?), authorization (are you allowed?) and admission control (does the object follow the rules?). Only then is it stored in etcd. A failure at any step stops the request. REQUEST kubectl · user service account controller 1 · AUTHN Who are you? client certificates bearer tokens OIDC 2 · AUTHZ Are you allowed? Node · RBAC Webhook · ABAC 3 · ADMISSION Is the object OK? validate mutate ETCD stored fail → 401 Unauthorized fail → 403 Forbidden fail → rejected

Every request goes through authentication, authorization and admission control before it's stored in etcd. Diagram: The House of Routing.

The third step, admission control, checks the incoming object: it can reject it (for example, an image without a pinned version) or modify it (for example, add default values). You'll see it in more detail when you study policies.

Authentication: who are you?

Kubernetes distinguishes two kinds of accounts:

  • Users: people, such as administrators and developers. Kubernetes doesn't manage them: there's no User object and no kubectl create user command. Identities come from outside, from a certificate or from a provider such as a corporate directory.
  • Service accounts: for applications and processes. These are Kubernetes objects, and you'll see them further down.

Every authentication request is handled by the kube-apiserver, which supports several mechanisms:

MechanismHow it worksUse
Client certificatesThe user presents a certificate signed by the cluster CAThe most common in kubeadm clusters
TokensA token in the Authorization: Bearer headerService accounts and automation
OIDCAn external identity provider issues the tokenCompanies with single sign-on
Static token fileA list of tokens in a file on the API serverEasy but not recommended
# A user authenticates to kube-apiserver with a client certificate
curl https://kube-apiserver:6443/api/v1/pods \
  --cacert ca.crt --cert jane.crt --key jane.key

# kubectl does the same, reading those details from the kubeconfig
kubectl get pods --kubeconfig ~/.kube/config
Watch out. The static password file (basic authentication) no longer exists: it was removed in Kubernetes 1.19. The token file is still available, but it stores secrets in plain text and you have to restart the API server for every change.

TLS certificates

In a cluster, everyone identifies themselves with certificates. There are three kinds:

  • The certificate authority (CA): signs all the others. Its ca.crt and ca.key pair is the most valuable thing in the cluster.
  • Server certificates: the kube-apiserver, etcd and the kubelet present them to prove who they are.
  • Client certificates: used by administrators, the scheduler, the controller manager, kube-proxy and the API server itself when it talks to etcd or the kubelet.

In a user's certificate, the CN field is their name and the O field is their group. Kubernetes uses those two values later to decide what permissions they have.

# Private key and signing request (CSR) for user jane, group dev
openssl genrsa -out jane.key 2048
openssl req -new -key jane.key -subj "/CN=jane/O=dev" -out jane.csr

# Inspect a cluster certificate (kubeadm keeps them here)
openssl x509 -in /etc/kubernetes/pki/apiserver.crt -text -noout
kubeadm certs check-expiration

Instead of signing by hand with the CA, you can ask the cluster itself to sign, using the certificates API. An administrator reviews the request and approves it:

apiVersion: certificates.k8s.io/v1
kind: CertificateSigningRequest
metadata:
  name: jane
spec:
  request: <base64 of jane.csr>
  signerName: kubernetes.io/kube-apiserver-client
  expirationSeconds: 86400
  usages:
    - client auth
kubectl get csr
kubectl certificate approve jane
kubectl get csr jane -o jsonpath='{.status.certificate}' | base64 -d > jane.crt
Useful fact. With kubeadm, certificates live in /etc/kubernetes/pki/ and expire after one year. kubeadm certs check-expiration tells you when, and it's one of the first things you check if the API server stops responding.

The kubeconfig file

Typing the server, the CA, the certificate and the key in every command would be impossible. kubectl reads them from a kubeconfig file, ~/.kube/config by default, which has three lists:

  • clusters: where each API server is and which CA to trust.
  • users: the credentials you present.
  • contexts: combinations of a cluster and a user, with an optional namespace. current-context says which one kubectl uses.
Inside a kubeconfig file A kubeconfig file has three lists. Clusters say where the API server is and which CA to trust. Users hold the credentials. A context joins one cluster, one user and an optional namespace; current-context picks the one kubectl uses. CLUSTERS production server: https://…:6443 certificate-authority USERS jane client-certificate client-key CONTEXTS jane@production cluster + user namespace: dev current-context: jane@production kubectl config use-context switches between contexts

A context ties together a cluster, a user and a namespace. Diagram: The House of Routing.

apiVersion: v1
kind: Config
current-context: jane@production
clusters:
  - name: production
    cluster:
      server: https://203.0.113.10:6443
      certificate-authority: /etc/kubernetes/pki/ca.crt
users:
  - name: jane
    user:
      client-certificate: /home/jane/.kube/jane.crt
      client-key: /home/jane/.kube/jane.key
contexts:
  - name: jane@production
    context:
      cluster: production
      user: jane
      namespace: dev
kubectl config view
kubectl config get-contexts
kubectl config use-context jane@production
kubectl config set-context --current --namespace=dev

A kubeconfig doesn't create users or grant permissions: it only says which credentials you connect with. What you can do after that is decided by authorization.

API groups

Before granting permissions, it helps to know how the API is organized, because permissions are written in its terms. There are two kinds of groups:

  • The core group, at /api/v1: pods, services, namespaces, nodes, configmaps, secrets, serviceaccounts…
  • The named groups, at /apis/<group>/<version>: apps (deployments, replicasets, daemonsets), networking.k8s.io (networkpolicies, ingresses), rbac.authorization.k8s.io (roles, rolebindings)…

Each group contains resources, and verbs apply to each resource: get, list, watch, create, update, patch and delete.

kubectl api-resources            # resource, version and API group
kubectl api-versions             # available groups and versions
kubectl explain deployment       # GROUP: apps, VERSION: v1

Authorization: what can you do?

Once the API server knows who you are, it decides what you can do. The golden rule is the principle of least privilege: each person and each application gets only the permissions it needs, and nothing more.

ModeWhat it does
NodeAuthorizes each kubelet to read and write only what relates to its own node
RBACPermissions grouped into roles that are assigned to users, groups or service accounts. It's the standard
ABACA per-user policy in a JSON file. Hard to maintain: every change means editing the file and restarting the API server
WebhookDelegates the decision to an external service, such as Open Policy Agent (OPA)
AlwaysAllow / AlwaysDenyAllow or deny everything. For testing only

Modes are enabled with the API server's --authorization-mode option; kubeadm uses Node,RBAC. They're checked in order: the first one that approves or denies decides, and if none has an opinion, the request is rejected.

RBAC: Roles and RoleBindings

With RBAC you don't give permissions to a person, but to a role. Then you assign the role to whoever needs it. If you change the role, the change reaches everyone who has it.

Step 1: the Role lists the rules. Each rule combines API groups, resources and verbs, and optionally specific names with resourceNames:

apiVersion: rbac.authorization.k8s.io/v1
kind: Role
metadata:
  name: developer
  namespace: dev
rules:
  - apiGroups: [""]               # "" is the core group
    resources: ["pods"]
    verbs: ["get", "list", "create", "delete"]
  - apiGroups: [""]
    resources: ["configmaps"]
    resourceNames: ["web-config"] # only this object
    verbs: ["get", "update"]

Step 2: the RoleBinding ties the role to the subjects: users, groups or service accounts.

apiVersion: rbac.authorization.k8s.io/v1
kind: RoleBinding
metadata:
  name: jane-developer
  namespace: dev
subjects:
  - kind: User
    name: jane
    apiGroup: rbac.authorization.k8s.io
roleRef:
  kind: Role
  name: developer
  apiGroup: rbac.authorization.k8s.io
RBAC: roles and bindings Inside the dev namespace, the Role developer lists what can be done: verbs on resources. The RoleBinding links that role to subjects: the user jane, a group or a service account. Outside any namespace, a ClusterRole and a ClusterRoleBinding do the same for the whole cluster, for example to read nodes. NAMESPACE · dev ROLE · developer pods: get list create delete configmaps/web-config: get update ROLEBINDING jane-developer SUBJECTS User · jane Group · dev ServiceAccount · ci CLUSTER-WIDE CLUSTERROLE node-reader CLUSTERROLEBINDING ops-node-reader SUBJECTS Group · ops

The Role says what can be done; the RoleBinding says who. Diagram: The House of Routing.

To check permissions, kubectl auth can-i answers yes or no. With --as, an administrator can test someone else's permissions without knowing their credentials:

kubectl get roles,rolebindings -n dev
kubectl describe role developer -n dev
kubectl auth can-i create deployments
kubectl auth can-i delete pods --as jane -n dev
kubectl auth can-i list nodes --as jane
Remember. RBAC only adds permissions: there are no "deny" rules. Anything not explicitly allowed is forbidden.

ClusterRoles

A Role and its RoleBinding live inside a namespace. But some resources don't belong to any namespace: nodes, namespaces, persistentvolumes or clusterroles themselves. For those, and to grant permissions across all namespaces at once, there are the ClusterRole and the ClusterRoleBinding.

kubectl api-resources --namespaced=true    # pods, services, roles…
kubectl api-resources --namespaced=false   # nodes, namespaces, clusterroles…
apiVersion: rbac.authorization.k8s.io/v1
kind: ClusterRole
metadata:
  name: node-reader
rules:
  - apiGroups: [""]
    resources: ["nodes"]
    verbs: ["get", "list", "watch"]
---
apiVersion: rbac.authorization.k8s.io/v1
kind: ClusterRoleBinding
metadata:
  name: ops-node-reader
subjects:
  - kind: Group
    name: ops
    apiGroup: rbac.authorization.k8s.io
roleRef:
  kind: ClusterRole
  name: node-reader
  apiGroup: rbac.authorization.k8s.io
CombinationResult
Role + RoleBindingPermissions in one namespace
ClusterRole + ClusterRoleBindingPermissions across the whole cluster
ClusterRole + RoleBindingA reusable role, applied in a single namespace

Service accounts

Applications talk to the API server too: a dashboard that lists pods, Prometheus collecting metrics or a CI tool that deploys. That's what service accounts (ServiceAccounts) are for.

  • Every namespace has a default account, which is automatically assigned to any pod that doesn't name another one. It has minimal permissions.
  • The pod gets a token in /var/run/secrets/kubernetes.io/serviceaccount/. It's a short-lived token that the kubelet renews on its own. Since version 1.24, Kubernetes no longer creates a Secret with a permanent token for each account.
  • For a one-off token, for example for an external system, you use kubectl create token.
kubectl create serviceaccount dashboard-sa -n dev
kubectl get serviceaccounts -n dev
kubectl create token dashboard-sa -n dev --duration=1h
apiVersion: v1
kind: Pod
metadata:
  name: dashboard
  namespace: dev
spec:
  serviceAccountName: dashboard-sa
  automountServiceAccountToken: true
  containers:
    - name: dashboard
      image: nginx:1.27-alpine

A service account is authorized just like a user: with a Role or ClusterRole and its binding. If an application doesn't need to talk to the API, you can stop it from mounting the token with automountServiceAccountToken: false.

Image security

When you write image: nginx, Kubernetes reads it as docker.io/library/nginx:latest: the public Docker Hub registry, the library account and the latest version. For your own images you'll use a private registry, and the kubelet will need credentials to pull them.

Step 1: store the credentials in a Secret of type docker-registry.

kubectl create secret docker-registry regcred \
  --docker-server=registry.example.com \
  --docker-username=ci-bot \
  --docker-password='<password>' \
  --docker-email=ci-bot@example.com

Step 2: reference it in the pod with imagePullSecrets.

apiVersion: v1
kind: Pod
metadata:
  name: api
spec:
  containers:
    - name: api
      image: registry.example.com/equipo/api:2.4.1
  imagePullSecrets:
    - name: regcred
Good practice. Always use a pinned version (api:2.4.1) instead of latest: you'll know exactly what's running, and an update in the registry won't change your application without warning.

Security contexts

A container shares the node's kernel, so the user and privileges it runs with matter. The securityContext defines them at two levels:

  • Pod level: applies to all of its containers.
  • Container level: applies only to that container and overrides the pod's. Linux capabilities can only be set here.
apiVersion: v1
kind: Pod
metadata:
  name: web
spec:
  securityContext:              # pod level: applies to every container
    runAsUser: 1000
    runAsNonRoot: true
  containers:
    - name: nginx
      image: nginxinc/nginx-unprivileged:1.27-alpine
      securityContext:          # container level: overrides the pod level
        allowPrivilegeEscalation: false
        readOnlyRootFilesystem: true
        capabilities:
          drop: ["ALL"]

This configuration makes the container run as user 1000 instead of root, prevents it from gaining privileges, makes its file system read-only and drops all Linux capabilities.

Network Policies

By default, Kubernetes lets every pod talk to every other pod, in any namespace. It's convenient, but if someone compromises the frontend, they go straight to the database.

A NetworkPolicy is an object that attaches to a group of pods through labels and defines what traffic they can receive (ingress) and send (egress). As soon as a policy selects a pod, that pod only accepts the traffic the policy allows.

A NetworkPolicy for the database By default every pod can talk to every other pod. The policy db-policy selects the pods labeled role=db and only allows ingress from pods labeled role=api on TCP port 5432. Traffic from the web pod to the database is now blocked. role=web frontend role=api backend role=db postgres :5432 NetworkPolicy db-policy ingress: role=api allowed TCP 5432 ✓ ✗ web → db: blocked by the policy Without any NetworkPolicy, Kubernetes allows all pod-to-pod traffic.

The database only accepts connections from the API on port 5432. Diagram: The House of Routing.

apiVersion: networking.k8s.io/v1
kind: NetworkPolicy
metadata:
  name: db-policy
  namespace: prod
spec:
  podSelector:
    matchLabels:
      role: db
  policyTypes:
    - Ingress
  ingress:
    - from:
        - podSelector:
            matchLabels:
              role: api
      ports:
        - protocol: TCP
          port: 5432

A very common pattern is to start by denying all incoming traffic in a namespace and then open only what's needed:

apiVersion: networking.k8s.io/v1
kind: NetworkPolicy
metadata:
  name: default-deny-ingress
  namespace: prod
spec:
  podSelector: {}        # every pod in the namespace
  policyTypes:
    - Ingress            # no ingress rules: nothing gets in
Important. Kubernetes stores Network Policies, but the network plugin (CNI) is what enforces them. Calico and Cilium enforce them; Flannel on its own doesn't. With a CNI that doesn't support them, the policy exists but does nothing.

KCNA-style challenge

Answer before you open the solution. Getting it wrong here is the cheapest way to learn.

1. Which kubectl command do you use to create a user in Kubernetes?

None. Kubernetes doesn't manage users: identities come from certificates, tokens or an external provider. What it does create is service accounts.

2. A request gets a 403 Forbidden error. Which step failed?

Authorization. The API server knows who you are, but you don't have permission. An authentication failure returns 401.

3. You need a group to be able to read the cluster's nodes. Role or ClusterRole?

ClusterRole, with a ClusterRoleBinding. Nodes don't belong to any namespace, so a Role can't refer to them.

4. Which account does a pod use if it doesn't set serviceAccountName?

The default account of its namespace, which Kubernetes assigns automatically.

5. You create a correct NetworkPolicy, but traffic still gets through. What do you check first?

The network plugin. If the CNI doesn't support Network Policies, like Flannel on its own, the policy is stored but not enforced.

Key takeaways

  • Everything goes through the kube-apiserver: first authentication, then authorization, then admission control.
  • Kubernetes doesn't manage users; it does manage service accounts.
  • Components identify themselves with TLS certificates signed by the cluster CA; in a user's certificate, CN is the name and O is the group.
  • The kubeconfig ties clusters and users together in contexts; it doesn't grant permissions.
  • RBAC: the Role says what, the RoleBinding says who. For cluster-wide resources, use ClusterRole and ClusterRoleBinding.
  • Private images are pulled with a docker-registry Secret and imagePullSecrets.
  • The securityContext avoids running as root and drops privileges; the container's setting overrides the pod's.
  • Without Network Policies, all traffic between pods is allowed, and the CNI has to support them.

In the next chapter you'll move on to orchestration networking: the cluster network, the pod network, CNI plugins, DNS and Ingress.

Official resources

Source and credits. Chapter written from Jesús Espinoza's study notes on KodeKloud's KCNA course (January to April 2026). Text drafted with AI assistance; original diagrams by The House of Routing. Technical details and YAML examples were checked against the official Kubernetes and CNCF documentation.

Navigate