NetworkPolicies
Default deny, explicit allows, and the policy that blocked the front door
By default every pod can reach every other pod in the cluster, in any namespace. A compromised pod can then reach your database. NetworkPolicies restrict that. They're enforced by the network plugin (kindnet supports them; some plugins don't, and then policies are silently ignored).
Policies are allow-lists: once any policy selects a pod for ingress, only traffic that some policy allows gets in.
Tested
./scripts/lab.sh network_policy.py
from the toolbox pod in namespace `labs`:
labs -> web Service (web.shop:8000) allowed
labs -> redis (redis.shop:6379) blocked (command terminated with exit code 1)
labs -> Gateway Service (shop-nginx.shop:80) allowed (200)
from a web pod, via its /api/visits endpoint (talks to redis):
web -> redis: {"pod": "web-7cb7f4d4cd-8rf6l", ..., "visits": 2}The "blocked" result was checked separately: the same nc reaches web
on port 8000 fine, so the failure to reach Redis comes from the policy, not
the tool.
The policy that blocked the front door
The first version of these policies had only the default deny and the
web and redis allows. After applying them, every request through the
Gateway hung until timeout: no error, no response.
The Gateway's NGINX pod lives in the shop namespace (NGINX Gateway Fabric
provisions it next to the Gateway), so the default deny selected it too.
Traffic arriving through the NodePort was dropped before reaching NGINX.
Policy 2 above fixed it.
A default deny applies to every pod in the namespace, including ones
you didn't write: gateway data planes, sidecars, operators' pods,
monitoring exporters. Before applying one, list the pods in the
namespace (kubectl get pods --show-labels) and decide for each who must
reach it. And denied traffic looks like a hang, not an error: when
requests time out after a policy change, suspect the policy first.
Egress
These policies only restrict ingress. Restricting egress (what pods can connect to) stops a compromised pod from calling out to the internet or scanning the cluster, but every policy must then allow DNS (UDP/TCP 53 to CoreDNS) explicitly, or name resolution breaks everywhere.
Lab
- Run
network_policy.py. Then deletegateway-ingressand curllocalhost:8180. How does the failure look? - Add an egress default-deny to
shopand allow only DNS and Redis for web. What breaks first? - Allow
labsto reach Redis on 6379 only from pods labeledrole: debug, and test from the toolbox with and without that label.