Review Kubernetes NetworkPolicy Pod selection

Verify that the policy selects the intended namespace and Pods.

Description

A NetworkPolicy’s podSelector selects Pods in the policy’s own namespace. An empty selector selects all of them. A policy for future Pods can legitimately have no current matches.

Potential impact

An incorrect label can leave the intended Pods without isolation or interrupt traffic to other Pods.

Remediation

Compare all matchLabels and matchExpressions conditions with actual Pod labels. Check that the network plugin enforces the policy and that policyTypes covers the intended directions. Test required and blocked connections with all applicable allow rules in effect.

Examples

Both examples select Ingress and specify no ingress allow rules. Another policy can still allow traffic to the same Pods.

Before

yaml
apiVersion: networking.k8s.io/v1
kind: NetworkPolicy
metadata:
  name: test-network-policy
spec:
  podSelector:
    matchLabels:
      app: rarelabel
  policyTypes:
    - Ingress

If no Pods carry app: rarelabel, this policy currently has no targets.

After

yaml
apiVersion: networking.k8s.io/v1
kind: NetworkPolicy
metadata:
  name: test-network-policy
spec:
  podSelector:
    matchLabels:
      app: nginx
  policyTypes:
    - Ingress

Changing the selector to app: nginx brings matching Pods under this ingress policy.

References