Skip to content
LF Cert Trainer

Lesson 89 · Section 7: Security

Lesson 89: Pod Security Admission: safe Pods per namespace

How the built-in PodSecurity admission controller checks every Pod against the privileged, baseline and restricted Pod Security Standards, what the enforce, audit and warn labels on a namespace do, how to roll a level out safely, and how to fix a rejected Pod. · 17 min read · 3 min video

1/8Pod Security Admission
0:00 / 3:03

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

Why Pod Security Admission exists

The previous lesson showed how a securityContext makes a container give up power: run as a normal user, drop capabilities, refuse privilege escalation. That protects you only if every Pod author does it. The same fields can also ask for power:

spec:
  hostPID: true                     # see every process on the node
  hostNetwork: true                 # use the node's network stack
  containers:
    - name: debug
      image: busybox:1.36
      securityContext:
        privileged: true            # full access to the node's devices and kernel
      volumeMounts:
        - { name: root, mountPath: /host }
  volumes:
    - name: root
      hostPath: { path: / }         # the node's whole filesystem

Anyone allowed to create a Pod like this owns the node: they can read the kubelet's credentials, the other Pods' secrets, and everything on the disk. RBAC cannot stop it, because RBAC only decides whether you may create Pods, not what is inside them.

Pod Security Admission (PSA) fills that gap. It is an admission controller built into the API server, called PodSecurity, that checks each Pod against a set of rules called the Pod Security Standards and can reject the ones that ask for too much. It is turned on by default since Kubernetes 1.25, and you configure it with labels on namespaces.

Where the check happensreadspassesviolateskubectl applypod.yamlkube-apiserverauthn, RBACPodSecurityadmissionNamespace labelsenforce: baselineetcdPod stored403 Forbiddenviolates PodSecurity
Where the check happens. A Pod create request passes authentication and RBAC, then admission. The PodSecurity admission controller reads the labels of the Pod's namespace and checks the Pod against the chosen level. A violation of the enforce level is rejected; warn and audit only report.

Parts:

  • kubectl apply (pod.yaml)
  • kube-apiserver (authn, RBAC)
  • PodSecurity (admission)
  • Namespace labels (enforce: baseline)
  • etcd (Pod stored)
  • 403 Forbidden (violates PodSecurity)

Connections:

  • kubectl apply to kube-apiserver
  • kube-apiserver to PodSecurity
  • Namespace labels to PodSecurity: reads
  • PodSecurity to etcd: passes
  • PodSecurity to 403 Forbidden: violates

The three levels: Pod Security Standards

Three levels, each stricter than the laststricterstricterprivilegedno rulesbaselineno host accessrestrictedhardenedCNI, CSI, kube-proxysystem namespacesMost applicationsunchanged imagesHardened appsnon-root images
Three levels, each stricter than the last. privileged allows everything. baseline blocks the settings that let a Pod take over its node. restricted also requires the hardening of a well-behaved application: non-root, no privilege escalation, all capabilities dropped, a seccomp profile.

Parts:

  • privileged (no rules)
  • baseline (no host access)
  • restricted (hardened)
  • CNI, CSI, kube-proxy (system namespaces)
  • Most applications (unchanged images)
  • Hardened apps (non-root images)

Connections:

  • privileged to baseline: stricter
  • baseline to restricted: stricter
  • privileged to CNI, CSI, kube-proxy
  • baseline to Most applications
  • restricted to Hardened apps

The Pod Security Standards are three fixed, cumulative levels. You cannot write your own rules with PSA; you choose a level.

LevelIdeaTypical users
privilegedNo restrictions at allSystem components that need the node: CNI and CSI agents, kube-proxy, monitoring agents
baselineBlock known ways to escalate to the node; allow the default PodAlmost every ordinary application, unchanged
restrictedBaseline plus current hardening best practiceApplications built to run as non-root, security-sensitive namespaces

What baseline forbids (the main rules):

