Security contexts and Pod Security Standards

Intermediate · 19 min

What a container may do on its node: securityContext fields that drop root powers, and Pod Security Admission enforcing baseline and restricted per namespace.

Before thisPods in depthRBAC

Prepare-sh · 19 min

Security contexts and Pod Security Standards

The player loads from youtube-nocookie.com when you press play. Nothing reaches YouTube before that.

Taught by Prepare-shReport a problem with this video
Not started
Set this lesson's status

What you'll learn

  • Containers share the node's kernel. A container running as root with default capabilities is one kernel bug or misconfiguration away from the node.
  • securityContext sets the process's identity and powers: runAsNonRoot and runAsUser, allowPrivilegeEscalation: false, capabilities.drop: [ALL], readOnlyRootFilesystem, and seccompProfile RuntimeDefault.
  • The Pod Security Standards define three levels. privileged allows anything, baseline blocks known escalations (host namespaces, hostPath, privileged), and restricted also requires the hardening fields.
  • Pod Security Admission applies a level per namespace with labels, in enforce, audit and warn modes, pinned to a policy version. Enforce rejects Pods, but not the Deployments that create them.
  • Turning on enforce is safe to rehearse: a server-side dry-run of the label lists the existing Pods that would violate it, and warn mode shows violations at apply time.
  • Since policy v1.35, restricted lets a Pod run as root inside a user namespace (hostUsers: false), where UID 0 maps to an unprivileged UID on the node.

A container is a process on a shared kernel

RBAC decides who may create a Pod. It says nothing about what that Pod can do once it runs. And a container is not a VM. It is a process on the node, fenced by namespaces and cgroups, sharing the node’s kernel with every other Pod. By default that process often runs as UID 0 with a set of Linux capabilities. A Pod that asks for privileged: true, the host’s PID namespace and a hostPath mount of / simply is root on the node.

So clusters need two things: a way for each Pod to declare a low-privilege configuration, and a way for the cluster to refuse Pods that don’t. The first is the securityContext. The second is Pod Security Admission enforcing the Pod Security Standards.

The securityContext

Set at Pod level (applies to all containers) or container level (wins). A hardened Pod:

apiVersion: v1
kind: Pod
metadata: {name: api}
spec:
  securityContext:
    runAsNonRoot: true
    runAsUser: 10001
    runAsGroup: 10001
    fsGroup: 10001
    seccompProfile: {type: RuntimeDefault}
  containers:
  - name: api
    image: ghcr.io/example/api:1.4.2
    securityContext:
      allowPrivilegeEscalation: false
      readOnlyRootFilesystem: true
      capabilities:
        drop: ["ALL"]
        add: ["NET_BIND_SERVICE"]
    volumeMounts: [{name: tmp, mountPath: /tmp}]
  volumes:
  - name: tmp
    emptyDir: {}

What each field buys:

  • runAsNonRoot / runAsUser / runAsGroup: the process isn’t UID 0. With runAsNonRoot alone, the kubelet refuses to start an image whose user is root (CreateContainerConfigError) rather than guessing.
  • allowPrivilegeEscalation: false sets the kernel’s no_new_privs flag, so setuid binaries like sudo or an exploitable pkexec can’t raise privileges.
  • capabilities.drop: [ALL] removes the root powers a process holds. Add back only what’s needed, usually just NET_BIND_SERVICE for ports below 1024.
  • seccompProfile: RuntimeDefault applies the container runtime’s syscall filter, which blocks dozens of rarely needed and often exploited syscalls.
  • readOnlyRootFilesystem stops an attacker writing tools into the image’s filesystem. Give the app an emptyDir for scratch space.
  • fsGroup makes mounted volumes group-owned by that GID so a non-root process can write them.

The docker lesson on capabilities and seccomp shows the same mechanisms underneath.

The three Pod Security Standards

The standards are a fixed, versioned definition, not a configurable policy:

  • privileged: no restrictions. For system components like CNI agents and storage drivers.
  • baseline: blocks known privilege escalations. No privileged, no host namespaces (hostNetwork, hostPID, hostIPC), no hostPath volumes, no host ports, capabilities only from a safe default list, no unsafe sysctls or proc mounts. Most apps pass unchanged.
  • restricted: baseline plus the hardening above: allowPrivilegeEscalation: false, drop ALL, runAsNonRoot, a seccomp profile, and only common volume types.

Pod Security Admission

The built-in admission controller (it replaced PodSecurityPolicy, removed in 1.25) applies a standard per namespace through labels:

pod-security.kubernetes.io/enforce=restricted       # reject violating Pods
pod-security.kubernetes.io/enforce-version=v1.37    # pin the rules
pod-security.kubernetes.io/warn=restricted          # warn the client
pod-security.kubernetes.io/audit=restricted         # annotate the audit log

Before enforcing on a namespace that already runs things, rehearse. On a lab API server, a server-side dry-run of the label on namespace prod, which held one plain nginx Pod:

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

Existing Pods are never evicted. After labelling for real, a new plain Pod was refused, with each fix spelled out:

