โšก
Zero to Platform Architect2026
Phase 6: Service Mesh & Cilium eBPF

Lesson 2: Zero-Trust Security, Layer 7 Cilium Network Policies & Exception Handling

๐Ÿง  The Concept (Explain Like Iโ€™m 5)

By default, a Kubernetes cluster is a giant house with no interior doors:

  • The Dangerous Default (Lateral Movement): If a burglar smashes through the front living room window (a compromised public-facing web microservice), they can walk freely into the master bedroom, open the unlocked safe, and steal the jewels (querying internal customer databases, extracting Stripe keys, and pivoting to cloud IAM metadata).
  • Zero-Trust Network Policies (The Steel Vault Doors): You install biometric, reinforced steel blast doors between every single room in the house:
    1. Default Deny: Every single door is locked shut 24/7. No room can talk to any other room unless an explicit architectural rule permits it.
    2. Layer 7 Inspection (The Security Intercom): Even if the bedroom door is unlocked for a trusted family member, an armed guard stands at the door inspecting every spoken word. If the family member says: โ€œPlease hand me the documentโ€ (HTTP GET /api/v1/orders), the guard permits it. But if they whisper: โ€œDelete the audit logsโ€ (HTTP DELETE /api/v1/records) or attempt to download the database, the guard slams the door shut instantly!

๐Ÿข The Enterprise Context (Why Platform Architects Care)

  1. Compliance Mandates (PCI-DSS 4.0, HIPAA, SOC 2): Payment Card Industry standards strictly mandate network micro-segmentation between Cardholder Data Environments (CDE) and general corporate workloads. Workloads in non-compliant namespaces must be mathematically incapable of initiating TCP connections to payment databases.
  2. The Failure of Native Kubernetes NetworkPolicies (L3/L4 Limitations): Native Kubernetes NetworkPolicy resources can only filter traffic by IP address and TCP/UDP port. If an attacker exploits an application vulnerability (such as Log4j or SQL injection) on an allowed port (e.g. port 80 or 443), standard Kubernetes policies are 100% blind to the attack. CiliumNetworkPolicy inspects HTTP verbs, REST API paths, gRPC methods, and Kafka topics at Layer 7!
  3. FQDN-Based Egress Control (No More Flapping IP Whitelists): Modern microservices depend on third-party SaaS APIs (Stripe, Twilio, OpenAI, GitHub). Because cloud providers use dynamic Anycast IPs that change constantly, hardcoding IP ranges into firewall rules is impossible. Cilium intercepts DNS lookups and dynamically writes in-kernel eBPF rules restricted to verified domain names (toFQDNs: [{ matchName: "api.stripe.com" }]).

๐Ÿ—บ๏ธ Visual Architecture: Cilium L7 Zero-Trust Enforcement

flowchart TD
    subgraph FrontendZone ["Public Web Zone (Untrusted)"]
        LegitClient["Legitimate Frontend Pod<br/>(app: frontend)"]
        HackedPod["Compromised Frontend Pod<br/>(Attacker Controlled via RCE)"]
    end

    subgraph KernelPlane ["Host Linux Kernel (eBPF & Cilium Data Plane)"]
        eBPF_Filter["<b>eBPF In-Kernel Filter (tc / sockops)</b><br/>โ€ข Fastpath L3/L4 enforcement<br/>โ€ข Redirects matching L7 traffic to node-local Envoy proxy"]
    end

    subgraph BackendZone ["Secure Payment Zone (PCI-DSS Restricted)"]
        PaymentPod["<b>Payment API Pod (:8080)</b><br/>(app: payment-service)"]
    end

    LegitClient -->|"HTTP GET /api/v1/orders/123"| eBPF_Filter
    HackedPod -.->|"HTTP DELETE /api/v1/records"| eBPF_Filter
    HackedPod -.->|"TCP Port 22 SSH Probe"| eBPF_Filter

    eBPF_Filter -->|"L7 Rule Matches: ALLOW โœ…"| PaymentPod
    eBPF_Filter --x|"L7 Verb Mismatch: 403 FORBIDDEN โŒ"| PaymentPod
    eBPF_Filter --x|"Port 22 Denied: PACKET DROPPED โŒ"| PaymentPod

๐Ÿ”ฌ Under the Hood: eBPF Socket Filtering vs. Node-Local Envoy Proxy

