Skip to main content

Security

πŸ“˜ Know

Be able to explain it and pass its lab once. Phase 6 of the Learning Path.

Docs: Controlling access to the API Β· RBAC Β· Service accounts Β· Security context Β· Pod Security Standards Β· Custom resources

Overview​

Every request to the API server passes three gates in order. Authentication decides who you are (certificate, OIDC token, ServiceAccount token). Authorization decides whether that identity may do this verb on this resource, almost always through RBAC. Admission control can then change or reject the object itself: inject defaults, enforce quotas, block privileged Pods. Inside the Pod, a SecurityContext limits what the container process may do on the node. The same API machinery is also how Kubernetes is extended: a CustomResourceDefinition adds a new kind, and an Operator is a controller that reconciles it (β†’ Architecture).

RBAC: a RoleBinding in namespace team-a connects subjects (User jane, ServiceAccount ci-bot) to Role deployer, which grants get, list, create and update on deployments and pods in team-a; a RoleBinding can also reference ClusterRole view, still scoped to team-aRBAC: a RoleBinding in namespace team-a connects subjects (User jane, ServiceAccount ci-bot) to Role deployer, which grants get, list, create and update on deployments and pods in team-a; a RoleBinding can also reference ClusterRole view, still scoped to team-a

Figure 9-1: RBAC. Amber marks the binding, the only object that connects an identity to permissions. Green is what those permissions reach: verbs on resources, inside one namespace.

Key concepts​

The request pipeline​

StageQuestionMechanismsFailure you'll see
AuthenticationWho are you?Client certs, OIDC tokens, ServiceAccount tokens401 Unauthorized
AuthorizationMay you do this?RBAC (also Node, Webhook)403 Forbidden: ... cannot create resource "deployments"
Mutating admissionShould the object change?LimitRanger defaults, ServiceAccount injection, webhooksObject differs from what you applied
Validating admissionIs the object allowed?ResourceQuota, Pod Security Admission, ValidatingAdmissionPolicy, webhooksforbidden: exceeded quota, violates PodSecurity "restricted"

RBAC objects​

ObjectScopeContains
RoleNamespaceRules: apiGroups + resources + verbs
ClusterRoleClusterSame rules, plus cluster-scoped resources (nodes, PVs)
RoleBindingNamespacesubjects β†’ one roleRef
ClusterRoleBindingClustersubjects β†’ one ClusterRole, in every namespace
RoleBound withResult
RoleRoleBindingPermissions in that namespace. The normal case.
ClusterRoleRoleBindingPermissions in the binding's namespace only. Reuse one definition across namespaces.
ClusterRoleClusterRoleBindingPermissions in every namespace and on cluster-scoped resources
RoleClusterRoleBindingInvalid. A ClusterRoleBinding can only reference a ClusterRole.

RBAC is additive. There are no deny rules; access is denied unless some binding allows it.

ServiceAccounts​

FactConsequence
Every namespace has a default ServiceAccountPods without serviceAccountName use it. Give workloads their own.
Tokens are short-lived and projected into the PodMounted at /var/run/secrets/kubernetes.io/serviceaccount/
automountServiceAccountToken: falseNo token in the Pod. Set it for apps that never call the API.
Subject name formatsystem:serviceaccount:<namespace>:<name> in kubectl auth can-i --as

SecurityContext​

FieldLevelEffect
runAsNonRoot: truePod or containerKubelet refuses to start a container that would run as UID 0
runAsUser / runAsGroupPod or containerUID / GID of the process
fsGroupPodGroup ownership of mounted volumes, so a non-root user can write
allowPrivilegeEscalation: falseContainerBlocks setuid binaries gaining privileges
readOnlyRootFilesystem: trueContainerWrites only to mounted volumes
capabilities.drop: ["ALL"]ContainerRemoves Linux capabilities such as binding ports below 1024
privileged: trueContainerFull host access. Almost never.
seccompProfile.type: RuntimeDefaultPod or containerFilters dangerous syscalls

Container-level settings override Pod-level ones.

Pod Security Admission​

Label a namespace to enforce one of three Pod Security Standards:

LevelBlocksUse for
privilegedNothingSystem namespaces (CNI, storage drivers)
baselineHost namespaces, privileged containers, hostPathDefault for most namespaces
restrictedAlso root users, privilege escalation, capabilities beyond NET_BIND_SERVICEApplication namespaces

One label turns it on: kubectl label namespace team-a pod-security.kubernetes.io/enforce=restricted.

Deeper dive

Each level can be applied in three modes, one label per mode: enforce rejects the Pod, warn returns a warning to the client, audit records it in the audit log. Roll out with warn and audit first to find violations, then switch to enforce. Pin the standard's version with pod-security.kubernetes.io/enforce-version, or latest moves with each upgrade.

