Zum Inhalt springen
Trainingslager IT-Trainingslager

Tag 12: NetworkPolicies

Ziel: Du sperrst Pod-Verkehr standardmäßig, öffnest gezielt Wege auf L3, L4 und L7, erlaubst Egress nach DNS-Namen und setzt clusterweite Sperren, die kein Allow aufhebt. · Dauer: ca. 90 min · Voraussetzung: Tag 0

Briefing

  • CKNE: Network Security and Policy – „Securing Traffic with Network Policies“.
  • Ohne Policy spricht jeder Pod mit jedem. Die erste Policy, die einen Pod in einer Richtung auswählt, schaltet dort Default Deny ein; danach addieren sich Allows.
  • NetworkPolicy kennt nur L3/L4 und kein Deny. CiliumNetworkPolicy (CNP) kann L7, DNS-Namen, Entities und Deny; die CiliumClusterwideNetworkPolicy (CCNP) gilt clusterweit.
  • Nachweis immer dreifach: curl/nc, hubble observe --verdict DROPPED, Policy-Status im Agenten (cilium-dbg endpoint list).
 tag12-other/good (role=client) ──┐
 tag12-other/bad  ────────────────┤
 tag12/client (app=client) ───────┴──> tag12/notes-api :8080 (Service :80)
        └──> kube-dns · Nodes :10250 · router .123 · Internet (nur per Name)

Drill 1: Das Testfeld

Zwei Namespaces, beide mit dem Label ckne=tag12 (für Drill 8). Die Clients sind curlimages/curl – das Image bringt curl, nc und nslookup mit:

mkdir -p ~/ckne/tag12 && cd ~/ckne/tag12
k create namespace tag12
k create namespace tag12-other
k label namespace tag12 tag12-other ckne=tag12
k -n tag12 create deployment notes-api \
  --image=ghcr.io/thomaszachmann/notes-api:0.5.1 --replicas=2 --port=8080 \
  $do > notes-api.yaml
k set env --local -f notes-api.yaml NOTES_API_KEY=lab-key-123 -o yaml \
  > notes-api-env.yaml
k apply -f notes-api-env.yaml
k -n tag12 expose deployment notes-api --port=80 --target-port=8080
k -n tag12 run client --image=curlimages/curl:8.17.0 -l app=client,role=client \
  --command -- sleep infinity
k -n tag12-other run good --image=curlimages/curl:8.17.0 -l role=client \
  --command -- sleep infinity
k -n tag12-other run bad --image=curlimages/curl:8.17.0 \
  --command -- sleep infinity
k -n tag12 rollout status deployment notes-api
k wait --for=condition=Ready pod --all -n tag12-other
k -n tag12 get cep
k -n tag12 exec client -- curl -s -m3 notes-api/version
k -n tag12-other exec good -- curl -s -m3 notes-api.tag12/version
k -n tag12-other exec bad -- curl -s -m3 notes-api.tag12/version

Erwartet (gekürzt):

deployment "notes-api" successfully rolled out
pod/bad condition met
pod/good condition met
NAME                         SECURITY IDENTITY   ENDPOINT STATE   IPV4
client                       15951               ready            10.0.2.58
notes-api-665494b9df-dkctb   64913               ready            10.0.1.112
notes-api-665494b9df-nd4cg   64913               ready            10.0.2.198
0.5.1
0.5.1
0.5.1

Alle drei Clients erreichen notes-api. Policies arbeiten mit diesen Identitäten, nicht mit IPs: Beide notes-api-Pods tragen dieselben Labels und damit dieselbe Identity.

Fortschritt speichern? Kostenlos registrieren

Drill 2: Default Deny und die DNS-Ausnahme

Eine Policy mit leerem podSelector und beiden policyTypes, aber ohne Regeln, sperrt alles im Namespace:

cat > default-deny.yaml <<'EOF'
apiVersion: networking.k8s.io/v1
kind: NetworkPolicy
metadata:
  name: default-deny
  namespace: tag12
spec:
  podSelector: {}
  policyTypes:
  - Ingress
  - Egress
EOF
k apply -f default-deny.yaml
k -n tag12 exec client -- nslookup -timeout=2 notes-api
k -n tag12 exec client -- curl -s -m3 10.96.0.1:443
hubble observe -P --port-forward-port 0 --verdict DROPPED --namespace tag12 --last 2

Erwartet (gekürzt, Zeitstempel weggelassen):

;; connection timed out; no servers could be reached
command terminated with exit code 1
command terminated with exit code 28
tag12/client:60376 (ID:15951) <> 172.16.0.126:6443 (kube-apiserver)
  policy-verdict:none EGRESS DENIED (TCP Flags: SYN)
tag12/client:60376 (ID:15951) <> 172.16.0.126:6443 (kube-apiserver)
  Policy denied DROPPED (TCP Flags: SYN)

