Skip to content
Hands-on IT IT Drills

Appendix A: Cheat Sheet

Tested with Kubernetes 1.37 (kind 0.33), Cilium 1.20, Kyverno 1.19.1 (chart 3.9.1), Kyverno CLI 1.19.1 and Chainsaw 0.2.15. Names and labels match the demo app.

Tools in the lab

alias cc=~/guard-lab/code/demo/conncheck.sh
# A connection from inside a Pod (source: Pod name or value of app=)
cc shop/frontend http://api.shop
cc shop/api tcp://db.shop:5432
# With an expectation: exit 0 = as expected, 1 = deviation
cc default/client http://api.shop deny
# Longer timeout under load or for targets on the internet
TIMEOUT=5 cc default/client https://example.com
# Target matrix vs. actual (file: "<ns>/<pod|app> <url> allow|deny")
~/guard-lab/code/np-tests/np-matrix.sh matrix.tsv
# As a Markdown table for the CI summary
~/guard-lab/code/np-tests/np-matrix.sh --md matrix.tsv >> "$GITHUB_STEP_SUMMARY"
# A different conncheck.sh (e.g. in the CI checkout)
CC=$PWD/code/demo/conncheck.sh code/np-tests/np-matrix.sh code/np-tests/matrix.tsv
Output / exit conncheck.sh np-matrix.sh
0 allowed or as expected all lines as expected
1 blocked or deviation at least one ✘
2 usage error, source missing file missing (line with exit 2 = error)
HTTP 403/502 counts as allowed connection was established, check L7 separately
Message Meaning First suspect
Timeout packet dropped or DNS starved policy, egress DNS
DNS-Fehler name does not exist (an answer came back) typo, namespace
abgelehnt port closed, no process port, Service, Pod
keine Verbindung TCP test failed like timeout

NetworkPolicy patterns

# Default deny for everything (ingress and egress) in the namespace
spec: {podSelector: {}, policyTypes: [Ingress, Egress]}
# Allow DNS (always together with 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}]
# Everything within the own namespace (ingress and egress)
ingress: [{from: [{podSelector: {}}]}]
egress: [{to: [{podSelector: {}}]}]
# Monitoring: exactly one Pod from exactly one namespace, only port metrics
ingress:
- from:
  - namespaceSelector:
      matchLabels: {kubernetes.io/metadata.name: monitoring}
    podSelector:
      matchLabels: {app: scraper}
  ports: [{port: metrics}]
# Internet without cluster networks
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}]
# Port range (numeric only, not with a named port)
ports: [{protocol: TCP, port: 9000, endPort: 9200}]

Selector semantics

Notation under from/to Meaning Rule of thumb
- namespaceSelector + podSelector (one dash) Pods with X in namespaces with Y AND
- namespaceSelector / - podSelector (two dashes) namespaces with Y or Pods with X in the own NS OR
- podSelector: {} all Pods in the own namespace own NS only
- namespaceSelector: {} all Pods in all namespaces entire cluster
ingress: [{}] everything from everywhere free pass
policyTypes: [Egress] without egress nothing may leave deny egress
Rule Consequence
Policies are additive union of all permissions, no deny field
Pod selected once isolated for this direction (even by an “exception”)
Port and source stay coupled per rule
Port in the policy container port after DNAT (8080, not Service port 80)
Connection between two isolated Pods egress at the sender and ingress at the receiver
Return packets need no rule (stateful)
ipBlock for Pod IPs unspecified; use selectors for cluster targets
kubernetes.io/metadata.name set by the API server, cannot be forged

Cilium: CNP and CCNP

Field Purpose Example
endpointSelector protected Pods (like podSelector) matchLabels: {app: api}
fromEndpoints / toEndpoints Pods as the other side k8s:io.kubernetes.pod.namespace: monitoring
fromEntities / toEntities logical targets world, cluster, host, kube-apiserver
toFQDNs egress by domain matchName: example.com, matchPattern: "*.github.com"
toCIDR / toCIDRSet IP networks 169.254.169.254/32
toPorts[].ports[] port as a string {port: "8080", protocol: TCP}
toPorts[].rules.http L7 rules (Envoy) {method: GET, path: "/api/.*"}
toPorts[].rules.dns DNS proxy, mandatory for toFQDNs matchPattern: "*"
ingressDeny / egressDeny explicit denial, beats every allow tenant separation
enableDefaultDeny false = policy closes nothing else guardrails in CCNP
specs several rules in one object CCNP tenant-deny
prefix k8s:io.cilium.k8s.namespace.labels. select namespace labels …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 Effect Filter Effect
--verdict DROPPED dropped only --type policy-verdict policy decisions only
--from-pod ns/pod source --to-pod ns/pod target
--namespace ns source or target --to-namespace ns target only
--to-port 8080 target port (after DNAT) --to-ip 1.2.3.4 target IP
--protocol http L7 HTTP flows --http-status 403 HTTP status
--to-fqdn name target domain --label app=api endpoint label
-f / --last N live / last N -o json export
Hubble output Meaning
policy-verdict:none INGRESS DENIED no rule matches, default deny
policy-verdict:L3-L4 … ALLOWED an L3/L4 rule allowed it
Policy denied by denylist DROPPED deny rule (ingressDeny/egressDeny)
http-request DROPPED an L7 rule denied it (client sees 403)