How does Cilium enforce Layer 7 policies without destroying application throughput?

  1. Layer 3/4 Fastpath (Kernel Space): When Pod A sends packets to Pod B, Ciliumโ€™s eBPF programs attached to the network interface (tc traffic control hooks) inspect the Security Identities of both endpoints. If Layer 4 rules block the traffic (e.g. unauthorized port), the packet is dropped directly in the Linux kernel in sub-microsecond time with zero CPU overhead.
  2. Layer 7 Inspection (Node-Local Envoy Proxy): If the policy declares Layer 7 rules (http: rules), eBPF intercepts the TCP socket using sockops and transparently splices the connection into a lightweight, high-performance node-local Envoy Proxy. Envoy inspects the HTTP headers, path, and method, enforcing the policy before forwarding the payload to the destination container.

๐Ÿ’ป Production Manifests: Zero-Trust CiliumNetworkPolicies

1. Enterprise Default Deny All Ingress and Egress (default-deny.yaml)

Apply this baseline to every production namespace:

apiVersion: "cilium.io/v2"
kind: CiliumNetworkPolicy
metadata:
  name: default-deny-all-traffic
  namespace: workloads-payment
spec:
  description: "Strict Zero-Trust: Lock down all inbound and outbound traffic by default"
  endpointSelector: {} # Matches every pod in the namespace
  ingress:
    - {} # Empty list = Deny all ingress
  egress:
    - {} # Empty list = Deny all egress

2. Fine-Grained Layer 7 HTTP & FQDN Egress Policy (payment-policy.yaml)

apiVersion: "cilium.io/v2"
kind: CiliumNetworkPolicy
metadata:
  name: payment-service-l7-guardrail
  namespace: workloads-payment
spec:
  endpointSelector:
    matchLabels:
      app: payment-service

  # Ingress: Allow frontend to invoke strictly designated REST endpoints
  ingress:
    - fromEndpoints:
        - matchLabels:
            app: frontend-web
            io.kubernetes.pod.namespace: workloads-frontend
      toPorts:
        - ports:
            - port: "8080"
              protocol: TCP
          rules:
            http:
              - method: "GET"
                path: "^/api/v1/orders/[0-9]+$"
              - method: "POST"
                path: "^/api/v1/checkout$"

  # Egress: Allow outbound connectivity ONLY to Stripe API and CoreDNS
  egress:
    # Rule 1: Allow outbound HTTPS strictly to Stripe API FQDN
    - toFQDNs:
        - matchName: "api.stripe.com"
      toPorts:
        - ports:
            - port: "443"
              protocol: TCP

    # Rule 2: MANDATORY: Whitelist CoreDNS for cluster name resolution
    - toEndpoints:
        - matchLabels:
            k8s:io.kubernetes.pod.namespace: kube-system
            k8s-app: kube-dns
      toPorts:
        - ports:
            - port: "53"
              protocol: ANY
          rules:
            dns:
              - matchPattern: "*"

โš ๏ธ Real-World Failure Modes, Exceptions & Break-Glass Playbooks

Exception 1: The โ€œDefault Deny DNS Blackoutโ€ Trap

  • The Catastrophe: A security engineer applies the standard default-deny-all policy to the payment namespace. Seconds later, all microservices crash with:
    java.net.UnknownHostException: database.corp.internal: Temporary failure in name resolution
  • The Root Cause: In Kubernetes, DNS resolution is an outbound network packet on UDP/TCP port 53 directed to the CoreDNS pods in kube-system. When you block all egress, you block DNS lookups! The pod cannot resolve external APIs, database endpoints, or sibling services.
  • The Architectural Rule: Every single CiliumNetworkPolicy that restricts egress must explicitly include an egress rule permitting DNS on port 53 to kube-system.

Exception 2: FQDN Proxy TTL Expiration During Long-Lived Streaming Sockets

  • The Failure: A payment pod maintains a long-lived gRPC or WebSocket streaming connection to an external vendor API. Exactly 5 minutes after connection establishment, Cilium abruptly severs the TCP connection.
  • The Root Cause: Ciliumโ€™s FQDN engine populates its internal eBPF IP allowlist based on the DNS TTL (Time-To-Live) returned by CoreDNS. If Stripeโ€™s DNS response has a TTL of 300 seconds (5 minutes), Ciliumโ€™s garbage collector expires the IP from the eBPF allowlist after 5 minutes, treating subsequent packets on the active TCP stream as unauthorized!
  • The Architectural Fix: In cilium-config, configure tofqdns-min-ttl to enforce a minimum retention period for active connection IPs:
    tofqdns-min-ttl: 3600 # Cache resolved FQDN IPs for at least 1 hour

