Tag 9: Pod Security Standards und SecurityContext
Ziel: Du erzwingst Pod Security Standards per Namespace-Label, liest Verstöße und machst Workloads
restricted-fähig. · Dauer: ca. 60 min · Voraussetzung: Tag 8
Briefing
- CKS: Minimize Microservice Vulnerabilities – „Use appropriate pod security standards“.
- Pod Security Admission (PSA) ist im API-Server fest eingebaut und per Default aktiv. Gesteuert wird pro Namespace über Labels, kein Webhook, keine CRD.
- Drei Stufen:
privileged(alles),baseline(keine Host-Zugriffe, keinprivileged),restricted(zusätzlich Nicht-Root,drop ALL, seccomp). - Drei Modi:
enforce(ablehnen),warn(Warnung an den Client),audit(Vermerk im Audit-Log, Tag 15). Jeder Modus hat ein-version-Label.
pod-security.kubernetes.io/<modus>=<stufe>
pod-security.kubernetes.io/<modus>-version=v1.37 | latest
modus: enforce | warn | audit stufe: privileged | baseline | restricted
Vorbereitung:
mkdir -p ~/cks/tag09 && cd ~/cks/tag09
k create ns tag09
k config set-context --current --namespace=tag09
curl -s http://172.16.0.126:30500/v2/notes-api/tags/listErwartet:
{"name":"notes-api","tags":["1.0"]}
Fehlt das Image (die Registry nutzt emptyDir und vergisst alles beim Neustart), baue es aus dem Begleitrepo:
cd ~/cks
git clone https://github.com/thomaszachmann/cks-zum-anfassen
cd cks-zum-anfassen/notes-api
cat > Dockerfile <<'EOF'
FROM docker.io/library/golang:1.27-alpine AS build
WORKDIR /src
COPY go.mod go.sum ./
RUN go mod download
COPY . .
ARG VERSION=dev
RUN CGO_ENABLED=0 go build -ldflags="-s -w -X main.version=${VERSION}" \
-o /out/notes-api .
FROM docker.io/library/alpine:3.23
COPY --from=build /out/notes-api /usr/local/bin/notes-api
USER 65532:65532
EXPOSE 8080
ENTRYPOINT ["notes-api"]
EOF
podman build -t 172.16.0.126:30500/notes-api:1.0 --build-arg VERSION=1.0 .
podman push --tls-verify=false 172.16.0.126:30500/notes-api:1.0
cd ~/cks/tag09Drill 1: Die unsichere Ausgangslage
Ein typischer Altbestand: die App ohne jeden SecurityContext und ein „Debug-Pod“ mit Vollzugriff auf den Node.
k create secret generic notes-key --from-literal=NOTES_API_KEY=lab-key-123
k create deploy notes --image=172.16.0.126:30500/notes-api:1.0
k set env deploy/notes --from=secret/notes-key
cat > toolbox.yaml <<'EOF'
apiVersion: v1
kind: Pod
metadata:
name: toolbox
spec:
hostPID: true
containers:
- name: c
image: busybox:1.37
command: ["sleep", "infinity"]
securityContext:
privileged: true
EOF
k apply -f toolbox.yaml
k rollout status deploy/notes
k wait --for=condition=Ready pod/toolbox
k get pods
k exec toolbox -- ps -o pid,comm | head -3Erwartet:
NAME READY STATUS RESTARTS AGE
notes-7d6b8b9c78-fd9c2 1/1 Running 0 19s
toolbox 1/1 Running 0 18s
PID COMMAND
1 systemd
2 kthreadd
PID 1 ist systemd des Nodes: Mit hostPID
sieht (und mit privileged beeinflusst) der Container jeden
Prozess des Hosts, auch kubelet und containerd. Ohne Labels lässt der
Namespace das zu – er verhält sich wie privileged.
Fortschritt speichern? Kostenlos registrieren
Drill 2: Erst warnen, dann erzwingen
warn und audit blockieren nichts. Damit
siehst du, was restricted bräche, bevor es weh tut:
k label ns tag09 \
pod-security.kubernetes.io/warn=restricted \
pod-security.kubernetes.io/warn-version=v1.37 \
pod-security.kubernetes.io/audit=restricted \
pod-security.kubernetes.io/audit-version=v1.37
k run probe --image=busybox:1.37 -- sleep 1dErwartet:
namespace/tag09 labeled
Warning: would violate PodSecurity "restricted:v1.37": allowPrivilegeEscalation != false
(container "probe" must set securityContext.allowPrivilegeEscalation=false),
unrestricted capabilities (container "probe" must set
securityContext.capabilities.drop=["ALL"]), runAsNonRoot != true (pod or container
"probe" must set securityContext.runAsNonRoot=true), seccompProfile (pod or container
"probe" must set securityContext.seccompProfile.type to "RuntimeDefault" or "Localhost")
pod/probe created
Die Warnung ist die Checkliste: Jede Klammer nennt Feld und Sollwert.
audit schreibt dieselbe Information als Annotation
pod-security.kubernetes.io/audit-violations ins Audit-Log –
das ist erst ab Tag 15 eingeschaltet.
Fortschritt speichern? Kostenlos registrieren
Drill 3: Vorhandene Pods prüfen mit –dry-run=server
Bevor du enforce setzt, fragst du den API-Server, welche
laufenden Pods die neue Stufe verletzen würden:
k label --dry-run=server --overwrite ns tag09 \
pod-security.kubernetes.io/enforce=restricted \
pod-security.kubernetes.io/enforce-version=v1.37
k label --dry-run=server --overwrite ns tag09 \
pod-security.kubernetes.io/enforce=baseline \
pod-security.kubernetes.io/enforce-version=v1.37Erwartet:
Warning: existing pods in namespace "tag09" violate the new PodSecurity enforce level
"restricted:v1.37"
Warning: notes-7d6b8b9c78-fd9c2 (and 1 other pod): allowPrivilegeEscalation != false,
unrestricted capabilities, runAsNonRoot != true, seccompProfile
Warning: toolbox: host namespaces, privileged, allowPrivilegeEscalation != false,
unrestricted capabilities, runAsNonRoot != true, seccompProfile
namespace/tag09 labeled (server dry run)
Warning: existing pods in namespace "tag09" violate the new PodSecurity enforce level
"baseline:v1.37"
Warning: toolbox: host namespaces, privileged
namespace/tag09 labeled (server dry run)
baseline stört nur toolbox,
restricted alle. Dasselbe für den ganzen Cluster (ändert
nichts, nur Probe):
k label --dry-run=server --overwrite ns --all \
pod-security.kubernetes.io/enforce=baselineErwartet (gekürzt):
namespace/default labeled (server dry run)
Warning: existing pods in namespace "kube-system" violate the new PodSecurity enforce
level "baseline:latest"
Warning: cilium-kf854 (and 2 other pods): forbidden AppArmor profile, non-default
capabilities, host namespaces, hostPath volumes, hostPort, probe or lifecycle host,
privileged, seLinuxOptions, seccompProfile
Warning: etcd-cp1 (and 3 other pods): host namespaces, hostPath volumes, hostPort, probe
or lifecycle host
Warning: kube-proxy-7b5pz (and 2 other pods): host namespaces, hostPath volumes,
privileged
namespace/kube-system labeled (server dry run)
...
kube-system braucht Host-Zugriff (CNI, kube-proxy,
Static Pods) – dort bleibt es bei privileged.
Fortschritt speichern? Kostenlos registrieren
Drill 4: baseline erzwingen
k label --overwrite ns tag09 \
pod-security.kubernetes.io/enforce=baseline \
pod-security.kubernetes.io/enforce-version=v1.37
k get pod toolbox
sed 's/name: toolbox/name: toolbox2/' toolbox.yaml | k apply -f -
k run hn --image=busybox:1.37 --overrides='{"spec":{"hostNetwork":true}}' -- sleep 1dErwartet:
Warning: existing pods in namespace "tag09" violate the new PodSecurity enforce level
"baseline:v1.37"
Warning: toolbox: host namespaces, privileged
namespace/tag09 labeled
NAME READY STATUS RESTARTS AGE
toolbox 1/1 Running 0 39s
Error from server (Forbidden): error when creating "STDIN": pods "toolbox2" is
forbidden: violates PodSecurity "baseline:v1.37": host namespaces (hostPID=true),
privileged (container "c" must not set securityContext.privileged=true)
Error from server (Forbidden): pods "hn" is forbidden: violates PodSecurity
"baseline:v1.37": host namespaces (hostNetwork=true)
Falle: PSA prüft nur beim Anlegen. toolbox läuft weiter
– du musst ihn selbst entfernen. Ein hostPath-Volume
scheitert genauso mit hostPath volumes (volume "…").
k delete pod toolbox probe --nowFortschritt speichern? Kostenlos registrieren
Drill 5: restricted – Deployment da, Pods nicht
k create ns tag09-strict
k label ns tag09-strict \
pod-security.kubernetes.io/enforce=restricted \
pod-security.kubernetes.io/enforce-version=v1.37
k -n tag09-strict create secret generic notes-key \
--from-literal=NOTES_API_KEY=lab-key-123
k -n tag09-strict create deploy notes --image=172.16.0.126:30500/notes-api:1.0
k -n tag09-strict set env deploy/notes --from=secret/notes-key
k -n tag09-strict get deploy notes
k -n tag09-strict get events --field-selector reason=FailedCreate \
-o jsonpath='{.items[0].message}{"\n"}'Erwartet (gekürzt):
Warning: would violate PodSecurity "restricted:v1.37": allowPrivilegeEscalation != false
...
deployment.apps/notes created
NAME READY UP-TO-DATE AVAILABLE AGE
notes 0/1 0 0 3s
Error creating: pods "notes-7d6b8b9c78-wfvf8" is forbidden: violates PodSecurity
"restricted:v1.37": allowPrivilegeEscalation != false (container "notes-api" must set
securityContext.allowPrivilegeEscalation=false), ...
Das Deployment selbst wird angelegt (nur eine Warnung); erst der
ReplicaSet-Controller scheitert beim Pod. In der Prüfung heißt das
Symptom „0/1 und kein Pod“ – die Ursache steht in den Events oder in
k describe rs.
Fortschritt speichern? Kostenlos registrieren
Drill 6: Verstöße beheben
Die vier Punkte aus der Warnung, als Patch auf das Pod-Template:
cat > fix.yaml <<'EOF'
spec:
template:
spec:
securityContext:
runAsNonRoot: true
seccompProfile:
type: RuntimeDefault
containers:
- name: notes-api
securityContext:
allowPrivilegeEscalation: false
capabilities:
drop: ["ALL"]
EOF
k -n tag09-strict patch deploy notes --patch-file fix.yaml
k -n tag09-strict rollout status deploy/notes
k -n tag09-strict exec deploy/notes -- \
grep -E '^Uid|CapEff|NoNewPrivs|Seccomp:' /proc/1/status
k -n tag09-strict exec deploy/notes -- wget -qO- localhost:8080/healthzErwartet:
deployment.apps/notes patched
deployment "notes" successfully rolled out
Uid: 65532 65532 65532 65532
CapEff: 0000000000000000
NoNewPrivs: 1
Seccomp: 2
ok
Jeder Wert ist nachgewiesen: Nicht-Root (65532), keine Capabilities,
no_new_privs, seccomp-Filter aktiv. Der
Strategic-Merge-Patch fügt die Felder über den Container-Namen zusammen;
readOnlyRootFilesystem verlangt restricted
übrigens nicht (Tag 18).
Fortschritt speichern? Kostenlos registrieren
Drill 7: runAsNonRoot – Admission sagt ja, kubelet sagt nein
cat > shell.yaml <<'EOF'
apiVersion: v1
kind: Pod
metadata:
name: shell
spec:
securityContext:
runAsNonRoot: true
seccompProfile:
type: RuntimeDefault
containers:
- name: c
image: busybox:1.37
command: ["sleep", "1d"]
securityContext:
allowPrivilegeEscalation: false
capabilities:
drop: ["ALL"]
EOF
k -n tag09-strict apply -f shell.yaml
k -n tag09-strict get pod shell -w # Strg+C, sobald der Fehlerstatus steht
k -n tag09-strict describe pod shell | grep -m1 'Error:'Erwartet (gekürzt):
pod/shell created
NAME READY STATUS RESTARTS AGE
shell 0/1 CreateContainerConfigError 0 7s
... Error: container has runAsNonRoot and image will run as root (pod:
"shell_tag09-strict(b26d…)", container: c)
PSA prüft nur, ob runAsNonRoot: true
gesetzt ist. Ob das Image wirklich als Nicht-Root
startet, merkt erst das kubelet. busybox hat keinen USER –
also einen numerischen Benutzer vorgeben:
k -n tag09-strict delete pod shell --now
sed -i 's/^ runAsNonRoot: true/&\n runAsUser: 1000/' shell.yaml
k -n tag09-strict apply -f shell.yaml
k -n tag09-strict wait --for=condition=Ready pod/shell
k -n tag09-strict exec shell -- idErwartet:
pod/shell condition met
uid=1000 gid=0(root) groups=0(root)
Fortschritt speichern? Kostenlos registrieren
Drill 8: Gefährliche Pods im Cluster finden
Ohne PSA-Labels musst du selbst suchen. jq ist in der
Prüfung üblicherweise vorhanden; sonst hilft
-o custom-columns (Speed-Drill 3):
k get pods -A -o json | jq -r '.items[]
| select(.spec.hostNetwork or .spec.hostPID or .spec.hostIPC)
| .metadata.namespace + "/" + .metadata.name'
k get pods -A -o json | jq -r '.items[]
| select(any(.spec.containers[], .spec.initContainers[]?;
.securityContext.privileged))
| .metadata.namespace + "/" + .metadata.name'
k get pods -A -o json | jq -r '.items[]
| select(any(.spec.volumes[]?; .hostPath))
| .metadata.namespace + "/" + .metadata.name'Erwartet (gekürzt, nur Systempods – deine
tag09-Pods sind sauber):
kube-system/cilium-envoy-7kl7t
kube-system/cilium-kf854
kube-system/etcd-cp1
kube-system/kube-proxy-7b5pz
...
kube-system/cilium-kf854
kube-system/kube-proxy-7b5pz
...
initContainers gehören dazu: Bei Cilium ist
privileged nur dort gesetzt. Und woher kommt PSA
überhaupt?
sudo grep admission /etc/kubernetes/manifests/kube-apiserver.yamlErwartet:
- --enable-admission-plugins=NodeRestriction
PodSecurity steht nicht da, weil es zu den
Default-Plugins gehört
(k -n kube-system exec kube-apiserver-cp1 -- kube-apiserver -h | grep enable-admission-plugins
listet sie). Cluster-weite Vorgaben und Ausnahmen (Namespaces, Benutzer,
RuntimeClasses) setzt eine AdmissionConfiguration mit
kind: PodSecurityConfiguration, eingebunden per
--admission-control-config-file. Das ist ein
API-Server-Eingriff wie in Tag 6 – hier nur zum Wissen, nicht
ausführen.
Fortschritt speichern? Kostenlos registrieren
Übung: Speed-Drills
- Namespace
tag09-team:baselineerzwingen,restrictedwarnen und auditieren, alle Versionen auf v1.37 gepinnt. Zeitziel: 1 min - Prüfe, welche Pods in
tag09gegenrestrictedverstoßen, ohne etwas zu ändern. Zeitziel: 30 s - Liste alle Pods im Cluster mit
hostNetwork: true– ohnejq. Zeitziel: 1 min - Pod
sleeper(busybox:1.37,sleep 1d) läuft intag09-strict. Zeitziel: 2 min
Lösung
k create ns tag09-team
k label ns tag09-team \
pod-security.kubernetes.io/enforce=baseline \
pod-security.kubernetes.io/enforce-version=v1.37 \
pod-security.kubernetes.io/warn=restricted \
pod-security.kubernetes.io/warn-version=v1.37 \
pod-security.kubernetes.io/audit=restricted \
pod-security.kubernetes.io/audit-version=v1.37
k label --dry-run=server --overwrite ns tag09 \
pod-security.kubernetes.io/enforce=restricted
k get pods -A -o custom-columns=\
NS:.metadata.namespace,NAME:.metadata.name,HOSTNET:.spec.hostNetwork | grep -E 'NS|true'
k run sleeper --image=busybox:1.37 $do -- sleep 1d > sleeper.yamlsleeper.yaml ergänzen (Pod- und Container-Ebene):
spec:
securityContext:
runAsNonRoot: true
runAsUser: 1000
seccompProfile:
type: RuntimeDefault
containers:
- name: sleeper
image: busybox:1.37
args: ["sleep", "1d"]
securityContext:
allowPrivilegeEscalation: false
capabilities:
drop: ["ALL"]k -n tag09-strict apply -f sleeper.yaml
k -n tag09-strict wait --for=condition=Ready pod/sleeperErwartet (gekürzt):
namespace/tag09-team labeled
Warning: existing pods in namespace "tag09" violate the new PodSecurity enforce level
"restricted:v1.37"
Warning: notes-7d6b8b9c78-fd9c2: allowPrivilegeEscalation != false, unrestricted
capabilities, runAsNonRoot != true, seccompProfile
namespace/tag09 labeled (server dry run)
NS NAME HOSTNET
kube-system cilium-envoy-7kl7t true
...
pod/sleeper condition met
In Aufgabe 2 gilt restricted:v1.37, obwohl du keine
Version angibst: Das vorhandene Label enforce-version=v1.37
bleibt stehen.
Fortschritt speichern? Kostenlos registrieren
Kontrollpunkt
k get ns -l pod-security.kubernetes.io/enforce=restrictedErwartet: tag09-strict ist dabei.
k get ns tag09-strict \
-o jsonpath='{.metadata.labels.pod-security\.kubernetes\.io/enforce-version}{"\n"}'Erwartet: v1.37
k -n tag09-strict get deploy notesErwartet: notes 1/1 1 1 …
k get pod toolboxErwartet:
Error from server (NotFound): pods "toolbox" not found
Challenge
Spiele den Altbestand ein (unten). Danach soll Namespace
tag09-ch restricted in Version v1.37 erzwingen
und das Deployment legacy trotzdem laufen – ohne Host-Netz,
ohne Host-Pfad, ohne privileged.
k create ns tag09-ch
k -n tag09-ch create secret generic notes-key \
--from-literal=NOTES_API_KEY=lab-key-123
cat > legacy.yaml <<'EOF'
apiVersion: apps/v1
kind: Deployment
metadata:
name: legacy
spec:
selector:
matchLabels:
app: legacy
template:
metadata:
labels:
app: legacy
spec:
hostNetwork: true
containers:
- name: notes-api
image: 172.16.0.126:30500/notes-api:1.0
env:
- name: PORT
value: "18080"
envFrom:
- secretRef:
name: notes-key
securityContext:
privileged: true
volumeMounts:
- name: logs
mountPath: /host-logs
volumes:
- name: logs
hostPath:
path: /var/log
EOF
k -n tag09-ch apply -f legacy.yamlHinweis: Erst mit --dry-run=server die
Liste der Verstöße holen, dann das Label setzen – der laufende Pod wird
dadurch nicht entfernt, erst der Rollout zählt.
Lösung
k label --dry-run=server --overwrite ns tag09-ch \
pod-security.kubernetes.io/enforce=restricted \
pod-security.kubernetes.io/enforce-version=v1.37Erwartet:
Warning: existing pods in namespace "tag09-ch" violate the new PodSecurity enforce level
"restricted:v1.37"
Warning: legacy-6b55476555-2kbmg: host namespaces, privileged, allowPrivilegeEscalation
!= false, unrestricted capabilities, restricted volume types, runAsNonRoot != true,
seccompProfile
namespace/tag09-ch labeled (server dry run)
restricted volume types: Erlaubt sind nur configMap,
csi, downwardAPI, emptyDir, ephemeral, persistentVolumeClaim, projected
und secret. Label setzen, dann in legacy.yaml
hostNetwork, privileged,
volumeMounts und volumes löschen und die
bekannten Felder ergänzen:
k label --overwrite ns tag09-ch \
pod-security.kubernetes.io/enforce=restricted \
pod-security.kubernetes.io/enforce-version=v1.37 spec:
securityContext:
runAsNonRoot: true
seccompProfile:
type: RuntimeDefault
containers:
- name: notes-api
image: 172.16.0.126:30500/notes-api:1.0
env:
- name: PORT
value: "18080"
envFrom:
- secretRef:
name: notes-key
securityContext:
allowPrivilegeEscalation: false
capabilities:
drop: ["ALL"]k -n tag09-ch apply -f legacy.yaml
k -n tag09-ch rollout status deploy/legacy
k label --dry-run=server --overwrite ns tag09-ch \
pod-security.kubernetes.io/enforce-version=latestErwartet:
deployment.apps/legacy configured
deployment "legacy" successfully rolled out
namespace/tag09-ch labeled (server dry run)
Keine Warnung mehr. Warum enforce-version=latest als
Probe? Setzt du dasselbe Label mit demselben Wert, meldet kubectl
not labeled und PSA prüft gar nichts – die Probe braucht
eine echte Änderung.
Aufräumen:
k config set-context --current --namespace=default
k delete ns tag09 tag09-strict tag09-team tag09-chFortschritt speichern? Kostenlos registrieren
Prüfungstipp
- Falsche Werte lehnt der API-Server ab
(
must be one of privileged, baseline, restricted, Versionmust be "latest" or "v1.x"). Einen Tippfehler im Schlüssel (…/enforcee) nimmt er dagegen still an – danach mit--show-labelsprüfen. - Nach
enforcelaufen alte Pods weiter. Wenn die Aufgabe „keine verletzenden Pods“ verlangt, Pods neu erzeugen (k rollout restart) oder löschen. - Doku: kubernetes.io → Concepts → Security → „Pod Security Standards“ (Feldliste je Stufe) und Tasks → „Enforce Pod Security Standards with Namespace Labels“.
Enterprise-Notiz
- Version pinnen (
v1.37), damit ein Cluster-Upgrade nicht über Nacht Workloads sperrt; vor dem Anheben mit--dry-run=serverundwarnauf der neuen Version testen. - Cluster-Default
baselineenforce plusrestrictedwarn/audit perAdmissionConfiguration, Ausnahmen nur für System-Namespaces. - Wer Namespaces anlegen oder labeln darf, kann PSA abschalten –
namespacespatchundupdateper RBAC eng halten (Tag 5). - Für feinere Regeln (erlaubte Registries, Pflicht-Labels) kommen Kyverno, Gatekeeper oder ValidatingAdmissionPolicy dazu.