Zum Inhalt springen
Trainingslager IT-Trainingslager

Tag 8: Sicherheit im Pod

Ziel: Alle Pods von notes laufen unter Pod Security „restricted”: ohne root, ohne Capabilities, mit schreibgeschütztem Dateisystem und ohne Token für die Kubernetes-API. · Dauer: ca. 90 min · Voraussetzung: Tag 7

Briefing

  • Bisher gilt, was Image und Runtime vorgeben: Capabilities, beschreibbares Dateisystem und das Token des ServiceAccounts default in jedem Container.
  • Pod Security Admission prüft jeden neuen Pod gegen eine von drei Stufen: privileged, baseline, restricted. Labels am Namespace legen Stufe und Modus fest (enforce lehnt ab, warn warnt kubectl, audit schreibt ins Audit-Log).
  • Der securityContext steht am Pod (User, Gruppe, fsGroup, seccomp) und am Container (Capabilities, Privilege Escalation, read-only).
  • Ein eigener ServiceAccount ohne Token, RBAC regelt, was ein Konto an der API darf.
 kubectl apply ─► API-Server ─► Admission „PodSecurity" (Labels am Namespace notes)
                                  enforce=restricted → Pod wird abgelehnt
                                  warn=restricted    → Warnung an kubectl
 Pod  securityContext: runAsNonRoot · runAsUser/Group · fsGroup · seccompProfile
  └─ Container securityContext: allowPrivilegeEscalation · readOnlyRootFilesystem
                                capabilities.drop [ALL]

Drill 1: Was ein Pod heute darf

source ~/k8s-lab/setup/env.sh
mkdir -p ~/k8s-lab/tag08 && cd ~/k8s-lab/tag08
cp -R "$LAB/code/notes/." . && cp -R "$LAB/code/tag07/notes/." .
kubectl exec deploy/web -- id
kubectl exec deploy/web -- sh -c 'touch /app/x; touch /tmp/x && echo "/tmp beschreibbar"
  grep -E "^(CapBnd|NoNewPrivs)" /proc/1/status'
kubectl exec deploy/web -- ls /var/run/secrets/kubernetes.io/serviceaccount

Erwartet (gekürzt):

uid=1000(node) gid=1000(node) groups=1000(node)
touch: /app/x: Permission denied
/tmp beschreibbar
CapBnd: 00000000a80425fb
NoNewPrivs: 0
ca.crt
namespace
token

web läuft als node, weil das Dockerfile es so will – Kubernetes hat nichts verlangt. Die Capabilities im Bounding-Set kennst du aus „Docker Compose zum Anfassen”. Neu ist das Token: Kubernetes hängt in jeden Pod ein Token des ServiceAccounts default. Damit meldet sich jeder Prozess im Container an der API an:

kubectl exec deploy/web -- sh -c '
  T=$(cat /var/run/secrets/kubernetes.io/serviceaccount/token)
  wget -qO- --no-check-certificate --header "Authorization: Bearer $T" \
    https://kubernetes.default.svc/api/v1/namespaces/notes/secrets'
kubectl auth can-i list secrets --as=system:serviceaccount:notes:default

Erwartet:

wget: server returned error: HTTP/1.1 403 Forbidden
command terminated with exit code 1
no

403 statt 401: Die API hat das Token akzeptiert und weiß, wer anfragt – nur fehlt (noch) die Berechtigung. Bekommt default später eine Rolle, hat jeder Angreifer in web sie auch. web braucht die API nicht, also soll das Token weg.

Fortschritt speichern? Kostenlos registrieren

Drill 2: Pod Security Admission

Bevor du etwas scharf schaltest, fragst du den API-Server, was passieren würde:

kubectl label --dry-run=server --overwrite ns notes \
  pod-security.kubernetes.io/enforce=baseline
kubectl label --dry-run=server --overwrite ns notes \
  pod-security.kubernetes.io/enforce=restricted

Erwartet (gekürzt, Namen, IPs und Zeiten weichen bei dir ab):

