Zum Inhalt springen
Trainingslager IT-Trainingslager

Tag 8: SecurityContext und ServiceAccounts

Ziel: Du lässt Container mit möglichst wenig Rechten laufen und gibst Pods eine eigene Identität gegenüber der Kubernetes-API. · Dauer: ca. 60 min · Voraussetzung: Tag 6

Briefing

CKAD: Application Environment, Configuration and Security (25 %) – „Understand ServiceAccounts”, „Understand Application Security (SecurityContexts, Capabilities, etc.)“.

spec.securityContext                 Pod-Ebene: runAsUser, runAsGroup, fsGroup,
                                     runAsNonRoot, seccompProfile
spec.containers[].securityContext    Container-Ebene: dieselben runAs*-Felder
                                     (gewinnen) plus capabilities,
                                     readOnlyRootFilesystem, allowPrivilegeEscalation

RBAC (wer darf was) folgt an Tag 9; heute geht es um die Identität selbst.

mkdir -p ~/ckad/tag08 && cd ~/ckad/tag08
k create ns tag08
k config set-context --current --namespace=tag08

Drill 1: runAsNonRoot

cat <<'EOF' | k apply -f -
apiVersion: v1
kind: Pod
metadata:
  name: web
spec:
  securityContext:
    runAsNonRoot: true
  containers:
  - name: nginx
    image: nginx:1.29
EOF
k get pod web
k describe pod web | grep -m1 "Error:"

Erwartet (gekürzt):

NAME   READY   STATUS                       RESTARTS   AGE
web    0/1     CreateContainerConfigError   0          10s
  Warning  Failed  7s (x3 over 9s)  kubelet  spec.containers{nginx}: Error: container
  has runAsNonRoot and image will run as root (pod: "web_tag08(ef75…)",
  container: nginx)

Der Kubelet prüft vor dem Start, mit welchem Benutzer das Image läuft. nginx startet als root – also kein Start. notes-api läuft als 65532 und besteht die Prüfung (Drill 5).

k delete pod web --now

Fortschritt speichern? Kostenlos registrieren

Drill 2: Benutzer, Gruppe, fsGroup

cat <<'EOF' | k apply -f -
apiVersion: v1
kind: Pod
metadata:
  name: ids
spec:
  securityContext:
    runAsUser: 1000
    runAsGroup: 3000
    fsGroup: 2000
  containers:
  - name: c
    image: busybox:1.37
    command: ["sh", "-c", "sleep 3600"]
    volumeMounts:
    - name: data
      mountPath: /data
  volumes:
  - name: data
    emptyDir: {}
EOF
k wait --for=condition=Ready pod/ids
k exec ids -- id
k exec ids -- sh -c 'touch /data/f; ls -ln /data; ls -ldn /data'
k exec ids -- touch /f

Erwartet:

uid=1000 gid=3000 groups=2000,3000
total 0
-rw-r--r--    1 1000     2000             0 Nov 18 15:47 f
drwxrwsrwx    2 0        2000          4096 Nov 18 15:47 /data
touch: /f: Permission denied

fsGroup gehört den Volumes: Das Verzeichnis bekommt Gruppe 2000 und das SetGID-Bit (s), neue Dateien erben die Gruppe. So kann ein Nicht-root-Prozess in Volumes schreiben.

Fortschritt speichern? Kostenlos registrieren

Drill 3: Container-Ebene und schreibgeschütztes Dateisystem

cat <<'EOF' | k apply -f -
apiVersion: v1
kind: Pod
metadata:
  name: hard
spec:
  securityContext:
    runAsUser: 1000
  containers:
  - name: c
    image: busybox:1.37
    command: ["sh", "-c", "sleep 3600"]
    securityContext:
      runAsUser: 2000
      readOnlyRootFilesystem: true
      allowPrivilegeEscalation: false
    volumeMounts:
    - name: tmp
      mountPath: /tmp
  volumes:
  - name: tmp
    emptyDir: {}
EOF
k wait --for=condition=Ready pod/hard
k exec hard -- id -u
k exec hard -- touch /etc/x
k exec hard -- touch /tmp/x && echo tmp ok
k exec hard -- grep NoNewPrivs /proc/1/status

Erwartet:

2000
touch: /etc/x: Read-only file system
tmp ok
NoNewPrivs: 1

Container-Ebene schlägt Pod-Ebene (2000 statt 1000). Mit schreibgeschütztem Root-FS bekommt jedes Verzeichnis, das die App wirklich schreibt, ein emptyDir. allowPrivilegeEscalation: false setzt no_new_privs: setuid-Programme wie sudo bringen keine zusätzlichen Rechte mehr.

Fortschritt speichern? Kostenlos registrieren

Drill 4: Capabilities und seccomp

cat <<'EOF' | k apply -f -
apiVersion: v1
kind: Pod
metadata:
  name: caps
spec:
  containers:
  - name: c
    image: busybox:1.37
    command: ["sh", "-c", "sleep 3600"]
    securityContext:
      capabilities:
        drop: ["ALL"]
        add: ["NET_BIND_SERVICE"]
      seccompProfile:
        type: RuntimeDefault
