Zum Inhalt springen
Trainingslager IT-Trainingslager

Tag 18: Unveränderliche Container und Spurensuche

Ziel: Du machst Container zur Laufzeit unveränderlich, findest Schreibspuren und verdächtige Prozesse mit Bordmitteln und nimmst einen kompromittierten Pod aus dem Verkehr. · Dauer: ca. 75 min · Voraussetzung: Tag 9 und Tag 2

Briefing

  • CKS: Monitoring, Logging and Runtime Security – „Ensure immutability of containers at runtime“ und „Investigate and identify phases of attack and bad actors within the environment“.
  • Unveränderlich heißt: Root-Dateisystem schreibgeschützt, Schreibplätze nur als emptyDir, möglichst keine Shell und kein Paketmanager im Image.
  • Spurensuche läuft auf dem Node: crictl liefert Container-ID und Host-PID, /proc liefert Programm, Argumente, Sockets und Dateisystem des Prozesses.
  • Falco (Tag 16) und Tetragon (Tag 17) melden so etwas automatisch – heute nur Bordmittel, damit du weißt, was hinter deren Meldungen steckt.
k get pod -o wide ──> Node ──> crictl ps ──> crictl inspect ──> PID
                                                                 |
     /proc/<pid>/{exe,cmdline,cgroup,root,mounts} · nsenter -n ss <─┘
mkdir -p ~/cks/tag18 && cd ~/cks/tag18
k create ns tag18
k config set-context --current --namespace=tag18
k create secret generic notes-key --from-literal=NOTES_API_KEY=lab-key-123

(lab-key-123 ist ein reiner Lab-Wert)

Das Image notes-api:1.0 muss in der Registry liegen (sonst wie in Tag 9 bauen).

Drill 1: notes-api mit schreibgeschütztem Root-FS

cat > notes.yaml <<'EOF'
apiVersion: v1
kind: Pod
metadata:
  name: notes
  labels:
    app: notes
spec:
  securityContext:
    runAsNonRoot: true
    seccompProfile:
      type: RuntimeDefault
  containers:
  - name: notes-api
    image: 172.16.0.126:30500/notes-api:1.0
    envFrom:
    - secretRef:
        name: notes-key
    securityContext:
      readOnlyRootFilesystem: true
      allowPrivilegeEscalation: false
      capabilities:
        drop: ["ALL"]
EOF
k apply -f notes.yaml
k wait --for=condition=Ready pod/notes
k exec notes -- wget -qO- localhost:8080/healthz
k exec notes -- touch /tmp/x
k exec notes -- awk '$2=="/"{print $1, $2, substr($4,1,2)}' /proc/mounts

Erwartet:

pod/notes condition met
ok
touch: /tmp/x: Read-only file system
command terminated with exit code 1
overlay / ro

Das Overlay-Root-FS ist ro eingehängt. Ein Angreifer kann kein Werkzeug nachladen und kein Binary austauschen. notes-api schreibt nichts auf die Platte, braucht also nicht einmal ein /tmp.

Fortschritt speichern? Kostenlos registrieren

Drill 2: nginx braucht Schreibplätze

Die meisten Images schreiben irgendwo hin. Das Log verrät, wohin:

k apply -f - <<'EOF'
apiVersion: v1
kind: Pod
metadata:
  name: web
spec:
  containers:
  - name: web
    image: nginx:1.29
    securityContext:
      readOnlyRootFilesystem: true
EOF

Nach etwa zehn Sekunden:

k get pod web
k logs web | tail -1

Erwartet:

NAME   READY   STATUS   RESTARTS     AGE
web    0/1     Error    1 (6s ago)   8s
nginx: [emerg] mkdir() "/var/cache/nginx/client_temp" failed (30: Read-only file system)

nginx schreibt Cache und Temp-Dateien unter /var/cache/nginx und die PID-Datei nach /run; /tmp kommt als Schreibplatz für Skripte dazu. Für jedes dieser Verzeichnisse ein emptyDir:

k delete pod web --now
cat > web.yaml <<'EOF'
apiVersion: v1
kind: Pod
metadata:
  name: web
  labels:
    run: web
spec:
  containers:
  - name: web
    image: nginx:1.29
    securityContext:
      readOnlyRootFilesystem: true
    volumeMounts:
    - name: cache
      mountPath: /var/cache/nginx
    - name: run
      mountPath: /run
    - name: tmp
      mountPath: /tmp
  volumes:
  - name: cache
    emptyDir: {}
  - name: run
    emptyDir: {}
  - name: tmp
    emptyDir: {}
