TExcelTAD
Home › Cloud & Container Security › Pod Security Standards and Hardened Pods

Pod Security Standards and Hardened Pods

Every escape class of the container lessons is switched on in the pod spec: privileged: true, hostPID, a hostPath volume, an added capability, a missing seccomp profile. Kubernetes defines three Pod Security Standards that sort those settings into levels, and a built-in admission controller, Pod Security Admission (PSA), that enforces a level per namespace. Together they turn "please write secure pod specs" into "the API server refuses insecure ones". This lesson shows the levels, evaluates pods against them, and scans manifests before they reach the cluster. Security Contexts & Pod Security introduced the fields; here they are reviewed as an attacker would read them.

The three levels

Level Meant for Forbids (main points)
privileged system components that need the host (CNI, storage and monitoring agents) nothing
baseline ordinary workloads, with minimal changes privileged, hostNetwork/hostPID/hostIPC, hostPath volumes, hostPort, adding capabilities beyond a small default list, custom AppArmor/SELinux types that weaken confinement, procMount: Unmasked, unsafe sysctls
restricted anything that can follow current hardening practice everything in baseline, plus requires runAsNonRoot: true (and no UID 0), allowPrivilegeEscalation: false, capabilities.drop: ["ALL"] (only NET_BIND_SERVICE may be added), seccompProfile RuntimeDefault or Localhost, and only safe volume types

PSA reads namespace labels: pod-security.kubernetes.io/enforce: restricted rejects violating pods; audit and warn only log or warn, which is how you roll it out. Each label can be pinned to a Kubernetes version (enforce-version: v1.34) so a cluster upgrade doesn't change the rules under you.

A Pod Security evaluator

The program checks pod specs against simplified versions of the baseline and restricted rules and simulates PSA for a namespace labelled enforce: restricted. The specs are from the lab cluster.

python · try it yourself
import yaml

BASELINE_CAPS = {"AUDIT_WRITE", "CHOWN", "DAC_OVERRIDE", "FOWNER", "FSETID", "KILL", "MKNOD", "NET_BIND_SERVICE",
                 "SETFCAP", "SETGID", "SETPCAP", "SETUID", "SYS_CHROOT"}

def violations(pod):
    spec, base, restr = pod["spec"], [], []
    psc = spec.get("securityContext", {})
    for flag in ("hostNetwork", "hostPID", "hostIPC"):
        if spec.get(flag):
            base.append(flag)
    for v in spec.get("volumes", []):
        if "hostPath" in v:
            base.append(f"hostPath volume {v['hostPath']['path']}")
    for c in spec["containers"]:
        sc = c.get("securityContext", {})
        if sc.get("privileged"):
            base.append(f"{c['name']}: privileged")
        extra = set(sc.get("capabilities", {}).get("add", [])) - BASELINE_CAPS
        if extra:
            base.append(f"{c['name']}: adds {sorted(extra)}")
        if any(p.get("hostPort") for p in c.get("ports", [])):
            base.append(f"{c['name']}: hostPort")
        # restricted-only rules (container settings override pod settings)
        if not sc.get("runAsNonRoot", psc.get("runAsNonRoot")) or sc.get("runAsUser", psc.get("runAsUser")) == 0:
            restr.append(f"{c['name']}: runAsNonRoot not true")
        if sc.get("allowPrivilegeEscalation") is not False:
            restr.append(f"{c['name']}: allowPrivilegeEscalation not false")
        if "ALL" not in sc.get("capabilities", {}).get("drop", []):
            restr.append(f"{c['name']}: capabilities not dropped (ALL)")
        if set(sc.get("capabilities", {}).get("add", [])) - {"NET_BIND_SERVICE"}:
            restr.append(f"{c['name']}: adds capabilities other than NET_BIND_SERVICE")
        prof = sc.get("seccompProfile", psc.get("seccompProfile", {})).get("type")
        if prof not in ("RuntimeDefault", "Localhost"):
            restr.append(f"{c['name']}: seccompProfile {prof or 'unset'}")
    return base, restr

