In this lesson, you will learn how to restrict your pods from reaching unauthorized external endpoints, effectively plugging potential data exfiltration paths.
By default, Kubernetes clusters follow a flat network model where pods can reach out to any destination—internal or external. This is a significant security risk: if a pod is compromised, an attacker could tunnel sensitive data to a malicious external server or pull down secondary payloads. To mitigate this, we use NetworkPolicies to enforce strict egress controls.
The Strategy: Whitelisting Egress
Instead of attempting to block "bad" traffic, we move to a "deny-by-default" egress posture. We define a policy that blocks all outgoing traffic by default and then explicitly white-list only the specific IP ranges or domains required for your application to function (such as a specific database or an API endpoint).
Here is how you define a policy to restrict egress traffic to a specific range:
kind: NetworkPolicy
apiVersion: networking.k8s.io/v1
metadata:
name: restrict-egress-to-api
namespace: production
spec:
podSelector:
matchLabels:
app: sensitive-worker
policyTypes:
- Egress
egress:
- to:
- ipBlock:
cidr: 203.0.113.0/24 # Only allow traffic to this external network
ports:
- protocol: TCP
port: 443
Why This Matters
When you apply this configuration, the Kubernetes CNI plugin intercepts all traffic originating from pods labeled app: sensitive-worker. Any attempt to connect to an external IP outside of the 203.0.113.0/24 range will be dropped at the node level.
This creates a "sandbox" effect. Even if an attacker gains shell access to a pod, they cannot reach their command-and-control server or external storage buckets, because the network fabric itself refuses to route that traffic. Always pair this with your existing Namespace isolation and inter-pod traffic rules to ensure a hardened, multi-layered defense.
Key Takeaway: Implement an egress-deny-all policy and use CIDR whitelisting to ensure pods can only communicate with explicitly approved external services, effectively neutralizing most data exfiltration attempts.