HANDS-ON LAB Intermediate

Securing Kubernetes Networks with NetworkPolicy: Default Deny & SSRF Protection

Enforce zero-trust pod isolation: configure default deny ingress/egress policies, whitelist CoreDNS, and block AWS/GCP cloud metadata SSRF.

Vibe DevOps·· ~10 min read
KubernetesYAMLkubectlCalicoDevSecOps

Key Takeaways & Prerequisites

  • Kubernetes defaults to a Flat Network where any Pod can send and receive traffic from any other Pod in the cluster without restriction.
  • Implementing Default Deny for both Ingress and Egress is a mandatory Zero Trust principle to prevent lateral movement by attackers.
  • When enforcing Default Deny Egress, always whitelist port 53 UDP/TCP to CoreDNS first; otherwise, cluster DNS resolution breaks immediately.
  • Use ipBlock with except 169.254.169.254/32 to eliminate SSRF attacks targeting the Node's Cloud Instance Metadata IAM credentials.

Architecture & Execution Flow

  1. 01 →Flat Network RiskUnrestricted lateral threat
  2. 02 →Default Deny & DNSLock down & whitelist DNS
  3. 03 →Pod IsolationAuthorize legitimate flows
  4. 04 →Block MetadataEliminate cloud SSRF risks
Table of Contents

Out of the box, default Kubernetes cluster networking follows a flat network paradigm: any pod can communicate with any other pod across the entire cluster without perimeter barriers or access controls. While this unconstrained connectivity accelerates service discovery and rapid prototyping in early development, it represents an existential security liability in production and multi-tenant environments.

If a publicly exposed frontend pod or edge container is compromised via Remote Code Execution (RCE) or Server-Side Request Forgery (SSRF), the adversary instantly gains an unhindered foothold inside the cluster network. From this vantage point, they can execute port scans, pivot toward sensitive backend services, exfiltrate data from internal data stores (lateral movement), or—even worse—query the Instance Metadata Service (169.254.169.254) on AWS or GCP to harvest the host node's underlying IAM role credentials.

The industry-standard approach for establishing defense-in-depth and enforcing a Zero Trust posture within Kubernetes is NetworkPolicy. This guide walks through an end-to-end implementation of NetworkPolicies: establishing a baseline namespace-wide default-deny, securely whitelisting CoreDNS resolution paths, enforcing pod-to-pod isolation, and systematically mitigating cloud metadata exfiltration.

Scope and Prerequisites: The Kubernetes NetworkPolicy manifests (YAML) in this guide have been syntax-validated using PyYAML. Bash verification scripts have been verified with bash -n. API semantics and operational behaviors align with upstream Kubernetes v1.30+ and Calico CNI specifications. This guide isolates all lab environments to safeguard live cluster resources and highlights critical operational failure modes.

1. Architectural Foundations and NetworkPolicy Enforcement Mechanics

Before crafting manifests, it is essential to understand how Kubernetes and the underlying Container Network Interface (CNI) enforce packet-filtering rules at the kernel level:

1.1. The Role of the CNI Plugin in NetworkPolicy Enforcement

A fundamental Kubernetes architectural nuance: the Kubernetes API server merely stores and validates NetworkPolicy resource definitions—it does not inspect or filter network packets directly. Policy enforcement delegates entirely to the cluster's Container Network Interface (CNI) plugin:

  • CNIs with NetworkPolicy support: Calico, Cilium, Weave Net, Kube-router, or AWS VPC CNI (with NetworkPolicy Controller enabled). These plugins compile declarative YAML rules into kernel-level primitives such as iptables chains, ipset collections, or eBPF programs attached directly to container virtual ethernet pairs (veth).
  • CNIs WITHOUT NetworkPolicy support: Flannel (in its default mode, which provides standard VXLAN routing without packet filtering). If you apply a NetworkPolicy on a vanilla Flannel cluster, the kubectl apply invocation succeeds, but no packets will be dropped.

1.2. Pod Isolation States and Evaluation Order

According to standard Kubernetes network policy evaluation semantics: 1. By default, a pod is non-isolated for Ingress and Egress; all inbound and outbound traffic is permitted. 2. The moment at least one NetworkPolicy selects a pod (podSelector matches pod labels) and specifies policyTypes: [Ingress] or [Egress], that pod shifts into an isolated state for the defined direction. 3. Once isolated, any traffic not explicitly matched by an allowlist rule is dropped by the CNI. 4. NetworkPolicies are additive (union semantics): if multiple policies target a pod, traffic is permitted if it matches the criteria of at least one policy.

