تخطي إلى المحتوى
Korur

What a Kubernetes NetworkPolicy compiles to

NetworkPolicy semantics as a function, and what Calico and Cilium compile them into: chains, IP sets, LPM tries, conntrack and ClusterNetworkPolicy tiers.

A NetworkPolicy is the one security object in Kubernetes that the control plane does not enforce. The API server validates it, stores it and hands it to whoever watches. If nothing watches, the object does nothing, and the documentation says so plainly: creating a NetworkPolicy resource without a controller that implements it will have no effect.1 The object has no status either. The status field was removed from the v1 type and its protobuf tag is kept only as a tombstone, so nothing in the API tells you whether a policy has been programmed into any node.2

That leaves two questions that most policy reviews skip. What does the spec mean, precisely, as a function from a connection to allow or deny? And what does a particular network plugin turn it into: which chains or maps, which keys, evaluated at which hook, on which packets? This article answers both for Kubernetes v1.37, using Calico v3.33.0 and Cilium v1.20.4 as the two compilers, and then follows the cluster-scoped API that started as AdminNetworkPolicy and is now ClusterNetworkPolicy. The argument is simple. The spec is an unordered union of allow sets. Every dataplane is an ordered, first-match machine. The surprises live in the translation between the two, and they are predictable once you have read the translator.

The semantics as a function

Start with isolation, because it is the concept the API never names as a field. A pod is isolated for ingress if any NetworkPolicy in its namespace selects it and has Ingress in its policyTypes; the same holds independently for egress. Isolation is a side effect of being selected. A pod that no policy selects is non-isolated in both directions and every connection is allowed.1 There is no object you can inspect to learn whether a pod is isolated; you derive it by evaluating every policy's podSelector against the pod's labels.

Once a pod is isolated in a direction, the allowed connections in that direction are the union of what every applicable policy allows. The documentation states it without qualification: policies do not conflict, they are additive, and order of evaluation does not affect the result. For a connection between two pods, the egress side of the source and the ingress side of the destination must both allow it. Reply traffic of an allowed connection is implicitly allowed. Two exceptions sit outside the rule language. A pod cannot block access to itself, and traffic between a pod and the node it runs on is always allowed.1 Kubelet runs on the node and sends liveness and readiness probes from there, so this exception, not any rule a policy author writes, is what keeps probes working under a default-deny policy. The sources disagree on the direction of the node exception. The concept page says traffic "to and from" the node is always allowed, while the comment on the ingress field in types.go, which the API reference renders, names the pod's local node only as an ingress source and the egress field says nothing about it.12

Written as predicates, the v1 semantics fit on one screen. This is our notation, not an API object; every clause maps to a sentence in the concept page or the API reference, and the comments mark where the two differ.

NetworkPolicy v1 semantics as predicates over a new connection ctext
isolated_in(p)  = exists P in ns(p): p matches P.podSelector and "Ingress" in P.policyTypes
isolated_out(p) = exists P in ns(p): p matches P.podSelector and "Egress"  in P.policyTypes

ingress_ok(dst, c) =
      not isolated_in(dst)
   or c.src == dst                      # a pod cannot block itself
   or c.src is the node that runs dst   # concept page and types.go
   or exists P selecting dst with "Ingress",
        exists R in P.ingress:
          peer_ok(R.from, c.src) and port_ok(R.ports, dst, c)

egress_ok(src, c) =
      not isolated_out(src)
   or c.dst == src                      # a pod cannot block itself
   or c.dst is the node that runs src   # concept page only ("to and from")
   or exists P selecting src with "Egress",
        exists R in P.egress:
          peer_ok(R.to, c.dst) and port_ok(R.ports, c.dst, c)

allowed(c)          = egress_ok(c.src, c) and ingress_ok(c.dst, c)
allowed(reply of c) = allowed(c)

peer_ok([], x)    = true          # empty or missing from/to: any peer
port_ok([], _, _) = true          # empty or missing ports: any port

Two details in that sketch decide most real outcomes. First, policyTypes has a default that is easy to misread: if the field is absent, Ingress is always set and Egress is set only when the policy has an egress section. An egress-only policy, or a policy meant to deny all egress, must say Egress explicitly.3 Second, empty lists mean opposite things depending on where they sit. An empty ingress list on an isolating policy allows nothing; an empty from inside a rule allows every source.

Spec shapes and what they evaluate to
Spec fragmentEffect on the selected pods
policyTypes absent, no egress keyIngress isolation only; egress untouched
policyTypes absent, egress presentIngress and egress isolation
policyTypes: [Egress], no egress rulesEgress isolation with nothing allowed out, DNS included
Ingress in policyTypes, ingress empty or absentIngress isolation with nothing allowed in, except from the local node
ingress: [{}]Every source on every port; no other policy can then deny ingress to these pods
Rule with ports but no fromAny source, restricted to the listed ports
Port entry without protocolTCP
spec.podSelector: {}Every pod in the policy's namespace

The union semantics make NetworkPolicy safe to compose across teams and weak as a guardrail. Anyone with write access to a namespace can add an allow, and no policy in that namespace can subtract it. The documentation lists explicit deny, cluster-wide defaults, logging of blocked connections and targeting Services by name among the things the API cannot do.1 Everything later in this article that looks like precedence, tiers or order is either a plugin extension or the separate cluster-scoped API.

Peers, selectors and ports

