Pages

Topics

Tools

↑↓navigate↵openescclose
All guides

Kubernetes securityContext, Capabilities, and Pod Security Standards

The five fields that remove most container escapes, which of them only exist at container level, and how the restricted profile enforces the same settings at admission.

~4 min readKubernetes
#Kubernetes#Security#PodSecurity#Capabilities
3D illustration of a container cube wrapped in a hardened shield with lock icons for user and capabilities

Quick Summary

securityContext is where a container's privileges are narrowed. It exists at two levels — pod and container — and container fields override pod fields for the container they belong to. The five settings that remove most container escapes: runAsNonRoot: true, allowPrivilegeEscalation: false, readOnlyRootFilesystem: true, capabilities.drop: ["ALL"], and seccompProfile.type: RuntimeDefault.

Capabilities are the meaningful half of root. A Linux container starts with a default set (CAP_NET_RAW, CAP_CHOWN, CAP_SETUID, …) that is far more than a web server needs; dropping ALL and adding back only what is used narrows the blast radius without changing the image. privileged: true is the opposite: it grants all capabilities and device access, and is almost never required outside a CNI or storage driver.

Pod Security Standards turn these settings into an admission policy at the namespace level. restricted is the hardened profile and refuses pods that omit seccompProfile, allow privilege escalation, run as root, or keep capabilities beyond a small allow-list. Labelling a namespace is the enforceable, cluster-wide version of writing the same fields by hand.

Basic Syntax & Core Signatures

yaml
apiVersion: v1 kind: Pod metadata: name: api spec: securityContext: # pod level: applies to all containers runAsNonRoot: true runAsUser: 10001 runAsGroup: 10001 fsGroup: 10001 # volume ownership for mounted files fsGroupChangePolicy: OnRootMismatch seccompProfile: type: RuntimeDefault # RuntimeDefault | Localhost | Unconfined containers: - name: api image: registry.example.com/shop/api:4.2.0 securityContext: # container level: overrides pod level allowPrivilegeEscalation: false readOnlyRootFilesystem: true privileged: false capabilities: drop: ["ALL"] add: ["NET_BIND_SERVICE"] # only if binding to port < 1024 procMount: Default volumeMounts: - { name: tmp, mountPath: /tmp } - { name: cache, mountPath: /app/.cache } volumes: - name: tmp emptyDir: {} - name: cache emptyDir: {}
yaml
# Namespace labels: the policy as admission control apiVersion: v1 kind: Namespace metadata: name: shop labels: pod-security.kubernetes.io/enforce: restricted pod-security.kubernetes.io/enforce-version: latest pod-security.kubernetes.io/audit: restricted pod-security.kubernetes.io/warn: restricted
bash
kubectl -n shop get deploy api -o jsonpath=\ '{.spec.template.spec.containers[0].securityContext}{"\n"}' kubectl -n shop auth can-i --list kubectl label --dry-run=server --overwrite ns shop \ pod-security.kubernetes.io/enforce=restricted # warns about existing pods kubectl run t --rm -it --image=busybox:1.36 --restart=Never -- sh -c 'id; capsh --print 2>/dev/null || grep Cap /proc/self/status'

Key Comparison Table

SettingLevelDefaultEffect
runAsNonRootpod / containerfalseRefuses to start if the image user is UID 0
runAsUserpod / containerimage USERSets the UID
allowPrivilegeEscalationcontainertrue (false when runAsNonRoot… not implied)Blocks setuid escalation
readOnlyRootFilesystemcontainerfalseRoot filesystem mounted read-only
capabilities.dropcontainerinherited default setRemoving ALL is the strong form
seccompProfile.typepod / containerUnconfined before PSARuntimeDefault is the runtime's filter
privilegedcontainerfalseAll capabilities, all devices
fsGrouppodnoneGroup ownership of volume files
ProfileRejectsAllows
privilegedNothing essentiallyHost access, privileged containers
baselineprivileged, host namespaces, hostPath, NET_RAW additionsDefault capabilities, root
restrictedPrivilege escalation, running as root, missing seccomp, added caps beyond NET_BIND_SERVICEA hardened pod that declares everything
SymptomMeaning
container has runAsNonRoot and image will run as rootImage has no numeric USER; set runAsUser
Permission denied writing to /app after readOnlyRootFilesystemMount an emptyDir where the app writes
Operation not permitted binding port 80Add NET_BIND_SERVICE or listen above 1024
Pod rejected with violates PodSecurity "restricted"A field above does not satisfy the profile

Practical Edge Cases & Deep Dives

1. allowPrivilegeEscalation: false and the setuid gap