Operational Warning: Applying a Default Deny policy to an active production namespace before defining explicit allow rules will induce an immediate service outage. The safe rollout pattern is strictly: Deploy Allow Rules → Validate label matching → Enforce Default Deny.

2. Lab Environment Setup

To execute this lab without incurring cloud infrastructure costs, you can run Minikube or Kind with Calico CNI configured on your local workstation:

# Create a dedicated namespace for testing
kubectl create namespace production

# Label the namespace to support cross-namespace filtering
kubectl label namespace production env=production

# Deploy a test client pod equipped with curl and nslookup
kubectl run client --namespace=production \
  --image=curlimages/curl:8.6.0 \
  --labels="app=client,role=frontend" \
  --command -- sleep 3600

3. Implementing Zero Trust NetworkPolicies: Step-by-Step

Configuring Default Deny Ingress/Egress and CoreDNS Whitelisting in Kubernetes
Figure 1: Enforcing default-deny ingress/egress namespace-wide while opening UDP/TCP port 53 to CoreDNS.

Step 1: Enforce Default Deny and Allowlist CoreDNS

The baseline tenet of Zero Trust architecture: deny all traffic unless explicitly authorized.

Create default-deny-all.yaml:

apiVersion: networking.k8s.io/v1
kind: NetworkPolicy
metadata:
  name: default-deny-all
  namespace: production
spec:
  podSelector: {} # Applies to all pods in the namespace
  policyTypes:
  - Ingress
  - Egress

When you apply this policy, every pod in the production namespace becomes fully isolated. Even internal DNS resolution fails because outbound UDP packets to port 53 are dropped. Consequently, workloads cannot resolve internal database hostnames or external APIs.

Therefore, an explicit egress policy permitting traffic to CoreDNS in the kube-system namespace must accompany the default-deny baseline. Create allow-dns-egress.yaml:

apiVersion: networking.k8s.io/v1
kind: NetworkPolicy
metadata:
  name: allow-dns-egress
  namespace: production
spec:
  podSelector: {} # Permits all pods in the namespace to resolve DNS
  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

Apply the configuration and verify DNS functionality:

kubectl apply -f default-deny-all.yaml
kubectl apply -f allow-dns-egress.yaml

# Verify CoreDNS resolution functions as expected via nslookup
kubectl -n production exec pod/client -- nslookup kubernetes.default

Step 2: Enforce Pod-to-Pod Isolation with Label-Based Ingress Filtering

Consider a topology with two microservices: frontend and backend. Requirements: - backend listens exclusively on port 8080. - Only pods labeled app: frontend may initiate connections to backend. - All other pods (such as analytics, an ad-hoc crawler, or an unauthorized intruder pod) within the same namespace must be blocked.

Verifying the Pod Isolation Traffic Matrix with curl via NetworkPolicy
Figure 2: The backend accepts ingress traffic strictly from Frontend:8080 and drops packets from untrusted pods.

Create the configuration file backend-allow-frontend.yaml:

apiVersion: networking.k8s.io/v1
kind: NetworkPolicy
metadata:
  name: backend-allow-frontend
  namespace: production
spec:
  podSelector:
    matchLabels:
      app: backend # Targets backend pods exclusively
  policyTypes:
  - Ingress
  ingress:
  - from:
    - podSelector:
        matchLabels:
          app: frontend # Restricts ingress strictly to frontend pods
    ports:
    - protocol: TCP
      port: 8080

Deploy the mock backend and validate enforcement:

# Deploy mock backend listening on HTTP port 8080
kubectl run backend --namespace=production \
  --image=hashicorp/http-echo:0.2.3 \
  --labels="app=backend" \
  -- -text="Hello from secure backend" -listen=:8080

# Apply policy targeting the backend
kubectl apply -f backend-allow-frontend.yaml

# 1. Test from authorized frontend pod -> Success
kubectl -n production exec pod/client -- curl -s -m 3 http://backend:8080

# 2. Deploy untrusted pod (lacking app=frontend label) -> Connection timed out
kubectl run untrusted --namespace=production \
  --image=curlimages/curl:8.6.0 \
  --labels="app=untrusted" \
  --command -- sleep 3600

kubectl -n production exec pod/untrusted -- curl -s -m 3 http://backend:8080
# Output: curl: (28) Connection timed out after 3000 milliseconds

Step 3: Mitigate SSRF Exploitation Against Instance Metadata Service (169.254.169.254)

In managed cloud environments (AWS EKS, GCP GKE, Azure AKS), cluster nodes access the link-local Instance Metadata Service (IMDS) at 169.254.169.254.