RuleNot allowed
Host namespaceshostNetwork: true, hostPID: true, hostIPC: true
Privileged containerssecurityContext.privileged: true
CapabilitiesAdding capabilities beyond the default set (for example NET_ADMIN, SYS_ADMIN)
HostPath volumesAny hostPath volume
Host portshostPort (other than 0)
Other kernel featuresUnsafe sysctls, a custom AppArmor or SELinux type that weakens isolation, procMount: Unmasked, seccompProfile: Unconfined

What restricted requires in addition:

RuleRequired
Non-rootrunAsNonRoot: true (Pod or every container), and runAsUser not 0
No privilege escalationallowPrivilegeEscalation: false on every container
Capabilitiescapabilities.drop: ["ALL"] on every container; only NET_BIND_SERVICE may be added back
SeccompseccompProfile.type: RuntimeDefault or Localhost (Pod or every container)
Volume typesOnly ConfigMap, Secret, emptyDir, projected, downwardAPI, PVC, ephemeral, CSI and a few more; no hostPath, NFS and the like directly

A Pod that passes restricted looks like this. These lines are worth knowing by heart:

spec:
  securityContext:
    runAsNonRoot: true
    seccompProfile:
      type: RuntimeDefault
  containers:
    - name: web
      image: nginxinc/nginx-unprivileged:1.27     # an image that runs as a non-root user
      securityContext:
        allowPrivilegeEscalation: false
        capabilities:
          drop: ["ALL"]

The three modes

Three modes, one level eachNamespace shopthree labelsenforce=baselinerejects the Podwarn=restrictedwarning to kubectlaudit=restrictednote in audit log
Three modes, one level each. A namespace can set a different level for each mode. A common rollout: enforce baseline now, and warn and audit at restricted, so you see what would break before you tighten enforce.

Parts:

  • Namespace shop (three labels)
  • enforce=baseline (rejects the Pod)
  • warn=restricted (warning to kubectl)
  • audit=restricted (note in audit log)

Connections:

  • Namespace shop to enforce=baseline
  • Namespace shop to warn=restricted
  • Namespace shop to audit=restricted

A level alone does nothing; it is applied in a mode:

ModeA Pod that violates the level...Where you see it
enforceIs rejectedError from server (Forbidden) in kubectl
warnIs admittedWarning: lines printed by kubectl
auditIs admittedAn annotation on the event in the API server's audit log

A namespace can set any combination, with a different level per mode. That is the key to rolling out a stricter level without breaking anything: keep enforce where it is, and set warn and audit one level stricter. Developers see warnings on every apply, the audit log collects the offenders, and once the warnings stop you raise enforce.

Configuring it: namespace labels

Everything is a label on the namespace, in the form pod-security.kubernetes.io/<MODE>: <LEVEL>:

apiVersion: v1
kind: Namespace
metadata:
  name: shop
  labels:
    pod-security.kubernetes.io/enforce: baseline
    pod-security.kubernetes.io/enforce-version: v1.34
    pod-security.kubernetes.io/warn: restricted
    pod-security.kubernetes.io/warn-version: latest
    pod-security.kubernetes.io/audit: restricted
LabelValues
pod-security.kubernetes.io/enforce, /warn, /auditprivileged, baseline or restricted
pod-security.kubernetes.io/enforce-version, /warn-version, /audit-versionlatest (default) or a minor version such as v1.34

The version labels exist because the standards grow over time: a new release can add a check to restricted. With latest, an upgrade of the control plane can suddenly reject Pods that were fine yesterday. Pinning enforce-version: v1.34 keeps the 1.34 rules until you change the label. A common pattern is to pin enforce and leave warn on latest, so you hear about new checks before they bite.

A namespace with no labels is checked against the cluster default, which is privileged in all three modes unless an administrator changed it (see below). That is why a fresh cluster lets you create the dangerous Pod above.

Labelling is a normal namespace update, so it needs RBAC permission to update or patch the namespace. Giving someone that permission lets them choose their own level.