Hubble zeigt nicht die ClusterIP 10.96.0.1, sondern das echte Ziel: Cilium übersetzt Service-Adressen schon am Socket, die Policy sieht danach das Backend. Jetzt DNS zu CoreDNS erlauben – UDP und TCP, weil große Antworten über TCP kommen:

cat > allow-dns.yaml <<'EOF'
apiVersion: networking.k8s.io/v1
kind: NetworkPolicy
metadata:
  name: allow-dns
  namespace: tag12
spec:
  podSelector: {}
  policyTypes:
  - Egress
  egress:
  - to:
    - namespaceSelector:
        matchLabels:
          kubernetes.io/metadata.name: kube-system
      podSelector:
        matchLabels:
          k8s-app: kube-dns
    ports:
    - protocol: UDP
      port: 53
    - protocol: TCP
      port: 53
EOF
k apply -f allow-dns.yaml
k -n tag12 exec client -- nslookup notes-api.tag12.svc.cluster.local
k -n tag12 exec client -- curl -s -m3 notes-api/version
hubble observe -P --port-forward-port 0 --namespace tag12 --to-port 53 --last 1

Erwartet (gekürzt):

Name:   notes-api.tag12.svc.cluster.local
Address: 10.109.31.111
command terminated with exit code 28
tag12/client:47319 (ID:15951) -> kube-system/coredns-559f6c778d-nz7t6:53 (ID:13185)
  policy-verdict:L3-L4 EGRESS ALLOWED (UDP)

DNS geht, notes-api noch nicht – Egress vom Client und Ingress bei notes-api sind beide zu. Den Policy-Status zeigt der Agent auf dem Node des Clients:

NODE=$(k -n tag12 get pod client -o jsonpath='{.spec.nodeName}')
CP=$(k -n kube-system get pod -l k8s-app=cilium \
  --field-selector spec.nodeName=$NODE -o name)
k -n kube-system exec $CP -c cilium-agent -- cilium-dbg endpoint list \
  | grep -E 'ENDPOINT|app=client|app=notes-api'

Erwartet (gekürzt):

ENDPOINT   POLICY (ingress)   POLICY (egress)   IDENTITY   LABELS ...         IPv4
388        Enabled            Enabled           15951      k8s:app=client     10.0.2.58
3952       Enabled            Enabled           64913      k8s:app=notes-api  10.0.2.198

Enabled heißt: Für diese Richtung gilt Default Deny. Du siehst nur den notes-api-Pod auf diesem Node – cilium-dbg kennt nur lokale Endpoints.

Fortschritt speichern? Kostenlos registrieren

Drill 3: Selektoren kombinieren – die UND/ODER-Falle

Client darf zu notes-api; notes-api soll nur role=client-Pods aus tag12-other annehmen. Erster Versuch:

cat > client-egress.yaml <<'EOF'
apiVersion: networking.k8s.io/v1
kind: NetworkPolicy
metadata:
  name: client-egress
  namespace: tag12
spec:
  podSelector:
    matchLabels:
      role: client
  policyTypes:
  - Egress
  egress:
  - to:
    - podSelector:
        matchLabels:
          app: notes-api
    ports:
    - protocol: TCP
      port: 8080
EOF
cat > api-ingress.yaml <<'EOF'
apiVersion: networking.k8s.io/v1
kind: NetworkPolicy
metadata:
  name: api-ingress
  namespace: tag12
spec:
  podSelector:
    matchLabels:
      app: notes-api
  policyTypes:
  - Ingress
  ingress:
  - from:
    - namespaceSelector:
        matchLabels:
          kubernetes.io/metadata.name: tag12-other
    - podSelector:
        matchLabels:
          role: client
    ports:
    - protocol: TCP
      port: 8080
EOF
k apply -f client-egress.yaml -f api-ingress.yaml
k -n tag12 exec client -- curl -s -m3 notes-api/version
k -n tag12-other exec good -- curl -s -m3 notes-api.tag12/version
k -n tag12-other exec bad -- curl -s -m3 notes-api.tag12/version

Erwartet:

networkpolicy.networking.k8s.io/client-egress created
networkpolicy.networking.k8s.io/api-ingress created
0.5.1
0.5.1
0.5.1

Auch bad kommt durch. Zwei Listeneinträge (zwei -) sind ODER: „ganzer Namespace tag12-other“ oder „role=client im eigenen Namespace“. Für UND gehören beide Selektoren in einen Eintrag – lösche in api-ingress.yaml das - vor podSelector und rücke die Zeile auf namespaceSelector ein:

  ingress:
  - from:
    - namespaceSelector:
        matchLabels:
          kubernetes.io/metadata.name: tag12-other
      podSelector:
        matchLabels:
          role: client
    ports:
    - protocol: TCP
      port: 8080