If an application container possesses an SSRF vulnerability (e.g., link preview, webhook dispatching, or image fetching), an attacker can supply http://169.254.169.254/latest/meta-data/iam/security-credentials/ to exfiltrate the host node's temporary IAM credentials.

To eliminate this blast radius, configure an egress policy permitting public internet egress while strictly excluding 169.254.169.254/32 using the ipBlock stanza's except parameter.

Mitigating SSRF attacks against Cloud Metadata via NetworkPolicy ipBlock exceptions
Figure 3: Packets destined for 169.254.169.254/32 are dropped at the pod's veth boundary by the CNI, neutralizing SSRF attempts.

Create frontend-egress-secure.yaml:

apiVersion: networking.k8s.io/v1
kind: NetworkPolicy
metadata:
  name: frontend-egress-secure
  namespace: production
spec:
  podSelector:
    matchLabels:
      app: frontend
  policyTypes:
  - Egress
  egress:
  # 1. Permit egress to internal backend
  - to:
    - podSelector:
        matchLabels:
          app: backend
    ports:
    - protocol: TCP
      port: 8080
  # 2. Permit public internet access (HTTP/HTTPS) while blocking metadata and internal VPC ranges
  - to:
    - ipBlock:
        cidr: 0.0.0.0/0
        except:
        - 169.254.169.254/32 # Cloud Instance Metadata Service
        - 10.0.0.0/8          # Internal VPC CIDR block
    ports:
    - protocol: TCP
      port: 80
    - protocol: TCP
      port: 443

Apply the policy and verify outbound perimeter isolation:

kubectl apply -f frontend-egress-secure.yaml

# Attempt to query the cloud metadata IP from the frontend pod
kubectl -n production exec pod/client -- curl -s -m 3 http://169.254.169.254/latest/meta-data/
# Expected output: Connection timed out after 3 seconds!

4. Common Operational Pitfalls and Failure Modes

  1. YAML Syntax Trap: Empty Array ([]) vs. Empty Object ({}):
  2. Inside an ingress: or egress: block, defining ingress: [] means drop all incoming traffic unconditionally.
  3. Defining ingress: [{}] means allow all incoming traffic from any source.
  4. A single misplaced bracket can invert a maximum-security perimeter into an unauthenticated ingress path.
  5. Logical AND vs. OR Semantics in from / to Blocks:
  6. Within a single list item: ```yaml from:
    • namespaceSelector: matchLabels: { env: prod } podSelector: matchLabels: { app: api } `` This evaluates as a logical **AND**: the source pod must belong to a namespace labeledenv: prod**AND** carry the labelapp: api`.
  7. When declared as distinct list items: ```yaml from:
    • namespaceSelector: matchLabels: { env: prod }
    • podSelector: matchLabels: { app: api } `` This evaluates as a logical **OR**: allows traffic from *any* pod in a namespace labeledenv: prod**OR** *any* pod carryingapp: api` within the local namespace.
  8. Omitting Ingress Rules for Kubelet Probes:
  9. The host Kubelet dispatches livenessProbe and readinessProbe health checks directly from the node's IP address. If ingress NetworkPolicies are overly restrictive and do not accommodate node IP addresses or host subnets, Kubelet probes fail. Consequently, the control plane marks healthy pods as Unhealthy, triggering continuous, cascading restart loops.
  10. Silent Failures with Unsupported CNIs (e.g., Vanilla Flannel):
  11. Default Flannel installations do not reject NetworkPolicy manifests, but silently ignore them. Always inspect cluster networking using kubectl get pods -n kube-system to confirm that Calico, Cilium, or AWS VPC CNI is operational before relying on policy enforcement.

5. Teardown and Cleanup

After concluding verification, clean up test resources to reclaim cluster capacity:

# Delete all NetworkPolicies in the production namespace
kubectl delete networkpolicy --all -n production

# Delete the namespace and mock workloads
kubectl delete namespace production

6. References and Further Reading

  • Kubernetes Official Documentation: Network Policies Reference (Validated November 02, 2026): https://kubernetes.io/docs/concepts/services-networking/network-policies/
  • AWS EKS Best Practices Guides: Security Best Practices - Restricting Access to IMDS (Validated November 02, 2026): https://aws.github.io/aws-eks-best-practices/security/docs/iam/#restrict-access-to-the-instance-profile-assigned-to-the-worker-node
  • Project Calico Documentation: About Network Policy and Zero Trust Security (Validated November 02, 2026): https://docs.tigera.io/calico/latest/network-policy/
Read critically, test before applying. Examples reflect Vibe DevOps lab environments; adjust parameters to your infrastructure and verify in staging first.← Back to Hands-on Labs

Next Recommended Labs