ClusterNetworkPolicy (v1alpha2)

 Admin tier (priority 0..1000, lowest first) ── Accept / Deny ──► done
      │ Pass or no match
 namespace NetworkPolicies ── Pod covered ──► Allow / default deny
      │ Pod not covered by any NetworkPolicy
 Baseline tier ── Accept / Deny ──► done   (otherwise: allowed)
Field Values Note
spec.tier Admin, Baseline replaces ANP and BANP (v1alpha1)
spec.priority 0–1000 equal priority with overlap: undefined
spec.subject namespaces or pods (with namespaceSelector) whom the rule protects
ingress[].from / egress[].to namespaces, pods, networks (egress only) other side
action Accept, Deny, Pass Pass hands off to NetworkPolicies
protocols tcp: {destinationPort: {number: 9113}} replaces ports from v1alpha1
Implementation Status 2026
kube-network-policies ClusterNetworkPolicy v1alpha2
Calico from 3.32, plus its own GlobalNetworkPolicy with tiers
OVN-Kubernetes, Antrea ANP/BANP v1alpha1
Cilium none, CiliumClusterwideNetworkPolicy instead

Kyverno: policy types (policies.kyverno.io/v1)

Type Short name Purpose Important fields
ValidatingPolicy vpol check, Audit/Warn/Deny validations, validationActions
MutatingPolicy mpol set defaults mutations (ApplyConfiguration, JSONPatch)
GeneratingPolicy gpol create objects generate, evaluation.synchronize
ImageValidatingPolicy ivpol signatures, attestations matchImageReferences, attestors
DeletingPolicy dpol scheduled deletion schedule, conditions
PolicyException – time-limited exception policyRefs, matchConditions, expiresAt
ClusterPolicy (kyverno.io/v1) cpol the old JMESPath world deprecated in 1.19

Namespaced variants: nvpol, nmpol, ngpol, nivpol, ndpol.

Field Effect
matchConstraints.resourceRules group, version, resource, operation
matchConstraints.namespaceSelector namespace labels (for namespaces: their own labels)
matchConstraints.objectSelector labels of the object itself
matchConditions CEL pre-filter, separate “finegrained” webhook
variables intermediate values, access via variables.<name>
validations[].message / messageExpression fixed or computed message
validationActions [Audit], [Warn], [Deny], [Audit, Warn]
failurePolicy Fail (default) or Ignore when Kyverno is down
webhookConfiguration.timeoutSeconds 1–30, after that failurePolicy applies
evaluation.background.enabled background scan on/off
evaluation.generateExisting.enabled GeneratingPolicy for existing objects too
autogen.podControllers.controllers control autogen for Deployments & co.
autogen.validatingAdmissionPolicy.enabled additionally generate a native VAP

CEL snippets

# Optional fields without errors
object.spec.?hostNetwork.orValue(false)
object.metadata.?labels[?'app'].orValue('')        # keys with - or /
# All containers incl. init and ephemeral
object.spec.containers + object.spec.?initContainers.orValue([])
  + object.spec.?ephemeralContainers.orValue([])
# Collect violations, message with names
object.spec.containers.filter(c, !has(c.resources)).map(c, c.name).join(', ')
# Compare quantities (never as strings)
quantity(c.resources.limits['memory']).isGreaterThan(quantity('512Mi'))
# Image library (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
# Time (Kyverno: time.now(), not now())
timestamp(object.spec.expiresAt) < time.now() + duration('2160h')
# Live data from the cluster (type any: dyn() before exists/all)
resource.Get("v1", "configmaps", "kyverno", "allowed-registries").data
dyn(resource.List('networking.k8s.io/v1', 'networkpolicies', ns).items)
# Mutation via ApplyConfiguration
Object{metadata: Object.metadata{labels: {"guard-lab/defaults": "applied"}}}
# Generate
generator.Apply(object.metadata.name, [variables.source])

Kyverno CLI

# Apply a policy to manifests (namespace labels via -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
# With an exception, as a PolicyReport
kyverno apply policy.yaml -r pods.yaml --exceptions exception.yaml
kyverno apply policy.yaml -r pods.yaml -p --output-format json
# Context for resource.List/Get offline
kyverno apply policy.yaml -r ns.yaml --context-file context.yaml
# Unit tests: every kyverno-test.yaml, recursively
kyverno test .
kyverno test tests/image-hygiene --remove-color --detailed-results
kyverno test . -o junit       # mixes logs into stdout, see ci/kyverno-junit.sh
# Migrate stored versions
kyverno migrate --help
Result in kyverno test Meaning
Pass / Ok expectation met, object really checked
Pass / Excluded object does not match the selection, always counts as passed
Fail / Want fail, got pass expectation missed
RULE empty CEL policy, hence isValidatingPolicy: true instead of 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            # keep the namespace for debugging
spec:
  namespaceTemplate:
    metadata: {labels: {guard-lab: demo}}   # so that namespaceSelector matches
  steps:
  - try:
    - apply: {file: pod-latest.yaml, expect: [{check: {($error != null): true}}]}
    - error: {file: pod-latest.yaml}        # object must not exist
    - assert: {file: pod-good.yaml}         # object must exist like this

Troubleshooting

# NetworkPolicies: what applies to this 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: is it running, what is it blocking?
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
# Find generated objects
kubectl get netpol -A -l app.kubernetes.io/managed-by=kyverno \
  -L generate.kyverno.io/policy-name
# Emergency exit for a dead Kyverno (then restart it; the webhooks come back)
kubectl delete validatingwebhookconfiguration,mutatingwebhookconfiguration \
  -l webhook.kyverno.io/managed-by=kyverno