k apply -f api-ingress.yaml
k -n tag12 exec client -- curl -s -m3 notes-api/version
k -n tag12-other exec good -- curl -s -m3 notes-api.tag12/version
k -n tag12-other exec bad -- curl -s -m3 notes-api.tag12/version
k -n tag12 describe networkpolicy api-ingress \
  | sed -n '/Allowing ingress/,/Not affecting/p'
hubble observe -P --port-forward-port 0 --verdict DROPPED --namespace tag12 \
  --to-port 8080 --last 4

Erwartet (gekürzt):

command terminated with exit code 28
0.5.1
command terminated with exit code 28
  Allowing ingress traffic:
    To Port: 8080/TCP
    From:
      NamespaceSelector: kubernetes.io/metadata.name=tag12-other
      PodSelector: role=client
  Not affecting egress traffic
tag12/client:59482 (ID:15951) <> tag12/notes-api-…-nd4cg:8080 (ID:64913)
  Policy denied DROPPED (TCP Flags: SYN)
tag12-other/bad:36910 (ID:6458) <> tag12/notes-api-…-dkctb:8080 (ID:64913)
  Policy denied DROPPED (TCP Flags: SYN)

bad ist draußen – aber jetzt auch der eigene client: Ein Eintrag mit namespaceSelector gilt nicht mehr für den eigenen Namespace. describe zeigt UND als zwei Zeilen unter einem From:. Den eigenen Client als zweiten Eintrag ergänzen:

cat >> api-ingress.yaml <<'EOF'
  - from:
    - podSelector:
        matchLabels:
          role: client
    ports:
    - protocol: TCP
      port: 8080
EOF
k apply -f api-ingress.yaml
k -n tag12 exec client -- curl -s -m3 notes-api/version
k -n tag12-other exec good -- curl -s -m3 notes-api.tag12/version
k -n tag12-other exec bad -- curl -s -m3 notes-api.tag12/version

Erwartet:

networkpolicy.networking.k8s.io/api-ingress configured
0.5.1
0.5.1
command terminated with exit code 28

Fortschritt speichern? Kostenlos registrieren

Drill 4: ipBlock mit except, Node-IPs und Portbereiche

Der Client soll ins Heimnetz 172.16.0.0/24, aber nicht zum router:

cat > client-lan.yaml <<'EOF'
apiVersion: networking.k8s.io/v1
kind: NetworkPolicy
metadata:
  name: client-lan
  namespace: tag12
spec:
  podSelector:
    matchLabels:
      role: client
  policyTypes:
  - Egress
  egress:
  - to:
    - ipBlock:
        cidr: 172.16.0.0/24
        except:
        - 172.16.0.123/32
EOF
k apply -f client-lan.yaml
k -n tag12 exec client -- nc -zv -w2 172.16.0.1 443
k -n tag12 exec client -- nc -zv -w2 172.16.0.123 22
k -n tag12 exec client -- nc -zv -w2 172.16.0.228 10250
k -n tag12 exec client -- nc -zv -w2 172.16.0.126 6443
hubble observe -P --port-forward-port 0 --verdict DROPPED --namespace tag12 \
  --since 20s | grep client

Erwartet (gekürzt, je Ziel eine Zeile):

172.16.0.1 (172.16.0.1:443) open
nc: 172.16.0.123 (172.16.0.123:22): Operation timed out
nc: 172.16.0.228 (172.16.0.228:10250): Operation timed out
nc: 172.16.0.126 (172.16.0.126:6443): Operation timed out
tag12/client:39305 (ID:15951) <> 172.16.0.123:22 (ID:16777272) Policy denied DROPPED
tag12/client:42831 (ID:15951) <> 172.16.0.228:10250 (remote-node) Policy denied DROPPED
tag12/client:45411 (ID:15951) <> 172.16.0.126:6443 (kube-apiserver) Policy denied …

Gateway .1 geht, router ist per except gesperrt – wie gewollt. Aber auch worker1 und cp1 sind zu, obwohl sie im CIDR liegen: Cilium gibt Node-IPs die Identitäten host, remote-node oder kube-apiserver, und ipBlock erfasst in der Standardeinstellung nur world (die ID:16777272 ist eine lokale CIDR-Identity). Calico & Co. würden die Nodes durchlassen. Abhilfe in Cilium: toEntities (Drill 5).

Portbereiche gibt es mit endPort. Zum router nur TCP 20 bis 23:

cat > client-router.yaml <<'EOF'
apiVersion: networking.k8s.io/v1
kind: NetworkPolicy
metadata:
  name: client-router
  namespace: tag12
spec:
  podSelector:
    matchLabels:
      role: client
  policyTypes:
  - Egress
  egress:
  - to:
    - ipBlock:
        cidr: 172.16.0.123/32
    ports:
    - protocol: TCP
      port: 20
      endPort: 23
EOF
k apply -f client-router.yaml
k -n tag12 exec client -- nc -zv -w2 172.16.0.123 22
k -n tag12 exec client -- curl -s -m3 http://172.16.0.123
k -n tag12-other exec bad -- curl -s -m3 http://172.16.0.123
hubble observe -P --port-forward-port 0 --verdict DROPPED --namespace tag12 \
  --to-port 80 --last 1

