TExcelTAD
Home › Cloud & Container Security › NetworkPolicies: Default Deny and Egress

NetworkPolicies: Default Deny and Egress

By default, every pod in a Kubernetes cluster can connect to every other pod, in every namespace, on every port, and to anything outside the cluster the nodes can reach, including the cloud metadata address. For an attacker who has compromised one pod, the cluster network is flat: the database of another team, the monitoring stack's admin API and the node's metadata service are all one connection away. NetworkPolicies are the cluster's firewall rules: label-based allow-lists for traffic into (ingress) and out of (egress) pods. They are also easy to get subtly wrong, because their semantics differ from a classic firewall. Network Policies introduced the object; this lesson evaluates policies as a reviewer would and builds a default-deny design for the lab namespace. The general design ideas are in Microsegmentation.

Semantics that trip reviewers

  • A pod is unrestricted until at least one policy selects it for a direction. Policies only ever add allowed traffic; there are no deny rules and no order.
  • Once selected for ingress (or egress), only traffic allowed by some selecting policy passes, in that direction. Replies to allowed connections are allowed (policies are stateful).
  • podSelector: {} selects every pod in the policy's namespace; a policy with policyTypes: [Ingress, Egress] and no rules is therefore default deny for the namespace.
  • Inside one from/to entry, namespaceSelector and podSelector together mean pods with these labels in namespaces with those labels; as two separate entries they mean either. One dash changes the meaning.
  • Enforcement depends on the network plugin. The API accepts NetworkPolicies even when the CNI ignores them (some basic plugins do); check that yours enforces them (Calico, Cilium and the major managed-service plugins do, sometimes as an option you must turn on).

An evaluator for the lab namespace

The program implements those rules for the lab cluster: a shop namespace with web, api and db pods, a monitoring namespace, DNS in kube-system, and the metadata address outside. It prints the connection matrix with no policies, then with a default-deny design.

python · try it yourself
import ipaddress

ns_labels = {"shop": {"team": "shop"}, "monitoring": {"team": "platform"}, "kube-system": {"kubernetes.io/metadata.name": "kube-system"}}
pods = {"web": ("shop", {"app": "web"}), "api": ("shop", {"app": "api"}), "db": ("shop", {"app": "db"}),
        "prometheus": ("monitoring", {"app": "prometheus"}), "coredns": ("kube-system", {"k8s-app": "kube-dns"})}
EXTERNAL = {"metadata 169.254.169.254": "169.254.169.254", "payments 203.0.113.80": "203.0.113.80"}

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

def peer_ok(peer, src):
    if "ipBlock" in peer:
        if src not in EXTERNAL.values():
            return False
        ip = ipaddress.ip_address(src)
        return ip in ipaddress.ip_network(peer["ipBlock"]["cidr"]) and not any(
            ip in ipaddress.ip_network(e) for e in peer["ipBlock"].get("except", []))
    if src not in pods:
        return False
    ns, labels = pods[src]
    ns_ok = sel(peer["namespaceSelector"], ns_labels[ns]) if "namespaceSelector" in peer else ns == peer["_ns"]
    return ns_ok and sel(peer.get("podSelector", {}), labels)

def allowed(policies, src, dst, port):
    def check(direction, pod, other):
        if pod not in pods:
            return True                                   # external endpoints have no policies
        ns, labels = pods[pod]
        selecting = [p for p in policies if p["ns"] == ns and sel(p["podSelector"], labels) and direction in p["types"]]
        if not selecting:
            return True                                   # not isolated in this direction
        for p in selecting:
            for rule in p.get(direction.lower(), []):
                peers = rule.get("from" if direction == "Ingress" else "to", [{}])
                ports = rule.get("ports")
                if (not ports or port in [x["port"] for x in ports]) and any(
                        (pp == {} or peer_ok({**pp, "_ns": p["ns"]}, other)) for pp in peers):
                    return True
        return False
    return check("Egress", src, dst) and check("Ingress", dst, src)

FLOWS = [("web", "api", 8080), ("web", "db", 5432), ("api", "db", 5432), ("prometheus", "api", 9090),
         ("web", "coredns", 53), ("web", "metadata 169.254.169.254", 80), ("api", "payments 203.0.113.80", 443),
         ("prometheus", "db", 5432)]
def matrix(title, policies):
    print(f"== {title}")
    for s, d, port in FLOWS:
        dst_ip = EXTERNAL.get(d, d)
        print(f"   {s:10} -> {d:26} :{port:<5} {'allow' if allowed(policies, s, dst_ip, port) else 'DENY'}")

