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.
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
- 01 →Flat Network RiskUnrestricted lateral threat
- 02 →Default Deny & DNSLock down & whitelist DNS
- 03 →Pod IsolationAuthorize legitimate flows
- 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
iptableschains,ipsetcollections, oreBPFprograms 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 applyinvocation 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 Denypolicy 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
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.
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.
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
- YAML Syntax Trap: Empty Array (
[]) vs. Empty Object ({}): - Inside an
ingress:oregress:block, definingingress: []means drop all incoming traffic unconditionally. - Defining
ingress: [{}]means allow all incoming traffic from any source. - A single misplaced bracket can invert a maximum-security perimeter into an unauthenticated ingress path.
- Logical AND vs. OR Semantics in
from/toBlocks: - 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`.
- namespaceSelector:
matchLabels: { env: prod }
podSelector:
matchLabels: { app: api }
- 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.
- Omitting Ingress Rules for Kubelet Probes:
- The host Kubelet dispatches
livenessProbeandreadinessProbehealth 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 asUnhealthy, triggering continuous, cascading restart loops. - Silent Failures with Unsupported CNIs (e.g., Vanilla Flannel):
- Default Flannel installations do not reject NetworkPolicy manifests, but silently ignore them. Always inspect cluster networking using
kubectl get pods -n kube-systemto 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/