11 min readSecurity fundamentals

Kubernetes NetworkPolicy: Locking Down East-West Pod Traffic

By default, every Kubernetes pod can reach any other pod. Learn how CNI plugins enforce NetworkPolicies, avoid YAML AND/OR traps, and block lateral movement.

Technical illustration: Pods Can Talk to Everything by Default: Locking East-West Traffic with NetworkPolicies

A single vulnerable image-resizing library in a marketing landing page should never expose a payment database. Yet during incident response in multi-tenant Kubernetes clusters, that exact lateral path appears over and over again. An attacker exploits remote code execution inside a low-privilege web container in marketing-prod, drops a lightweight scanner, and discovers that TCP connections to a Redis cache in payments-prod succeed on the very first attempt. No gateway blocked the probe, no firewall logged an alert, and crossing into a separate Kubernetes namespace offered zero network resistance.

This behavior surprises many engineers who assume namespaces act like virtual private clouds or VLANs. In reality, Kubernetes creates namespaces to organize API objects, quotas, and Role-Based Access Control (RBAC) boundaries, not to segment packets on the wire. Unless you explicitly declare and enforce isolation rules, every workload inside a cluster sits on a single flat network.

Why Does Kubernetes Allow All Pod-to-Pod Traffic by Default?

Kubernetes mandates a flat networking model so every pod receives a unique, cluster-routable IP address and can communicate directly with any other pod without Network Address Translation (NAT). Out of the box, namespaces do not restrict Layer 3 IP routing or Layer 4 TCP/UDP connections, meaning all internal east-west traffic flows freely.

To picture why this happens, think of a modern open-plan office building that has badge readers at the front lobby but zero locks on any interior room. Security teams often invest heavily in north-south controls at the building entrance, such as Web Application Firewalls (WAFs), TLS termination, and Kubernetes Ingress controllers. Once an intruder slips past that outer perimeter through a compromised application container, every internal hallway leads straight to databases, caches, and internal admin APIs. That lateral pod-to-pod movement is what infrastructure engineers call east-west traffic.

Kubernetes intentionally chose this design to remove the port-mapping headaches of early container orchestrators. The Kubernetes network model rests on three strict invariants:

  1. Every pod can communicate with pods on any other node without NAT.
  2. System agents on a node (such as the kubelet) can communicate with every pod running on that node.
  3. The IP address a pod sees for itself inside its network namespace is identical to the IP address other pods use to reach it.

Because flat reachability is baked into the platform contract, Kubernetes ships without default firewall rules between workloads. A NetworkPolicy resource (networking.k8s.io/v1) is the native API mechanism designed to carve virtual doors and badge checks back into that open floor plan.

How Do CNI Plugins and Linux Packet Filtering Enforce NetworkPolicies?

The Kubernetes API server only stores and validates NetworkPolicy YAML manifests in etcd; it never inspects or drops a single network packet. Actual packet filtering happens locally on every worker node inside the Container Network Interface (CNI) plugin, which programs kernel primitives such as iptables, nftables, or eBPF maps.

Understanding where enforcement sits on the host clarifies several common surprises during debugging. Each pod runs inside an isolated Linux network namespace connected to the host node's root network namespace through a virtual Ethernet (veth) pair. When Pod A sends traffic to a Kubernetes Service IP (ClusterIP), kube-proxy (or an eBPF service proxy) intercepts the outbound packet using kernel connection tracking (conntrack) and performs Destination NAT (DNAT), rewriting the virtual Service IP to the real IP address of a healthy backend pod, Pod B.

Because DNAT resolves Service ClusterIPs into concrete Pod IPs, NetworkPolicy evaluation operates on Pod identities and resolved Pod IPs rather than abstract Service names. That is why a NetworkPolicy attaches via podSelector labels on the pods themselves, never by referencing a Service object.

flowchart LR PodA["Pod A (app: frontend)"] --> VethA["veth pair (Node 1)"] VethA --> KubeProxy["kube-proxy / eBPF DNAT (ClusterIP to Pod IP)"] KubeProxy --> Network["Node Network / Overlay"] Network --> CNICheck{"CNI Policy Engine (eBPF / iptables)"} CNICheck -->|"Rule matches Pod A label"| PodB["Pod B (app: backend, :8080)"] CNICheck -->|"No matching allow rule"| Drop["Silent Packet Drop"]

One operational trap catches teams constantly: the Kubernetes API server accepts NetworkPolicy objects even when the cluster's CNI plugin does not support them. Plugins focused solely on basic overlay routing, such as default Flannel or simple kubenet setups, ignore networking.k8s.io/v1 resources completely. Running kubectl apply returns a clean confirmation while 100% of east-west traffic continues flowing unblocked. Before relying on any policy, you must confirm your CNI (such as Calico, Cilium, Antrea, or a cloud provider's policy-capable CNI) actively reconciles NetworkPolicy rules.