matrix("no policies", [])
APP = lambda name: {"matchLabels": {"app": name}}
policies = [
    {"ns": "shop", "podSelector": {}, "types": ["Ingress", "Egress"]},                       # default deny
    {"ns": "shop", "podSelector": {}, "types": ["Egress"], "egress": [                         # DNS for everyone
        {"to": [{"namespaceSelector": {"matchLabels": {"kubernetes.io/metadata.name": "kube-system"}},
                 "podSelector": {"matchLabels": {"k8s-app": "kube-dns"}}}], "ports": [{"port": 53}]}]},
    {"ns": "shop", "podSelector": APP("api"), "types": ["Ingress"], "ingress": [
        {"from": [{"podSelector": APP("web")}], "ports": [{"port": 8080}]},
        {"from": [{"namespaceSelector": {"matchLabels": {"team": "platform"}}, "podSelector": APP("prometheus")}], "ports": [{"port": 9090}]}]},
    {"ns": "shop", "podSelector": APP("web"), "types": ["Egress"], "egress": [{"to": [{"podSelector": APP("api")}], "ports": [{"port": 8080}]}]},
    {"ns": "shop", "podSelector": APP("api"), "types": ["Egress"], "egress": [
        {"to": [{"podSelector": APP("db")}], "ports": [{"port": 5432}]},
        {"to": [{"ipBlock": {"cidr": "0.0.0.0/0", "except": ["10.0.0.0/8", "169.254.169.254/32"]}}], "ports": [{"port": 443}]}]},
    {"ns": "shop", "podSelector": APP("db"), "types": ["Ingress"], "ingress": [{"from": [{"podSelector": APP("api")}], "ports": [{"port": 5432}]}]},
]
matrix("default deny + allow rules", policies)
== no policies
   web        -> api                        :8080  allow
   web        -> db                         :5432  allow
   api        -> db                         :5432  allow
   prometheus -> api                        :9090  allow
   web        -> coredns                    :53    allow
   web        -> metadata 169.254.169.254   :80    allow
   api        -> payments 203.0.113.80      :443   allow
   prometheus -> db                         :5432  allow
== default deny + allow rules
   web        -> api                        :8080  allow
   web        -> db                         :5432  DENY
   api        -> db                         :5432  allow
   prometheus -> api                        :9090  allow
   web        -> coredns                    :53    allow
   web        -> metadata 169.254.169.254   :80    DENY
   api        -> payments 203.0.113.80      :443   allow
   prometheus -> db                         :5432  DENY

Without policies, the compromised-web-pod scenario is as bad as it gets: web reaches the database directly, the metadata service, and anything else. With the design, each flow that the architecture diagram shows is allowed and nothing else: web only talks to api and DNS, api to db and to HTTPS outside the private ranges and metadata, db only accepts api. Prometheus can scrape api (its own rule, selecting the monitoring namespace and the Prometheus pod in one entry) but not the database. Note that monitoring has no policies of its own here; the allow for Prometheus's egress comes from it being un-isolated, which is the next namespace to fix.

How weak network isolation is detected

  • Coverage: namespaces with no policy selecting all pods (podSelector: {} with both types), pods not selected by any ingress policy. Tools such as kube-linter, Kubescape, or the CNI's own policy views (Cilium Hubble, Calico) report this.
  • Effective reachability: evaluate the policies, as above, or test from a pod in scope (kubectl run --rm -it … -- nc -zv db 5432); a policy that looks right but uses the wrong label is only found this way.
  • Flow logs: Hubble/Calico flow logs or VPC flow logs of pod traffic show unexpected connections, including attempts to 169.254.169.254 from application pods (also a runtime detection, Runtime Detection).

How it is fixed

  1. Default deny both directions in every application namespace, created with the namespace (in the platform's namespace template).
  2. Add DNS egress for all pods, then one policy per real flow, by labels, with ports.
  3. Block metadata and internal ranges from application egress (ipBlock with except), complementing IMDSv2 and hop limit 1 (IMDS).
  4. Use the CNI's extended policies where needed: DNS-name-based egress (Cilium toFQDNs, Calico domain policies), cluster-wide defaults, logging of denied flows.

Pitfalls

  • Default deny for ingress only: egress stays wide open, which is the direction exfiltration and lateral movement need.
  • namespaceSelector and podSelector written as two list items when one item was meant: the rule then allows the whole namespace or those pods anywhere.
  • Policies that select pods by labels the pods don't have (typos), which silently select nothing.

Practice

1. Split Prometheus's rule into two list items: {"namespaceSelector": …} and {"podSelector": APP("prometheus")}. Who can reach api:9090 now?

Every pod in any namespace labelled team: platform, or any pod labelled app: prometheus in shop (a bare podSelector means the policy's own namespace). The intended "Prometheus in monitoring" becomes much broader.

2. Remove the DNS policy. Which flow changes, and what breaks in practice?

web -> coredns :53 becomes DENY. In practice every pod in shop stops resolving names, so even the allowed flows by service name fail. Default-deny designs always start with DNS.

3. The api pod is allowed HTTPS to 0.0.0.0/0 except private ranges and metadata. Is that good egress control?

It blocks lateral movement and metadata access, but it still allows HTTPS to any Internet host, so data can leave. If the payment provider is the only destination, restrict to its ranges or use an egress gateway or proxy with a domain allow-list (Egress Control).

Test yourself

Without any NetworkPolicy, which pods can a pod reach?

  1. Only pods in its namespace
  2. Every pod in every namespace, and outside destinations the node can reach
  3. None
  4. Only Services

What does a policy with podSelector {} and policyTypes [Ingress, Egress] and no rules do?

  1. Allows everything
  2. Denies all ingress and egress for every pod in its namespace (default deny)
  3. Nothing
  4. Deletes pods

In the design, why can web not reach the database?

  1. The database is down
  2. web's egress allows only api:8080 and DNS, and db's ingress allows only api
  3. Port 5432 is blocked by the node
  4. Policies deny it explicitly

What must be true for NetworkPolicies to have any effect?

  1. The cluster is managed
  2. The network plugin (CNI) enforces them
  3. Pods run as root
  4. Ingress controller installed