CRDs and Operators​

PieceWhat it isExample
CustomResourceDefinitionAdds a new kind to the API, with a schemakind: Backup in group ops.example.com
Custom resourceAn instance of that kindBackup nightly-db
OperatorA controller that watches the kind and reconciles itCreates CronJobs and PVCs for each Backup

A CRD without a controller only stores data. The Operator is what makes it do something. The minimal CRD in kubectl essentials adds kind: Backup; a custom resource is then ordinary YAML:

# fragment: needs the Backup CRD installed
apiVersion: ops.example.com/v1
kind: Backup
metadata:
name: nightly-db
spec:
schedule: "0 2 * * *"
retainDays: 7

kubectl essentials​

RBAC, imperatively:

kubectl create serviceaccount ci-bot
kubectl create role deployer --verb=get,list,watch,create,update,patch --resource=deployments,pods
kubectl create rolebinding ci-bot-deployer --role=deployer --serviceaccount=team-a:ci-bot -n team-a
kubectl create rolebinding jane-view --clusterrole=view --user=jane -n team-a
kubectl create clusterrole node-reader --verb=get,list --resource=nodes

Check what an identity can do:

kubectl auth can-i create deployments -n team-a --as=system:serviceaccount:team-a:ci-bot
kubectl auth can-i --list -n team-a --as=jane
kubectl auth whoami
kubectl create token ci-bot -n team-a --duration=10m # short-lived token for testing

Security context and admission:

kubectl explain pod.spec.securityContext
kubectl explain pod.spec.containers.securityContext
kubectl label namespace team-a pod-security.kubernetes.io/enforce=restricted
kubectl exec <pod> -- id # which UID/GID the process has
Deeper dive

Inspect extensions:

kubectl get crd
kubectl api-resources --api-group=ops.example.com
kubectl explain backup.spec # works for CRDs with a schema

A Role and its binding:

apiVersion: rbac.authorization.k8s.io/v1
kind: Role
metadata:
name: deployer
rules:
- apiGroups: ["apps"] # "" is the core group (pods, services, secrets)
resources: ["deployments"]
verbs: ["get", "list", "watch", "create", "update", "patch"]
- apiGroups: [""]
resources: ["pods", "pods/log"] # subresources are listed separately
verbs: ["get", "list"]
---
apiVersion: rbac.authorization.k8s.io/v1
kind: RoleBinding
metadata:
name: ci-bot-deployer
subjects:
- kind: ServiceAccount
name: ci-bot
namespace: team-a # required for ServiceAccount subjects
roleRef:
apiGroup: rbac.authorization.k8s.io
kind: Role
name: deployer

A Pod that passes the restricted standard:

apiVersion: v1
kind: Pod
metadata:
name: hardened
spec:
automountServiceAccountToken: false
securityContext:
runAsNonRoot: true
runAsUser: 1000
runAsGroup: 3000
fsGroup: 2000
seccompProfile: {type: RuntimeDefault}
containers:
- name: app
image: busybox:1.36
command: ["sh", "-c", "id; touch /data/ok && echo wrote; sleep 3600"]
securityContext:
allowPrivilegeEscalation: false
readOnlyRootFilesystem: true
capabilities: {drop: ["ALL"]}
volumeMounts: [{name: data, mountPath: /data}]
volumes:
- name: data
emptyDir: {}

A minimal CRD:

apiVersion: apiextensions.k8s.io/v1
kind: CustomResourceDefinition
metadata:
name: backups.ops.example.com # <plural>.<group>
spec:
group: ops.example.com
scope: Namespaced
names: {plural: backups, singular: backup, kind: Backup, shortNames: [bk]}
versions:
- name: v1
served: true
storage: true
schema:
openAPIV3Schema:
type: object
properties:
spec:
type: object
required: [schedule]
properties:
schedule: {type: string}
retainDays: {type: integer, minimum: 1}

πŸ§ͺ Lab​

Lab 6-2 β˜…β˜…

Requires: Standard lab setup Β· How the tiers work.

Least privilege, then a hardened Pod.

Goal

  1. In namespace lab6-2, create ServiceAccount ci-bot and a Role that allows managing Deployments and reading Pods and their logs. Bind it.
  2. Prove ci-bot can create Deployments but can't delete them, and can't read Secrets.
  3. Label lab6-2 to enforce restricted. Try kubectl run bad --image=nginx:1.27 and read the error.
  4. Run the hardened Pod above and confirm its UID and that the root filesystem is read-only.
  5. Install the Backup CRD, create a Backup object, and list it with its short name.

Verify

