From 1a9fab57f5fe24f16d289888aa06ee4854fc3c0a Mon Sep 17 00:00:00 2001 From: atlas Date: Fri, 27 Nov 2026 23:06:25 +0100 Subject: [PATCH] move flannel's wireguard port to 51830, advertise the node address as the tunnel endpoint, drop the 51820 assertion --- docs/4-implementation/k8s/node.md | 53 +++++++++++++---- nix/host-modules/k8s/node.nix | 86 ++++++++++++++++++--------- nix/module-eval/k8s.nix | 98 ++++++++++++++++++++++--------- nix/vm-tests/k8s-join.nix | 34 ++++++++--- 4 files changed, 194 insertions(+), 77 deletions(-) diff --git a/docs/4-implementation/k8s/node.md b/docs/4-implementation/k8s/node.md index dc7cbe244..e0e803b98 100644 --- a/docs/4-implementation/k8s/node.md +++ b/docs/4-implementation/k8s/node.md @@ -24,13 +24,19 @@ cluster of its own beyond that one main node, and it replicates no service. k3s publishes the public keys through the API server, and a node drops a frame from a host that holds no listed key, whatever address it comes from. A joined node takes the mode from the server and needs no flag. The - tunnel is the device `flannel-wg`, on UDP 51820, and the cluster is IPv4 - only, so there is no IPv6 device or port. Every node runs the same mode: - a node that runs another one doesn't reach the others' pods. A WireGuard - interface of the host's own that listens on UDP 51820, like the `wg0` of the - [semi-spread example](../../2-handbook/swarm/semi-spread-deploy.md#the-vpn-raw-wireguard), - can't share the port, and the evaluation fails when `networking.wireguard` - or `networking.wg-quick` declares one. + tunnel is the device `flannel-wg`, and the cluster is IPv4 only, so there + is no IPv6 device or port. Every node runs the same mode: a node that runs + another one doesn't reach the others' pods. +- **Tunnel port:** UDP 51830, set by `--flannel-conf`, which names a net-conf + file the module writes with the pod range (`deploy.k8s.podCidr`) and the + tunnel's `ListenPort`. k3s has no flag for the port, and flannel's own + default, 51820, is the port of the `wg0` that a host in the + [semi-spread example](../../2-handbook/swarm/semi-spread-deploy.md#the-vpn-raw-wireguard) + runs, and a host in that mesh is a cluster node as well. Every node reads + its own file, so a joined host passes the flag too and sets the same + `deploy.k8s.podCidr` as the main node. The option + `deploy.k8s.flannelWgPort` holds the port, and the firewall rule and the + tests read it. - **Images:** the node holds k3s's own images and the image of each service that [renders manifests](manifests.md) on this host, in containerd before k3s starts. No registry service exists. A pod names its image with @@ -126,12 +132,15 @@ there pulls its image from a peer. On the main node, set the addresses: - `deploy.k8s.address`: the address the other nodes reach this one on. Set, - it's the node's IP (`--node-ip`) and the API certificate lists it - (`--tls-san`). Unset, k3s picks the default route's address, as it did before - the option existed. + it's the node's IP (`--node-ip`) and its external IP (`--node-external-ip`), + the server runs `--flannel-external-ip`, and the API certificate lists it + (`--tls-san`). flannel then points the tunnel at that address. Unset, + k3s picks the default route's address for the node, and flannel binds the + tunnel to the default route's interface and advertises that interface's + address, which has to be one of the peers' `nodeAddresses`. - `deploy.k8s.nodeAddresses`: the addresses of the nodes that may join. The firewall admits these ports from them and from no other source: TCP 6443 - (the API, and the image mirror), TCP 10250 (the kubelet), UDP 51820 (flannel's + (the API, and the image mirror), TCP 10250 (the kubelet), UDP 51830 (flannel's WireGuard tunnel) and TCP 5001 (the mirror's peers). The tunnel checks the peer's key as well as its address, so the source filter is a second check. It writes iptables rules @@ -187,10 +196,28 @@ this by hand: registry.hyperhive.invalid: ``` -4. Start k3s as an agent: +4. Write the flannel net-conf, which names the tunnel's port, to + `/etc/rancher/k3s/flannel-net-conf.json`. `` is the main node's + `deploy.k8s.podCidr`: + + ```json + { + "Network": "", + "EnableIPv4": true, + "EnableIPv6": false, + "IPv6Network": "::/0", + "Backend": { + "Type": "wireguard", + "PersistentKeepaliveInterval": 25, + "ListenPort": 51830 + } + } + ``` + +5. Start k3s as an agent: ```bash - k3s agent --server https://
:6443 --token-file --node-ip + k3s agent --server https://
:6443 --token-file --node-ip --node-external-ip --flannel-conf /etc/rancher/k3s/flannel-net-conf.json ``` The machine's firewall has to admit the same four ports from the main node and diff --git a/nix/host-modules/k8s/node.nix b/nix/host-modules/k8s/node.nix index 4f5f8e9ff..be99b6937 100644 --- a/nix/host-modules/k8s/node.nix +++ b/nix/host-modules/k8s/node.nix @@ -89,12 +89,42 @@ let ${registryHost}: ''; - # flannel's WireGuard backend listens on 51820/udp for IPv4 and names its - # device `flannel-wg` (`ListenPort` and `createWGDev` in flannel v0.28's - # `pkg/backend/wireguard/wireguard.go`, the version k3s 1.35 vendors). The - # cluster is IPv4 only, so the IPv6 port and `flannel-wg-v6` do not exist. - flannelWgPort = 51820; + # flannel's WireGuard backend names its device `flannel-wg` and binds + # `ListenPort` (`createWGDev` and `RegisterNetwork` in flannel v0.28's + # `pkg/backend/wireguard/wireguard.go`, the version k3s 1.35 vendors), whose + # default, 51820, is the port of a host's own `wg0` in the semi-spread + # example. k3s writes the backend's config itself and has no option for the + # port, so the node hands it a net-conf through `--flannel-conf` + # (`pkg/executor/embed/embed.go`: a given file is used as is). The fields are + # the ones k3s's own template fills (`flannelConf` and `wireguardNativeBackend` + # in `pkg/agent/flannel/setup.go`) for an IPv4-only cluster, so there is no + # IPv6 port or `flannel-wg-v6`. + flannelWgPort = 51830; flannelWgIface = "flannel-wg"; + flannelNetConf = pkgs.writeText "flannel-net-conf.json" ( + builtins.toJSON { + Network = cfg.podCidr; + EnableIPv4 = true; + EnableIPv6 = false; + IPv6Network = "::/0"; + Backend = { + Type = "wireguard"; + PersistentKeepaliveInterval = 25; + ListenPort = flannelWgPort; + }; + } + ); + # flannel binds the tunnel to the interface of the default route and names + # that interface's address as the peers' endpoint (`LookupExtInterface` in + # k3s' `pkg/agent/flannel/flannel.go`) unless the node has an external IP and + # the server runs `--flannel-external-ip`, which makes the endpoint that IP + # (the `public-ip-overwrite` annotation, `pkg/subnet/kube/kube.go` in + # flannel). A node with an `address` advertises it, so the tunnel runs on + # the address the firewall admits whatever the default route is. + flannelFlags = [ + "--flannel-conf=${flannelNetConf}" + ] + ++ lib.optional (cfg.address != null) "--node-external-ip=${cfg.address}"; # What the nodes of a cluster reach each other on, and the firewall rules # that admit those ports from the nodes' addresses and from no others. The @@ -185,7 +215,8 @@ in ({option}`services.hyperhive.network.bridgeIp`) nor {option}`services.hyperhive.deploy.k8s.serviceCidr`, nor any network the host routes to. k3s's own default, `10.42.0.0/16`, contains the - hive bridge's default subnet. + hive bridge's default subnet. A host that joins sets the same value as + the main node: its flannel reads the range from this option. ''; }; @@ -222,6 +253,17 @@ in ''; }; + flannelWgPort = lib.mkOption { + type = lib.types.port; + readOnly = true; + internal = true; + default = flannelWgPort; + description = '' + The UDP port flannel's WireGuard tunnel listens on. The firewall admits + it from the nodes' addresses. + ''; + }; + cniInterfaces = lib.mkOption { type = lib.types.listOf lib.types.str; default = [ @@ -297,10 +339,11 @@ in example = "192.168.1.10"; description = '' The address the other nodes of the cluster reach this node on. Set, it - is the node's IP (`--node-ip`), so flannel's tunnel endpoint and the - node's registered address are it, and a server also lists it in its API + is the node's IP (`--node-ip`) and its external IP + (`--node-external-ip`), so the node's registered address and flannel's + tunnel endpoint are it, and a server also lists it in its API certificate (`--tls-san`). Null leaves k3s to pick the address of the - default route. + default route for the node and for the tunnel. ''; }; @@ -314,7 +357,7 @@ in description = '' The IPv4 addresses of the nodes that may join this cluster. The firewall admits the cluster's node-to-node ports (TCP 6443 for the API - and the image mirror, TCP 10250 for the kubelet, UDP 51820 for flannel's + and the image mirror, TCP 10250 for the kubelet, UDP ${toString flannelWgPort} for flannel's WireGuard tunnel, TCP 5001 for the mirror's peers) from these addresses and from no others. The tunnel authenticates its peers as well: a host that holds no key the cluster lists gets no frame onto the pod @@ -370,23 +413,6 @@ in services.hyperhive.deploy.k8s.enable = lib.mkDefault (enabledServices != [ ] && cfg.join == null); assertions = [ - { - assertion = - !(cfg.enable || cfg.join != null) - || !(lib.elem flannelWgPort ( - lib.catAttrs "listenPort" ( - lib.attrValues config.networking.wireguard.interfaces - ++ lib.attrValues config.networking.wg-quick.interfaces - ) - )); - message = '' - services.hyperhive.deploy.k8s runs flannel's WireGuard tunnel on UDP - ${toString flannelWgPort}, and a WireGuard interface of - networking.wireguard.interfaces or networking.wg-quick.interfaces - listens on it too: the second device cannot bind the port. Give that - interface another listenPort. - ''; - } { assertion = cfg.enable || cfg.join != null || enabledServices == [ ]; message = '' @@ -464,7 +490,9 @@ in "--cluster-domain=${clusterDomain}" "--cluster-dns=${clusterDns}" "--flannel-backend=wireguard-native" + "--flannel-external-ip" ] + ++ flannelFlags ++ lib.optional (cfg.address != null) "--tls-san=${cfg.address}"; # k3s's own images come first: the mirror holds only the hyperhive # images, so the node pulls nothing else, not even CoreDNS. @@ -519,7 +547,9 @@ in nodeIP = cfg.address; # `--flannel-backend` is a server flag: an agent takes the backend from # the server's config (`controlConfig.FlannelBackend` in k3s' - # `pkg/agent/config/config.go`), so it runs WireGuard without a flag. + # `pkg/agent/config/config.go`). The net-conf is read from the node's own + # file, so the agent names it too, with the pod range the server runs. + extraFlags = flannelFlags; # k3s's own images first, for the reason the server's are: a node with # no route to a public registry pulls nothing else. images = [ config.services.k3s.package.airgap-images ]; diff --git a/nix/module-eval/k8s.nix b/nix/module-eval/k8s.nix index abc453607..f7b9bd220 100644 --- a/nix/module-eval/k8s.nix +++ b/nix/module-eval/k8s.nix @@ -67,10 +67,21 @@ let swarm.hives.h2.domain = "h2.t.local"; }; + # The mesh interface a federated hive runs on the same host (`wg0` on UDP + # 51820, as in the semi-spread example), which the two fixtures below carry: + # a host that is a cluster node and in the mesh is the expected deployment. + semiSpreadWg = { + networking.wireguard.interfaces.wg0 = { + ips = [ "10.77.0.2/24" ]; + listenPort = 51820; + privateKeyFile = "/etc/wireguard/wg0.key"; + }; + }; + # A host that joins that cluster: an agent with the store identity its join # token is read under. The only fixture without `deploy.k8s.enable`, which # is what it claims about. - joined = hive { + joined = hiveWith [ semiSpreadWg ] { deploy.k8s.join.server = "192.168.1.10"; deploy.k8s.address = "192.168.1.11"; deploy.hive-controller.tls = { @@ -117,27 +128,16 @@ let nodeOffRefusals = lib.filter (a: !a.assertion) nodeOffRefused.assertions; # A node every assertion refuses: no rendering, a pod range containing the - # hive bridge's subnet, a service range inside the pod range, and a WireGuard - # interface on the port flannel's tunnel binds. - nodeRefused = - hiveWith - [ - { - networking.wireguard.interfaces.wg0 = { - listenPort = 51820; - privateKeyFile = "/etc/wireguard/wg0.key"; - }; - } - ] - { - deploy.k8s.enable = true; - k8s.enable = false; - network.enable = true; - deploy.k8s.podCidr = "10.42.0.0/16"; - deploy.k8s.serviceCidr = "10.42.128.0/17"; - }; + # hive bridge's subnet, and a service range inside the pod range. + nodeRefused = hive { + deploy.k8s.enable = true; + k8s.enable = false; + network.enable = true; + deploy.k8s.podCidr = "10.42.0.0/16"; + deploy.k8s.serviceCidr = "10.42.128.0/17"; + }; # The node on a host with no hive bridge, so no address to resolve names to. - nodeNoBridge = hive { deploy.k8s.enable = true; }; + nodeNoBridge = hiveWith [ semiSpreadWg ] { deploy.k8s.enable = true; }; coreDnsKey = "hyperhive-host-services.override"; refusals = lib.filter (a: !a.assertion) nodeRefused.assertions; refuses = needle: lib.any (a: hasInfix needle a.message) refusals; @@ -435,10 +435,50 @@ let && !(lib.elem "flannel.1" joined.networking.firewall.trustedInterfaces); } { - # The all-local host, with no WireGuard interface, is the control: every - # assertion holds there. - name = "the node refuses a WireGuard interface of the host's own on the port flannel's tunnel binds"; - ok = lib.all (a: a.assertion) withNode.assertions && refuses "flannel's WireGuard tunnel on UDP"; + # The mesh interface is the control that the fixtures carry what the + # case is about, and its port is what the tunnel must not take. + name = "a cluster node that is also in the semi-spread mesh evaluates, and flannel's tunnel listens on a port other than the mesh's"; + ok = + let + port = nodeNoBridge.services.hyperhive.deploy.k8s.flannelWgPort; + # The net-conf spelled out here, so the path (a hash of its text) says + # what the file holds, the tunnel's port among it. + expected = pkgs.writeText "flannel-net-conf.json" ( + builtins.toJSON { + Network = "10.200.0.0/16"; + EnableIPv4 = true; + EnableIPv6 = false; + IPv6Network = "::/0"; + Backend = { + Type = "wireguard"; + PersistentKeepaliveInterval = 25; + ListenPort = port; + }; + } + ); + flag = "--flannel-conf=${expected}"; + in + nodeNoBridge.networking.wireguard.interfaces.wg0.listenPort == 51820 + && joined.networking.wireguard.interfaces.wg0.listenPort == 51820 + && lib.all (a: a.assertion) nodeNoBridge.assertions + && lib.all (a: a.assertion) joined.assertions + && port != 51820 + && joined.services.hyperhive.deploy.k8s.flannelWgPort == port + && lib.elem flag nodeNoBridge.services.k3s.extraFlags + && lib.elem flag withNode.services.k3s.extraFlags + && lib.elem flag joined.services.k3s.extraFlags; + } + { + # Without an address, the node of the same server is the control: it + # advertises no external IP, and the tunnel follows the default route. + name = "a node with an address advertises it as its external IP so flannel's tunnel runs on it, and the server asks flannel to use external IPs"; + ok = + lib.elem "--node-external-ip=192.168.1.10" withNode.services.k3s.extraFlags + && lib.elem "--flannel-external-ip" withNode.services.k3s.extraFlags + && lib.elem "--node-external-ip=192.168.1.11" joined.services.k3s.extraFlags + && !(lib.elem "--flannel-external-ip" joined.services.k3s.extraFlags) + && lib.elem "--flannel-external-ip" nodeNoBridge.services.k3s.extraFlags + && !(lib.any (lib.hasPrefix "--node-external-ip") nodeNoBridge.services.k3s.extraFlags); } { # The names are the control that the search finds something: the swarm's @@ -2840,7 +2880,7 @@ let forNodes = address: [ (rule address "tcp" "6443") (rule address "tcp" "10250") - (rule address "udp" "51820") + (rule address "udp" (toString onCluster.services.hyperhive.deploy.k8s.flannelWgPort)) (rule address "tcp" "5001") ]; nodeLines = lib.filter (l: hasInfix "--dport" l && hasInfix "nixos-fw -s" l) ( @@ -2851,10 +2891,12 @@ let && lib.length nodeLines == 8 && !(hasInfix "--dport 6443" nodeNoBridge.networking.firewall.extraCommands) && !(lib.elem 6443 onCluster.networking.firewall.allowedTCPPorts) - && !(lib.elem 51820 onCluster.networking.firewall.allowedUDPPorts) + && !(lib.elem onCluster.services.hyperhive.deploy.k8s.flannelWgPort onCluster.networking.firewall.allowedUDPPorts) && !(hasInfix "8472" rules) && !(hasInfix "8472" joined.networking.firewall.extraCommands) - && hasInfix (rule "192.168.1.10" "udp" "51820") joined.networking.firewall.extraCommands; + && hasInfix (rule "192.168.1.10" "udp" ( + toString joined.services.hyperhive.deploy.k8s.flannelWgPort + )) joined.networking.firewall.extraCommands; } { # The main node is the control for each absence. diff --git a/nix/vm-tests/k8s-join.nix b/nix/vm-tests/k8s-join.nix index 0f390a6ec..493bc1a83 100644 --- a/nix/vm-tests/k8s-join.nix +++ b/nix/vm-tests/k8s-join.nix @@ -161,6 +161,7 @@ pkgs.testers.runNixOSTest { environment.variables.KUBECONFIG = "/etc/rancher/k3s/k3s.yaml"; environment.etc = { "k8s-join/probe-ref".text = probeRef; + "k8s-join/flannel-port".text = toString config.services.hyperhive.deploy.k8s.flannelWgPort; "k8s-join/pod-on-joiner.json".text = builtins.toJSON ( pod "on-joiner" probeRef { "kubernetes.io/hostname" = "joiner"; } ); @@ -258,6 +259,7 @@ pkgs.testers.runNixOSTest { JOIN_TOKEN = "/run/k3s-join/token" JOINER_IP = "${joinIp}" MAIN_IP = "${mainIp}" + FLANNEL_PORT = main.succeed("cat /etc/k8s-join/flannel-port").strip() PROBE_REF = main.succeed("cat /etc/k8s-join/probe-ref").strip() MISSING_REF = "${missingRef}" HOST = "${images.registryHost}" @@ -281,6 +283,7 @@ pkgs.testers.runNixOSTest { main.wait_until_succeeds(command, timeout=timeout) except Exception: diagnose(units) + print(main.execute("kubectl get pods -o wide; kubectl logs net-main")[1]) raise @@ -421,13 +424,13 @@ pkgs.testers.runNixOSTest { with subtest("the node-to-node ports are open to the joining machine's address only"): rules = main.succeed("iptables -S nixos-fw").splitlines() - for port, proto in [("6443", "tcp"), ("10250", "tcp"), ("51820", "udp"), ("5001", "tcp")]: + for port, proto in [("6443", "tcp"), ("10250", "tcp"), (FLANNEL_PORT, "udp"), ("5001", "tcp")]: matching = [r for r in rules if f"--dport {port} " in r and f"-p {proto} " in r] assert matching, (port, rules) assert all(f"-s {JOINER_IP}/32" in r for r in matching), (port, matching) assert not [r for r in rules if "--dport 8472" in r], rules joiner_rules = joiner.succeed("iptables -S nixos-fw").splitlines() - assert [r for r in joiner_rules if "--dport 51820 " in r and f"-s {MAIN_IP}/32" in r], joiner_rules + assert [r for r in joiner_rules if f"--dport {FLANNEL_PORT} " in r and f"-s {MAIN_IP}/32" in r], joiner_rules assert not [r for r in joiner_rules if "--dport 8472" in r], joiner_rules with subtest("a pod with the poller's state selector runs on the main node"): @@ -445,6 +448,7 @@ pkgs.testers.runNixOSTest { wait_running("on-joiner", 300) except AssertionError: diagnose_pull() + print(main.execute("kubectl get pods -o wide; kubectl logs net-main")[1]) raise assert pod(main, "on-joiner")["spec"]["nodeName"] == "joiner" joiner.succeed(f"k3s ctr images ls -q | grep -qxF '{containerd_name}'") @@ -461,7 +465,7 @@ pkgs.testers.runNixOSTest { keys = {} for node in [main, joiner]: assert "wireguard" in node.succeed("ip -d link show flannel-wg") - assert node.succeed("wg show flannel-wg listen-port").strip() == "51820" + assert node.succeed("wg show flannel-wg listen-port").strip() == FLANNEL_PORT node.fail("ip link show flannel.1") assert node.succeed("ss -H -lun 'sport = :8472'").strip() == "", "something listens on UDP 8472" assert "-i flannel-wg " in node.succeed("iptables -S nixos-fw") @@ -469,6 +473,12 @@ pkgs.testers.runNixOSTest { assert keys["main"] != keys["joiner"], keys assert main.succeed("wg show flannel-wg peers").split() == [keys["joiner"]] assert joiner.succeed("wg show flannel-wg peers").split() == [keys["main"]] + # The endpoint is the address the nodes reach each other on, not the + # default route's: the test machines' default route is a private network + # of their own that reaches no peer. + for node, peer_key, peer_ip in [(main, keys["joiner"], JOINER_IP), (joiner, keys["main"], MAIN_IP)]: + endpoints = dict(l.split() for l in node.succeed("wg show flannel-wg endpoints").splitlines()) + assert endpoints == {peer_key: f"{peer_ip}:{FLANNEL_PORT}"}, endpoints with subtest("a pod on the joining machine fetches a page from a pod on the main node, through the tunnel"): main.succeed("kubectl apply -f /etc/k8s-join/pod-net-main.json -f /etc/k8s-join/pod-net-joiner.json") @@ -477,11 +487,19 @@ pkgs.testers.runNixOSTest { assert pod(main, "net-main")["spec"]["nodeName"] == "main" assert pod(main, "net-joiner")["spec"]["nodeName"] == "joiner" target = pod(main, "net-main")["status"]["podIP"] + url = f"http://{target}:${toString netPort}/" + # The server answers inside its own pod: the control that a failure below + # is the network's. + main.wait_until_succeeds("kubectl exec net-main -- wget -qO- -T 5 http://127.0.0.1:${toString netPort}/ | grep -qx ${netPage}", timeout=60) before = wg_transfer(joiner, "flannel-wg") - main.wait_until_succeeds( - f"kubectl exec net-joiner -- wget -qO- -T 5 http://{target}:${toString netPort}/ | grep -qx ${netPage}", - timeout=180, - ) + try: + main.wait_until_succeeds(f"kubectl exec net-joiner -- wget -qO- -T 5 {url} | grep -qx ${netPage}", timeout=120) + except Exception: + for node in [main, joiner]: + print(f"--- {node.name}") + print(node.execute("wg show flannel-wg; ip -4 route; ip -s link show flannel-wg; iptables -S FORWARD; iptables -S nixos-fw")[1]) + print(main.execute("kubectl get pods -o wide; kubectl logs net-main")[1]) + raise after = wg_transfer(joiner, "flannel-wg") assert after[0] > before[0] and after[1] > before[1], (before, after) for node in [main, joiner]: @@ -495,7 +513,7 @@ pkgs.testers.runNixOSTest { main.succeed( "ip link add rogue type wireguard && " f"wg set rogue private-key /root/rogue.key listen-port 51999 peer {keys['joiner']} " - f"endpoint {JOINER_IP}:51820 allowed-ips {victim}/32 && " + f"endpoint {JOINER_IP}:{FLANNEL_PORT} allowed-ips {victim}/32 && " "ip addr add 10.99.0.1/32 dev rogue && ip link set rogue up && " f"ip route add {victim}/32 dev rogue" )