pods = list(yaml.safe_load_all("""
metadata: {name: web}
spec:
  securityContext: {runAsNonRoot: true, runAsUser: 10001, seccompProfile: {type: RuntimeDefault}}
  containers:
  - name: web
    securityContext: {allowPrivilegeEscalation: false, readOnlyRootFilesystem: true, capabilities: {drop: [ALL]}}
---
metadata: {name: legacy-api}
spec:
  containers:
  - name: api
    ports: [{containerPort: 8080}]
---
metadata: {name: proxy}
spec:
  securityContext: {runAsNonRoot: true, runAsUser: 101, seccompProfile: {type: RuntimeDefault}}
  containers:
  - name: nginx
    ports: [{containerPort: 80}]
    securityContext: {allowPrivilegeEscalation: false, capabilities: {drop: [ALL], add: [NET_BIND_SERVICE]}}
---
metadata: {name: node-agent}
spec:
  hostPID: true
  hostNetwork: true
  volumes: [{name: root, hostPath: {path: /}}]
  containers:
  - name: agent
    securityContext: {privileged: true, capabilities: {add: [SYS_ADMIN]}}
"""))
for pod in pods:
    base, restr = violations(pod)
    level = "privileged" if base else ("baseline" if restr else "restricted")
    admitted = "admitted" if level == "restricted" else "REJECTED"
    print(f"{pod['metadata']['name']:11} meets {level:10} -> ns shop (enforce=restricted): {admitted}")
    for v in base:
        print(f"   baseline   {v}")
    for v in restr:
        print(f"   restricted {v}")
web         meets restricted -> ns shop (enforce=restricted): admitted
legacy-api  meets baseline   -> ns shop (enforce=restricted): REJECTED
   restricted api: runAsNonRoot not true
   restricted api: allowPrivilegeEscalation not false
   restricted api: capabilities not dropped (ALL)
   restricted api: seccompProfile unset
proxy       meets restricted -> ns shop (enforce=restricted): admitted
node-agent  meets privileged -> ns shop (enforce=restricted): REJECTED
   baseline   hostNetwork
   baseline   hostPID
   baseline   hostPath volume /
   baseline   agent: privileged
   baseline   agent: adds ['SYS_ADMIN']
   restricted agent: runAsNonRoot not true
   restricted agent: allowPrivilegeEscalation not false
   restricted agent: capabilities not dropped (ALL)
   restricted agent: adds capabilities other than NET_BIND_SERVICE
   restricted agent: seccompProfile unset

The web and proxy pods meet restricted (the proxy may add NET_BIND_SERVICE to listen on port 80). legacy-api breaks no baseline rule but none of the restricted ones are set: it would run as whatever the image says, probably root, with the default capability set and no seccomp. That is the typical state of an unreviewed workload, and warn/audit labels are how you find all of them before switching to enforce. node-agent needs the privileged level; such agents belong in their own namespace (for example kube-system or node-agents) labelled privileged, with tight RBAC on who may create pods there.

Scanning manifests before they reach the cluster

The same rules, and more, run in CI with a manifest scanner. The session scans the insecure pod spec from the escape lesson and the hardened deployment of the web service; it runs in your sandbox on local files.

bash · try it yourself
mkdir insecure hardened
cat > insecure/pod.yaml <<'Y'
apiVersion: v1
kind: Pod
metadata: {name: debug, namespace: shop}
spec:
  hostPID: true
  containers:
    - name: debug
      image: registry.lab.test/tools/debug:latest
      securityContext: {privileged: true}
      volumeMounts: [{name: sock, mountPath: /var/run/docker.sock}]
  volumes:
    - name: sock
      hostPath: {path: /var/run/docker.sock}
Y
cat > hardened/web.yaml <<'Y'
apiVersion: apps/v1
kind: Deployment
metadata: {name: web, namespace: shop}
spec:
  replicas: 2
  selector: {matchLabels: {app: web}}
  template:
    metadata: {labels: {app: web}}
    spec:
      serviceAccountName: web
      automountServiceAccountToken: false
      securityContext:
        runAsNonRoot: true
        runAsUser: 10001
        runAsGroup: 10001
        seccompProfile: {type: RuntimeDefault}
      containers:
        - name: web
          image: registry.lab.test/shop/web@sha256:4f2c9a7e1b3d5f6a8c0e2d4b6a8f0c1e3d5b7a9c0e2f4d6b8a0c2e4f6a8b0c1d
          ports: [{containerPort: 8000}]
          securityContext:
            allowPrivilegeEscalation: false
            readOnlyRootFilesystem: true
            capabilities: {drop: ["ALL"]}
          resources:
            requests: {cpu: 100m, memory: 128Mi}
            limits: {cpu: 500m, memory: 256Mi}
          volumeMounts: [{name: tmp, mountPath: /tmp}]
      volumes: [{name: tmp, emptyDir: {}}]
