From 51ae57fb021f90c302bdc5f0f475dc400d37abca Mon Sep 17 00:00:00 2001 From: atlas Date: Fri, 27 Nov 2026 15:10:15 +0100 Subject: [PATCH] k8s: deny ingress to every pod by default --- docs/4-implementation/k8s/manifests.md | 23 +++-- docs/4-implementation/k8s/node.md | 9 +- nix/host-modules/k8s/default.nix | 8 +- nix/host-modules/k8s/render.nix | 22 +++++ nix/host-modules/k8s/runtime.nix | 2 +- nix/module-eval/k8s.nix | 46 +++++++++- nix/vm-tests/k8s-controller.nix | 26 +++++- nix/vm-tests/k8s-nats.nix | 12 +++ nix/vm-tests/k8s-services.nix | 120 ++++++++++++++++++++++--- 9 files changed, 241 insertions(+), 27 deletions(-) diff --git a/docs/4-implementation/k8s/manifests.md b/docs/4-implementation/k8s/manifests.md index b280afac6..f13222a5c 100644 --- a/docs/4-implementation/k8s/manifests.md +++ b/docs/4-implementation/k8s/manifests.md @@ -31,7 +31,9 @@ A service gets manifests on the host whose configuration deploys it: | `swarm-victorialogs` | Deployment | Service, NetworkPolicy, PersistentVolume and Claim | | `swarm-logs-auth` | Deployment | ServiceAccount, two Services, NetworkPolicy | -`namespace.yaml` holds the Namespace ([Pod Security](#pod-security)). +`namespace.yaml` holds the Namespace ([Pod Security](#pod-security)), and +`default-deny-ingress/networkpolicy.yaml` its default-deny ingress policy +([Network](#pods)). ## One source: the unit @@ -129,16 +131,25 @@ credential directory. provider (`identity`), the queue's port (`queue`) and the hive collector's (`collector`). The policy allows its pod on the queue's port too. The node trusts the pod network's interfaces, so without the policy a pod reaches every port of - the host. A service without `egress` has no - policy. A service with a listener and `egress` (`swarm-logs-auth`) has the one - policy: it admits the node to the listener and nothing else, and allows the - egress above. + the host. A service with neither `egress` nor a listener has no policy of + its own and relies on the namespace's `default-deny-ingress`, which selects + every pod and admits nobody. The cluster's policy engine takes the union of + the policies that select a pod and always admits the node's own addresses, so + the node reaches a pod, and so does whatever its own policy names. A service with + a listener and `egress` (`swarm-logs-auth`) has the one policy: it admits the + node to the listener and nothing else, and allows the egress above. - **Probes:** a service with an opt-in health listener gets its variable set to `0.0.0.0:8080`, with liveness on `/healthz` and readiness on `/readyz` (see [Readiness checks](../swarm/readiness.md)). `swarm-controller` is one of them, with `SWARM_CONTROLLER_HEALTH_ADDR`. A third-party daemon with no health variable, `victoria-logs`, names a `probe` path instead (`/health`), which both probes - request on its listener. + request on its listener. The health port takes no credential, because the + kubelet's probes carry none and the routes answer a status code with no body. + Only the node reaches it, through the namespace's default-deny + ingress policy and the pod's own policy, which admit no other pod and no + client of the bridge. The port is an exception to mara's ruling ("if you can reach + it, even just in the cluster, it needs auth"): the kubelet has no credential + to send. - **Listener and init container:** a service with a TCP `listener` (`swarm-controller`, with `swarm.controller.tcp.enable`) publishes its port with a ClusterIP Service, admits only the node to it with a NetworkPolicy, and diff --git a/docs/4-implementation/k8s/node.md b/docs/4-implementation/k8s/node.md index a817a32d2..a9548fb9c 100644 --- a/docs/4-implementation/k8s/node.md +++ b/docs/4-implementation/k8s/node.md @@ -37,9 +37,12 @@ cluster of its own beyond that one main node, and it replicates no service. the addresses in `deploy.k8s.nodeAddresses` only, which is empty by default ([Joining nodes](#joining-nodes)). - **NetworkPolicy:** k3s's own controller (kube-router, iptables) enforces - NetworkPolicy objects; the node doesn't turn it off. A pod no policy selects - reaches whatever it can route to. [The manifests](manifests.md#pods) say which - pods have one. + NetworkPolicy objects; the node doesn't turn it off. The namespace has one + policy, `default-deny-ingress`, that selects every pod and admits nobody, so + the node's own addresses reach a pod, and so does whatever a policy of its + own admits. Other pods and the bridge's agents don't reach a port a pod opens + later until a policy names it. [The manifests](manifests.md#pods) + say which pods have a policy of their own. - **Secret store:** the store gets a second listener and an auth mount for the pods' ServiceAccount tokens, described under [Logging in to the secret store](#logging-in-to-the-secret-store). diff --git a/nix/host-modules/k8s/default.nix b/nix/host-modules/k8s/default.nix index 91187d56e..9a68bfd74 100644 --- a/nix/host-modules/k8s/default.nix +++ b/nix/host-modules/k8s/default.nix @@ -57,7 +57,8 @@ in internal = true; description = '' What ./runtime.nix applies: each enabled service's - objects, the namespace object, and the CA ConfigMap's name + objects, the namespace's own objects (the namespace and its + default-deny ingress policy), and the CA ConfigMap's name and host files. ''; }; @@ -72,7 +73,10 @@ in userNamespaces ; services = withoutContext rendered.services; - namespaceObject = withoutContext rendered.objects.namespace; + namespaceObjects = withoutContext [ + rendered.objects.namespace + rendered.objects."default-deny-ingress/networkpolicy" + ]; }; # The images those pods run, for a node to load: ./node.nix. diff --git a/nix/host-modules/k8s/render.nix b/nix/host-modules/k8s/render.nix index 35c0c662e..81787d913 100644 --- a/nix/host-modules/k8s/render.nix +++ b/nix/host-modules/k8s/render.nix @@ -1190,6 +1190,28 @@ in }; }; } + # Every pod of the namespace is selected for ingress and no rule admits + # anyone, so a pod is reachable from the node alone until a policy of its own + # admits more. The cluster's policy engine takes the union of the policies + # that select a pod and always admits the node's own addresses, so the + # kubelet's probes and the host's gateway still reach every pod. A port a pod + # opens later is closed to the other pods and to the hive bridge without a + # line here. + // { + "default-deny-ingress/networkpolicy" = { + apiVersion = "networking.k8s.io/v1"; + kind = "NetworkPolicy"; + metadata = { + name = "default-deny-ingress"; + inherit (k8sCfg) namespace; + labels."app.kubernetes.io/part-of" = "hyperhive"; + }; + spec = { + podSelector = { }; + policyTypes = [ "Ingress" ]; + }; + }; + } // lib.concatMapAttrs (_: w: w.objects) enabled; # The image each enabled service's pod runs: what the main node imports, diff --git a/nix/host-modules/k8s/runtime.nix b/nix/host-modules/k8s/runtime.nix index 4c9c2840d..a0f8e556e 100644 --- a/nix/host-modules/k8s/runtime.nix +++ b/nix/host-modules/k8s/runtime.nix @@ -59,7 +59,7 @@ in # configuration drops before it activates the new configuration, and # the files are linked in by the activation. services.k3s.manifests = { - hyperhive-namespace.content = rendered.namespaceObject; + hyperhive-namespace.content = rendered.namespaceObjects; } // lib.genAttrs onCluster (name: { content = lib.attrValues rendered.services.${name}.objects; diff --git a/nix/module-eval/k8s.nix b/nix/module-eval/k8s.nix index 8410089e4..f00f01cce 100644 --- a/nix/module-eval/k8s.nix +++ b/nix/module-eval/k8s.nix @@ -820,7 +820,11 @@ let "swarm-stt" "swarm-victorialogs" ] - && onCluster.services.k3s.manifests.hyperhive-namespace.content.kind == "Namespace" + && + map (o: o.kind) onCluster.services.k3s.manifests.hyperhive-namespace.content == [ + "Namespace" + "NetworkPolicy" + ] && lib.sort lib.lessThan (map (o: o.kind) onCluster.services.k3s.manifests.swarm-notify-router.content) == [ @@ -965,6 +969,39 @@ let "swarm-ci-metrics" ]; } + { + # The policy is pinned by value: an empty selector is the property, since + # a `matchLabels` would leave every pod it does not name open, and a rule + # would admit someone. The pods the lists name have no ingress policy of + # their own and rely on it; the speech-to-text pod and the controller are + # the controls that the lookup finds a pod's own policy. + name = "the namespace has a default-deny ingress policy that selects every pod and admits nobody, and the pods without an ingress policy of their own rely on it"; + ok = + let + policy = objects."default-deny-ingress/networkpolicy"; + manifest = onCluster.services.k3s.manifests.hyperhive-namespace.content; + ownPolicy = name: objects ? "${name}/networkpolicy"; + in + policy.kind == "NetworkPolicy" + && policy.metadata.namespace == "hyperhive" + && + policy.spec == { + podSelector = { }; + policyTypes = [ "Ingress" ]; + } + && lib.elem policy manifest + && lib.all (name: !(ownPolicy name)) [ + "swarm-notify-router" + "swarm-review-classifier" + "swarm-claude-login" + "swarm-ci-metrics" + ] + && lib.all ownPolicy [ + "swarm-stt" + "swarm-controller" + "swarm-nats" + ]; + } { # The policy is pinned by value: the ports are literals, not the options # the render reads. The router's pod is the control that a service @@ -1040,12 +1077,13 @@ let ports = [ (tcp 4222) ]; } ] - # Only the controller (its listener), the log store and its responders - # (listeners), the queue and this pod have a policy: the others have no - # egress and no listener. + # The namespace's default, the controller (its listener), the log store + # and its responders (listeners), the queue and this pod have a policy: + # the others have no egress and no listener, and rely on the default. && lib.sort lib.lessThan (lib.filter (n: lib.hasSuffix "/networkpolicy" n) (lib.attrNames objects)) == [ + "default-deny-ingress/networkpolicy" "swarm-controller/networkpolicy" "swarm-logs-auth/networkpolicy" "swarm-nats/networkpolicy" diff --git a/nix/vm-tests/k8s-controller.nix b/nix/vm-tests/k8s-controller.nix index f9af1c3bd..6ac151c64 100644 --- a/nix/vm-tests/k8s-controller.nix +++ b/nix/vm-tests/k8s-controller.nix @@ -28,6 +28,7 @@ let inherit (pkgs) lib; bridgeIp = "10.42.0.1"; + agentIp = "10.42.0.200"; baoName = "bao.t.local"; baoPort = 8200; podPort = 8208; @@ -135,7 +136,10 @@ pkgs.testers.runNixOSTest { nodes.machine = { config, ... }: { - imports = [ self.nixosModules.default ]; + imports = [ + self.nixosModules.default + ./lib/agent-netns.nix + ]; services.hyperhive = { deploy.k8s.enable = true; @@ -544,6 +548,26 @@ pkgs.testers.runNixOSTest { for _ in range(3): assert machine.execute(dials(other, ip, PORT))[0] != 0 + with subtest("a client of the hive bridge and another pod cannot reach the controller's pod, and the node reads its health port"): + deny = json.loads(kube(machine, "get networkpolicy default-deny-ingress -o json"))["spec"] + assert deny == {"podSelector": {}, "policyTypes": ["Ingress"]}, deny + bridge_if = machine.succeed("ip -o -4 addr show | grep -F 'inet ${bridgeIp}/' | cut -d' ' -f2").strip() + machine.succeed( + "ip link add va type veth peer name vb && ip link set vb netns agent " + f"&& ip link set va master {bridge_if} && ip link set va up " + "&& ip -n agent addr add ${agentIp}/24 dev vb && ip -n agent link set vb up && ip -n agent link set lo up " + "&& ip -n agent route add default via ${bridgeIp}" + ) + pod_ip = kube(machine, f"get pod {pod_name} -o jsonpath='{{.status.podIP}}'").strip() + code = machine.succeed(f"curl -s -o /dev/null -w '%{{http_code}}' --max-time 5 http://{pod_ip}:8080/healthz").strip() + assert code == "200", code + # The listener is reached by the node's own dial, the control that the + # refusals below are the policy's. + machine.succeed(f"timeout 5 bash -c ' str: + return f"ip netns exec agent timeout 5 bash -c ' str: + return kube(machine, f"get pod {name} -o jsonpath='{{.status.podIP}}'").strip() + + peers = {name: pod_pid(name) for name in (SERVICE, CLASSIFIER, LOGIN)} + coredns_pid = pod_pid("coredns") + health = { + SERVICE: (pod_ip(service_pods(SERVICE)[0].removeprefix("pod/")), [8080]), + STT: (stt_ip, [8080]), + CLASSIFIER: (pod_ip(DAEMON_PODS[CLASSIFIER]), [8080]), + LOGIN: (pod_ip(DAEMON_PODS[LOGIN]), [8080]), + LOGS_AUTH: (auth_ip, [8080, 8083]), + } + # Every listener the pods open: the health ports, the store, and the + # responders' own. + listeners = { + **health, + VL: (vl_ip, [9428]), + LOGS_AUTH: (auth_ip, [8080, 8081, 8082, 8083]), + } + + def sources(target: str): + peer = next(pid for name, pid in peers.items() if name != target) + return { + "a pod of kube-system": lambda ip, port: dials(coredns_pid, ip, port), + "a peer pod of the namespace": lambda ip, port: dials(peer, ip, port), + "a client of the hive bridge": agent_dials, + } + + # The node answers each health port with a status and no body, the + # control that every dial below refuses a port that is open. + for name, (ip, ports) in health.items(): + for port in ports: + code = machine.succeed(f"curl -s -o /dev/null -w '%{{http_code}}' --max-time 5 http://{ip}:{port}/healthz").strip() + assert code == "200", (name, port, code) + machine.succeed(f"curl -sf --max-time 5 http://{vl_ip}:9428/health") + for name, (ip, ports) in listeners.items(): + for port in ports: + machine.succeed(f"timeout 5 bash -c '