EOF
k apply -f web.yaml
k wait --for=condition=Ready pod/web
k exec web -- touch /usr/share/nginx/html/index.html
k exec web -- touch /tmp/ok && echo tmp ok

Erwartet:

pod/web condition met
touch: cannot touch '/usr/share/nginx/html/index.html': Read-only file system
command terminated with exit code 1
tmp ok

Die Webseite ist nicht mehr manipulierbar (kein Defacement), /tmp bleibt nutzbar. Die Log-Zeile can not modify /etc/nginx/conf.d/default.conf (read-only file system?) ist nur ein Hinweis des Entrypoint-Skripts, kein Fehler.

Fortschritt speichern? Kostenlos registrieren

Drill 3: Schreibspuren auf dem Node finden

Ein beschreibbarer Container, in dem „jemand“ ein Binary ablegt und /etc/passwd ergänzt:

k run drift --image=busybox:1.37 -- sleep 1d
k wait --for=condition=Ready pod/drift
k exec drift -- sh -c 'cp /bin/busybox /usr/bin/kworker
  echo x::0:0::/:/bin/sh >> /etc/passwd'
k get pod drift -o wide

Erwartet (gekürzt):

NAME    READY   STATUS    RESTARTS   AGE   IP             NODE      ...
drift   1/1     Running   0          3s    10.244.1.177   worker2   ...

Jede Änderung landet in der beschreibbaren Overlay-Schicht (upperdir). Auf dem Node aus der Spalte NODE (hier worker2):

ssh [email protected]
ID=$(sudo crictl ps --namespace tag18 --name drift -q)
PID=$(sudo crictl inspect -o go-template --template '{{.info.pid}}' $ID)
U=$(sudo grep -o -m1 'upperdir=[^,]*' /proc/$PID/mounts | cut -d= -f2)
sudo find $U -type f -printf '%P\n'
sudo tail -1 $U/etc/passwd
exit

Erwartet:

usr/bin/kworker
etc/hostname
etc/passwd
etc/hosts
etc/resolv.conf
x::0:0::/:/bin/sh

hostname, hosts und resolv.conf legt die Container-Runtime als Mount-Punkte für die Dateien des kubelet an – normal. kworker und passwd sind die Spuren. Mit readOnlyRootFilesystem stünden hier nur die drei Mount-Punkte.

Fortschritt speichern? Kostenlos registrieren

Drill 4: Shell und Paketmanager aufspüren

Wer eine Shell findet, kann improvisieren; wer apk oder apt-get findet, kann nachinstallieren:

k exec notes -- sh -c 'for b in sh apk apt-get wget nc; do command -v $b; done'
k exec web -- sh -c 'for b in sh apk apt-get curl; do command -v $b; done'
k run noshell --image=registry.k8s.io/pause:3.10.2
k wait --for=condition=Ready pod/noshell
k exec noshell -- sh

Erwartet (gekürzt):

/bin/sh
/sbin/apk
/usr/bin/wget
/usr/bin/nc
/usr/bin/sh
/usr/bin/apt-get
/usr/bin/curl
error: Internal error occurred: ... exec: "sh": executable file not found in $PATH

notes-api auf Alpine bringt Shell, Paketmanager und nc mit – das geschrumpfte Image aus Tag 13 hat das nicht; hier nutzen wir bewusst 1.0. Ein Image ohne Shell untersuchst du mit einem Ephemeral Container, der den Prozess-Namespace des Ziels teilt:

k debug -it noshell --image=busybox:1.37 --target=noshell -- ps

Erwartet (gekürzt):

PID   USER     TIME  COMMAND
    1 65535     0:00 /pause
   18 root      0:00 ps

Welche Pods sind überhaupt nicht unveränderlich?

k get pods -o custom-columns='NAME:.metadata.name,IMAGE:.spec.containers[*].image,'\
'RO:.spec.containers[*].securityContext.readOnlyRootFilesystem'

Erwartet:

NAME      IMAGE                              RO
drift     busybox:1.37                       <none>
noshell   registry.k8s.io/pause:3.10.2       <none>
notes     172.16.0.126:30500/notes-api:1.0   true
web       nginx:1.29                         true

Fortschritt speichern? Kostenlos registrieren

Drill 5: Verdächtigen Prozess untersuchen

Das Deployment shop liefert scheinbar nur eine Webseite aus – nebenbei läuft eine Bind-Shell auf Port 4444:

k create deploy shop --image=busybox:1.37 $do \
  -- sh -c 'nc -lk -p 4444 -e /bin/sh & httpd -f -p 8080' > shop.yaml