How it works

  1. Pod create (or update) reaches admission
  2. Read the labels of the Pod's namespace
  3. Evaluate the Pod spec against each mode's level and version
  4. enforce violated: reject with 403 and every reason
  5. warn violated: add Warning headers
  6. audit violated: annotate the audit event
  7. Otherwise: admit
What PodSecurity does with a Pod request

A few details decide how it behaves in practice:

  • Only Pods are enforced. enforce checks Pod objects. A Deployment, StatefulSet, Job or CronJob with a bad template is accepted; it is the Pods it tries to create that are rejected, by the controller's requests. warn and audit also check the Pod templates of workload objects, so a warning appears on kubectl apply -f deployment.yaml.
  • Running Pods are left alone. Labelling a namespace does not evict anything. The API server checks the existing Pods once and returns warnings for those that violate the new enforce level, but they keep running. They are rejected only when they are recreated.
  • Some updates are never blocked. An update to a running Pod that only changes its metadata (labels, most annotations), activeDeadlineSeconds or tolerations is allowed even if the Pod violates the level, so a non-compliant Pod can still be labelled.
  • Exemptions skip all checks. Pods in namespaces, created by usernames or using RuntimeClasses listed as exemptions in the admission configuration are not checked in any mode.
Under the hood · Cluster-wide defaults and exemptions: the admission configuration

The namespace labels are the everyday way. An administrator can also give PodSecurity a configuration file, through the API server flag --admission-control-config-file:

apiVersion: apiserver.config.k8s.io/v1
kind: AdmissionConfiguration
plugins:
  - name: PodSecurity
    configuration:
      apiVersion: pod-security.admission.config.k8s.io/v1
      kind: PodSecurityConfiguration
      defaults:                       # for namespaces without labels
        enforce: baseline
        enforce-version: latest
        audit: restricted
        warn: restricted
      exemptions:
        usernames: []                 # requests by these users are not checked
        runtimeClasses: []            # Pods with these RuntimeClasses are not checked
        namespaces: [kube-system]     # Pods in these namespaces are not checked

On a kubeadm cluster the API server is a static Pod, so the file has to be mounted into it by editing /etc/kubernetes/manifests/kube-apiserver.yaml (flag, volumes and volumeMounts), exactly like the encryption configuration in the Secrets lessons. Namespace labels always win over the defaults; exemptions win over both.

Exempting a username has a catch: Pods created by controllers are created by the controller's identity, not by the user who made the Deployment. Exempting a user exempts only the Pods that user creates directly.

Under the hood · PSA replaced PodSecurityPolicy

Older material mentions PodSecurityPolicy (PSP), a cluster-scoped object that Pods had to be authorised to "use" through RBAC. It was hard to reason about (which policy applies to which Pod?) and could also change Pods. It was deprecated in 1.21 and removed in 1.25, the same release in which Pod Security Admission became stable. If an exam task or a blog post mentions kind: PodSecurityPolicy or policy/v1beta1, it describes something that no longer exists.

When the three fixed levels are not enough (for example "images must come from our registry" or "every Pod needs a team label"), clusters add a policy engine as a validating webhook, such as Kyverno or OPA Gatekeeper, or write a ValidatingAdmissionPolicy in CEL. Those are covered in the admission controller lessons.

Using it

Example · Enforce baseline on a namespace

The task: "Pods in namespace team-a must not be able to run privileged containers or use the host's namespaces".

kubectl label ns team-a pod-security.kubernetes.io/enforce=baseline
kubectl get ns team-a --show-labels

Check that it works:

kubectl -n team-a run test --image=busybox:1.36 --restart=Never \
  --overrides='{"spec":{"containers":[{"name":"test","image":"busybox:1.36","command":["sleep","3600"],"securityContext":{"privileged":true}}]}}'
# Error from server (Forbidden): pods "test" is forbidden: violates PodSecurity "baseline:latest":
#   privileged (container "test" must not set securityContext.privileged=true)
kubectl -n team-a run ok --image=busybox:1.36 --restart=Never -- sleep 3600   # created

Example · Find out what restricted would break, before enforcing it