How Does NetworkPolicy Isolation State Work?

Every pod starts in a non-isolated state where all incoming (ingress) and outgoing (egress) connections are permitted. The moment at least one NetworkPolicy selects that pod for a given traffic direction, the pod switches to an isolated state in that direction, shifting from allow-all to an implicit deny-all baseline modified only by explicit allow rules.

Two structural rules govern how Kubernetes combines policies, and both trip up teams migrating from traditional firewalls:

First, isolation is directional and controlled by policyTypes. If you apply a policy that lists only Ingress under policyTypes and defines rules for port 8080, the target pod becomes isolated for ingress, dropping all other inbound ports. However, its egress remains completely non-isolated, meaning a compromised container can still initiate outbound connections to internal databases or external command-and-control servers.

Second, NetworkPolicy rules are purely additive. Standard Kubernetes NetworkPolicy has no Deny action and no rule priority ordering. When multiple policies select the same pod, the CNI evaluates the logical union (OR) of all matching allow rules across every policy.

flowchart TD Packet["Packet arrives at or leaves Pod"] --> CheckSelect{"Does any NetworkPolicy select this Pod for this direction?"} CheckSelect -->|"No (Non-isolated)"| AllowAll["Allow traffic by default"] CheckSelect -->|"Yes (Isolated)"| CheckUnion{"Does packet match the union of allow rules?"} CheckUnion -->|"Yes"| AllowMatch["Allow traffic"] CheckUnion -->|"No"| DropPacket["Drop packet silently"]

If Policy A allows TCP port 8080 from role: frontend and Policy B allows TCP port 9090 from role: prometheus, the backend pod accepts both connections. Because policies cannot override each other with explicit denials, security boundaries depend on keeping the baseline restrictive and auditing every additive rule granted to a namespace.

Vulnerable vs. Hardened Configuration: Building Zero-Trust East-West Rules

Securing cluster communication requires pairing a namespace-wide default-deny baseline with narrow, direction-specific allow policies. Relying solely on individual service policies leaves unlabelled debug pods, temporary jobs, and outbound egress paths completely exposed.

Configuration Pattern Ingress Behavior Egress Behavior Lateral Movement Risk
No NetworkPolicy Open to all pods in all namespaces Open to cluster and internet High: full cross-namespace scanning
Ingress-only allowlist on target pod Restricted to selected callers Wide open on all ports Medium: compromised pod can pivot outbound
Namespace default-deny + scoped Ingress Drops all unpermitted inbound traffic Drops unpermitted outbound traffic Low (requires explicit DNS and egress rules)
Default-deny + scoped Ingress/Egress + IMDS block Least-privilege L3/L4 callers only Explicit DNS + required destinations only Minimal L3/L4 blast radius

Vulnerable Baseline: Open East-West Reachability

Consider a backend payment API deployed in the payments namespace without any NetworkPolicy applied. Even though the pod serves internal traffic on port 8080, any workload anywhere in the cluster can connect directly to it.

apiVersion: v1
kind: Pod
metadata:
  name: backend
  namespace: payments
  labels:
    app: payment-api
    tier: backend
spec:
  containers:
  - name: api
    image: app.example/payment-api:1.4.2
    ports:
    - containerPort: 8080

From an unrelated pod in a completely different namespace, a rogue process can query the service directly without authentication at the network layer.

$ kubectl exec -n marketing deploy/image-worker -- curl -sS --max-time 2 http://backend.payments.svc.cluster.local:8080/health
{"status":"ok","db":"connected"}

Hardened Baseline: Default-Deny Plus Least-Privilege Rules

To eliminate implicit trust, start by locking down every pod in the payments namespace with a default-deny policy for both ingress and egress. An empty podSelector: {} matches every pod in the namespace, and specifying both Ingress and Egress under policyTypes with no allow arrays drops all traffic until explicit rules open specific paths.

apiVersion: networking.k8s.io/v1
kind: NetworkPolicy
metadata:
  name: default-deny-all
  namespace: payments
spec:
  podSelector: {}
  policyTypes:
  - Ingress
  - Egress

With the baseline locked, create targeted allow policies for each workload. Notice that the backend-allow-ingress policy below uses a single list item combining namespaceSelector and podSelector so only pods carrying app: web-gateway inside a namespace labeled kubernetes.io/metadata.name: edge can reach port 8080.

apiVersion: networking.k8s.io/v1
kind: NetworkPolicy
metadata:
  name: backend-allow-ingress
  namespace: payments