k apply -f shop.yaml
k expose deploy shop --port=80 --target-port=8080
k run client --image=busybox:1.37 -- sleep 1d
k wait --for=condition=Ready pod/client
k get pod -l app=shop -o custom-columns=NAME:.metadata.name,NODE:.spec.nodeName,\
IP:.status.podIP
IP=$(k get pod -l app=shop -o jsonpath='{.items[0].status.podIP}')
k exec client -- sh -c "echo id | nc -w 2 $IP 4444"

Erwartet:

NAME                   NODE      IP
shop-87c56f54f-5bk77   worker2   10.244.1.141
uid=0(root) gid=0(root) groups=0(root),10(wheel)

Wer Port 4444 erreicht, ist root im Container. k exec … ps würde den Prozess zeigen – aber in einem kompromittierten Container traust du ps nicht. Also vom Node aus der Spalte NODE (hier worker2):

ssh [email protected]
ID=$(sudo crictl ps --namespace tag18 --name busybox -q)
PID=$(sudo crictl inspect -o go-template --template '{{.info.pid}}' $ID)
echo $PID
ps -o pid,ppid,user,cmd --ppid $PID
NC=$(pgrep -x nc)
sudo ls -l /proc/$NC/exe
sudo cat /proc/$NC/cmdline | tr '\0' ' '; echo
sudo nsenter -t $PID -n ss -tlnp

Erwartet:

13482
    PID    PPID USER     CMD
  13496   13482 root     nc -lk -p 4444 -e /bin/sh