Exception 3: Security Identity Exhaustion in High-Churn Clusters

  • The Outage: In high-churn clusters running thousands of dynamic batch jobs or ephemeral test runners, Cilium fails to assign identities to newly launched pods. Pods remain stuck in ContainerCreating with:
    Error: failed to allocate Cilium security identity: exhausted identity space
  • The Root Cause: Cilium allocates a unique numeric Security Identity (1 to 65535) for each unique set of Kubernetes labels. If developers inject dynamic timestamps, git commit hashes, or random UUIDs as pod labels (e.g., build-id: 9a8b1c2d), every pod receives a unique identity, exhausting the 16-bit identity table in etcd!
  • The Prevention: Configure identity-labels in the Cilium Helm chart to restrict identity evaluation strictly to semantic architecture labels (app, environment, tier), ignoring dynamic deployment hashes.

๐Ÿ“ Staff Architect & SRE Interview Scenarios

โ“ ๐ŸŸข Low Difficulty: Why does Cilium outperform native iptables NetworkPolicies?

Question: In a Kubernetes cluster with 5,000 pods and 20,000 network policies, why does traditional Calico / iptables network filtering experience catastrophic performance degradation, while Cilium eBPF maintains constant latency?

Answer: Traditional iptables uses linear sequential packet evaluation (O(N) algorithmic complexity). For every incoming packet, the Linux kernel must iterate through up to 20,000 sequential rules from top to bottom, consuming massive CPU cycles and adding milliseconds of latency. Cilium uses eBPF BPF Maps (In-Kernel Hash Tables) providing O(1) constant-time lookup. Regardless of whether the cluster has 10 rules or 100,000 rules, the kernel evaluates the packet in single-digit nanoseconds.

โ“ ๐ŸŸก Medium Difficulty: CiliumNetworkPolicy vs CiliumClusterwideNetworkPolicy

Question: What is the operational difference between CiliumNetworkPolicy (CNP) and CiliumClusterwideNetworkPolicy (CCNP)?

Answer:

  • CiliumNetworkPolicy: Scoped strictly to a single Kubernetes namespace. Controlled by application squad teams to enforce workload-specific ingress/egress rules.
  • CiliumClusterwideNetworkPolicy: Cluster-scoped. Controlled exclusively by platform security teams to enforce non-negotiable enterprise guardrails across all namespaces (e.g., globally enforcing DNS egress to CoreDNS, or blocking all pods across the cluster from querying the AWS EC2 Instance Metadata Service 169.254.169.254).
โ“ ๐Ÿ”ด Hard Difficulty: Preventing AWS Instance Metadata Service (IMDS) Exploitation

Question: How do platform architects use Cilium to prevent SSRF (Server-Side Request Forgery) attacks from stealing the underlying nodeโ€™s IAM instance credentials via the AWS metadata endpoint?

Answer: Attackers exploiting an SSRF vulnerability query http://169.254.169.254/latest/meta-data/iam/security-credentials/ to steal the nodeโ€™s IAM credentials. Platform architects deploy a CiliumClusterwideNetworkPolicy that explicitly denies egress to the link-local IP 169.254.169.254/32 for all workload pods, while whitelisting only designated system pods (like AWS Node Problem Detector). Pods attempting to reach the metadata service are blocked directly in the kernel before the packet ever leaves the virtual network interface.

โ“ ๐ŸŸฃ Complex Difficulty: What is eBPF Host-Routing (Bypassing the TCP/IP Stack)?

Question: What is Cilium eBPF Host-Routing, and how does it achieve sub-millisecond pod-to-pod network transmission compared to traditional Linux bridge routing?

Answer: In traditional Linux container networking, a packet traveling from Pod A to Pod B must traverse multiple network layers: the container veth interface โ†’ host veth interface โ†’ netfilter iptables hooks โ†’ Linux IP routing table โ†’ destination veth interface. This involves multiple context switches and memory copies.

Cilium eBPF Host-Routing: Attaches eBPF programs directly to the tc (traffic control) hook of the physical network card and container virtual interfaces. Using eBPF helper functions (bpf_redirect), Cilium bypasses the entire host Linux network stack, iptables tables, and conntrack evaluation, moving raw packet buffers directly from the source socket to the destination socket in memory, reducing network latency by over 50%.