Erwartet (gekürzt):

172.16.0.123 (172.16.0.123:22) open
command terminated with exit code 28
command terminated with exit code 7
tag12/client:44219 (ID:15951) <> 172.16.0.123:80 (ID:16777272) Policy denied DROPPED

Port 22 geht trotz except in client-lan: Policies addieren sich, ein except nimmt nur aus der eigenen Regel etwas heraus. Merke die curl-Exit-Codes: 7 = Verbindung abgelehnt (Paket kam an, nichts lauscht), 28 = Timeout (Policy hat verworfen). --to-ip lässt sich übrigens nicht mit --namespace kombinieren, --to-port schon.

Fortschritt speichern? Kostenlos registrieren

Drill 5: CiliumNetworkPolicy auf L3/L4 mit Entities

Ab hier nur noch Cilium-Policies. Beide Arten wirken gemeinsam – zum Lernen räumst du die NetworkPolicies weg:

k -n tag12 delete networkpolicy --all
cat > cnp-client.yaml <<'EOF'
apiVersion: cilium.io/v2
kind: CiliumNetworkPolicy
metadata:
  name: client
  namespace: tag12
spec:
  endpointSelector:
    matchLabels:
      app: client
  egress:
  - toEndpoints:
    - matchLabels:
        k8s:io.kubernetes.pod.namespace: kube-system
        k8s:k8s-app: kube-dns
    toPorts:
    - ports:
      - port: "53"
        protocol: ANY
  - toEndpoints:
    - matchLabels:
        app: notes-api
    toPorts:
    - ports:
      - port: "8080"
        protocol: TCP
  - toEntities:
    - host
    - remote-node
    toPorts:
    - ports:
      - port: "10250"
        protocol: TCP
EOF
cat > cnp-notes-api.yaml <<'EOF'
apiVersion: cilium.io/v2
kind: CiliumNetworkPolicy
metadata:
  name: notes-api
  namespace: tag12
spec:
  endpointSelector:
    matchLabels:
      app: notes-api
  ingress:
  - fromEndpoints:
    - matchLabels:
        app: client
    toPorts:
    - ports:
      - port: "8080"
        protocol: TCP
EOF
k apply -f cnp-client.yaml -f cnp-notes-api.yaml
k -n tag12 get cnp
k -n tag12 exec client -- curl -s -m3 notes-api/version
for ip in 172.16.0.126 172.16.0.228 172.16.0.83; do
  k -n tag12 exec client -- nc -zv -w2 $ip 10250
done
k -n tag12 exec client -- nc -zv -w2 172.16.0.126 6443
k -n tag12-other exec good -- curl -s -m3 notes-api.tag12/version

Erwartet:

NAME        AGE   VALID
client      5s    True
notes-api   5s    True
0.5.1
172.16.0.126 (172.16.0.126:10250) open
172.16.0.228 (172.16.0.228:10250) open
172.16.0.83 (172.16.0.83:10250) open
nc: 172.16.0.126 (172.16.0.126:6443): Operation timed out
command terminated with exit code 1
command terminated with exit code 28

Selektoren ohne Namespace-Label meinen den Namespace der Policy; das Label k8s:io.kubernetes.pod.namespace wählt fremde Namespaces. host ist der eigene Node, remote-node sind alle anderen – so erreichst du das kubelet (10250) überall; den API-Server (6443) nicht, weil nur Port 10250 freigegeben ist – für ihn gäbe es die Entity kube-apiserver. VALID True heißt nur: Syntax ok. Was der Agent daraus macht:

k -n kube-system exec $CP -c cilium-agent -- cilium-dbg endpoint list \
  | grep -E 'ENDPOINT|app=client|app=notes-api'
k -n kube-system exec $CP -c cilium-agent -- cilium-dbg policy get \
  k8s:io.cilium.k8s.policy.name=notes-api k8s:io.cilium.k8s.policy.namespace=tag12
cilium config view | grep '^enable-policy '

Erwartet (gekürzt):