spec:
  podSelector:
    matchLabels:
      app: payment-api
  policyTypes:
  - Ingress
  ingress:
  - from:
    - namespaceSelector:
        matchLabels:
          kubernetes.io/metadata.name: edge
      podSelector:
        matchLabels:
          app: web-gateway
    ports:
    - protocol: TCP
      port: 8080

Because default-deny-all also blocks outbound traffic, the backend pod now needs explicit egress rules to resolve DNS names via CoreDNS and talk to its PostgreSQL database on TCP 5432. If the pod must also reach an external payment processor over TLS, use an ipBlock rule with except exclusions so it cannot connect to private RFC 1918 subnets or the cloud instance metadata service (169.254.169.254/32).

apiVersion: networking.k8s.io/v1
kind: NetworkPolicy
metadata:
  name: backend-allow-egress
  namespace: payments
spec:
  podSelector:
    matchLabels:
      app: payment-api
  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
  - to:
    - podSelector:
        matchLabels:
          app: payments-db
    ports:
    - protocol: TCP
      port: 5432
  - to:
    - ipBlock:
        cidr: 0.0.0.0/0
        except:
        - 10.0.0.0/8
        - 172.16.0.0/12
        - 192.168.0.0/16
        - 169.254.169.254/32
    ports:
    - protocol: TCP
      port: 443

Runtime Verification on Local and Cluster Endpoints

Once applied, test both an unauthorized caller and an authorized gateway pod, as well as the pod's local loopback interface. Loopback traffic on localhost remains inside the pod's own network namespace and is unaffected by CNI pod-to-pod policies, while cross-pod requests from unpermitted pods fail with a connection timeout because packets are dropped silently.

$ kubectl exec -n payments backend -- curl -sS http://localhost:8080/health
{"status":"ok","db":"connected"}
 
$ kubectl exec -n marketing deploy/image-worker -- curl -sS --max-time 2 http://backend.payments.svc.cluster.local:8080/health
curl: (28) Connection timed out after 2001 milliseconds
 
$ kubectl exec -n edge deploy/web-gateway -- curl -sS --max-time 2 http://backend.payments.svc.cluster.local:8080/health
{"status":"ok","db":"connected"}

Which NetworkPolicy YAML Traps Cause Accidental Exposure or Outages?

The most dangerous bug in NetworkPolicy authoring is a single hyphen indentation error inside from or to peer arrays. Misplacing one dash turns a strict logical intersection (AND) into a permissive union (OR), silently exposing sensitive services across every namespace in the cluster.

The YAML Hyphen Trap: AND vs. OR Selectors

In Kubernetes YAML, each element beginning with a hyphen - inside the from or to array represents an independent NetworkPolicyPeer entry evaluated with OR. By contrast, placing namespaceSelector and podSelector inside the same array item without a second hyphen evaluates them together with AND.

# DANGEROUS (OR): Allows ANY pod in namespace 'edge' OR ANY pod labeled 'app: web-gateway' in 'payments'
from:
- namespaceSelector:
    matchLabels:
      kubernetes.io/metadata.name: edge
- podSelector:
    matchLabels:
      app: web-gateway
 
# SAFE (AND): Allows ONLY pods labeled 'app: web-gateway' inside namespace 'edge'
from:
- namespaceSelector:
    matchLabels:
      kubernetes.io/metadata.name: edge
  podSelector:
    matchLabels:
      app: web-gateway

That single extra - before podSelector is extraordinarily easy to miss in code review. In the dangerous version, any compromised pod in edge can access the backend regardless of its label, and any pod in payments that happens to carry app: web-gateway is admitted too.

Forgetting CoreDNS Egress Rules