Y
scan() { trivy config -q -f json "$@" | jq -r '[.Results[].Misconfigurations[]?] | "\(length) findings", (sort_by(.ID)[] | select(.Severity == "HIGH" or .Severity == "CRITICAL" or $all) | "   \(.Severity) \(.ID) \(.Title)")' --argjson all "${ALL:-false}"; }
echo "== insecure (HIGH and CRITICAL shown)"; scan insecure
echo "== hardened (all shown)"; ALL=true scan hardened
printf '# registry.lab.test is our private registry (signed images, admission-checked)\nKSV-0125\n' > hardened/.trivyignore
echo "== hardened, with a documented exception"; (cd hardened && ALL=true scan .)
== insecure (HIGH and CRITICAL shown)
21 findings
   HIGH KSV-0006 hostPath volume mounted with docker.sock
   HIGH KSV-0010 Access to host PID
   HIGH KSV-0014 Root file system is not read-only
   HIGH KSV-0017 Privileged
   HIGH KSV-0118 Default security context configured
== hardened (all shown)
1 findings
   MEDIUM KSV-0125 Restrict container images to trusted registries
== hardened, with a documented exception
0 findings

The insecure pod fails 21 checks, five of them HIGH: privileged, host PID, the Docker socket as a hostPath, a writable root filesystem and the default security context. The hardened deployment fails only one, and that one is about the scanner's built-in list of trusted registries, which doesn't know the lab's private registry. The right response is a documented exception (an ignore entry with the reason next to it), not deleting the check: in another repository, an image from an unknown registry is a real finding.

How weak pod security is detected

  • Namespace labels: namespaces without pod-security.kubernetes.io/enforce, or with privileged on application namespaces. kubectl label --dry-run=server --overwrite ns shop pod-security.kubernetes.io/enforce=restricted lists the existing pods that would violate the level without changing anything.
  • Manifests in CI: Trivy, Kubescape, Checkov or kube-linter on every chart and manifest.
  • Running pods: audit logs with PSA audit annotations (pod-security.kubernetes.io/audit-violations), posture tools, and the runtime view of the previous lessons.

How it is fixed

  1. Label every namespace: enforce: baseline immediately, warn and audit at restricted; fix the warnings; then enforce: restricted.
  2. Make the hardened securityContext the default in your Helm charts and templates (golden paths), so new services start compliant.
  3. Isolate the few workloads that need privileged in dedicated namespaces with restricted RBAC and, ideally, dedicated nodes.
  4. Add a policy engine for what PSA doesn't cover (image registries and signatures, readOnlyRootFilesystem, resource limits, labels): Admission Control.

Pitfalls

  • PSA checks pods, but rejects them when a controller creates them: a Deployment is accepted and its ReplicaSet then fails to create pods. (The warn and audit modes do check the pod templates of Deployments, Jobs and other workloads, so they show the problem at kubectl apply time; enforce only acts on the pods.) Watch for FailedCreate events, or check at the workload level in CI.
  • Exempting a whole namespace because one pod needs host access.
  • Believing restricted covers everything: it doesn't require a read-only root filesystem, resource limits or trusted images.

Practice

1. Add runAsUser: 0 to the web container's securityContext. What does the evaluator say?

web drops to baseline and is rejected: web: runAsNonRoot not true (container settings override pod settings, and UID 0 is root). At run time, the kubelet would also refuse to start a container with runAsNonRoot: true and UID 0.

2. Which settings make legacy-api restricted-compliant, and what might break?

Pod or container runAsNonRoot: true with a non-zero runAsUser, allowPrivilegeEscalation: false, capabilities: {drop: [ALL]} and seccompProfile: {type: RuntimeDefault}. Images that expect root (writing to /var, binding port 80, chown at start) need small changes: a writable volume, port ≥ 1024 or NET_BIND_SERVICE, files owned at build time.

3. Why put the restricted level in warn and audit before enforce?

To find every existing violation (warnings in kubectl output, annotations in audit logs) without breaking deployments, fix them, and then enforce without surprises.

Test yourself

Which Pod Security level forbids privileged containers and host namespaces but not running as root?

  1. privileged
  2. baseline
  3. restricted
  4. none

What does the label pod-security.kubernetes.io/enforce: restricted do?

  1. Logs violations only
  2. Makes the API server reject pods in that namespace that violate the restricted standard
  3. Encrypts Secrets
  4. Blocks all pods

Which capability may a restricted pod add?

  1. SYS_ADMIN
  2. NET_ADMIN
  3. NET_BIND_SERVICE
  4. None at all

Why was KSV-0125 on the hardened deployment handled with an ignore entry and a comment?

  1. To hide a real problem
  2. The scanner's trusted-registry list doesn't include the organisation's private registry; the exception is documented and justified
  3. Trivy requires it
  4. The check is broken