kubectl -n lab6-2 auth can-i create deployments --as=system:serviceaccount:lab6-2:ci-bot # yes
kubectl -n lab6-2 auth can-i delete deployments --as=system:serviceaccount:lab6-2:ci-bot # no
kubectl -n lab6-2 auth can-i get secrets --as=system:serviceaccount:lab6-2:ci-bot # no
kubectl -n lab6-2 logs hardened # uid=1000 gid=3000 groups=2000,3000, then: wrote
kubectl -n lab6-2 get bk
🟑 Hints
  1. kubectl create serviceaccount, kubectl create role -h (look at --verb and --resource), kubectl create rolebinding -h (look at --serviceaccount=<ns>:<name>). Logs are the pods/log subresource.
  2. "Check a permission" in Command Patterns. A ServiceAccount's user name is system:serviceaccount:<ns>:<name>.
  3. kubectl label namespace with pod-security.kubernetes.io/enforce=restricted.
  4. Save the Pod above as hardened.yaml. Its logs print id. Try writing outside /data with kubectl exec.
  5. Save the CRD above as backup-crd.yaml. The object's apiVersion is <group>/<version> from the CRD.
🟒 Guided
  1. Create the lab namespace.

    kubectl create namespace lab6-2
  2. Create the identity the CI system will use.

    kubectl -n lab6-2 create serviceaccount ci-bot
  3. A Role that manages Deployments, but has no delete verb.

    kubectl -n lab6-2 create role deployer --verb=get,list,watch,create,update,patch --resource=deployments
  4. A Role that reads Pods and their logs.

    kubectl -n lab6-2 create role pod-reader --verb=get,list --resource=pods,pods/log
  5. Bind the first Role to the ServiceAccount.

    kubectl -n lab6-2 create rolebinding ci-bot-deployer --role=deployer --serviceaccount=lab6-2:ci-bot
  6. Bind the second Role to the ServiceAccount.

    kubectl -n lab6-2 create rolebinding ci-bot-pod-reader --role=pod-reader --serviceaccount=lab6-2:ci-bot
  7. Ask the API server as ci-bot: yes.

    kubectl -n lab6-2 auth can-i create deployments --as=system:serviceaccount:lab6-2:ci-bot
  8. No: delete isn't in the Role.

    kubectl -n lab6-2 auth can-i delete deployments --as=system:serviceaccount:lab6-2:ci-bot
  9. No: nothing grants Secrets.

    kubectl -n lab6-2 auth can-i get secrets --as=system:serviceaccount:lab6-2:ci-bot
  10. Enforce the restricted Pod Security Standard on the namespace.

    kubectl label namespace lab6-2 pod-security.kubernetes.io/enforce=restricted
  11. Try a default nginx Pod: rejected.

    kubectl -n lab6-2 run bad --image=nginx:1.27
    Error: violates PodSecurity "restricted:latest": allowPrivilegeEscalation != false,
    unrestricted capabilities, runAsNonRoot != true, seccompProfile ...
  12. Create the hardened Pod above, saved as hardened.yaml.

    kubectl -n lab6-2 apply -f hardened.yaml
  13. Read its output: uid=1000 gid=3000 groups=2000,3000, then "wrote".

    kubectl -n lab6-2 logs hardened
  14. Try to write to the root filesystem: Read-only file system.

    kubectl -n lab6-2 exec hardened -- touch /etc/x
  15. Install the CRD above, saved as backup-crd.yaml.

    kubectl apply -f backup-crd.yaml
  16. Create one Backup object from inline YAML.

    kubectl -n lab6-2 apply -f - <<'EOF'
    apiVersion: ops.example.com/v1
    kind: Backup
    metadata:
    name: nightly-db
    spec:
    schedule: "0 2 * * *"
    retainDays: 7
    EOF
  17. List it by short name: stored, but nothing happens, because no Operator watches it.

    kubectl -n lab6-2 get bk
  18. Run the βœ… Check below, then delete everything the lab created.

    kubectl delete namespace lab6-2
  19. The CRD is cluster-scoped, so delete it separately.

    kubectl delete crd backups.ops.example.com

βœ… Check