namespace/notes labeled (server dry run)
namespace/notes labeled (server dry run)
Warning: existing pods in namespace "notes" violate the new PodSecurity enforce level
"restricted:latest"
Warning: api-f9c7bb64f-75dcz (and 7 other pods): allowPrivilegeEscalation != false,
unrestricted capabilities, runAsNonRoot != true, seccompProfile

baseline (kein privileged, kein hostPath, keine Host-Namespaces) erfüllt notes schon. restricted verlangt vier Dinge mehr – genau die Liste in der Warnung. Trag die Labels in k8s/namespace.yaml ein:

# k8s/namespace.yaml (Ausschnitt) – Stand Ende Tag 8
apiVersion: v1
kind: Namespace
metadata:
  name: notes
  labels:
    pod-security.kubernetes.io/enforce: restricted
    pod-security.kubernetes.io/warn: restricted
kubectl apply -f k8s/namespace.yaml
kubectl get pods -l app.kubernetes.io/name=web
kubectl rollout restart deploy/web
kubectl get rs -l app.kubernetes.io/name=web
kubectl get events --field-selector reason=FailedCreate \
  -o custom-columns=MSG:.message | tail -1

Erwartet (gekürzt):

namespace/notes configured
Warning: existing pods in namespace "notes" violate the new PodSecurity enforce level
"restricted:latest"
Warning: api-f9c7bb64f-75dcz (and 7 other pods): allowPrivilegeEscalation != false, …
limitrange/defaults unchanged
resourcequota/notes unchanged
NAME                   READY   STATUS    RESTARTS   AGE
web-857bcf49dc-cc95h   1/1     Running   0          78s
web-857bcf49dc-xpkxw   1/1     Running   0          78s
Warning: would violate PodSecurity "restricted:latest": allowPrivilegeEscalation !=
false (container "web" must set securityContext.allowPrivilegeEscalation=false), …
deployment.apps/web restarted
NAME             DESIRED   CURRENT   READY   AGE
web-55b6dc6795   1         0         0       5s
web-857bcf49dc   2         2         2       84s
Error creating: pods "web-55b6dc6795-xm65l" is forbidden: violates PodSecurity
"restricted:latest": allowPrivilegeEscalation != false (container "web" must set …
  • Laufende Pods bleiben unangetastet – geprüft wird nur beim Anlegen.
  • warn meldet schon beim Ändern des Deployments, enforce lehnt erst den Pod ab. Den Fehler siehst du deshalb nicht bei kubectl, sondern am ReplicaSet (CURRENT 0) und in den Events.
  • :latest heißt: die Regeln der aktuellen Kubernetes-Version. Mit pod-security.kubernetes.io/enforce-version: v1.37 frierst du sie ein.

Der Rollout von web hängt jetzt; die beiden alten Pods bedienen weiter. Das reparierst du in Drill 4.

Fortschritt speichern? Kostenlos registrieren

Drill 3: api mit securityContext

api ist das einfachste Ziel: scratch-Image, numerischer User 65532, schreibt nichts. Ergänze in k8s/api.yaml unter template.spec und am Container:

    spec:
      serviceAccountName: notes
      securityContext:
        runAsNonRoot: true
        seccompProfile:
          type: RuntimeDefault
      terminationGracePeriodSeconds: 30
      containers:
        - name: api
          securityContext:
            allowPrivilegeEscalation: false
            readOnlyRootFilesystem: true
            capabilities:
              drop: [ALL]
          image: notes-api:0.2.0
          # … Rest wie an Tag 7
  • Pod-Ebene: runAsNonRoot lässt den Kubelet den Start verweigern, falls das Image doch als root liefe; RuntimeDefault aktiviert das seccomp-Profil der Runtime.
  • Container-Ebene: kein Rechtegewinn über setuid, Wurzel-Dateisystem read-only, alle Capabilities weg.
kubectl apply --dry-run=server -f k8s/api.yaml
kubectl apply -f k8s/api.yaml
kubectl get rs -l app.kubernetes.io/name=api
kubectl get events --field-selector reason=FailedCreate \
  -o custom-columns=MSG:.message | grep api | tail -1

Erwartet (gekürzt):

deployment.apps/api configured (server dry run)
service/api unchanged (server dry run)
deployment.apps/api configured
service/api unchanged
NAME             DESIRED   CURRENT   READY   AGE
api-6474977fbf   1         0         0       2m7s
api-f9c7bb64f    3         3         3       3m41s
Error creating: pods "api-6474977fbf-" is forbidden: error looking up service account
notes/notes: serviceaccount "notes" not found

Der Dry-Run war grün, trotzdem entsteht kein Pod: Den ServiceAccount notes gibt es noch nicht. Er gehört in k8s/namespace.yaml – ans Ende der Datei:

---
apiVersion: v1
kind: ServiceAccount
metadata:
  name: notes
  namespace: notes
automountServiceAccountToken: false
kubectl apply -f k8s/namespace.yaml
kubectl rollout status deploy/api --timeout 120s
kubectl get pod -l app.kubernetes.io/name=api \
  -o jsonpath='{.items[0].spec.containers[0].volumeMounts[*].mountPath}{"\n"}'

Erwartet:

namespace/notes unchanged
limitrange/defaults unchanged
resourcequota/notes unchanged
serviceaccount/notes created
deployment "api" successfully rolled out
/etc/notes

Der ReplicaSet-Controller versucht es mit wachsendem Abstand erneut; nach rund einer halben Minute läuft der Rollout von selbst weiter. Im Pod hängt nur noch /etc/notes – das Token-Verzeichnis fehlt, weil automountServiceAccountToken: false am ServiceAccount steht. Ein Pod könnte es mit demselben Feld in spec wieder anfordern.

Fortschritt speichern? Kostenlos registrieren

Drill 4: web und die Falle mit dem Benutzernamen

Bau dieselben Blöcke in k8s/web.yaml ein, dazu ein /tmp als emptyDir – sonst wäre gar nichts mehr beschreibbar:

    spec:
      serviceAccountName: notes
      securityContext:
        runAsNonRoot: true
        seccompProfile:
          type: RuntimeDefault
      containers:
        - name: web
          securityContext:
            allowPrivilegeEscalation: false
            readOnlyRootFilesystem: true
            capabilities:
              drop: [ALL]
          # … image, env, ports, resources wie an Tag 6
          volumeMounts:
            - name: tmp
              mountPath: /tmp
          # … Probes
      volumes:
        - name: tmp
          emptyDir: {}
kubectl apply -f k8s/web.yaml
sleep 15
kubectl get pods -l app.kubernetes.io/name=web
kubectl get events --field-selector reason=Failed -o custom-columns=MSG:.message \
  | tail -1

Erwartet (gekürzt):

deployment.apps/web configured
service/web unchanged
NAME                   READY   STATUS                       RESTARTS   AGE
web-79cdcdcd9c-qmw5p   0/1     CreateContainerConfigError   0          15s
web-857bcf49dc-cc95h   1/1     Running                      0          4m57s
web-857bcf49dc-xpkxw   1/1     Running                      0          4m57s
Error: container has runAsNonRoot and image has non-numeric user (node), cannot
verify user is non-root (pod: "web-79cdcdcd9c-qmw5p_notes(…)", container: web)

Das Node-Image setzt USER node – einen Namen. Der Kubelet sieht nicht in die /etc/passwd des Images und kann nicht beweisen, dass node nicht UID 0 ist. Also nennst du die UID selbst (sie stand in Drill 1 bei id):

      securityContext:
        runAsNonRoot: true
        runAsUser: 1000
        runAsGroup: 1000
        seccompProfile:
          type: RuntimeDefault
kubectl apply -f k8s/web.yaml
kubectl rollout status deploy/web --timeout 120s
kubectl exec deploy/web -- sh -c 'id; touch /app/x; touch /x
  touch /tmp/x && echo "/tmp beschreibbar"
  grep -E "^(CapBnd|NoNewPrivs|Seccomp):" /proc/1/status
  ls /var/run/secrets/kubernetes.io/serviceaccount'

Erwartet:

deployment.apps/web configured
service/web unchanged
deployment "web" successfully rolled out
uid=1000(node) gid=1000(node) groups=1000(node)
touch: /app/x: Read-only file system
touch: /x: Read-only file system
/tmp beschreibbar
CapBnd: 0000000000000000
NoNewPrivs: 1
Seccomp:    2
ls: /var/run/secrets/kubernetes.io/serviceaccount: No such file or directory
command terminated with exit code 1

Keine Capabilities, kein Rechtegewinn, seccomp aktiv (2 = Filter), kein Token. Derselbe Fehler trifft jedes Image mit Namen im USER – auch curlimages/curl (curl_user, UID 100) an Tag 10.

Fortschritt speichern? Kostenlos registrieren

Drill 5: worker und das fehlende /tmp

worker bekommt die Blöcke aus Drill 3 (User 65532 ist numerisch) und ebenfalls ein emptyDir für /tmp. Braucht er das wirklich? Ohne /tmp läuft er zunächst – aber jede Bibliothek, die eine Temp-Datei anlegt, scheitert (im Test ausprobiert):

FileNotFoundError: [Errno 2] No usable temporary directory found in ['/tmp',
'/var/tmp', '/usr/tmp', '/app']

Mit dem Volume (vollständige Datei: code/tag08/notes/k8s/worker.yaml):

          volumeMounts:
            - name: api-key
              mountPath: /etc/notes
              readOnly: true
            - name: tmp
              mountPath: /tmp
      volumes:
        - name: api-key
          secret:
            secretName: notes-api
        - name: tmp
          emptyDir: {}
kubectl apply -f k8s/worker.yaml
kubectl rollout status deploy/worker --timeout 90s
kubectl exec deploy/worker -- python -c \
  'import tempfile, os; print(tempfile.gettempdir(), os.getuid())'

Erwartet:

deployment.apps/worker configured
deployment "worker" successfully rolled out
/tmp 65532

Ein emptyDir lebt so lange wie der Pod. Mit medium: Memory läge es im RAM (wie tmpfs bei Docker) und zählte zum Speicherlimit.

Fortschritt speichern? Kostenlos registrieren

Drill 6: Postgres als UID 70

Jetzt db. Erst nur die Blöcke aus Drill 3 in k8s/db.yaml:

kubectl apply -f k8s/db.yaml
sleep 20
kubectl get pod db-0
kubectl get events --field-selector involvedObject.name=db-0,reason=Failed \
  -o custom-columns=MSG:.message | tail -1

Erwartet (gekürzt):

service/db unchanged
statefulset.apps/db configured
NAME   READY   STATUS                       RESTARTS   AGE
db-0   0/1     CreateContainerConfigError   0          19s
Error: container has runAsNonRoot and image will run as root (pod: "db-0_notes(…)",
container: postgres)

Das Postgres-Image startet als root und wechselt erst im Entrypoint zu postgres. Das Alpine-Image hat dafür UID/GID 70 – also gleich so starten:

      securityContext:
        runAsNonRoot: true
        runAsUser: 70
        runAsGroup: 70
        fsGroup: 70
        seccompProfile:
          type: RuntimeDefault
kubectl apply -f k8s/db.yaml
kubectl delete pod db-0
sleep 25
kubectl get pod db-0
kubectl logs db-0 --tail 2

Erwartet (gekürzt):

service/db unchanged
statefulset.apps/db configured
pod "db-0" deleted from notes namespace
NAME   READY   STATUS             RESTARTS     AGE
db-0   0/1     CrashLoopBackOff   2 (5s ago)   24s
… FATAL:  could not create lock file "/var/run/postgresql/.s.PGSQL.5432.lock":
Read-only file system
… LOG:  database system is shut down

Achtung: Hängt ein StatefulSet-Pod in einem Fehlerzustand, ersetzt der Controller ihn nach einem apply nicht von selbst (im Test: db-0 blieb auf der alten Revision). Die Doku nennt das „Forced rollback”: kaputten Pod von Hand löschen.

Socket und Lock-Datei brauchen ein beschreibbares Verzeichnis. Zwei emptyDir dazu (vollständige Datei: code/tag08/notes/k8s/db.yaml):

          volumeMounts:
            - name: data
              mountPath: /var/lib/postgresql
            - name: run
              mountPath: /var/run/postgresql
            - name: tmp
              mountPath: /tmp
      volumes:
        - name: run
          emptyDir: {}
        - name: tmp
          emptyDir: {}
kubectl apply -f k8s/db.yaml
kubectl delete pod db-0
kubectl rollout status sts/db --timeout 120s
kubectl exec db-0 -- sh -c 'id; ls -ldn /var/run/postgresql /var/lib/postgresql \
  /var/lib/postgresql/18/docker'
kubectl exec db-0 -- psql -U notes -tAc 'select count(*) from notes'

Erwartet (gekürzt):

service/db unchanged
statefulset.apps/db configured
pod "db-0" deleted from notes namespace
partitioned roll out complete: 1 new pods have been updated...
uid=70(postgres) gid=70(postgres) groups=70(postgres)
drwxrwxrwx    3 0        0             4096 … /var/lib/postgresql
drwx------   19 70       0             4096 … /var/lib/postgresql/18/docker
drwxrwsrwx    2 0        70            4096 … /var/run/postgresql
3
  • fsGroup: 70 gibt Volumes die Gruppe 70 (plus setgid-Bit): sichtbar am emptyDir. Am Daten-Volume greift es in kind nicht – der local-path-Provisioner legt hostPath-Volumes an (0777). Auf echtem Block-Storage sorgt fsGroup dafür, dass UID 70 ein frisches Volume beschreiben darf.
  • Die Daten aus Tag 7 sind da: Das Entrypoint-Skript hatte sie damals schon UID 70 übergeben.

Während der Drills war die Datenbank weg; api meldete sich unbereit. Im Lab in Ordnung.

Fortschritt speichern? Kostenlos registrieren

Drill 7: migrate – Jobs sind unveränderlich

migrate bekommt die Blöcke aus Drill 3, nichts weiter (vollständige Datei: code/tag08/notes/k8s/migrate.yaml). Liegt der Job aus Tag 7 noch im Cluster (ttlSecondsAfterFinished: 600 löscht ihn zehn Minuten nach dem Ende), scheitert apply. Im Test war er noch da:

kubectl get job migrate
kubectl apply -f k8s/migrate.yaml

Erwartet (gekürzt):

NAME      STATUS     COMPLETIONS   DURATION   AGE
migrate   Complete   1/1           7s         8m28s
The Job "migrate" is invalid: spec.template: Invalid value: {…}: field is immutable

Das Pod-Template eines Jobs lässt sich nach dem Anlegen nicht ändern. Bei dir kommt statt der Fehlermeldung vermutlich job.batch/migrate created – dann ist der alte Job schon abgelaufen. Der sichere Weg ist immer: löschen und neu anlegen.

kubectl delete job migrate --ignore-not-found
kubectl apply -f k8s/migrate.yaml
kubectl wait --for=condition=complete job/migrate --timeout 60s
kubectl logs job/migrate

Erwartet (gekürzt):

job.batch "migrate" deleted from notes namespace
job.batch/migrate created
job.batch/migrate condition met
time=… level=INFO msg="migration complete" table=notes

Probier die Sperre noch einmal mit einer Änderung am frischen Job:

sed 's/notes-api:0.2.0/notes-api:0.1.0/' k8s/migrate.yaml | kubectl apply -f -

Erwartet (gekürzt):

The Job "migrate" is invalid: spec.template: Invalid value: {…}: field is immutable

Dieses Löschen-und-neu-Anlegen erledigt an Tag 10 ein Helm-Hook mit before-hook-creation.

Fortschritt speichern? Kostenlos registrieren

Drill 8: RBAC – Role und RoleBinding

notes braucht keine Rechte an der API. Wie man sie vergibt, übst du an einem Test-Konto reader, das Pods und ihre Logs lesen darf – mehr nicht:

cat > rbac-test.yaml <<'EOF'
# rbac-test.yaml – nur für Tag 8, Drill 8 (danach löschen)
apiVersion: v1
kind: ServiceAccount
metadata:
  name: reader
automountServiceAccountToken: false
---
apiVersion: rbac.authorization.k8s.io/v1
kind: Role
metadata:
  name: pod-reader
rules:
  - apiGroups: [""]
    resources: [pods, pods/log]
    verbs: [get, list, watch]
---
apiVersion: rbac.authorization.k8s.io/v1
kind: RoleBinding
metadata:
  name: reader-pod-reader
subjects:
  - kind: ServiceAccount
    name: reader
    namespace: notes
roleRef:
  apiGroup: rbac.authorization.k8s.io
  kind: Role
  name: pod-reader
EOF
kubectl apply --dry-run=server -f rbac-test.yaml && kubectl apply -f rbac-test.yaml
SA=system:serviceaccount:notes:reader
for v in "list pods" "get pods/log" "delete pods" "get secrets" \
  "list pods -n default"; do
  printf '%-22s %s\n' "$v" "$(kubectl auth can-i $v --as=$SA)"
done
kubectl get pods -l app.kubernetes.io/name=db --as=$SA
kubectl get secrets --as=$SA

Erwartet (gekürzt):

serviceaccount/reader created (server dry run)
role.rbac.authorization.k8s.io/pod-reader created (server dry run)
rolebinding.rbac.authorization.k8s.io/reader-pod-reader created (server dry run)
serviceaccount/reader created
role.rbac.authorization.k8s.io/pod-reader created
rolebinding.rbac.authorization.k8s.io/reader-pod-reader created
list pods              yes
get pods/log           yes
delete pods            no
get secrets            no
list pods -n default   no
NAME   READY   STATUS    RESTARTS   AGE
db-0   1/1     Running   0          47s
Error from server (Forbidden): secrets is forbidden: User
"system:serviceaccount:notes:reader" cannot list resource "secrets" in API group ""
in the namespace "notes"
  • Eine Role ist eine Liste erlaubter Verben auf Ressourcen in einem Namespace. RBAC kennt nur Erlaubnisse, kein Verbot – was nicht erlaubt ist, ist verboten.
  • Die RoleBinding verknüpft die Role mit Subjekten (ServiceAccount, User, Gruppe). Für den ganzen Cluster heißen die Gegenstücke ClusterRole und ClusterRoleBinding.
  • --as lässt dich als anderes Konto fragen, ohne dessen Token zu kennen. Das darfst du, weil der Admin-Kontext von kind alles darf.

kubectl auth can-i --list --as=$SA zeigt alle Rechte des Kontos auf einmal. Weg mit dem Test-Konto:

kubectl delete -f rbac-test.yaml && rm rbac-test.yaml

Erwartet:

serviceaccount "reader" deleted from notes namespace
role.rbac.authorization.k8s.io "pod-reader" deleted from notes namespace
rolebinding.rbac.authorization.k8s.io "reader-pod-reader" deleted from notes namespace

Fortschritt speichern? Kostenlos registrieren

Kontrollpunkt

kubectl get ns notes --show-labels

Erwartet: enforce und warn stehen auf restricted.

NAME    STATUS   AGE     LABELS
notes   Active   5m44s   kubernetes.io/metadata.name=notes,pod-security.kubernetes.io
/enforce=restricted,pod-security.kubernetes.io/warn=restricted
kubectl get pods -o custom-columns=NAME:.metadata.name,SA:.spec.serviceAccountName

Erwartet: alle Pods mit ServiceAccount notes.

NAME                     SA
api-6474977fbf-hb4m2     notes
api-6474977fbf-sclm9     notes
api-6474977fbf-x7fjk     notes
db-0                     notes
migrate-b89df            notes
web-df4dcfbcf-7tlbs      notes
web-df4dcfbcf-h9q44      notes
worker-b4b948756-5wqmf   notes
kubectl exec deploy/web -- id
kubectl exec deploy/web -- touch /x

Erwartet: web läuft als UID 1000, das Dateisystem ist schreibgeschützt.

uid=1000(node) gid=1000(node) groups=1000(node)
touch: /x: Read-only file system
command terminated with exit code 1
kubectl exec deploy/web -- ls /var/run/secrets/kubernetes.io

Erwartet: kein ServiceAccount-Token im Pod.

ls: /var/run/secrets/kubernetes.io: No such file or directory
command terminated with exit code 1
kubectl exec db-0 -- id

Erwartet: Postgres läuft als UID 70.

uid=70(postgres) gid=70(postgres) groups=70(postgres)

Challenge

Starte im Namespace notes einen Pod debug mit busybox:1.37, der einmal id, touch /x und wget -qO- http://api:8080/version ausführt – und von restricted zugelassen wird.

Hinweis: busybox läuft ohne USER im Image als root; kubectl run ohne Sicherheitsangaben wird abgelehnt.

Lösung

kubectl run debug --image=busybox:1.37 --restart=Never -- id
cat > debug.yaml <<'EOF'
# debug.yaml – Challenge Tag 8: busybox unter restricted
apiVersion: v1
kind: Pod
metadata:
  name: debug
spec:
  serviceAccountName: notes
  restartPolicy: Never
  securityContext:
    runAsNonRoot: true
    runAsUser: 65532
    runAsGroup: 65532
    seccompProfile:
      type: RuntimeDefault
  containers:
    - name: debug
      image: busybox:1.37
      command: [sh, -c, "id; touch /x; wget -qO- http://api:8080/version"]
      securityContext:
        allowPrivilegeEscalation: false
        readOnlyRootFilesystem: true
        capabilities:
          drop: [ALL]
EOF
kubectl apply -f debug.yaml
kubectl wait --for=jsonpath='{.status.phase}'=Succeeded pod/debug --timeout 60s
kubectl logs debug
kubectl delete -f debug.yaml

Erwartet (gekürzt):

Error from server (Forbidden): pods "debug" is forbidden: violates PodSecurity
"restricted:latest": allowPrivilegeEscalation != false (container "debug" must set …
pod/debug created
pod/debug condition met
uid=65532 gid=65532 groups=65532
touch: /x: Read-only file system
0.2.0
pod "debug" deleted from notes namespace

Die UID darf beliebig sein, solange sie nicht 0 ist – busybox braucht keinen Eintrag in /etc/passwd. Requests und Limits ergänzt die LimitRange aus Tag 6. Ein bequemerer Weg zum Debuggen laufender Pods folgt an Tag 11 mit kubectl debug.

Fortschritt speichern? Kostenlos registrieren

Enterprise-Notiz

  • Pod Security Admission ist bewusst grob: drei feste Stufen pro Namespace. Feinere Regeln (erlaubte Registries, Pflicht-Labels, Signaturen) setzt eine Policy-Engine durch – siehe „Kyverno & NetworkPolicies zum Anfassen”.
  • Neue Namespaces bekommen per Vorlage (oder Policy) mindestens warn/audit auf restricted, damit Verstöße auffallen, bevor jemand enforce einschaltet.
  • RBAC nach dem Prinzip der geringsten Rechte: keine ClusterRoleBindings auf cluster-admin für Menschen im Alltag, Gruppen aus dem Identity-Provider statt Einzelpersonen, regelmäßig mit kubectl auth can-i --list prüfen.
  • Images mit numerischem USER bauen („Dockerfiles zum Anfassen”) – das erspart die runAsUser-Pflege in jedem Manifest.
  • Laufzeit-Erkennung (z. B. Falco) und ein eigenes seccomp-Profil sind die nächsten Schritte; RuntimeDefault ist der Mindeststand.