A peer in from or to has three fields, and the legal combinations carry different meanings. A podSelector alone selects pods in the policy's own namespace. A namespaceSelector alone selects every pod in the matching namespaces; an empty one selects all namespaces. Both in the same element select the matching pods inside the matching namespaces. An ipBlock excludes the other two.2 The YAML below differs by one dash, and the second form is a far wider policy than its author usually intended.

One peer with two selectors (AND) against two peers (OR)yaml
# role=client pods inside namespaces labelled user=alice
ingress:
- from:
  - namespaceSelector:
      matchLabels:
        user: alice
    podSelector:
      matchLabels:
        role: client
---
# every pod in user=alice namespaces, OR role=client pods in this namespace
ingress:
- from:
  - namespaceSelector:
      matchLabels:
        user: alice
  - podSelector:
      matchLabels:
        role: client

The documentation's advice is to run kubectl describe and read back how the server interpreted the policy.1 We go further and reject the second form in review unless the commit message states the OR in words. To select a namespace by name, use the label kubernetes.io/metadata.name, which the control plane sets on every namespace and keeps immutable; there is no name field.1

The ipBlock peer is where the spec stops being precise on purpose. CIDRs are meant for cluster-external addresses, because pod IPs are ephemeral. Ingress and egress paths often rewrite source or destination addresses, and whether that rewrite happens before or after policy evaluation is undefined: depending on the plugin, cloud provider and Service implementation, the source address a policy sees may be the client, a load balancer or a node.1 As the Cilium section shows, an ipBlock that covers pod addresses means different things on different plugins.

Named ports

A port entry may name a container port instead of a number.3 The name never travels on the wire. A TCP segment carries a 16-bit destination port, so every implementation has to resolve the name to a number per destination pod before a packet arrives, and two pods behind the same selector may legitimately map http to different numbers. Felix builds one hash:ip,port IP set per (selector, protocol, port name) triple: IPSetData.UniqueID hashes the selector's identifier, the protocol and the port name together, and the set holds one (IP, port) member per endpoint that matches the selector and declares that name for that protocol. When the rule has no selector in that direction, Felix uses the all selector. Two rules that share a port name but differ in selector therefore get different sets, and each member carries its own pod's number, which handles that per-pod divergence exactly.45 Cilium's datapath key holds dport as a big-endian 16-bit integer, so the agent resolves names before it writes the map.6 The cluster-scoped API makes the limit explicit: a CEL rule rejects named ports in rules whose peers are networks, nodes or domain names, because those have no named ports.7

Port ranges

endPort arrived through KEP-2079, alpha in v1.21, beta in v1.22 and stable in v1.25.8 It must be greater than or equal to port, both must be numeric, and a plugin that does not support the field applies the policy to the single port only.13 That fallback narrows the allow rather than widening it, so a missing feature shows up as a broken application, not as an exposure. The KEP's drawbacks section is candid about why the field took time: OpenFlow could not express a port range for a while, and eBPF-based plugins have to populate their maps differently.8 The Cilium section shows exactly how differently.

Replies, established flows and conntrack

Implicitly allowed replies force every implementation to be stateful. On Linux that means the netfilter connection tracker, or a tracker reimplemented in eBPF maps. Two orderings decide what a filter rule sees. Hook priorities order the callbacks registered on the same hook, and at PRE_ROUTING connection tracking (NF_IP_PRI_CONNTRACK, -200) runs before destination NAT (NF_IP_PRI_NAT_DST, -100).9 The filter table's FORWARD chain sits on a different hook: a forwarded packet traverses prerouting, then the routing decision, then forward, so the filter rules that a plugin hangs off FORWARD run only after both.10 Two consequences follow for any policy engine built on netfilter. By the time a filter rule runs, conntrack has already classified the packet as NEW, ESTABLISHED, RELATED or INVALID, so a rule can short-circuit on state.11 And kube-proxy's DNAT has already rewritten a Service virtual IP to a backend pod, so policy matches the backend pod address and its target port, never the Service port.

The harder question is what happens to a live connection when the policies that admitted it change. The API's answer is that it is implementation-defined whether a change takes effect for an existing connection, and the documentation recommends not modifying policies, pods or namespaces in ways that affect existing connections.1 That is a polite way of saying that revocation is not part of the contract. The two compilers below make opposite choices here, and the choice is visible in a few lines of each codebase.

Policy also lags pod creation. If a pod is created before the plugin has handled a policy that selects it, the pod may start unprotected. Once a policy is handled, new pods it selects must be isolated before any container starts, but allow rules may land after the isolation rules, so a fresh pod can briefly have no connectivity at all. Different nodes converge at different times: a new pod may reach a peer on one node seconds before it reaches a peer on another.1 An application that crashes on its first failed connection at startup is an application that will flap under policy, regardless of plugin.

Calico: tiers, chains, mark bits and IP sets

Calico compiles in two stages. In libcalico-go, K8sNetworkPolicyToCalico rewrites each v1 object into a Calico policy placed in the tier named default at order 1000, and k8sSelectorToCalico adds a term to every pod selector that restricts it to Kubernetes workloads.1213 Namespaces become profiles named kns.<namespace> whose labels carry the namespace's labels under the prefix pcns., plus pcns.projectcalico.org/name holding the namespace name.14 Each such profile allows all ingress and all egress.12 Hold on to that last fact: it is how non-isolated pods end up allowed.

