TExcelTAD
Home › Kubernetes › Network Policies

Network Policies

By default the Pod network is flat and open: every Pod can connect to every other Pod in every namespace. If an attacker gets into your front end, nothing stops them from talking straight to the database. NetworkPolicies are the firewall rules of Kubernetes.

Note: NetworkPolicies are enforced by the network plugin. Calico, Cilium, Antrea and most managed-cloud CNIs support them; a plugin without support (e.g. plain flannel) silently ignores them.

How policies select traffic

  1. podSelector picks the Pods the policy applies to (in the policy's namespace; {} = all Pods).
  2. policyTypes says which directions it controls: Ingress, Egress, or both.
  3. A Pod that is selected by at least one policy for a direction becomes isolated for that direction: only traffic allowed by some policy gets through.
  4. Policies are additive (a union of allows). There are no deny rules; order doesn't matter.
  5. A Pod not selected by any policy stays fully open.

Default deny, then allow

The usual pattern is to deny everything in a namespace and then open what's needed:

yaml
apiVersion: networking.k8s.io/v1
kind: NetworkPolicy
metadata:
  name: default-deny
  namespace: shop
spec:
  podSelector: {}
  policyTypes: [Ingress]
---
apiVersion: networking.k8s.io/v1
kind: NetworkPolicy
metadata:
  name: api-allow-frontend
  namespace: shop
spec:
  podSelector:
    matchLabels: {app: api}
  policyTypes: [Ingress]
  ingress:
    - from:
        - podSelector:
            matchLabels: {app: frontend}
        - namespaceSelector:
            matchLabels: {kubernetes.io/metadata.name: monitoring}
      ports:
        - {protocol: TCP, port: 8000}
---
apiVersion: networking.k8s.io/v1
kind: NetworkPolicy
metadata:
  name: db-allow-api
  namespace: shop
spec:
  podSelector:
    matchLabels: {app: db}
  policyTypes: [Ingress]
  ingress:
    - from:
        - podSelector:
            matchLabels: {app: api}
      ports:
        - {protocol: TCP, port: 5432}

A policy evaluator

This model parses the three policies above and decides whether a connection is allowed, following the rules listed at the top:

python · try it yourself
import yaml

policies = list(yaml.safe_load_all("""
metadata: {name: default-deny, namespace: shop}
spec: {podSelector: {}, policyTypes: [Ingress]}
---
metadata: {name: api-allow-frontend, namespace: shop}
spec:
  podSelector: {matchLabels: {app: api}}
  policyTypes: [Ingress]
  ingress:
    - from:
        - podSelector: {matchLabels: {app: frontend}}
        - namespaceSelector: {matchLabels: {kubernetes.io/metadata.name: monitoring}}
      ports: [{protocol: TCP, port: 8000}]
---
metadata: {name: db-allow-api, namespace: shop}
spec:
  podSelector: {matchLabels: {app: db}}
  policyTypes: [Ingress]
  ingress:
    - from: [{podSelector: {matchLabels: {app: api}}}]
      ports: [{protocol: TCP, port: 5432}]
"""))

namespaces = {"shop": {"kubernetes.io/metadata.name": "shop"},
              "monitoring": {"kubernetes.io/metadata.name": "monitoring"}}

def selects(selector, labels):
    return all(labels.get(k) == v for k, v in selector.get("matchLabels", {}).items())

def peer_matches(peer, src, policy_ns):
    if "namespaceSelector" in peer and "podSelector" in peer:     # both in ONE element: AND
        return selects(peer["namespaceSelector"], namespaces[src["ns"]]) and selects(peer["podSelector"], src["labels"])
    if "namespaceSelector" in peer:
        return selects(peer["namespaceSelector"], namespaces[src["ns"]])
    if "podSelector" in peer:                                      # podSelector alone: same namespace only
        return src["ns"] == policy_ns and selects(peer["podSelector"], src["labels"])
    return False

def allowed(src, dst, port):
    applying = [p for p in policies if p["metadata"]["namespace"] == dst["ns"]
                and selects(p["spec"]["podSelector"], dst["labels"]) and "Ingress" in p["spec"]["policyTypes"]]
    if not applying:
        return "allowed (not isolated)"
    for p in applying:
        for rule in p["spec"].get("ingress", []):
            port_ok = not rule.get("ports") or any(pr["port"] == port for pr in rule["ports"])
            peer_ok = not rule.get("from") or any(peer_matches(peer, src, p["metadata"]["namespace"]) for peer in rule["from"])
            if port_ok and peer_ok:
                return f"allowed by {p['metadata']['name']}"
    return "DENIED"

frontend = {"ns": "shop", "labels": {"app": "frontend"}}
api = {"ns": "shop", "labels": {"app": "api"}}
db = {"ns": "shop", "labels": {"app": "db"}}
prometheus = {"ns": "monitoring", "labels": {"app": "prometheus"}}

tests = [("frontend", frontend, "api", api, 8000), ("frontend", frontend, "db", db, 5432),
         ("api", api, "db", db, 5432), ("api", api, "db", db, 22),
         ("prometheus", prometheus, "api", api, 8000), ("prometheus", prometheus, "db", db, 5432),
         ("api", api, "frontend", frontend, 80)]
for sname, s, dname, d, port in tests:
    print(f"{sname:10} -> {dname:8}:{port:<5} {allowed(s, d, port)}")
frontend   -> api     :8000  allowed by api-allow-frontend
frontend   -> db      :5432  DENIED
api        -> db      :5432  allowed by db-allow-api
api        -> db      :22    DENIED
prometheus -> api     :8000  allowed by api-allow-frontend
prometheus -> db      :5432  DENIED
api        -> frontend:80    DENIED

The front end can't reach the database, and even the API can only reach it on 5432. The front end itself is covered by default-deny, so nothing gets in there.

The AND/OR trap

Inside one from element, namespaceSelector and podSelector together mean AND. As two separate list items (two dashes), they mean OR. One character of YAML changes the meaning completely:

yaml
# AND: Pods labelled app=prometheus in the monitoring namespace
- from:
    - namespaceSelector: {matchLabels: {team: monitoring}}
      podSelector: {matchLabels: {app: prometheus}}

# OR: ANY Pod in monitoring, or app=prometheus Pods in this namespace
- from:
    - namespaceSelector: {matchLabels: {team: monitoring}}
    - podSelector: {matchLabels: {app: prometheus}}
python · try it yourself
import yaml

and_rule = yaml.safe_load("""
- namespaceSelector: {matchLabels: {team: monitoring}}
  podSelector: {matchLabels: {app: prometheus}}
""")
or_rule = yaml.safe_load("""
- namespaceSelector: {matchLabels: {team: monitoring}}
- podSelector: {matchLabels: {app: prometheus}}
""")
print("AND form has", len(and_rule), "peer with keys", sorted(and_rule[0]))
print("OR form has", len(or_rule), "peers:", [sorted(p) for p in or_rule])
AND form has 1 peer with keys ['namespaceSelector', 'podSelector']
OR form has 2 peers: [['namespaceSelector'], ['podSelector']]

Egress and DNS

If you isolate egress too, remember that Pods need DNS. A default-deny egress policy breaks every name lookup unless you allow UDP/TCP 53 to CoreDNS:

yaml
spec:
  podSelector: {}
  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}

ipBlock peers allow CIDR ranges (e.g. an external database 10.20.0.0/16). For layer-7 rules (HTTP paths, DNS names) look at CNI-specific policies such as CiliumNetworkPolicy.

Go further: NetworkPolicies: Default Deny and Egress evaluates policies for a lab namespace and covers the semantics that trip reviewers.

Test yourself

A Pod is not selected by any NetworkPolicy. What traffic may reach it?

  1. None
  2. All traffic
  3. Only traffic from its namespace
  4. Only DNS

What does podSelector: {} in a policy's spec select?

  1. No Pods
  2. All Pods in the policy's namespace
  3. All Pods in the cluster
  4. Only Pods without labels

After adding a default-deny **egress** policy, apps can't resolve hostnames. Why?

  1. CoreDNS crashed
  2. DNS traffic to kube-dns on port 53 is now blocked
  3. Services were deleted
  4. Ingress is blocked