Review Kubernetes NetworkPolicy Pod selection

Verify that the policy selects the intended namespace and Pods.

Description

If a NetworkPolicy podSelector does not match actual Pod labels, the expected network restrictions may not apply. A policy selects Pods in its own namespace; an empty selector selects all Pods in that namespace.

A policy prepared for future Pods may validly select none for a time. Check network plugin support and all policies applying to the selected Pods to understand the actual effect.

Potential impact

  • Intended Pods may lack isolation and communicate more broadly than expected.
  • Selecting the wrong Pods can interrupt legitimate traffic.

Remediation

  • Align the policy namespace, podSelector and actual Pod labels. Check all matchLabels or matchExpressions conditions.
  • Configure policyTypes, ingress and egress rules with a supporting network plugin, and test that required connections succeed while unwanted ones fail. Allowed traffic from multiple policies can be combined.

Examples

Both examples define Ingress policies without allow rules. Check actual Pods in the same namespace; ingress allowed by another policy can still be permitted.

Before

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

Pods labeled app=rarelabel are selected. If none exist, the 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

Pods labeled app=nginx are selected. They must exist, and a supporting plugin must enforce the policy for it to have an effect.

References