lrwxrwxrwx 1 root root 0 Nov 18 17:41 /proc/13496/exe -> /bin/nc
nc -lk -p 4444 -e /bin/sh
State  Recv-Q Send-Q Local Address:Port Peer Address:PortProcess
LISTEN 0      1                  *:4444            *:*    users:(("nc",pid=13496,fd=3))
LISTEN 0      9                  *:8080            *:*    users:(("httpd",pid=13482,…

crictl inspect liefert die Host-PID des Hauptprozesses (hier httpd), ps --ppid seine Kinder. exe zeigt den Pfad im Container, /proc/<pid>/root/ öffnet dessen Dateisystem vom Host aus. ss auf dem Host sieht Port 4444 nicht – der lebt im Netzwerk-Namespace des Pods, deshalb nsenter -n.

Fortschritt speichern? Kostenlos registrieren

Drill 6: Vom Host-Prozess zurück zum Pod

Oft ist es umgekehrt: Ein Alarm nennt nur eine PID auf dem Node. Die cgroup verrät den Container:

cat /proc/$NC/cgroup
CID=$(grep -o 'cri-containerd-[0-9a-f]*' /proc/$NC/cgroup | cut -d- -f3)
sudo crictl ps --id $CID -o json | jq -r '.containers[0] | .metadata.name + " "
  + .labels["io.kubernetes.pod.name"] + " " + .labels["io.kubernetes.pod.namespace"]'
sudo crictl inspect $CID > ~/inspect-shop.json
exit

Erwartet (Pfad gekürzt):

0::/kubepods.slice/kubepods-besteffort.slice/kubepods-besteffort-pode54eb65a_54ad_…
.slice/cri-containerd-62ab4e431ca47e04026def3c75802927dbf745fc5ed0d97dfb84264765afca5a
.scope
busybox shop-87c56f54f-5bk77 tag18

Die cgroup enthält Pod-UID und Container-ID; die Labels io.kubernetes.pod.* setzt das kubelet an jeden Container. Container-Name, Pod und Namespace – mehr braucht der Bericht nicht.

Fortschritt speichern? Kostenlos registrieren

Drill 7: Pod isolieren

Nicht sofort löschen: Erst aus dem Verkehr ziehen, dann Beweise sichern. Entfernst du das Label app, gibt das ReplicaSet den Pod frei (es startet Ersatz) und der Service schickt keinen Traffic mehr hin:

P=$(k get pod -l app=shop -o name)
k label $P app- quarantine=true
k get pods -l app=shop -L quarantine
k get pods -l quarantine=true
cat > quarantine.yaml <<'EOF'
apiVersion: networking.k8s.io/v1
kind: NetworkPolicy
metadata:
  name: quarantine
spec:
  podSelector:
    matchLabels:
      quarantine: "true"
  policyTypes:
  - Ingress
  - Egress
EOF
k apply -f quarantine.yaml
k get cep ${P#pod/} -o jsonpath='{.status.identity.labels}' \
  | grep -o 'k8s:quarantine=true'
k exec client -- sh -c "echo id | nc -w 2 $IP 4444"; echo "exit $?"

Erwartet (gekürzt):

pod/shop-87c56f54f-5bk77 modified
NAME                   READY   STATUS    RESTARTS   AGE   QUARANTINE
shop-87c56f54f-fljs8   1/1     Running   0          2s
NAME                   READY   STATUS    RESTARTS   AGE
shop-87c56f54f-5bk77   1/1     Running   0          23s
networkpolicy.networking.k8s.io/quarantine created
k8s:quarantine=true
command terminated with exit code 1
exit 1

Policy ohne Regeln, aber mit beiden policyTypes sperrt alles rein und raus – auch den Rückkanal des Angreifers. Achtung Cilium: Policies greifen über die Security-Identity des Endpoints, und die folgt den Pod-Labels mit Verzögerung (im Labor bis zu einer Minute). Bleibt die grep-Zeile leer, gilt noch die alte Identity und Port 4444 ist offen – kurz warten und wiederholen, erst dann testen.

Fortschritt speichern? Kostenlos registrieren

Drill 8: Beweise sichern und entfernen

mkdir -p evidence
k get $P -o yaml > evidence/pod.yaml
k logs $P > evidence/pod.log
k get events --field-selector involvedObject.name=${P#pod/} > evidence/events.txt
ls evidence
k delete $P --now
k scale deploy shop --replicas=0
k get deploy shop

Erwartet:

events.txt
pod.log
pod.yaml
pod "shop-87c56f54f-5bk77" deleted from tag18 namespace
deployment.apps/shop scaled
NAME   READY   UP-TO-DATE   AVAILABLE   AGE
shop   0/0     0            0           61s

Die Hintertür steht im Pod-Template – der Ersatz-Pod hatte sie auch. Darum das Deployment auf 0 (oder löschen), bis das Image geklärt ist. Zur Akte gehört auch ~/inspect-shop.json auf dem Node (Drill 6) – gesichert, solange der Container noch lief.

Fortschritt speichern? Kostenlos registrieren

Übung: Speed-Drills

  1. Deployment api (notes-api:1.0, Secret notes-key als Env) mit schreibgeschütztem Root-FS und emptyDir unter /tmp. Zeitziel: 3 min
  2. Liste alle Pods in tag18, bei denen ein Container kein readOnlyRootFilesystem: true hat. Zeitziel: 1 min
  3. Ermittle die Host-PID des Containers im Pod notes. Zeitziel: 2 min
  4. Isoliere den Pod drift mit der vorhandenen Policy. Zeitziel: 20 s

Lösung

k create deploy api --image=172.16.0.126:30500/notes-api:1.0 $do > api.yaml

Im Pod-Template ergänzen:

    spec:
      containers:
      - name: notes-api
        image: 172.16.0.126:30500/notes-api:1.0
        envFrom:
        - secretRef:
            name: notes-key
        securityContext:
          readOnlyRootFilesystem: true
        volumeMounts:
        - name: tmp
          mountPath: /tmp
      volumes:
      - name: tmp
        emptyDir: {}
k apply -f api.yaml
k rollout status deploy/api
k exec deploy/api -- sh -c 'touch /tmp/ok && touch /x'
k get pods -o json | jq -r '.items[]
  | select(any(.spec.containers[]; .securityContext.readOnlyRootFilesystem != true))
  | .metadata.name'
k get pod notes -o jsonpath='{.spec.nodeName}{"\n"}'
ssh [email protected]         # Node aus der Zeile davor, hier worker2
POD=$(sudo crictl pods --namespace tag18 --name '^notes$' -q)
ID=$(sudo crictl ps --pod $POD -q)
sudo crictl inspect -o go-template --template '{{.info.pid}}' $ID; echo
exit
k label pod drift quarantine=true

Erwartet (gekürzt):

touch: /x: Read-only file system
client
drift
noshell
worker2
13077
pod/drift labeled

Fortschritt speichern? Kostenlos registrieren

Kontrollpunkt

k get pod web -o jsonpath='{.spec.containers[0].securityContext.readOnlyRootFilesystem}'

Erwartet: true

k exec web -- touch /etc/x

Erwartet: touch: cannot touch '/etc/x': Read-only file system

k get netpol quarantine -o jsonpath='{.spec.policyTypes}{"\n"}'

Erwartet: ["Ingress","Egress"]

k get deploy shop

Erwartet: shop 0/0 0 0 …

Challenge

Spiele das Deployment unten ein. Danach lauscht in einem Pod ein Prozess auf TCP 31337. Finde nur mit Werkzeugen auf den Nodes Container, Pod und Namespace, sichere Pod-YAML und Container-Log nach ~/cks/tag18/evidence-cron/, isoliere den Pod und sorge dafür, dass der Prozess nicht wiederkommt.

k apply -f - <<'EOF'
apiVersion: apps/v1
kind: Deployment
metadata:
  name: cron
spec:
  selector:
    matchLabels:
      app: cron
  template:
    metadata:
      labels:
        app: cron
    spec:
      containers:
      - name: main
        image: busybox:1.37
        command: ["sleep", "infinity"]
      - name: log
        image: busybox:1.37
        command: ["sh", "-c", "while true; do nc -l -p 31337 -e /bin/sh; done"]
EOF

Hinweis: ss -tlnp auf dem Host sieht den Port nicht, pgrep sieht dagegen jeden Prozess des Nodes.

Lösung

Auf beiden Workern nachsehen (172.16.0.228 und 172.16.0.83):

ssh [email protected]
sudo ss -tlnp | grep 31337
pgrep -a -x nc
P=$(pgrep -x nc)
sudo nsenter -t $P -n ss -tlnp
CID=$(grep -o 'cri-containerd-[0-9a-f]*' /proc/$P/cgroup | cut -d- -f3)
sudo crictl ps --id $CID -o json | jq -r '.containers[0] | .metadata.name + " "
  + .labels["io.kubernetes.pod.name"] + " " + .labels["io.kubernetes.pod.namespace"]'
exit

Erwartet:

11099 nc -l -p 31337 -e /bin/sh
State  Recv-Q Send-Q Local Address:Port  Peer Address:PortProcess
LISTEN 0      1                  *:31337            *:*    users:(("nc",pid=11099,fd=3))
log cron-66f4cf9fd7-flzwf tag18

Der Container log ist der Täter, main ist unauffällig. Zurück auf cp1:

P=<Pod-Name aus der crictl-Ausgabe>   # hier cron-66f4cf9fd7-flzwf
k label pod $P app- quarantine=true
mkdir -p evidence-cron
k get pod $P -o yaml > evidence-cron/pod.yaml
k logs $P -c log > evidence-cron/log.txt
k scale deploy cron --replicas=0
k delete pod $P --now
k get deploy cron
k get pods -l quarantine=true

Erwartet (gekürzt):

pod/cron-66f4cf9fd7-flzwf modified
deployment.apps/cron scaled
pod "cron-66f4cf9fd7-flzwf" deleted from tag18 namespace
NAME   READY   UP-TO-DATE   AVAILABLE   AGE
cron   0/0     0            0           26s
NAME    READY   STATUS    RESTARTS   AGE
drift   1/1     Running   0          …

drift trägt das Label noch aus Speed-Drill 4.

Das Umlabeln hat bereits einen Ersatz-Pod mit derselben Hintertür gestartet – erst scale --replicas=0 beseitigt ihn. Der herausgelöste Pod gehört keinem ReplicaSet mehr und kann danach gelöscht werden.

Fortschritt speichern? Kostenlos registrieren

Aufräumen

Gilt für alle, auch ohne Challenge:

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

Prüfungstipp

  • „Make the pod immutable“ heißt fast immer: readOnlyRootFilesystem: true plus emptyDir für die Schreibpfade aus dem Log; oft zusätzlich privileged entfernen und Nicht-Root erzwingen.
  • „Delete pods that are not immutable / run as privileged“: mit custom-columns oder jq suchen, Ergebnis gegen die Aufgabe prüfen, dann den Besitzer (Deployment) beheben, nicht nur den Pod.
  • crictl braucht auf Prüfungs-Nodes sudo; crictl inspect ohne Template ist ein langes JSON – -o go-template --template '{{.info.pid}}' spart Zeit.

Enterprise-Notiz

  • Distroless- oder scratch-Images (Tag 13) nehmen Shell und Paketmanager weg; Debugging läuft dann über k debug mit Ephemeral Containers, per RBAC eng vergeben.
  • readOnlyRootFilesystem per Admission erzwingen (Kyverno, Gatekeeper oder ValidatingAdmissionPolicy) – PSA restricted verlangt es nicht.
  • Erkennung gehört nicht in Handarbeit: Falco (Tag 16) meldet Shells, Schreibzugriffe und Netcat-Listener, Tetragon (Tag 17) kann sie im Kernel blockieren.
  • Incident-Runbook vorab festlegen: Quarantäne-Label und Deny-All-Policy pro Namespace bereithalten, Beweise (YAML, Logs, crictl inspect, ggf. Checkpoint) vor dem Löschen.
  • Den Node selbst als verdächtig behandeln, wenn der Container privileged oder hostPID hatte – cordon, drain, neu aufsetzen.