k8sRuleToCalico expands every v1 rule into the cross product of its peers and its protocols, one Calico rule per peer per protocol, with each rule carrying all ports for that protocol. A port entry without a protocol becomes explicit TCP. A rule without any ports gets a nil protocol, which matches every IP protocol.12 The spec leaves ICMP undefined, and here the definition falls out of the converter: a rule with no ports admits ping, while a rule with ports admits only the listed transport.1

In Felix, WorkloadEndpointToIptablesChains emits two chains per pod interface: cali-tw-<iface> for traffic to the workload, which runs ingress policy, and cali-fw-<iface> for traffic from it, which runs egress policy. Each policy becomes a pair of chains with the prefixes cali-pi- and cali-po-, built by PolicyToIptablesChains and named by PolicyChainName, which hashes the policy identifier down when it would exceed the chain-name length limit.1516 The endpoint chain itself is assembled by endpointIptablesChain, and its rule order is the whole story.

Shape of cali-tw-<iface> for a pod selected by one Kubernetes policy, from endpointIptablesChain and appendConntrackRules at v3.33.0 (schematic, names abbreviated)text
cali-tw-<iface>
  ctstate RELATED,ESTABLISHED                -> ACCEPT
  ctstate INVALID                            -> DROP
                                             -> clear accept and pass mark bits
                                             -> clear pass mark      "Start of tier default"
  pass mark clear                            -> jump cali-pi-<policy>
  accept mark set                            -> RETURN               "Return if policy accepted"
  pass mark clear                            -> DROP                 "End of tier default. DROP if no policies passed packet"
                                             -> jump cali-pri-kns.<namespace>
  accept mark set                            -> RETURN               "Return if profile accepted"
                                             -> jump cali-pri-ksa.<namespace>.<serviceaccount>
  accept mark set                            -> RETURN               "Return if profile accepted"
                                             -> DROP                 "DROP if no profiles matched"

Read it top to bottom and the v1 semantics reappear. A pod no policy selects has no tier in its chain, falls straight through to its namespace profile, and is allowed. A pod selected in a direction gets a tier, and the end-of-tier drop turns selection into isolation. Policies inside the tier never deny; an allow rule in a cali-pi- chain sets the accept mark and the endpoint chain returns on that mark. Additive union is implemented as "try each policy chain, return on the first accept, drop if none did", which is a first-match machine producing a union-shaped answer. Every pod carries two profiles, kns.<namespace> and then ksa.<namespace>.<serviceaccount> for its service account, and endpointIptablesChain emits a jump and a return for each.1715 The ksa. profile carries the service account's labels and no rules, so its chain never sets the accept mark and only the kns. profile can accept.12 Profile chain names, like policy chain names, are hashed only when they would exceed the length limit.16 The pass mark is the hook for tiers whose policies hand a decision to the next tier, which matters again in the ClusterNetworkPolicy section.15

The first two rules are the established-flow decision. appendConntrackRules places a RELATED,ESTABLISHED accept ahead of every policy jump, and an INVALID drop after it unless that is disabled.15 Policy therefore runs only on packets conntrack calls NEW. If you delete the allow that admitted a connection, the next packet of that connection is ESTABLISHED and is accepted before any policy chain is consulted. The connection lives until its conntrack entry ends.

Inside a policy chain, Felix fights the shape of iptables. A rule is a conjunction of matches, while a Calico rule can carry lists that must be ORed: several CIDRs, more ports than one multiport match can hold, numeric ports alongside named-port IP sets. ProtoRuleToIptablesRules documents the workaround: it splits the rule into match blocks that write to two scratch mark bits, MarkScratch0 meaning "all blocks so far matched" and MarkScratch1, a single scratch bit that every block reuses. The first positive block writes its result straight into MarkScratch0; each later positive block writes to MarkScratch1, and a closing rule clears MarkScratch0 if MarkScratch1 stayed clear; negated blocks never touch the scratch bit and only clear MarkScratch0. Only the final rule with the remaining criteria tests the accumulated bit.16 SplitPortList cuts port lists into groups of at most 15 slots because multiport accepts up to 15 ports, with a range counting as two.1611

Selectors compile to IP sets rather than to rules. Felix names its main sets with the prefix cali40 or cali60 followed by a truncated hash of the set identifier, capped at 31 characters, and updates them by building a temporary set and swapping it in; the source notes that the kernel only swaps sets of the same type, which is why the set format carries a version token.185 Pod churn therefore changes set membership, not rules, and a rule's cost does not grow with the number of pods its selector matches. The same model renders to nftables when Felix's NFTablesMode resolves to enabled; the default is Auto, decided at startup.19

Cilium: identities and an LPM trie

Cilium does not compile policy to addresses. It compiles labels to numeric security identities and policy to entries keyed by identity. ParseNetworkPolicy in pkg/k8s/network_policy.go rewrites the v1 object into label selectors: the subject and same-namespace peers gain io.kubernetes.pod.namespace=<namespace>, namespace selector keys are moved under io.cilium.k8s.namespace.labels,20 and an empty namespace selector becomes "the namespace label exists". Every resulting entry is an allow, marked default-deny, in the Normal tier. When a direction is isolated but has no rules, the function emits an empty entry for that direction, which is how Kubernetes default deny maps onto Cilium's model.21 Ports without a protocol become TCP, and a missing port becomes port 0, the wildcard.21

At runtime each endpoint has its own policy map, named with the prefix cilium_policy_v3_ and the endpoint ID. Its type is BPF_MAP_TYPE_LPM_TRIE, and its size per endpoint is set by bpf-policy-map-max, 16384 entries by default.2223 Two structs, the key and the value, decide what a NetworkPolicy rule costs on that map.