A container running as UID 1000 can still execute a setuid-root binary inside the image and become root, because the kernel honours the file's setuid bit. allowPrivilegeEscalation: false sets no_new_privs on the process, which makes setuid and file capabilities ineffective for that process tree. It is the cheapest single hardening step and it has no effect on writability or networking.

text
$ kubectl exec api-xxx -- sh -c 'ls -l /bin/passwd; grep NoNewPrivs /proc/self/status' -rwsr-xr-x 1 root root ... /bin/passwd NoNewPrivs: 1

2. readOnlyRootFilesystem needs writable mounts, not a writable root

Most application images write to a handful of paths: /tmp, a cache directory, a log directory, or a PID file. With a read-only root those writes fail with EROFS and the container restarts, which looks like an application bug. Enumerate the paths first:

bash
kubectl exec -it api-xxx -- sh -c 'touch /x /tmp/y /app/z 2>&1; ls -la /app | head' # touch: /x: Read-only file system

Then mount an emptyDir for each writable path. Java's java.io.tmpdir, Python's __pycache__ writes, nginx's /var/cache/nginx and /var/run, and Node's .cache are the usual suspects. fsGroup matters at the same time: a mounted emptyDir is owned by root unless fsGroup is set, so a non-root container still cannot write.

3. Capabilities: what to drop and what to add back

yaml
capabilities: drop: ["ALL"] add: - NET_BIND_SERVICE # bind ports < 1024 - CHOWN # chown files owned by another user - SETUID / SETGID # su-exec, gosu entrypoints

NET_RAW is the capability behind raw sockets and is a common requirement for ping and for some service meshes; it is also the one restricted disallows adding. Most web services need nothing at all. A container that must change its own UID at start-up (an entrypoint that drops privileges via gosu) needs SETUID, SETGID, and often CHOWN — the reason that pattern is worse than a fixed runAsUser in the manifest.

4. seccompProfile: RuntimeDefault and the syscalls it blocks

The container runtime ships a default seccomp profile that blocks roughly 40 dangerous syscalls (kexec_load, add_key, mount for unprivileged users, and others). It is permissive enough for nearly every application, and restricted requires it. A Localhost profile is a per-node JSON file allowing a custom set — useful for a workload that needs one blocked syscall, at the cost of shipping the profile to every node.

yaml
securityContext: seccompProfile: type: Localhost localhostProfile: profiles/allow-keyctl.json # relative to the kubelet's seccomp root

5. Pod level versus container level, and the fields that only exist at one

runAsUser, runAsGroup, runAsNonRoot, fsGroup, seccompProfile, and supplementalGroups exist at both levels. allowPrivilegeEscalation, capabilities, readOnlyRootFilesystem, privileged, and procMount exist only at the container level — putting them under pod.spec.securityContext is silently ignored by the API server in most versions, which is a common cause of "I set it and nothing changed". Always verify the effective value on the pod:

bash
kubectl -n shop get pod api-xxx -o jsonpath=\ '{.spec.containers[0].securityContext}{"\n"}'

runAsNonRoot: true without runAsUser relies on the image's numeric USER; if the image says USER app (a name), the kubelet cannot verify non-root-ness and refuses to start the container.

Common Runtime & Configuration Mistakes

SymptomCauseFix
image will run as rootrunAsNonRoot with no numeric USERSet runAsUser numerically
Container crashloops writing filesRead-only root, no writable mountsemptyDir for each writable path
Permission denied on mounted volumefsGroup missing for a non-root UIDSet fsGroup
Cannot bind port 80NET_BIND_SERVICE droppedAdd the capability, or use 8080
Setting under the pod has no effectContainer-only field in pod contextMove it to the container's securityContext
Pod rejected under restrictedMissing seccompProfile or runAsNonRootDeclare all five fields
App fails on a blocked syscallRuntimeDefault seccompLocalhost profile with the syscall
Node driver stopped workingprivileged removedKeep privileged pods out of PS-namespaces
exec into pod deniedRBAC, not security contextGrant pods/exec verbs
Sudden failures after a namespace relabelAudit-only to enforceCheck warn output first

Security context is declarative hardening, and it only has an effect where it is actually set: on the container that runs the workload, and in a namespace whose Pod Security level enforces it. Write the five fields explicitly in every manifest, verify them on the running pod, and let the namespace label catch what a later contributor forgets.

Try matching browser tools

All tools

Small utilities that fit Kubernetes work — they run entirely in this browser tab, so nothing you paste leaves your device.

All Kubernetes guides

More in Kubernetes

All Kubernetes guides

The guides filed next to this one in Kubernetes, in library order.