ENDPOINT   POLICY (ingress)   POLICY (egress)   IDENTITY   LABELS ...         IPv4
388        Disabled           Enabled           15951      k8s:app=client     10.0.2.58
3952       Enabled            Disabled          64913      k8s:app=notes-api  10.0.2.198
[
  {
    "Subject": {
      "matchLabels": {
        "any:app": "notes-api",
        "k8s:io.kubernetes.pod.namespace": "tag12"
      }
    },
    "L3": [ { "matchLabels": { "any:app": "client", ... } } ],
    "L4": [ { "ports": [ { "port": "8080", "protocol": "TCP" } ] } ],
    ...
    "DefaultDeny": true,
    "Ingress": true,
...
Revision: 279
enable-policy                                     default

Anders als bei den NetworkPolicies vorher hat der Client jetzt nur Egress-Default-Deny: Eine CNP schaltet Default Deny nur für die Richtung ein, in der sie Regeln hat. policy get (in 1.20 als deprecated markiert) zeigt, wie der Agent die Policy übersetzt hat. enable-policy default ist der Policy-Enforcement-Mode: Endpoints ohne Policy sind offen. always erzwingt Default Deny für alle Endpoints – auch ohne Policy –, never schaltet Policies ganz ab (Helm-Wert policyEnforcementMode, hier nicht ändern).

Fortschritt speichern? Kostenlos registrieren

Drill 6: L7-Regeln für HTTP

notes-api soll vom Client nur lesende Aufrufe annehmen. Die rules.http hängen am Port:

cat > cnp-notes-api.yaml <<'EOF'
apiVersion: cilium.io/v2
kind: CiliumNetworkPolicy
metadata:
  name: notes-api
  namespace: tag12
spec:
  endpointSelector:
    matchLabels:
      app: notes-api
  ingress:
  - fromEndpoints:
    - matchLabels:
        app: client
    toPorts:
    - ports:
      - port: "8080"
        protocol: TCP
      rules:
        http:
        - method: GET
          path: "/(version|healthz)"
        - method: GET
          path: "/notes"
EOF
k apply -f cnp-notes-api.yaml
k -n tag12 exec client -- curl -s -m3 notes-api/version
k -n tag12 exec client -- curl -s -m3 notes-api/notes
k -n tag12 exec client -- curl -s -m3 -X POST -H 'X-API-Key: lab-key-123' \
  -d '{"text":"L7"}' notes-api/notes
k -n tag12 exec client -- curl -s -o /dev/null -w '%{http_code}\n' notes-api/notes/42
hubble observe -P --port-forward-port 0 --namespace tag12 --verdict DROPPED \
  --protocol http --last 2

Erwartet (gekürzt):

0.5.1
[]
Access denied
403
tag12/client:49996 (ID:15951) -> tag12/notes-api-…-dkctb:8080 (ID:64913)
  http-request DROPPED (HTTP/1.1 POST http://notes-api/notes)
tag12/client:57836 (ID:15951) -> tag12/notes-api-…-nd4cg:8080 (ID:64913)
  http-request DROPPED (HTTP/1.1 GET http://notes-api/notes/42)

Auf L7 gibt es keinen Timeout, sondern eine Antwort: Envoy beantwortet die verbotene Anfrage mit 403 Access denied. path ist ein regulärer Ausdruck über den ganzen Pfad, deshalb fällt /notes/42 durch. hubble observe --type l7 zeigt auch die erlaubten Anfragen samt Status und Latenz.

Fortschritt speichern? Kostenlos registrieren

Drill 7: Egress nach DNS-Namen (toFQDNs)

toFQDNs braucht den DNS-Proxy: Erst eine DNS-L7-Regel lässt Cilium die Antworten mitlesen und die IPs der Namen lernen.

cat > cnp-client-fqdn.yaml <<'EOF'
apiVersion: cilium.io/v2
kind: CiliumNetworkPolicy
metadata:
  name: client-fqdn
  namespace: tag12
spec:
  endpointSelector:
    matchLabels:
      app: client
  egress:
  - toEndpoints:
    - matchLabels:
        k8s:io.kubernetes.pod.namespace: kube-system
        k8s:k8s-app: kube-dns
    toPorts:
    - ports:
      - port: "53"
        protocol: ANY
      rules:
        dns:
        - matchPattern: "*"
  - toFQDNs:
    - matchName: example.com
    - matchPattern: "*.kubernetes.io"
    toPorts:
    - ports:
      - port: "443"
        protocol: TCP
EOF
k apply -f cnp-client-fqdn.yaml
k -n tag12 exec client -- curl -sI -m5 https://example.com | head -1
k -n tag12 exec client -- curl -sI -m5 https://blog.kubernetes.io | head -1
k -n tag12 exec client -- curl -sI -m5 https://kubernetes.io | head -1
k -n tag12 exec client -- curl -sI -m5 https://github.com | head -1
hubble observe -P --port-forward-port 0 --namespace tag12 --protocol dns --last 1
hubble observe -P --port-forward-port 0 --namespace tag12 --verdict DROPPED \
  --to-port 443 --last 1
k -n kube-system exec $CP -c cilium-agent -- cilium-dbg fqdn cache list

Erwartet (gekürzt):

HTTP/2 200
HTTP/2 302
command terminated with exit code 28
command terminated with exit code 28
tag12/client:37299 (ID:15951) <- kube-system/coredns-…-vwrtf:53 (ID:13185)
  dns-response proxy FORWARDED (DNS Answer "140.82.121.3" TTL: 30 (Proxy github.com. A))
tag12/client:50710 (ID:15951) <> 140.82.121.3:443 (world) Policy denied DROPPED
Endpoint   Source   FQDN                  TTL   ExpirationTime             IPs
388        lookup   example.com.          30    2026-11-18T23:28:08.131Z   2606:4700:…
388        lookup   kubernetes.io.        30    2026-11-18T23:28:11.431Z   15.197.167.9…
388        lookup   blog.kubernetes.io.   30    2026-11-18T23:28:10.634Z   34.107.204.2…
388        lookup   github.com.           30    2026-11-18T23:28:17.090Z   140.82.121.3
388        lookup   example.com.          5     2026-11-18T23:27:41.130Z   104.20.23.15…

*.kubernetes.io erfasst nicht kubernetes.io selbst – dafür brauchst du zusätzlich matchName. Die Namensauflösung klappt für alle Namen (matchPattern: "*" im DNS-Teil), gesperrt wird erst die TCP-Verbindung. Achtung, Policies wirken auf IPs, nicht auf Namen:

k -n tag12 exec client -- curl -sI -m5 https://www.example.com | head -1
k -n tag12 exec client -- nslookup www.example.com | grep -c 104.20.23.154

Erwartet:

HTTP/2 200
1

www.example.com liegt beim selben CDN auf denselben IPs wie example.com – und ist damit ebenfalls erreichbar. Bei Cloud-Diensten hinter gemeinsamen IPs ist FQDN-Egress deshalb gröber, als die Policy aussieht.

Fortschritt speichern? Kostenlos registrieren

Drill 8: Deny schlägt Allow, CCNP clusterweit

notes-api nimmt jetzt Verkehr aus dem ganzen Cluster an – nur bad nie. Allow und Deny in einer Policy:

k -n tag12 delete cnp notes-api
cat > cnp-notes-api-deny.yaml <<'EOF'
apiVersion: cilium.io/v2
kind: CiliumNetworkPolicy
metadata:
  name: notes-api-deny
  namespace: tag12
spec:
  endpointSelector:
    matchLabels:
      app: notes-api
  ingress:
  - fromEntities:
    - cluster
    toPorts:
    - ports:
      - port: "8080"
        protocol: TCP
  ingressDeny:
  - fromEndpoints:
    - matchLabels:
        k8s:io.kubernetes.pod.namespace: tag12-other
        run: bad
EOF
k apply -f cnp-notes-api-deny.yaml
k -n tag12 exec client -- curl -s -m3 notes-api/version
k -n tag12-other exec good -- curl -s -m3 notes-api.tag12/version
k -n tag12-other exec bad -- curl -s -m3 notes-api.tag12/version
hubble observe -P --port-forward-port 0 --verdict DROPPED --from-pod tag12-other/bad \
  --to-port 8080 --last 2

Erwartet (gekürzt):

0.5.1
0.5.1
command terminated with exit code 28
tag12-other/bad:50026 (ID:6458) <> tag12/notes-api-…-dkctb:8080 (ID:64913)
  policy-verdict:L3-Only INGRESS DENIED (TCP Flags: SYN)
tag12-other/bad:50026 (ID:6458) <> tag12/notes-api-…-dkctb:8080 (ID:64913)
  Policy denied by denylist DROPPED (TCP Flags: SYN)

fromEntities: cluster erlaubt auch bad, das Deny gewinnt trotzdem – egal in welcher Policy es steht. „denied by denylist“ unterscheidet es in Hubble vom normalen Default Deny. Nun eine Sperre für alle Pods der Namespaces mit ckne=tag12: kein SSH zum router. Clusterweite Objekte bekommen im Labor das Präfix tag12-:

k -n tag12-other exec bad -- nc -zv -w2 172.16.0.123 22
cat > ccnp-no-ssh.yaml <<'EOF'
apiVersion: cilium.io/v2
kind: CiliumClusterwideNetworkPolicy
metadata:
  name: tag12-no-router-ssh
spec:
  endpointSelector:
    matchLabels:
      k8s:io.cilium.k8s.namespace.labels.ckne: tag12
  egressDeny:
  - toCIDR:
    - 172.16.0.123/32
    toPorts:
    - ports:
      - port: "22"
        protocol: TCP
EOF
k apply -f ccnp-no-ssh.yaml
k get ccnp
k -n tag12-other exec bad -- nc -zv -w2 172.16.0.123 22
k -n tag12-other exec bad -- curl -sI -m5 https://example.com | head -1
k -n tag12-other exec good -- curl -s -m3 notes-api.tag12/version

Erwartet (gekürzt):

172.16.0.123 (172.16.0.123:22) open
ciliumclusterwidenetworkpolicy.cilium.io/tag12-no-router-ssh created
NAME                  VALID
tag12-no-router-ssh   True
nc: 172.16.0.123 (172.16.0.123:22): Operation timed out
command terminated with exit code 28
command terminated with exit code 28

SSH ist zu – aber bad und good kommen gar nicht mehr raus. Auch eine reine Deny-Policy schaltet Default Deny für ihre Richtung ein (k explain ccnp.spec.enableDefaultDeny). Für eine reine Leitplanke schaltest du das ab:

cat >> ccnp-no-ssh.yaml <<'EOF'
  enableDefaultDeny:
    egress: false
    ingress: false
EOF
k apply -f ccnp-no-ssh.yaml
k -n tag12-other exec bad -- nc -zv -w2 172.16.0.123 22
k -n tag12-other exec bad -- curl -sI -m5 https://example.com | head -1
k -n tag12-other exec good -- curl -s -m3 notes-api.tag12/version
hubble observe -P --port-forward-port 0 --namespace tag12-other --verdict DROPPED \
  --to-port 22 --last 1

Erwartet (gekürzt):

nc: 172.16.0.123 (172.16.0.123:22): Operation timed out
HTTP/2 200
0.5.1
tag12-other/bad:46209 (ID:6458) <> 172.16.0.123:22 (ID:16777277)
  Policy denied by denylist DROPPED (TCP Flags: SYN)

Und die AdminNetworkPolicy aus dem Kubernetes-Projekt network-policy-api? Ihr Nachfolger heißt ClusterNetworkPolicy (v1alpha2, Tiers Admin und Baseline). Cilium unterstützt ihn ab 1.20, aber nur mit Helm-Schalter und zusätzlicher CRD – im Labor ist beides aus:

k api-resources | grep -ciE 'adminnetworkpolic|clusternetworkpolic'
helm show values cilium/cilium --version 1.20.5 | grep -A2 '^k8sClusterNetworkPolicy'

Erwartet:

0
k8sClusterNetworkPolicy:
  # -- Enable support for K8s Cluster Network Policy
  enabled: false

Fortschritt speichern? Kostenlos registrieren

Übung: Speed-Drills

Im Namespace tag12-speed laufen web (nginx:1.29, app=web) und probe (curlimages/curl:8.17.0, app=probe, sleep infinity) – zuerst anlegen.

  1. Sperre jeden eingehenden Verkehr im Namespace tag12-speed. Zeitziel: 1 min
  2. Erlaube web auf Port 80 nur von Pods mit role=client aus tag12-other. Zeitziel: 2 min
  3. probe darf nur noch DNS und https://example.com. Zeitziel: 3 min
  4. Zeige die letzten verworfenen Flows im Namespace tag12-speed. Zeitziel: 20 s

Lösung

k create namespace tag12-speed
k -n tag12-speed run web --image=nginx:1.29 -l app=web
k -n tag12-speed run probe --image=curlimages/curl:8.17.0 -l app=probe \
  --command -- sleep infinity
k -n tag12-speed apply -f - <<'EOF'
apiVersion: networking.k8s.io/v1
kind: NetworkPolicy
metadata:
  name: deny-ingress
spec:
  podSelector: {}
  policyTypes:
  - Ingress
---
apiVersion: networking.k8s.io/v1
kind: NetworkPolicy
metadata:
  name: web-from-other
spec:
  podSelector:
    matchLabels:
      app: web
  ingress:
  - from:
    - namespaceSelector:
        matchLabels:
          kubernetes.io/metadata.name: tag12-other
      podSelector:
        matchLabels:
          role: client
    ports:
    - protocol: TCP
      port: 80
---
apiVersion: cilium.io/v2
kind: CiliumNetworkPolicy
metadata:
  name: probe-fqdn
spec:
  endpointSelector:
    matchLabels:
      app: probe
  egress:
  - toEndpoints:
    - matchLabels:
        k8s:io.kubernetes.pod.namespace: kube-system
        k8s:k8s-app: kube-dns
    toPorts:
    - ports:
      - port: "53"
        protocol: ANY
      rules:
        dns:
        - matchPattern: "*"
  - toFQDNs:
    - matchName: example.com
    toPorts:
    - ports:
      - port: "443"
        protocol: TCP
EOF
k wait --for=condition=Ready pod --all -n tag12-speed
WIP=$(k -n tag12-speed get pod web -o jsonpath='{.status.podIP}')
k -n tag12-other exec good -- curl -s -m3 -o /dev/null -w '%{http_code}\n' $WIP
k -n tag12-other exec bad -- curl -s -m3 -o /dev/null -w '%{http_code}\n' $WIP
k -n tag12-speed exec probe -- curl -sI -m5 https://example.com | head -1
k -n tag12-speed exec probe -- curl -sI -m5 https://github.com | head -1
hubble observe -P --port-forward-port 0 --verdict DROPPED --namespace tag12-speed \
  --last 2
k delete namespace tag12-speed

Erwartet (gekürzt):

200
000
command terminated with exit code 28
HTTP/2 200
command terminated with exit code 28
tag12-speed/probe:38546 (ID:5179) <> 140.82.121.3:443 (world) policy-verdict:none
  EGRESS DENIED (TCP Flags: SYN)
tag12-speed/probe:38546 (ID:5179) <> 140.82.121.3:443 (world) Policy denied DROPPED

Fortschritt speichern? Kostenlos registrieren

Kontrollpunkt

Stand nach Drill 8:

k -n tag12 get cnp

Erwartet: client, client-fqdn und notes-api-deny, alle VALID True.

k get ccnp

Erwartet: tag12-no-router-ssh mit VALID True.

k -n tag12 get networkpolicy

Erwartet: No resources found in tag12 namespace.

k -n tag12-other exec bad -- curl -s -m3 notes-api.tag12/version

Erwartet: command terminated with exit code 28 (Deny schlägt Allow).

k -n tag12 exec client -- curl -sI -m5 https://github.com

Erwartet: command terminated with exit code 28 (nicht in toFQDNs).

hubble observe -P --port-forward-port 0 --verdict DROPPED --namespace tag12 --last 5

Erwartet: Zeilen mit Policy denied oder Policy denied by denylist.

Challenge

notes-api soll vom Client nur noch GET /notes annehmen und POST /notes nur mit dem Header X-API-Key: lab-key-123 – alles andere lehnt schon Cilium ab, nicht erst die App.

Hinweis: k explain cnp.spec.ingress.toPorts.rules.http zeigt das Feld headers.

Lösung

k -n tag12 delete cnp notes-api-deny
cat > cnp-notes-api-write.yaml <<'EOF'
apiVersion: cilium.io/v2
kind: CiliumNetworkPolicy
metadata:
  name: notes-api-write
  namespace: tag12
spec:
  endpointSelector:
    matchLabels:
      app: notes-api
  ingress:
  - fromEndpoints:
    - matchLabels:
        app: client
    toPorts:
    - ports:
      - port: "8080"
        protocol: TCP
      rules:
        http:
        - method: GET
          path: "/notes"
        - method: POST
          path: "/notes"
          headers:
          - "X-API-Key: lab-key-123"
EOF
k apply -f cnp-notes-api-write.yaml
k -n tag12 exec client -- curl -s -o /dev/null -w '%{http_code}\n' -X POST \
  -d '{"text":"ohne"}' notes-api/notes
k -n tag12 exec client -- curl -s -o /dev/null -w '%{http_code}\n' -X POST \
  -H 'X-API-Key: falsch' -d '{"text":"falsch"}' notes-api/notes
k -n tag12 exec client -- curl -s -o /dev/null -w '%{http_code}\n' -X POST \
  -H 'X-API-Key: lab-key-123' -d '{"text":"richtig"}' notes-api/notes
k -n tag12 exec client -- curl -s -o /dev/null -w '%{http_code}\n' notes-api/version

Erwartet:

403
403
201
403

Ohne und mit falschem Schlüssel blockt Envoy (403 statt 401 der App), /version steht nicht mehr in der Liste. Die alte Policy notes-api-deny musste weg: Ihr L4-Allow für den ganzen Cluster hätte die L7-Regeln umgangen.

Fortschritt speichern? Kostenlos registrieren

Aufräumen

k delete ccnp tag12-no-router-ssh
k delete namespace tag12 tag12-other
k get ccnp

Erwartet: No resources found – die clusterweite Policy würde sonst neue Pods in Namespaces mit ckne=tag12 weiter treffen. Cilium-Helm-Werte hat dieser Tag nicht geändert.

Prüfungstipp

  • UND/ODER: namespaceSelector und podSelector im selben Listeneintrag = UND, getrennte - = ODER. Danach mit k describe networkpolicy gegenprüfen.
  • Egress-Sperren immer mit DNS-Ausnahme (UDP und TCP 53 zu k8s-app=kube-dns); Ports in Policies sind Container-Ports (8080), nicht Service-Ports (80).
  • Doku: kubernetes.io „Network Policies“, docs.cilium.io „Layer 3/4/7 Examples“, „DNS based“, „Deny Policies“, „Policy Enforcement Modes“.

Enterprise-Notiz

  • Default Deny pro Namespace kommt per Policy-Engine (Kyverno-generate) oder GitOps mit jedem neuen Namespace; Ausnahmen als PR mit Begründung.
  • Clusterweite Leitplanken (Metadaten-IP, Admin-Netze) als CCNP mit Deny und enableDefaultDeny: false – oder künftig als ClusterNetworkPolicy, Tier Admin.
  • Vor dem Scharfschalten policyAuditMode bzw. Hubble-Flows auswerten, welche Verbindungen tatsächlich gebraucht werden (Policy-Editor, hubble observe -o json).
  • ipBlock trifft in Cilium keine Node- und Pod-IPs (steuerbar per policyCIDRMatchMode); Node-Zugriffe per toEntities regeln.
  • FQDN-Policies hängen am DNS-Proxy: CoreDNS-Pfad, TTLs und gemeinsam genutzte CDN-IPs einplanen.