bpf/lib/policy.h at Cilium v1.20.4c
struct policy_key {
	struct bpf_lpm_trie_key lpm_key;
	__u32		sec_label;
	__u8		egress:1,
			pad:7;
	__u8		protocol; /* can be wildcarded if 'dport' is fully wildcarded */
	__be16		dport; /* can be wildcarded with CIDR-like prefix */
};

struct policy_entry {
	__be16		proxy_port;
	__u8		deny:1,
			reserved:2, /* bits used in Cilium 1.16, keep unused for Cilium 1.17 */
			lpm_prefix_length:5; /* map key protocol and dport prefix length */
	__u8		auth_type:7,
			has_explicit_auth_type:1;
	__u32		precedence;
	__u32		cookie;
};

An LPM trie matches the longest stored prefix of the key's data, read in network byte order; lookups must pass the full prefix length, and the map must be created with BPF_F_NO_PREALLOC.24 The key data here is 64 bits: identity, direction, protocol, port, in that order. Because the identity comes first, the trie cannot wildcard the identity while matching a port, so the program does that with a separate lookup. Because protocol and port come last, a rule on "any port" is a short prefix and a port range is a set of prefixes. The comment above the struct states both constraints: protocol may be wildcarded only if the port is fully wildcarded, and the port may be partially wildcarded only when the protocol is fixed.6

__policy_can_access performs the decision. It looks up the exact remote identity with a full-length key. If that entry has the maximum precedence, which implies a deny, it stops. Otherwise it repeats the lookup with the aggregate identity from aggregate_for_identity, and if both lookups miss, with identity 0. Between two hits it prefers the higher precedence, then the longer prefix, then the specific identity. No hit returns DROP_POLICY, code -133; a hit on a deny entry returns DROP_POLICY_DENY, code -181.625 The monitor prints reason 133 as "Policy denied" and reason 181 as "Policy denied by denylist".26 The cost of a decision is a bounded number of trie walks, independent of how many policies exist; what grows with policy is the map, not the per-packet work.

Identity for the remote side comes from cilium_ipcache_v2, a second LPM trie that maps address prefixes to identities and is consulted through lookup_ip4_remote_endpoint.27 This is the structural reason Cilium treats ipBlock differently from Calico. A CIDR selector applies only when Cilium cannot map the address to an endpoint identity. The Cilium documentation is explicit: CIDR rules do not apply to traffic where both sides are managed by Cilium or use a node IP, and by default CIDR selectors match neither pods nor nodes. The --policy-cidr-match-mode option can be set to pods or nodes to change that, at the cost of extra identities.28 On Calico an ipBlock is an address match and does match pod IPs, until the address is reused by a different pod. Neither behaviour is wrong under the spec, which told you to keep ipBlock for cluster-external addresses.1

Port ranges as prefixes

PortRangeToMaskedPorts in pkg/policy/portrange.go converts an endPort range into masked ports, a port value plus a mask of fixed leading bits, because the trie can only match prefixes.29 The minimal cover depends on alignment, not on the width of the range. The table applies the algorithm to the documentation's example range, the KEP's passive FTP range and an unaligned range; the counts are our own computation of the function's output.

Datapath cost of three endPort ranges
RangeCilium masked ports (value/fixed bits)Cilium entries per remote identityCalico multiport slots
32000 to 3276832000/8, 32256/7, 32768/1632 of 15
49152 to 6553549152/212 of 15
8000 to 80808000/10, 8064/12, 8080/1632 of 15

Multiply the middle column by the number of identities a peer selector matches and you have the map entries one rule costs on one endpoint, in one direction. That product, not the number of policies, is what approaches the 16384-entry default. Two levers keep it small: fewer distinct identities on the peer side, which means selecting on stable labels and not letting high-cardinality labels such as build hashes become identity-relevant, and ranges aligned on powers of two.

Policy on every packet

The established-flow choice sits in bpf/bpf_lxc.c. In ipv4_policy, which enforces ingress for a local endpoint, the conntrack result selects the path.

Excerpt of ipv4_policy, bpf/bpf_lxc.c at Cilium v1.20.4 (proxy, NAT and loopback handling elided)c
switch (ret) {
case CT_REPLY:
case CT_RELATED:
	/* Skip policy enforcement for return traffic. */
	...
	break;
default:
	...
	verdict = policy_can_ingress4(ctx, tuple, l4_off,
				      is_untracked_fragment, src_label, SECLABEL_IPV4,
				      &policy_match_type, &audited, ext_err, proxy_port,
				      &cookie);
	...
	/* Emit verdict if drop or if allow for CT_NEW. */
	if (verdict != CTX_ACT_OK || ret != CT_ESTABLISHED)
		send_policy_verdict_notify(ctx, src_label, tuple->dport, ...);

	if (verdict != CTX_ACT_OK)
		return verdict;
	break;
}

Only replies and related packets skip policy. Every packet in the original direction, NEW or ESTABLISHED, goes through the trie; the ESTABLISHED case is only excluded from verdict notifications, so the monitor is not flooded with allows. The egress path in the same file does the same for CT_NEW and CT_ESTABLISHED through policy_can_egress4, after Service translation has replaced the virtual IP with a backend.30 Remove the allow that admitted a connection and the next packet the client sends is dropped with DROP_POLICY. Cilium therefore revokes on the next original-direction packet, while Calico, which accepts ESTABLISHED packets before any policy chain, does not revoke until the connection's conntrack entry ends; the spec permits both.

