Anhang A: Spickzettel
Getestet mit Kubernetes 1.37 (kind 0.33), Cilium 1.20, Kyverno 1.19.1
(Chart 3.9.1), Kyverno-CLI 1.19.1 und Chainsaw 0.2.15. Namen und Labels
entsprechen der Demo-App.
Werkzeuge im Lab
alias cc=~/guard-lab/code/demo/conncheck.sh
# Eine Verbindung aus einem Pod heraus (Quelle: Pod-Name oder Wert von app=)
cc shop/frontend http://api.shop
cc shop/api tcp://db.shop:5432
# Mit Erwartung: Exit 0 = wie erwartet, 1 = Abweichung
cc default/client http://api.shop deny
# Längerer Timeout unter Last oder für Ziele im Internet
TIMEOUT=5 cc default/client https://example.com
# Soll-Matrix gegen Ist (Datei: "<ns>/<pod|app> <url> allow|deny")
~/guard-lab/code/np-tests/np-matrix.sh matrix.tsv
# Als Markdown-Tabelle für die CI-Zusammenfassung
~/guard-lab/code/np-tests/np-matrix.sh --md matrix.tsv >> "$GITHUB_STEP_SUMMARY"
# Anderes conncheck.sh (z. B. im CI-Checkout)
CC=$PWD/code/demo/conncheck.sh code/np-tests/np-matrix.sh code/np-tests/matrix.tsv
| Ausgabe / Exit |
conncheck.sh |
np-matrix.sh |
| 0 |
erlaubt bzw. wie erwartet |
alle Zeilen wie erwartet |
| 1 |
blockiert bzw. Abweichung |
mindestens ein ✘ |
| 2 |
Aufruffehler, Quelle fehlt |
Datei fehlt (Zeile mit Exit 2 = error) |
| HTTP 403/502 |
zählt als erlaubt |
Verbindung stand, L7 extra prüfen |
| Meldung |
Bedeutung |
Erster Verdacht |
Timeout |
Paket verworfen oder DNS verhungert |
Policy, Egress-DNS |
DNS-Fehler |
Name gibt es nicht (Antwort kam) |
Tippfehler, Namespace |
abgelehnt |
Port zu, kein Prozess |
Port, Service, Pod |
keine Verbindung |
TCP-Test gescheitert |
wie Timeout |
NetworkPolicy-Muster
# Default Deny für alles (Ingress und Egress) im Namespace
spec: {podSelector: {}, policyTypes: [Ingress, Egress]}
# DNS erlauben (immer zusammen mit Egress-Deny)
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}]
# Alles im eigenen Namespace (Ingress und Egress)
ingress: [{from: [{podSelector: {}}]}]
egress: [{to: [{podSelector: {}}]}]
# Monitoring: genau ein Pod aus genau einem Namespace, nur Port metrics
ingress:
- from:
- namespaceSelector:
matchLabels: {kubernetes.io/metadata.name: monitoring}
podSelector:
matchLabels: {app: scraper}
ports: [{port: metrics}]
# Internet ohne Cluster-Netze
egress:
- to: [{ipBlock: {cidr: 0.0.0.0/0, except: [10.0.0.0/8, 172.16.0.0/12,
192.168.0.0/16]}}]
ports: [{port: 443}]
# Portbereich (nur numerisch, nicht mit Named Port)
ports: [{protocol: TCP, port: 9000, endPort: 9200}]
Selektor-Semantik
Schreibweise unter from/to |
Bedeutung |
Merksatz |
- namespaceSelector + podSelector (ein
Strich) |
Pods mit X in Namespaces mit Y |
UND |
- namespaceSelector / - podSelector (zwei
Striche) |
Namespaces mit Y oder Pods mit X im eigenen NS |
ODER |
- podSelector: {} |
alle Pods im eigenen Namespace |
nur eigener NS |
- namespaceSelector: {} |
alle Pods in allen Namespaces |
ganzer Cluster |
ingress: [{}] |
alles von überall |
Freifahrtschein |
policyTypes: [Egress] ohne egress |
nichts darf raus |
Deny Egress |
| Regel |
Folge |
| Policies sind additiv |
Vereinigung aller Erlaubnisse, kein Deny-Feld |
| Pod einmal ausgewählt |
für diese Richtung isoliert (auch durch eine „Ausnahme”) |
| Port und Quelle |
bleiben pro Regel gekoppelt |
| Port in der Policy |
Container-Port nach DNAT (8080, nicht Service-Port 80) |
| Verbindung zwischen zwei isolierten Pods |
Egress beim Sender und Ingress beim Empfänger |
| Rückpakete |
brauchen keine Regel (zustandsbehaftet) |
ipBlock für Pod-IPs |
nicht spezifiziert, für Cluster-Ziele Selektoren nehmen |
kubernetes.io/metadata.name |
setzt der API-Server, nicht fälschbar |
Cilium: CNP und CCNP
| Feld |
Zweck |
Beispiel |
endpointSelector |
geschützte Pods (wie podSelector) |
matchLabels: {app: api} |
fromEndpoints / toEndpoints |
Pods als Gegenseite |
k8s:io.kubernetes.pod.namespace: monitoring |
fromEntities / toEntities |
logische Ziele |
world, cluster, host,
kube-apiserver |
toFQDNs |
Egress nach Domain |
matchName: example.com,
matchPattern: "*.github.com" |
toCIDR / toCIDRSet |
IP-Netze |
169.254.169.254/32 |
toPorts[].ports[] |
Port als String |
{port: "8080", protocol: TCP} |
toPorts[].rules.http |
L7-Regeln (Envoy) |
{method: GET, path: "/api/.*"} |
toPorts[].rules.dns |
DNS-Proxy, Pflicht für toFQDNs |
matchPattern: "*" |
ingressDeny / egressDeny |
explizites Verbot, schlägt jedes Allow |
Mandanten-Trennung |
enableDefaultDeny |
false = Policy schließt nichts anderes |
Leitplanken in CCNP |
specs |
mehrere Regeln in einem Objekt |
CCNP tenant-deny |
Präfix k8s:io.cilium.k8s.namespace.labels. |
Namespace-Labels selektieren |
…labels.tenant |
hubble observe
hubble observe -P --verdict DROPPED --namespace shop --last 20
hubble observe -P --type policy-verdict --to-namespace shop --print-policy-names
hubble observe -P --from-pod default/client --to-port 443 -f
hubble observe -P --protocol http --to-namespace shop --http-status 403
hubble observe -P --to-fqdn "*.github.com" --last 10
hubble observe -P --namespace shop --last 200 -o json > flows.json
| Filter |
Wirkung |
Filter |
Wirkung |
--verdict DROPPED |
nur Verworfenes |
--type policy-verdict |
nur Policy-Entscheidungen |
--from-pod ns/pod |
Quelle |
--to-pod ns/pod |
Ziel |
--namespace ns |
Quelle oder Ziel |
--to-namespace ns |
nur Ziel |
--to-port 8080 |
Ziel-Port (nach DNAT) |
--to-ip 1.2.3.4 |
Ziel-IP |
--protocol http |
L7-HTTP-Flows |
--http-status 403 |
HTTP-Status |
--to-fqdn name |
Ziel-Domain |
--label app=api |
Endpoint-Label |
-f / --last N |
live / letzte N |
-o json |
Export |
| Hubble-Ausgabe |
Bedeutung |
policy-verdict:none INGRESS DENIED |
keine Regel passt, Default Deny |
policy-verdict:L3-L4 … ALLOWED |
L3/L4-Regel hat erlaubt |
Policy denied by denylist DROPPED |
Deny-Regel (ingressDeny/egressDeny) |
http-request DROPPED |
L7-Regel hat verboten (Client sieht 403) |
ClusterNetworkPolicy (v1alpha2)
Admin-Tier (priority 0..1000, klein zuerst) ── Accept / Deny ──► fertig
│ Pass oder kein Treffer
NetworkPolicies des Namespace ── Pod erfasst ──► Allow / Default Deny
│ Pod von keiner NetworkPolicy erfasst
Baseline-Tier ── Accept / Deny ──► fertig (sonst: erlaubt)
| Feld |
Werte |
Hinweis |
spec.tier |
Admin, Baseline |
ersetzt ANP und BANP (v1alpha1) |
spec.priority |
0–1000 |
gleiche Priorität bei Überlappung: undefiniert |
spec.subject |
namespaces oder pods (mit
namespaceSelector) |
wen die Regel schützt |
ingress[].from / egress[].to |
namespaces, pods, networks
(nur Egress) |
Gegenseite |
action |
Accept, Deny, Pass |
Pass gibt an NetworkPolicies ab |
protocols |
tcp: {destinationPort: {number: 9113}} |
ersetzt ports aus v1alpha1 |
| Implementierung |
Stand 2026 |
| kube-network-policies |
ClusterNetworkPolicy v1alpha2 |
| Calico |
ab 3.32, dazu eigene GlobalNetworkPolicy mit Tiers |
| OVN-Kubernetes, Antrea |
ANP/BANP v1alpha1 |
| Cilium |
keine, stattdessen CiliumClusterwideNetworkPolicy |
Kyverno: Policy-Typen (policies.kyverno.io/v1)
| Typ |
Kurzname |
Zweck |
Wichtige Felder |
ValidatingPolicy |
vpol |
prüfen, Audit/Warn/Deny |
validations, validationActions |
MutatingPolicy |
mpol |
Defaults setzen |
mutations (ApplyConfiguration,
JSONPatch) |
GeneratingPolicy |
gpol |
Objekte erzeugen |
generate, evaluation.synchronize |
ImageValidatingPolicy |
ivpol |
Signaturen, Attestations |
matchImageReferences, attestors |
DeletingPolicy |
dpol |
zeitgesteuert löschen |
schedule, conditions |
PolicyException |
– |
befristete Ausnahme |
policyRefs, matchConditions,
expiresAt |
ClusterPolicy (kyverno.io/v1) |
cpol |
alte JMESPath-Welt |
deprecated in 1.19 |
Namespaced Varianten: nvpol, nmpol,
ngpol, nivpol, ndpol.
| Feld |
Wirkung |
matchConstraints.resourceRules |
Gruppe, Version, Ressource, Operation |
matchConstraints.namespaceSelector |
Namespace-Labels (bei Namespaces: eigene Labels) |
matchConstraints.objectSelector |
Labels des Objekts selbst |
matchConditions |
CEL-Vorfilter, eigener „finegrained”-Webhook |
variables |
Zwischenwerte, Zugriff per variables.<name> |
validations[].message /
messageExpression |
feste bzw. berechnete Meldung |
validationActions |
[Audit], [Warn], [Deny],
[Audit, Warn] |
failurePolicy |
Fail (Default) oder Ignore bei
Kyverno-Ausfall |
webhookConfiguration.timeoutSeconds |
1–30, danach greift failurePolicy |
evaluation.background.enabled |
Hintergrund-Scan an/aus |
evaluation.generateExisting.enabled |
GeneratingPolicy auch für Bestand |
autogen.podControllers.controllers |
Autogen für Deployments & Co. steuern |
autogen.validatingAdmissionPolicy.enabled |
zusätzlich native VAP erzeugen |
CEL-Schnipsel
# Optionale Felder ohne Fehler
object.spec.?hostNetwork.orValue(false)
object.metadata.?labels[?'app'].orValue('') # Schlüssel mit - oder /
# Alle Container inkl. Init und Ephemeral
object.spec.containers + object.spec.?initContainers.orValue([])
+ object.spec.?ephemeralContainers.orValue([])
# Verstöße sammeln, Meldung mit Namen
object.spec.containers.filter(c, !has(c.resources)).map(c, c.name).join(', ')
# Mengen vergleichen (nie als String)
quantity(c.resources.limits['memory']).isGreaterThan(quantity('512Mi'))
# Image-Bibliothek (Kyverno)
image(i).registry() in ['index.docker.io', 'kind-registry:5000']
!image(i).containsDigest() && image(i).tag() == 'latest'
# CIDR (Kubernetes-CEL)
cidr(p.ipBlock.cidr).prefixLength() >= 16
# Zeit (Kyverno: time.now(), nicht now())
timestamp(object.spec.expiresAt) < time.now() + duration('2160h')
# Live-Daten aus dem Cluster (Typ any: dyn() vor exists/all)
resource.Get("v1", "configmaps", "kyverno", "allowed-registries").data
dyn(resource.List('networking.k8s.io/v1', 'networkpolicies', ns).items)
# Mutation per ApplyConfiguration
Object{metadata: Object.metadata{labels: {"guard-lab/defaults": "applied"}}}
# Generieren
generator.Apply(object.metadata.name, [variables.source])
Kyverno-CLI
# Policy auf Manifeste anwenden (Namespace-Labels per -f/--values-file)
kyverno apply policy.yaml -r pods.yaml -f values.yaml --remove-color
kyverno apply policy.yaml -r ~/guard-lab/code/demo/ -f values.yaml -t
# Mit Ausnahme, als PolicyReport
kyverno apply policy.yaml -r pods.yaml --exceptions exception.yaml
kyverno apply policy.yaml -r pods.yaml -p --output-format json
# Kontext für resource.List/Get offline
kyverno apply policy.yaml -r ns.yaml --context-file context.yaml
# Unit-Tests: rekursiv jede kyverno-test.yaml
kyverno test .
kyverno test tests/image-hygiene --remove-color --detailed-results
kyverno test . -o junit # mischt Logs in stdout, siehe ci/kyverno-junit.sh
# Gespeicherte Versionen migrieren
kyverno migrate --help
Ergebnis in kyverno test |
Bedeutung |
Pass / Ok |
Erwartung erfüllt, Objekt wirklich geprüft |
Pass / Excluded |
Objekt passt nicht zur Auswahl, zählt immer als
bestanden |
Fail / Want fail, got pass |
Erwartung verfehlt |
RULE leer |
CEL-Policy, deshalb isValidatingPolicy: true statt
rule: |
Chainsaw
chainsaw lint test -f e2e/image-hygiene/chainsaw-test.yaml
chainsaw test e2e/ --report-format JUNIT-TEST --report-name chainsaw
chainsaw test e2e/ --skip-delete # Namespace zum Debuggen behalten
spec:
namespaceTemplate:
metadata: {labels: {guard-lab: demo}} # damit namespaceSelector greift
steps:
- try:
- apply: {file: pod-latest.yaml, expect: [{check: {($error != null): true}}]}
- error: {file: pod-latest.yaml} # Objekt darf nicht existieren
- assert: {file: pod-good.yaml} # Objekt muss so existieren
Troubleshooting
# NetworkPolicies: was gilt für diesen Pod?
kubectl -n shop get netpol
kubectl -n shop describe netpol api-from-frontend | sed -n '/Spec/,$p'
kubectl get ns --show-labels
kubectl -n shop exec deploy/frontend -- nslookup api.shop.svc.cluster.local
# Cilium
cilium status
kubectl -n kube-system exec ds/cilium -c cilium-agent -- cilium-dbg status
kubectl -n kube-system exec ds/cilium -c cilium-agent -- cilium-dbg fqdn cache list
kubectl -n kube-system exec ds/cilium -c cilium-agent -- cilium-dbg identity get 4012
kubectl get cnp,ccnp -A
# Kyverno: läuft es, was blockiert es?
kubectl -n kyverno get deploy,pdb
kubectl -n kyverno get endpointslice -l kubernetes.io/service-name=kyverno-svc
kubectl get validatingwebhookconfigurations -l webhook.kyverno.io/managed-by=kyverno
kubectl get vpol,mpol,gpol,ivpol,dpol
kubectl -n kyverno logs deploy/kyverno-admission-controller --since=10m | grep ERR
kubectl get polr -A; kubectl get clusterpolicyreports
kubectl get events -A --field-selector reason=PolicyViolation
kubectl run t -n shop -l app=t --image=nginxinc/nginx-unprivileged:latest \
--dry-run=server -o name
# Generierte Objekte finden
kubectl get netpol -A -l app.kubernetes.io/managed-by=kyverno \
-L generate.kyverno.io/policy-name
# Notausgang bei totem Kyverno (danach neu starten, Webhooks kommen zurück)
kubectl delete validatingwebhookconfiguration,mutatingwebhookconfiguration \
-l webhook.kyverno.io/managed-by=kyverno