EOF
k run plain --image=busybox:1.37 -- sleep 3600
k wait --for=condition=Ready pod/caps pod/plain
k exec plain -- grep -E 'CapEff|Seccomp:' /proc/1/status
k exec caps -- grep -E 'CapEff|Seccomp:' /proc/1/status
k exec plain -- chown 1000 /tmp && echo chown ok
k exec caps -- chown 1000 /tmp

Erwartet:

CapEff: 00000000a80425fb
Seccomp:    0
CapEff: 0000000000000400
Seccomp:    2
chown ok
chown: /tmp: Operation not permitted

Beide laufen als root, aber caps hat nur noch NET_BIND_SERVICE (Bit 10 = 0x400, Ports unter 1024). Ohne CHOWN darf selbst root keine Besitzer ändern. Capabilities schreibst du ohne CAP_-Präfix. Seccomp: 0 zeigt: Ohne Angabe läuft ein Pod ungefiltert; RuntimeDefault (2 = Filter aktiv) sperrt gefährliche Systemaufrufe.

Fortschritt speichern? Kostenlos registrieren

Drill 5: notes-api gehärtet

Alles zusammen ergibt, was der Pod-Security-Standard restricted (Tag 9) verlangt:

k create secret generic notes-key --from-literal=api-key=lab-key-123
cat <<'EOF' | k apply -f -
apiVersion: v1
kind: Pod
metadata:
  name: notes
spec:
  securityContext:
    runAsNonRoot: true
    seccompProfile:
      type: RuntimeDefault
  containers:
  - name: notes-api
    image: 172.16.0.126:30500/notes-api:1.0
    env:
    - name: NOTES_API_KEY
      valueFrom:
        secretKeyRef:
          name: notes-key
          key: api-key
    securityContext:
      readOnlyRootFilesystem: true
      allowPrivilegeEscalation: false
      capabilities:
        drop: ["ALL"]
EOF
k wait --for=condition=Ready pod/notes
k exec notes -- id
k exec notes -- wget -qO- localhost:8080/healthz

Erwartet:

pod/notes condition met
uid=65532 gid=0(root) groups=0(root)
ok

notes-api lauscht auf 8080 und schreibt nichts auf die Platte – darum braucht sie weder Capabilities noch ein emptyDir.

Fortschritt speichern? Kostenlos registrieren

Drill 6: Eigener ServiceAccount

Jeder Namespace hat einen ServiceAccount default. Eigene Accounts trennen Rechte pro App.

k create serviceaccount notes-sa
cat <<'EOF' | k apply -f -
apiVersion: v1
kind: Pod
metadata:
  name: api-client
spec:
  serviceAccountName: notes-sa
  containers:
  - name: c
    image: nginx:1.29
    command: ["sleep", "3600"]
EOF
k wait --for=condition=Ready pod/api-client
k exec api-client -- ls /var/run/secrets/kubernetes.io/serviceaccount
k get pod api-client -o jsonpath='{.spec.volumes[0].projected.sources[0]}{"\n"}'

Erwartet:

ca.crt
namespace
token
{"serviceAccountToken":{"expirationSeconds":3607,"path":"token"}}

Das Token ist kein Secret-Objekt mehr, sondern ein projiziertes, zeitlich begrenztes JWT (Volume kube-api-access-…, wie in Tag 5 Drill 6). nginx dient hier nur wegen curl.

Fortschritt speichern? Kostenlos registrieren

Drill 7: Mit dem Token die API fragen

k exec api-client -- sh -c 'D=/var/run/secrets/kubernetes.io/serviceaccount;
  curl -s --cacert $D/ca.crt -H "Authorization: Bearer $(cat $D/token)" \
  https://kubernetes.default.svc/api/v1/namespaces/tag08/pods' | grep -E 'message|code'

Erwartet:

  "message": "pods is forbidden: User \"system:serviceaccount:tag08:notes-sa\" cannot
  list resource \"pods\" in API group \"\" in the namespace \"tag08\"",
  "code": 403

403 heißt: Der API-Server kennt dich (Authentifizierung ok), aber du darfst nichts (keine RBAC-Regel). Ohne Token wärst du system:anonymous; ohne --cacert bricht curl mit Exit-Code 60 (Zertifikat unbekannt) ab. Dasselbe von außen, mit einem kurzlebigen Token:

TOKEN=$(k create token notes-sa --duration=10m)
k config view --raw \
  -o jsonpath='{.clusters[0].cluster.certificate-authority-data}' | base64 -d > ca.crt
curl -s --cacert ca.crt -H "Authorization: Bearer $TOKEN" \
  https://172.16.0.126:6443/api/v1/namespaces/tag08/pods | grep code
k auth can-i list pods --as=system:serviceaccount:tag08:notes-sa

Erwartet:

  "code": 403
no

k create token erzeugt das Token über die TokenRequest-API; nirgends wird es gespeichert. --audience legt fest, für wen es gilt.

Fortschritt speichern? Kostenlos registrieren