Where the compilers disagree

Calico v3.33.0 (iptables or nftables dataplane) against Cilium v1.20.4, for the same v1 objects
BehaviourCalicoCilium
Unit of matchPod IPs in IP sets; ports in multiport matchesIdentity, protocol and masked port in a per-endpoint LPM trie
Packets that see policyConntrack NEW only; RELATED,ESTABLISHED accepted firstEvery original-direction packet; replies and related skip
Allow removed under a live connectionConnection continues while its conntrack entry livesNext original-direction packet dropped, reason 13326
ipBlock covering pod IPsMatches by addressDoes not match pods or nodes unless --policy-cidr-match-mode is set
Rule with no portsAll IP protocols, ICMP includedWildcard protocol and port entry
endPort rangeOne range in a multiport match, two slotsPower-of-two masked ports, one entry each per identity
Named porthash:ip,port IP set per selector, protocol and port nameResolved to a number by the agent before the map write
Precedence beyond v1Ordered tiers with a pass mark; v1 in tier default at order 1000precedence in each map entry; tiers Admin 100, Normal 200, Baseline 25031

The rows that matter in an incident are the second, third and fourth. If your response plan says "push a deny-all policy to isolate the compromised namespace", on a conntrack-first dataplane that plan cuts new connections and leaves the attacker's established session alone. If your egress control to a database subnet is written as an ipBlock and the database later moves into the cluster, the same YAML keeps working on one plugin and silently stops matching on the other. None of this is a bug report against either project. It is the cost of an API that delegates its hardest semantics to the implementation.

A lab that shows the compiled form

The lab builds two identical kind clusters, one per plugin, applies the same objects and reads back what each plugin compiled. It is written for a Fedora 43 host with kernel 7.2.13 and Docker as the kind provider; kind nodes share the host kernel. Tool versions: kind v0.33.0 with its default node image for Kubernetes v1.37.0, pinned by digest as the release notes require,32 kubectl v1.37, Calico v3.33.0 from its release manifest, and cilium-cli v0.20.2, the maintained release, which supports Cilium 1.17 and newer, installing Cilium v1.20.4.33 Object names, flags and paths below are checked against the sources at those tags. The expected results are predictions derived from that source, so confirm them on your build; hashes, interface names and identity numbers will differ.

kind-np.yaml: three nodes, no default CNI, Calico's default pool as pod subnetyaml
kind: Cluster
apiVersion: kind.x-k8s.io/v1alpha4
networking:
  disableDefaultCNI: true
  podSubnet: 192.168.0.0/16
nodes:
- role: control-plane
- role: worker
- role: worker
Create both clusters and install the pluginsshell
IMG=kindest/node:v1.37.0@sha256:a1ed56cfb0e7b93589bdf97c8cd566405a265939e3620fc4f5de89adff580ae5

kind create cluster --name np-calico --config kind-np.yaml --image "$IMG"
kubectl --context kind-np-calico apply -f \
  https://raw.githubusercontent.com/projectcalico/calico/v3.33.0/manifests/calico.yaml
# Pin the iptables renderer so iptables-save shows the policy chains.
kubectl --context kind-np-calico -n kube-system set env daemonset/calico-node FELIX_NFTABLESMODE=Disabled
kubectl --context kind-np-calico -n kube-system rollout status daemonset/calico-node

kind create cluster --name np-cilium --config kind-np.yaml --image "$IMG"
cilium install --context kind-np-cilium --version 1.20.4
cilium status --context kind-np-cilium --wait
demo.yaml: a web server, a raw TCP sink, a client and three policiesyaml
apiVersion: v1
kind: Namespace
metadata:
  name: demo
---
apiVersion: v1
kind: Pod
metadata:
  name: web
  namespace: demo
  labels: {app: web}
spec:
  containers:
  - name: nginx
    image: nginx:1.27
    ports:
    - {name: http, containerPort: 80}
---
apiVersion: v1
kind: Pod
metadata:
  name: sink
  namespace: demo
  labels: {app: sink}
spec:
  containers:
  - name: nc
    image: busybox:1.37
    command: ["nc", "-l", "-p", "9000"]
---
apiVersion: v1
kind: Pod
metadata:
  name: client
  namespace: demo
  labels: {role: client}
spec:
  containers:
  - name: sh
    image: busybox:1.37
    command: ["sleep", "infinity"]
---
apiVersion: networking.k8s.io/v1
kind: NetworkPolicy
metadata:
  name: default-deny-ingress
  namespace: demo
spec:
  podSelector: {}
  policyTypes: [Ingress]
---
apiVersion: networking.k8s.io/v1
kind: NetworkPolicy
metadata:
  name: client-to-web
  namespace: demo
spec:
  podSelector:
    matchLabels: {app: web}
  ingress:
  - from:
    - podSelector:
        matchLabels: {role: client}
    ports:
    - {protocol: TCP, port: http}
---
apiVersion: networking.k8s.io/v1
kind: NetworkPolicy
metadata:
  name: client-to-sink
  namespace: demo
spec:
  podSelector:
    matchLabels: {app: sink}
  ingress:
  - from:
    - podSelector:
        matchLabels: {role: client}
    ports:
    - {protocol: TCP, port: 9000}