Teams applying default-deny-all with Egress isolation for the first time frequently take down an entire namespace within seconds. Application logs report UnknownHostException or dial tcp: lookup ...: i/o timeout because DNS queries to CoreDNS in kube-system are blocked alongside everything else. Always include both UDP and TCP on port 53 targeting k8s-app: kube-dns (or your cluster's specific DNS label), because large DNS responses and DNSSEC payloads fall back from UDP to TCP.

Kubelet Health Probes, hostNetwork, and ipBlock Quirks

Standard NetworkPolicy operates on pod network namespaces, which creates three edge cases engineers must account for in production:

  1. Kubelet health checks: livenessProbe, readinessProbe, and startupProbe traffic originates from the worker node's host network stack. Most modern CNIs (including Calico and Cilium) explicitly permit node-local kubelet probes to isolated pods so nodes do not kill healthy workloads, though custom firewall rules or strict host-level configurations can interfere.
  2. hostNetwork: true pods: Pods configured with hostNetwork: true share the node's root network namespace instead of receiving an isolated veth interface. Standard NetworkPolicy does not enforce isolation on hostNetwork workloads, making Pod Security Standards (Restricted profile) essential to forbid hostNetwork on normal application pods.
  3. ipBlock and Pod IPs: Kubernetes documentation explicitly warns against targeting cluster Pod CIDRs using ipBlock because pod IPs are ephemeral and subject to encapsulation or source NAT depending on node topology. Reserve ipBlock for static external endpoints, external databases outside the cluster, and metadata endpoint exclusions (169.254.169.254/32), while using label selectors for pod-to-pod traffic.

Port Ranges and Named Ports

Instead of opening broad port ranges blindly, Kubernetes 1.25+ provides stable endPort support so you can declare contiguous port ranges like port: 8000 with endPort: 8010 where your CNI supports it. You can also reference named container ports (such as port: http) in NetworkPolicy rules, which resolves dynamically to whatever containerPort each selected pod declares under that name and prevents policy drift during container refactors.

Operational Tradeoffs, Telemetry, and Defense in Depth

Enforcing zero-trust NetworkPolicy baselines shrinks an attacker's blast radius dramatically, yet it introduces real operational tradeoffs around kernel rule scaling, deployment velocity, and troubleshooting blind spots. Mature platform teams treat NetworkPolicies as one layer inside a broader defense-in-depth architecture backed by flow telemetry and RBAC controls.

Performance and Scale Tradeoffs

On clusters running iptables-based policy enforcement, every rule translates into sequential kernel chains. As clusters grow to thousands of services and tens of thousands of pods, linear O(n) rule evaluation and full-table reloads during pod churn can spike node CPU usage and add latency to new connection establishment. Switching to an eBPF-backed CNI such as Cilium replaces linear iptables traversal with constant-time O(1) eBPF hash map lookups, keeping enforcement overhead flat even at high pod density.

Observability for Silent Packet Drops

Because NetworkPolicy enforcement drops unauthorized packets silently at Layer 3 and Layer 4 without returning an ICMP unreachable or TCP RST in many CNI modes, blocked applications simply hang until their socket timeout expires. Without network flow visibility, developers frequently blame database slowness or application bugs for what is actually a missing policy rule. Deploy CNI-level flow telemetry, such as Cilium Hubble flow logs, Calico flow logs, or cloud VPC flow logs, and forward POLICY_DENIED events into your SIEM. Sudden bursts of denied connections from a single pod IP across sequential ports or toward 169.254.169.254 provide one of the highest-signal early indicators of an active in-cluster compromise.

Why NetworkPolicy Alone Is Not Enough

NetworkPolicies enforce identity based on pod labels and namespaces, not cryptographic identity or authorization tokens. If an attacker compromises a service account that holds RBAC permission to patch pods or delete NetworkPolicy objects in that namespace, they can relabel their own pod to app: web-gateway or erase the default-deny rule completely. Similarly, a NetworkPolicy allowing TCP 8080 from web-gateway to payment-api will not stop an attacker inside web-gateway from abusing an unauthenticated admin endpoint or SQL injection over that permitted port.

Durable cluster security pairs four complementary controls:

  1. RBAC least privilege: Ensure workload service accounts cannot create, modify, or delete NetworkPolicy objects or edit pod labels in production namespaces.
  2. Pod Security Standards (PSS): Enforce the Restricted profile via Pod Security Admission so workloads cannot escalate privileges, mount host paths, or request hostNetwork: true and CAP_NET_ADMIN to bypass CNI filtering.
  3. Admission policy checks: Validate NetworkPolicy manifests in CI and with ValidatingAdmissionPolicy or OPA Gatekeeper to catch the YAML OR hyphen trap before deployment.
  4. Service-mesh mTLS (Layer 7): For high-sensitivity services, pair L3/L4 NetworkPolicy containment with mutual TLS (using SPIFFE identities) so connections are cryptographically authenticated and authorized per HTTP/gRPC route.

Production Hardening Checklist

Before rolling out workloads to production, verify these six invariants across every application namespace:

  • Confirm the cluster CNI actively enforces networking.k8s.io/v1 NetworkPolicy objects by testing a deliberate drop rule.
  • Apply a baseline default-deny-all policy selecting podSelector: {} for both Ingress and Egress in every workload namespace.
  • Add explicit egress rules for CoreDNS (kube-dns on UDP and TCP port 53) in namespaces using default-deny egress.
  • Audit every from and to block to verify namespaceSelector and podSelector combinations use intentional AND (single list item) rather than accidental OR (separate hyphens).
  • Block east-west access to private CIDRs and the cloud metadata IP (169.254.169.254/32) inside external ipBlock egress rules.
  • Stream CNI policy drop logs to monitoring dashboards so both misconfigured deployments and lateral movement scans surface immediately.

References & Sources

Related Security Reads

Comments

No comments yet.

Comments are moderated before they appear.

Get new posts by email

No ads, no tracking. Just new posts, unsubscribe any time.