Error from server (Forbidden): pods "plain2" is forbidden: violates PodSecurity "restricted:v1.37":
allowPrivilegeEscalation != false (container "plain2" must set securityContext.allowPrivilegeEscalation=false),
unrestricted capabilities (container "plain2" must set securityContext.capabilities.drop=["ALL"]),
runAsNonRoot != true (pod or container "plain2" must set securityContext.runAsNonRoot=true),
seccompProfile (pod or container "plain2" must set securityContext.seccompProfile.type to "RuntimeDefault" or "Localhost")

The hardened Pod above was admitted, and the audit log recorded pod-security.kubernetes.io/enforce-policy: restricted:v1.37 on its create event. In a namespace enforcing baseline and warning on restricted, a plain nginx Pod was created with a warning, while a Pod with hostPID: true and a hostPath of / was refused: violates PodSecurity "baseline:latest": host namespaces (hostPID=true), hostPath volumes (volume "root"). A privileged: true container never even reached admission on this lab server. Validation rejected it as disallowed by cluster policy, because the API server runs without --allow-privileged.

The Deployment trap

Enforcement applies to Pods, not to Deployments, Jobs or DaemonSets. Creating a plain Deployment in prod printed a warning (warn and audit modes do check Pod templates) and then “succeeded”:

deployment.apps/web created
NAME   READY   UP-TO-DATE   AVAILABLE   AGE
web    0/1     0            0           4s

The real error was on the ReplicaSet, as repeating FailedCreate events: Error creating: pods "web-689b9bdbdd-ft6x2" is forbidden: violates PodSecurity "restricted:v1.37": .... If a rollout “does nothing”, check ReplicaSet events.

Root inside a user namespace

Some images genuinely need UID 0. With hostUsers: false (user namespaces, GA in 1.36), UID 0 in the container maps to an unprivileged UID range on the node. The restricted policy from v1.35 accounts for that. The same Pod, missing runAsNonRoot, was admitted to prod with hostUsers: false and refused without it (runAsNonRoot != true). That check’s source, check_runAsNonRoot.go, has a separate 1.35 version that applies the relaxation.

Rolling it out

  1. Label every namespace warn=restricted and audit=restricted. Collect violations without breaking anything.
  2. Fix workloads, mostly by adding the securityContext block above and using images that run as non-root.
  3. Enforce baseline everywhere, restricted where workloads comply, privileged only in system namespaces.
  4. Pin enforce-version. Leave warn on latest to preview future tightening.

PSA can’t make exceptions per workload or check anything outside these standards (image registries, required labels). That’s what general admission policy is for.

About the video

The embed is Prepare-sh’s “Kubernetes securityContext: run as non-root, drop capabilities and Pod Security Admission”, October 2026, 18 minutes. Going by its chapters and detailed description, it starts from a busybox Pod running as root, removes powers one at a time (dropping capabilities, runAsNonRoot and the start failure it causes, runAsUser, allowPrivilegeEscalation with the PwnKit bug as motivation, readOnlyRootFilesystem with an emptyDir, seccomp), then enforces restricted on a namespace and fixes nginx with the unprivileged image. It is a very new, very small channel, so the owner should check the narration by ear. I judged it from chapters and description only, since transcripts couldn’t be fetched. English was judged from the title, description and English caption track. The page shows no audio-language flag. Piyush’s longer CKA episode in deeper covers the same ground with more on capabilities.

What was run: the dry-run warnings, both rejections, the warn-mode creation, the audit annotations, the Deployment with zero Pods and its FailedCreate events, the allow-privileged rejection and the hostUsers: false comparison are real output from a local Kubernetes v1.37.3 API server whose nodes run no containers. Nothing executed, so runtime effects such as no_new_privs, seccomp filtering and CreateContainerConfigError are from the security-context docs and the Pod Security Standards page, checked 2026-11-28.

Where this fits

PSA is one admission controller with fixed rules. Next, writing your own: admission control and policy.

Check yourself

  1. 01A Deployment applied to a namespace with enforce=restricted reports created, but no Pods appear. Why, and where is the error?

    Pod Security Admission enforces on Pods, not on workload objects. The Deployment and ReplicaSet are created, then each Pod creation is rejected. The violation appears as FailedCreate events on the ReplicaSet (and as a warning when the Deployment was applied).

  2. 02Which four securityContext settings does the restricted level require that a default Pod lacks?

    allowPrivilegeEscalation: false, capabilities.drop including ALL, runAsNonRoot: true, and a seccompProfile of RuntimeDefault or Localhost. It also forbids everything baseline forbids, and limits added capabilities to NET_BIND_SERVICE.

  3. 03Why pin pod-security.kubernetes.io/enforce-version instead of using latest?

    Policy checks can tighten in new Kubernetes versions. Pinning keeps the rules a namespace was tested against through upgrades, while a warn label on latest shows what a future tightening would break.

  4. 04An app's image must run as root but you want restricted. What options does Kubernetes 1.37 give you?

    Run it with hostUsers: false. Restricted (policy v1.35+) allows root inside a user namespace because it maps to an unprivileged UID on the host. Otherwise rebuild the image to run as a non-root user, or exempt that namespace to baseline.

Go deeper

Notes

Private to you

Esc
↑↓ navigate↵ open? shortcuts

Keyboard shortcuts

Press Esc to close

Anywhere

⌘K
Search and commands
/
Search
?
This sheet
Esc
Close

Reading a lesson

J
Next lesson
K
Previous lesson
B
Bookmark