Apply and test reachability (repeat with CTX=kind-np-cilium)shell
CTX=kind-np-calico
kubectl --context $CTX apply -f demo.yaml
kubectl --context $CTX -n demo wait --for=condition=Ready --timeout=180s pod/web pod/sink pod/client
WEB=$(kubectl --context $CTX -n demo get pod web -o jsonpath='{.status.podIP}')
kubectl --context $CTX -n demo exec client -- wget -qO- -T 2 "http://$WEB/"   # allowed
kubectl --context $CTX -n demo run probe --rm -i --restart=Never \
  --image=busybox:1.37 -- wget -qO- -T 2 "http://$WEB/"                       # times out

On the Calico cluster, find the node that runs web and read its filter table. Expect a cali-tw- chain for the pod's host-side interface laid out like the schematic in the Calico section, with the profile jumps filled in as cali-pri-kns.demo and cali-pri-ksa.demo.default, because a pod that names no service account is assigned the namespace's default one,34 and with the tier default block holding two cali-pi- jumps, not one. Two policies select web, and because their selectors differ, endpointIptablesChain sees two single-policy groups, which ShouldBeInlined jumps to directly; each jump is followed by the "Return if policy accepted" rule.15 The policy chain for default-deny-ingress has no inbound rules, so PolicyToIptablesChains emits a single rule that carries only a comment and sets no mark.16 Nothing sets the accept mark there, the RETURN does not fire, and a packet that the client-to-web chain does not accept falls through to the end-of-tier DROP. That is how a default deny is compiled: not as a deny rule, but as a policy that marks nothing. The policy chain for client-to-web uses the named port http, so it should match the destination on an IP set with --match-set <name> dst,dst rather than on a literal port,35 and that set should be of type hash:ip,port.18

Read the compiled form on Calicoshell
NODE=$(kubectl --context kind-np-calico -n demo get pod web -o jsonpath='{.spec.nodeName}')
docker exec "$NODE" iptables-save -t filter | grep -E '^:cali-(tw|fw|pi|po)-'
docker exec "$NODE" iptables-save -t filter | grep -E '^-A cali-(tw|pi)-'
# The kind node image has no ipset binary; the calico-node container does.
CNODE=$(kubectl --context kind-np-calico -n kube-system get pod -l k8s-app=calico-node \
  --field-selector spec.nodeName="$NODE" -o name)
kubectl --context kind-np-calico -n kube-system exec "$CNODE" -c calico-node -- ipset list -n | grep '^cali40'
# The named-port set is the one the policy chain matches as dst,dst.
PSET=$(docker exec "$NODE" iptables-save -t filter | grep -E '^-A cali-pi-' \
  | grep -oE 'match-set cali40[^ ]+ dst,dst' | cut -d' ' -f2 | sort -u)
kubectl --context kind-np-calico -n kube-system exec "$CNODE" -c calico-node -- ipset list -t "$PSET"

On the Cilium cluster, the same objects should produce no chains at all. List the endpoints on the node that runs web to get its endpoint ID and identity, then dump the policy maps. Expect the web endpoint's ingress entries to carry the client identity with protocol TCP and port 80, since http resolves to 80 on that pod, and nothing else apart from the entries Cilium adds for its own reserved identities.

Read the compiled form on Ciliumshell
NODE=$(kubectl --context kind-np-cilium -n demo get pod web -o jsonpath='{.spec.nodeName}')
CPOD=$(kubectl --context kind-np-cilium -n kube-system get pod -l k8s-app=cilium \
  --field-selector spec.nodeName="$NODE" -o name)
kubectl --context kind-np-cilium -n kube-system exec "$CPOD" -c cilium-agent -- cilium-dbg endpoint list
kubectl --context kind-np-cilium -n kube-system exec "$CPOD" -c cilium-agent -- cilium-dbg identity list
kubectl --context kind-np-cilium -n kube-system exec "$CPOD" -c cilium-agent -- cilium-dbg bpf policy get --all
kubectl --context kind-np-cilium -n kube-system exec "$CPOD" -c cilium-agent -- cilium-dbg bpf ipcache list

The last experiment is the one worth running before you rely on policy for incident response. Open a raw TCP connection from client to sink, delete the allow, and keep typing. On Calico, the source predicts that lines keep arriving in the sink's log, because the RELATED,ESTABLISHED accept sits ahead of the policy jump. On Cilium, it predicts that the first line after the delete is dropped and that the monitor on the sink's node reports it with the reason "Policy denied".26 Policy for sink is enforced by the agent on the node that runs sink, which need not be the node that runs web, so the block resolves that agent again. Each terminal sets its own context, because shell variables do not carry over.

Revocation under a live connectionshell
# Every terminal: pick the cluster under test
CTX=kind-np-calico   # or kind-np-cilium

# Terminal 1: follow what the sink receives
kubectl --context $CTX -n demo logs -f sink

# Terminal 2: an interactive TCP session; type a line, it appears in terminal 1
SINK=$(kubectl --context $CTX -n demo get pod sink -o jsonpath='{.status.podIP}')
kubectl --context $CTX -n demo exec -it client -- nc "$SINK" 9000

# Terminal 3, Cilium only: watch drops on the node that runs sink
SNODE=$(kubectl --context kind-np-cilium -n demo get pod sink -o jsonpath='{.spec.nodeName}')
SPOD=$(kubectl --context kind-np-cilium -n kube-system get pod -l k8s-app=cilium \
  --field-selector spec.nodeName="$SNODE" -o name)
kubectl --context kind-np-cilium -n kube-system exec "$SPOD" -c cilium-agent -- cilium-dbg monitor --type drop