t() { [ "$2" = "$3" ] && echo "PASS $1" || echo "FAIL $1: got '$2', want '$3'"; }
sa=system:serviceaccount:lab6-2:ci-bot
t "ci-bot can create deployments" "$(kubectl -n lab6-2 auth can-i create deployments --as=$sa)" "yes"
t "ci-bot cannot delete them" "$(kubectl -n lab6-2 auth can-i delete deployments --as=$sa)" "no"
t "ci-bot can read Pod logs" "$(kubectl -n lab6-2 auth can-i get pods/log --as=$sa)" "yes"
t "ci-bot cannot read Secrets" "$(kubectl -n lab6-2 auth can-i get secrets --as=$sa)" "no"
t "restricted is enforced" "$(kubectl get ns lab6-2 -o jsonpath='{.metadata.labels.pod-security\.kubernetes\.io/enforce}')" "restricted"
t "hardened runs as 1000" "$(kubectl -n lab6-2 exec hardened -- id -u)" "1000"
t "root filesystem read-only" "$(kubectl -n lab6-2 exec hardened -- touch /etc/x 2>&1 | grep -c 'Read-only')" "1"
t "Backup stored" "$(kubectl -n lab6-2 get bk nightly-db -o jsonpath='{.spec.retainDays}')" "7"

Gotchas​

  • apiGroups must match. Deployments are in apps, Pods in "", Ingress in networking.k8s.io. kubectl api-resources shows the group.
  • Subresources are separate. pods doesn't grant pods/log or pods/exec.
  • ServiceAccount subjects need a namespace. Omitting it in YAML binds nothing useful.
  • roleRef is immutable. To point a binding at another role, delete and recreate it.
  • runAsNonRoot + a root image. Kubelet refuses to start it: CreateContainerConfigError: container has runAsNonRoot and image will run as root. Set runAsUser or use a non-root image.
  • readOnlyRootFilesystem breaks apps writing to /tmp. Mount an emptyDir there.
  • Non-root can't bind port 80. Listen on 8080 and map it in the Service.
  • kubectl auth can-i as yourself proves nothing. Always test with --as.

Scenario questions​

Q1 β˜… A Pod's app logs 403 Forbidden when it lists Pods through the API. How do you fix it?

Model answer
  • Clarify: what does the app need to do, exactly? Which namespace?
  • Observe: the error names the identity: system:serviceaccount:app:default cannot list resource "pods". kubectl get pod -o jsonpath='{.spec.serviceAccountName}' confirms it.
  • Hypothesise: the Pod runs as the default ServiceAccount, which has no permissions.
  • Fix: create a dedicated ServiceAccount, a Role with only get, list, watch on pods, and a RoleBinding. Set serviceAccountName. Verify with kubectl auth can-i --as.
  • Prevent: never grant permissions to default. Set automountServiceAccountToken: false on apps that don't call the API.

Q2 β˜…β˜… Give developers read-only access to every namespace, except Secrets.

Model answer
  • Clarify: all namespaces, including system ones? Is membership managed by an identity-provider group?
  • Observe: the built-in view ClusterRole already excludes Secrets.
  • Hypothesise: a ClusterRoleBinding from the developer group to view.
  • Fix: kubectl create clusterrolebinding devs-view --clusterrole=view --group=developers. If some namespaces are off-limits, use RoleBindings per namespace to the same ClusterRole instead.
  • Prevent: bind to groups, never to individual users, so joiners and leavers are handled in the identity provider.

Q3 β˜…β˜… After enabling restricted Pod Security on a namespace, a Deployment has 0 Pods. Why is nothing visible?

Model answer
  • Clarify: did the Deployment exist before the label, or was it applied after?
  • Observe: kubectl get pods is empty. kubectl describe rs shows FailedCreate ... violates PodSecurity "restricted:latest".
  • Hypothesise: admission rejects the Pods, not the Deployment, so the error appears on the ReplicaSet, one level down.
  • Fix: add the missing securityContext fields (non-root, drop ALL, no privilege escalation, RuntimeDefault seccomp).
  • Prevent: roll out warn and audit modes first to find violations, then switch to enforce.

Q4 β˜…β˜…β˜… What's an Operator, and when would you write one instead of a Helm chart?

Model answer
  • Clarify: what does the software need after install: backups, failover, version upgrades, resharding?
  • Observe: Helm renders YAML once per install or upgrade. Nothing runs afterwards.
  • Hypothesise: an Operator is a CRD plus a controller running the reconcile loop, encoding what a human operator would do. It keeps acting after installation.
  • Fix: use Helm when installation is the hard part. Use (or write) an Operator when day-2 operations are the hard part, such as a database that must promote a replica on failure.
  • Prevent: the cost: an Operator is software you maintain, with its own bugs and RBAC. Prefer a mature existing Operator to writing one.

Summary​

  • Authenticate, authorize, admit. 401, 403 and admission errors each point at a different stage.
  • RBAC is Role + Binding, additive only. A RoleBinding scopes even a ClusterRole to one namespace.
  • Give each workload its own ServiceAccount. Test with kubectl auth can-i --as.
  • SecurityContext hardens the process. Non-root, no escalation, drop ALL, read-only root.
  • CRDs add kinds; Operators make them act. Same reconcile loop as the built-in controllers.

Next in path β†’ Multi-Tenant Platform