Drill 8: Kein Token, wo keins nötig ist

Die meisten Apps sprechen nie mit der Kubernetes-API. Dann gehört das Token nicht in den Pod:

cat <<'EOF' | k apply -f -
apiVersion: v1
kind: Pod
metadata:
  name: no-token
spec:
  serviceAccountName: notes-sa
  automountServiceAccountToken: false
  containers:
  - name: c
    image: busybox:1.37
    command: ["sleep", "3600"]
EOF
k wait --for=condition=Ready pod/no-token
k exec no-token -- ls /var/run/secrets/kubernetes.io/serviceaccount

Erwartet:

ls: /var/run/secrets/kubernetes.io/serviceaccount: No such file or directory

Dasselbe Feld gibt es am ServiceAccount (k patch sa notes-sa -p '{"automountServiceAccountToken":false}'); der Wert am Pod gewinnt.

Fortschritt speichern? Kostenlos registrieren

Übung: Speed-Drills

  1. Pod secure (busybox:1.37, sleep 3600) läuft als Benutzer 1001, Gruppe 1001 und ohne Privilege Escalation. Zeitziel: 2 min
  2. ServiceAccount builder; Deployment ci (nginx:1.29) nutzt ihn. Zeitziel: 45 s
  3. Erzeuge ein Token für builder, eine Stunde gültig. Zeitziel: 20 s

Lösung

k run secure --image=busybox:1.37 $do --command -- sleep 3600 > secure.yaml
spec:
  securityContext:
    runAsUser: 1001
    runAsGroup: 1001
  containers:
  - name: secure
    image: busybox:1.37
    command: ["sleep", "3600"]
    securityContext:
      allowPrivilegeEscalation: false
k apply -f secure.yaml
k create sa builder
k create deploy ci --image=nginx:1.29
k set serviceaccount deploy/ci builder
k create token builder --duration=1h

Erwartet (gekürzt):

pod/secure created
serviceaccount/builder created
deployment.apps/ci created
deployment.apps/ci serviceaccount updated
eyJhbGciOiJSUzI1NiIs...

Fortschritt speichern? Kostenlos registrieren

Kontrollpunkt

k exec secure -- id

Erwartet: uid=1001 gid=1001 groups=1001

k get deploy ci -o jsonpath='{.spec.template.spec.serviceAccountName}{"\n"}'

Erwartet: builder

k get pod notes -o jsonpath='{.spec.containers[0].securityContext.capabilities}{"\n"}'

Erwartet: {"drop":["ALL"]}

Challenge

Pod peek (busybox:1.37) läuft mit notes-sa, soll aber kein API-Token am Standardort haben. Stattdessen braucht er unter /var/run/vault/token ein Token mit Audience vault, das nach 10 Minuten abläuft.

Hinweis: Ein projected Volume kann ein serviceAccountToken auch ohne Automount liefern.

Lösung

cat <<'EOF' | k apply -f -
apiVersion: v1
kind: Pod
metadata:
  name: peek
spec:
  serviceAccountName: notes-sa
  automountServiceAccountToken: false
  containers:
  - name: c
    image: busybox:1.37
    command: ["sleep", "3600"]
    volumeMounts:
    - name: vault-token
      mountPath: /var/run/vault
      readOnly: true
  volumes:
  - name: vault-token
    projected:
      sources:
      - serviceAccountToken:
          path: token
          audience: vault
          expirationSeconds: 600
EOF
k wait --for=condition=Ready pod/peek
k exec peek -- ls /var/run/vault
k exec peek -- cat /var/run/vault/token | cut -d. -f2 | base64 -d 2>/dev/null \
  | cut -c1-40

Erwartet:

token
{"aud":["vault"],"exp":1795017538,"iat":

600 Sekunden ist das Minimum für expirationSeconds. Vault (oder jeder andere Dienst) prüft Signatur und Audience über die TokenReview-API.

Aufräumen:

k config set-context --current --namespace=default
k delete ns tag08

Fortschritt speichern? Kostenlos registrieren

Prüfungstipp

  • Felder wie capabilities und readOnlyRootFilesystem gibt es nur am Container, fsGroup nur am Pod. Im Zweifel k explain pod.spec.securityContext und k explain pod.spec.containers.securityContext.
  • serviceAccountName am laufenden Pod ist unveränderlich – beim Deployment k set serviceaccount, beim Pod k replace --force.
  • Doku: kubernetes.io → Tasks → Configure Pods → „Configure a Security Context” und „Configure Service Accounts for Pods”.

Enterprise-Notiz

  • Pod Security Admission mit restricted auf allen App-Namespaces erzwingt die Felder aus Drill 5 (Tag 9).
  • Images mit festem, numerischem Nicht-root-USER bauen (Tag 2), sonst kann der Kubelet runAsNonRoot nicht prüfen.
  • ServiceAccount-Tokens sind Workload-Identität: Cloud-IAM (IRSA, Workload Identity) und Vault vertrauen ihnen über die Audience.
  • automountServiceAccountToken: false als Standard für alle ServiceAccounts ohne API-Bedarf.