# Terminal 4: remove the allow, then type another line in terminal 2
kubectl --context $CTX -n demo delete networkpolicy client-to-sink

From AdminNetworkPolicy to ClusterNetworkPolicy

KEP-2091, opened in 2021, proposed what v1 refuses to be: cluster-scoped policy with explicit actions and order. AdminNetworkPolicy had a priority from 0 to 1000, lower numbers first, rules evaluated in written order, and a Pass action that skips lower-precedence admin rules and delegates the decision to namespace NetworkPolicy. BaselineAdminNetworkPolicy set defaults that namespace policy could override, with no priority and no Pass.36 The KEP's metadata still lists alpha in v1.24 as its target, but the API never entered the core: it ships as CRDs from the SIG Network project sigs.k8s.io/network-policy-api.

NPEP-285 then merged the two resources into one, ClusterNetworkPolicy, with a tier field; the proposal argues that a persona-based name such as "Admin" was confusing and that the change had to happen before beta.37 As of November 2026 the current release is v0.2.1 of that project, serving API version v1alpha2 with ClusterNetworkPolicy as its single resource. Release v0.2.0 renamed Allow to Accept, replaced ports with a protocols field that matches TCP, UDP and SCTP explicitly, and reduced the maximum number of rules and peers from 100 to 25.38 Release v0.2.1 changed no API shape and moved named ports back to the experimental channel.39

The evaluation model is a three-tier pipeline: Admin, then namespace NetworkPolicy, then Baseline. Within a tier, a lower priority from 0 to 1000 is checked first, and two policies at the same priority that match the same connection resolve in an unspecified order. Accept and Deny end evaluation; an egress Accept still leaves the destination's ingress rules to apply. Pass skips the remaining rules of the current tier and moves to the next. A v1 NetworkPolicy always makes a final decision for the pods it selects, so Baseline only ever decides for pods that no namespace policy selects. If no tier decides, the default applies and pods may talk.7

An Admin tier rule that keeps DNS open and a Baseline tier default deny for egressyaml
apiVersion: policy.networking.k8s.io/v1alpha2
kind: ClusterNetworkPolicy
metadata:
  name: tenant-dns
spec:
  tier: Admin
  priority: 10
  subject:
    namespaces:
      matchLabels:
        example.com/tenant: "true"
  egress:
  - name: dns-to-kube-dns
    action: Accept
    to:
    - pods:
        namespaceSelector:
          matchLabels:
            kubernetes.io/metadata.name: kube-system
        podSelector:
          matchLabels:
            k8s-app: kube-dns
    protocols:
    - udp:
        destinationPort:
          number: 53
    - tcp:
        destinationPort:
          number: 53
---
apiVersion: policy.networking.k8s.io/v1alpha2
kind: ClusterNetworkPolicy
metadata:
  name: tenant-egress-baseline
spec:
  tier: Baseline
  priority: 10
  subject:
    namespaces:
      matchLabels:
        example.com/tenant: "true"
  egress:
  - name: default-deny
    action: Deny
    to:
    - networks: ["0.0.0.0/0", "::/0"]

Note the networks peer in the baseline. The type documentation warns that cluster-internal traffic is checked against it too, so 0.0.0.0/0 covers pod-to-pod traffic as well as the internet, which is exactly what a default deny wants and exactly what an exception rule does not.7 That is the opposite of Cilium's default for v1 ipBlock, and a reason to read every CIDR in a migration twice. The type also defines failure handling: a peer with no recognised field, which signals a newer CRD than the implementation knows, must fail closed, meaning match nothing for Accept and deny everything for Deny and Pass.7

Both plugins in this article already read v1alpha2. Calico v3.33.0 converts a ClusterNetworkPolicy into its own policy model in the built-in tier kube-admin or kube-baseline, with order equal to the priority, and notes in clusterNetPolicyTypes that those tiers default to pass. That is the pass-mark path in the endpoint chain shown earlier, with v1 policies sitting between the two tiers in default.4013 Cilium v1.20.4 vendors network-policy-api v0.2.0,41 maps the tiers onto its internal tiers Admin and Baseline, which policyentry.go defines as 100 and 250 around the Normal tier at 200 that holds v1 policy,31 and turns spec.priority plus the rule index divided by 100 into a per-rule priority. Support sits behind enable-k8s-cluster-network-policy, which defaults to false.424344

Our position is that ClusterNetworkPolicy is the right model and an alpha API. It removes the worst property of v1 for platform teams, the inability to express a guardrail a namespace owner cannot override, and it does so with semantics precise enough to compile. We would pilot it on a non-production cluster with the plugin's conformance results in hand, and we would not yet cite it as a control in a compliance statement.

How we write NetworkPolicy

Every namespace starts with default deny in both directions, plus an explicit egress allow to the cluster DNS pods on UDP and TCP 53. The documentation's own caution is that a default-deny egress policy also blocks DNS, and the failure mode, slow name resolution timeouts rather than clean refusals, is miserable to debug.1 Rules are written against container ports, by name for ingress where the workload declares them, because Service ports are gone by the time policy runs. We do not use ipBlock for anything that lives in the cluster, and we reject the two-element peer form in review unless the OR is intended and stated.

We test revocation, not just admission. The spec makes live-connection behaviour implementation-defined, so a runbook that isolates a namespace by policy has to say what happens to established sessions on the plugin actually deployed, and on a conntrack-first dataplane it has to add a step that ends those sessions, such as restarting the affected pods. The lab's last experiment takes minutes and settles the question for your cluster.