kubectl label --dry-run=server --overwrite ns team-a pod-security.kubernetes.io/enforce=restricted
# Warning: existing pods in namespace "team-a" violate the new PodSecurity enforce level "restricted:latest"
# Warning: ok: allowPrivilegeEscalation != false, unrestricted capabilities, runAsNonRoot != true, seccompProfile
# namespace/team-a labeled (server dry run)

--dry-run=server sends the change to the API server, which runs the checks and then throws the change away. To check every namespace at once, use kubectl label --dry-run=server --overwrite ns --all pod-security.kubernetes.io/enforce=baseline. Then roll out safely:

kubectl label --overwrite ns team-a pod-security.kubernetes.io/warn=restricted pod-security.kubernetes.io/audit=restricted
# fix the workloads until applying them prints no warnings, then:
kubectl label --overwrite ns team-a pod-security.kubernetes.io/enforce=restricted

Example · A Deployment whose Pods never appear

After someone labelled namespace shop with enforce=restricted, kubectl rollout restart deploy/web leaves the Deployment at 0/2 ready with no new Pods.

kubectl -n shop get rs                        # the newest ReplicaSet: DESIRED 2, CURRENT 0
kubectl -n shop describe rs web-7f9c8d5b6c | tail -n 3
# Warning  FailedCreate  replicaset-controller  Error creating: pods "web-7f9c8d5b6c-x2k4q" is forbidden:
#   violates PodSecurity "restricted:latest": allowPrivilegeEscalation != false (container "web" must set
#   securityContext.allowPrivilegeEscalation=false), unrestricted capabilities (...), runAsNonRoot != true (...),
#   seccompProfile (...)

Nothing is wrong with the Deployment object itself, which is why kubectl describe deploy shows little. The message lists every field to add. Edit the Deployment's Pod template with the restricted block shown earlier, and the ReplicaSet creates the Pods. If the image runs as root, also set runAsUser, or the Pods are admitted but fail with CreateContainerConfigError.

Example · Let a system namespace run privileged Pods

A monitoring agent's DaemonSet needs hostPID and hostPath. In a cluster whose default is baseline, give its namespace an explicit label:

kubectl label --overwrite ns monitoring pod-security.kubernetes.io/enforce=privileged

Keep such namespaces few, and make sure only administrators can create Pods in them, because any Pod there may take over a node.

Tricks

Common mistakes

  • Labelling the Pod or the Deployment instead of the namespace. PSA reads only namespace labels.
  • Expecting running Pods to be evicted. A new level applies to Pods created afterwards.
  • Looking for the error on the Deployment. Enforce rejects the Pods; the event is on the ReplicaSet.
  • Writing PodSecurityPolicy. It was removed in 1.25.
  • Using a root image under restricted. The Pod passes admission with runAsNonRoot: true and then fails to start.
  • Forgetting drop: ["ALL"] or the seccomp profile. Restricted needs all four settings, not just non-root.
  • Leaving the version on latest in production. A control plane upgrade can add checks; pin enforce-version.

Recap

  • Pod Security Admission is the built-in PodSecurity admission controller, on by default. It checks Pods against the Pod Security Standards: privileged (anything), baseline (no host access, no privileged containers), restricted (also non-root, no privilege escalation, drop ALL capabilities, seccomp RuntimeDefault).
  • Modes: enforce rejects, warn prints warnings, audit writes to the audit log. Each mode has its own level, set by pod-security.kubernetes.io/<mode>=<level> on the namespace, optionally pinned with -version.
  • Enforce checks Pods only: a Deployment with a bad template is accepted and its ReplicaSet reports FailedCreate. Running Pods are never evicted by a new label.
  • Roll out with kubectl label --dry-run=server, then warn and audit at the stricter level, then enforce.

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.

Practise: try it on a real cluster

A hands-on lab for this lesson. You get goals, not steps: any solution that reaches them passes.

  • Enforce the restricted Pod Security Standard on a namespace and make the app that already runs there comply.

    Build · Level 2 · standard · target 20 min

Discussion

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