Our own platform runs on Kubernetes with Argo CD for GitOps, and policies travel with the workloads they protect. Argo CD applies sync waves from the lowest number up, allows negative waves, and waits for a wave to be synced and healthy before it moves on, so NetworkPolicies go in an earlier wave than the Deployments they select.45 That narrows the window in which a pod can start before its policy exists but cannot remove it: a NetworkPolicy has no status, so "healthy" can only mean "stored by the API server", and the documentation is clear that there is no way to tell from the API when a plugin has handled a policy.21 Workloads that must not start without their egress path wait for it in an init container, which is the pattern the documentation itself recommends.

المراجع

  1. Network Policies Kubernetes documentation
  2. staging/src/k8s.io/api/networking/v1/types.go at v1.37.2 Kubernetes project, GitHub
  3. NetworkPolicy v1 API reference Kubernetes documentation
  4. felix/calc/rule_scanner.go at v3.33.0 (IPSetData.UniqueID) projectcalico/calico, GitHub
  5. ipset(8): hash:ip,port and swap netfilter project
  6. bpf/lib/policy.h at v1.20.4 cilium/cilium, GitHub
  7. apis/v1alpha2/clusternetworkpolicy_types.go at v0.2.1 kubernetes-sigs/network-policy-api, GitHub
  8. KEP-2079: Network Policy to support Port Ranges Kubernetes Enhancements, SIG Network
  9. include/uapi/linux/netfilter_ipv4.h at v6.12 (nf_ip_hook_priorities) Linux kernel source, GitHub mirror
  10. Netfilter hooks nftables wiki, netfilter project
  11. iptables-extensions(8): multiport and conntrack matches netfilter project
  12. libcalico-go/lib/backend/k8s/conversion/conversion.go at v3.33.0 projectcalico/calico, GitHub
  13. libcalico-go/lib/names/policy.go at v3.33.0 projectcalico/calico, GitHub
  14. libcalico-go/lib/backend/k8s/conversion/constants.go at v3.33.0 projectcalico/calico, GitHub
  15. felix/rules/endpoints.go at v3.33.0 projectcalico/calico, GitHub
  16. felix/rules/policy.go at v3.33.0 projectcalico/calico, GitHub
  17. libcalico-go/lib/backend/k8s/conversion/workload_endpoint_default.go at v3.33.0 projectcalico/calico, GitHub
  18. felix/ipsets/ipset_defs.go at v3.33.0 projectcalico/calico, GitHub
  19. felix/config/config_params.go at v3.33.0 projectcalico/calico, GitHub
  20. pkg/k8s/apis/cilium.io/const.go at v1.20.4 cilium/cilium, GitHub
  21. pkg/k8s/network_policy.go at v1.20.4 cilium/cilium, GitHub
  22. pkg/maps/policymap/policymap.go at v1.20.4 cilium/cilium, GitHub
  23. pkg/maps/policymap/cell.go at v1.20.4 cilium/cilium, GitHub
  24. BPF_MAP_TYPE_LPM_TRIE Linux kernel documentation
  25. bpf/lib/drop_reasons.h at v1.20.4 cilium/cilium, GitHub
  26. pkg/monitor/api/drop.go at v1.20.4 cilium/cilium, GitHub
  27. bpf/lib/eps.h at v1.20.4 cilium/cilium, GitHub
  28. Layer 3 Examples: CIDR based policy and policy-cidr-match-mode (v1.20.4 source) Cilium documentation, GitHub
  29. pkg/policy/portrange.go at v1.20.4 cilium/cilium, GitHub
  30. bpf/bpf_lxc.c at v1.20.4 cilium/cilium, GitHub
  31. pkg/policy/types/policyentry.go at v1.20.4 cilium/cilium, GitHub
  32. kind v0.33.0 release notes kubernetes-sigs/kind, GitHub
  33. cilium-cli README: Releases cilium/cilium-cli, GitHub
  34. Service Accounts Kubernetes documentation
  35. felix/iptables/match_builder.go at v3.33.0 (DestIPPortSet) projectcalico/calico, GitHub
  36. KEP-2091: Add support for AdminNetworkPolicy resources Kubernetes Enhancements, SIG Network
  37. NPEP-285: Combine ANP and BANP into ClusterNetworkPolicy SIG Network Policy API
  38. network-policy-api release v0.2.0 kubernetes-sigs, GitHub
  39. network-policy-api release v0.2.1 (API version v1alpha2) kubernetes-sigs, GitHub
  40. libcalico-go/lib/backend/k8s/conversion/clusternetworkpolicy.go at v3.33.0 projectcalico/calico, GitHub
  41. go.mod at v1.20.4 cilium/cilium, GitHub
  42. pkg/k8s/cluster_network_policy.go at v1.20.4 cilium/cilium, GitHub
  43. pkg/option/config.go at v1.20.4 cilium/cilium, GitHub
  44. pkg/defaults/defaults.go at v1.20.4 cilium/cilium, GitHub
  45. Sync Phases and Waves Argo CD documentation

هل تسمح لنا بأن نقيس كيف وصلت إلى هنا؟

نستخدم ملفات تعريف الارتباط التحليلية لنعرف أي صفحة تؤدي عملها وأي إعلان قادك إلى هنا. وإذا رفضت، فسيعمل الموقع تمامًا كما هو ولن نضع أي ملفات تعريف ارتباط تحليلية. سياسة ملفات تعريف الارتباط