Watch
0
0
Fork
You've already forked hyperhive
0

run flannel's wireguard-native backend on every k8s node

This commit is contained in:
atlas 2026-11-27 22:48:56 +01:00 • committed by mara
commit d09e2b403c
6 changed files with 225 additions and 29 deletions

View file

@ -18,6 +18,19 @@ cluster of its own beyond that one main node, and it replicates no service.
metrics-server are off, and the cluster encrypts its Secrets at rest
(`--secrets-encryption`). CoreDNS and the local-path provisioner stay on, so
pods have cluster DNS and PersistentVolumeClaims.
- **Pod network:** flannel's `wireguard-native` mode
(`--flannel-backend=wireguard-native`), so the traffic between nodes is
encrypted and authenticated. Each node holds a WireGuard key of its own,
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.
- **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
@ -33,7 +46,7 @@ cluster of its own beyond that one main node, and it replicates no service.
evaluation fails when one does: the bridge and the cluster would route the
same addresses. k3s's own default pod range, `10.42.0.0/16`, contains the
bridge's default subnet.
- **Firewall:** the pod network's interfaces, `cni0` and `flannel.1`, are
- **Firewall:** the pod network's interfaces, `cni0` and `flannel-wg`, are
trusted, so the node reaches its pods. The node-to-node ports are open to
the addresses in `deploy.k8s.nodeAddresses` only, which is empty by default
([Joining nodes](#joining-nodes)).
@ -118,8 +131,10 @@ On the main node, set the addresses:
the option existed.
- `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 8472 (flannel's
VXLAN tunnel) and TCP 5001 (the mirror's peers). It writes iptables rules
(the API, and the image mirror), TCP 10250 (the kubelet), UDP 51820 (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
and refuses a host with `networking.nftables.enable`. With the list empty,
no port is open.
@ -240,7 +255,7 @@ token against the node's own signing keys.
certificate and asks for no client certificate. A pod dials it by the name it
dials the store by, `bao.<swarm domain>`, which CoreDNS answers with the
bridge's address.
- **Firewall:** that port is open on `cni0` and `flannel.1` and on no other
- **Firewall:** that port is open on `cni0` and `flannel-wg` and on no other
interface. The bridge's firewall refuses it, so an agent on the bridge can't
connect. Binding an address doesn't isolate a port, because the kernel
accepts a packet for any local address on any interface, so the firewall

View file

@ -89,6 +89,13 @@ 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;
flannelWgIface = "flannel-wg";
# 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
# `extraCommands` run before the firewall's final refusal.
@ -103,7 +110,7 @@ let
}
{
proto = "udp";
port = 8472;
port = flannelWgPort;
}
{
proto = "tcp";
@ -164,7 +171,7 @@ in
stay off. Pods and services take their
addresses from {option}`services.hyperhive.deploy.k8s.podCidr` and
{option}`services.hyperhive.deploy.k8s.serviceCidr`. The firewall
trusts the pod network's interfaces (`cni0`, `flannel.1`), so the node
trusts the pod network's interfaces (`cni0`, `flannel-wg`), so the node
reaches its pods.
'';
};
@ -219,7 +226,7 @@ in
type = lib.types.listOf lib.types.str;
default = [
"cni0"
"flannel.1"
flannelWgIface
];
readOnly = true;
internal = true;
@ -307,9 +314,11 @@ 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 8472 for flannel's
VXLAN tunnel, TCP 5001 for the mirror's peers) from these addresses
and from no others. Empty opens none of them. The firewall's
and the image mirror, TCP 10250 for the kubelet, UDP 51820 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
network, whatever address it sends from. Empty opens none of them. The firewall's
iptables backend is required: the rules are not written for nftables.
'';
};
@ -361,6 +370,23 @@ 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 = ''
@ -437,6 +463,7 @@ in
"--data-dir=${dataDir}"
"--cluster-domain=${clusterDomain}"
"--cluster-dns=${clusterDns}"
"--flannel-backend=wireguard-native"
]
++ lib.optional (cfg.address != null) "--tls-san=${cfg.address}";
# k3s's own images come first: the mirror holds only the hyperhive
@ -490,6 +517,9 @@ in
serverAddr = "https://${cfg.join.server}:6443";
tokenFile = joinToken.file;
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.
# 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 ];

View file

@ -26,6 +26,7 @@ let
})
runGroup
hive
hiveWith
hiveWithController
baoSettings
bridgePorts
@ -116,14 +117,25 @@ 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, 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";
};
# 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";
};
# The node on a host with no hive bridge, so no address to resolve names to.
nodeNoBridge = hive { deploy.k8s.enable = true; };
coreDnsKey = "hyperhive-host-services.override";
@ -358,7 +370,8 @@ let
&& withNode.services.k3s.role == "server"
&& withNode.systemd.services ? k3s
&& lib.elem "cni0" withNode.networking.firewall.trustedInterfaces
&& lib.elem "flannel.1" withNode.networking.firewall.trustedInterfaces;
&& lib.elem "flannel-wg" withNode.networking.firewall.trustedInterfaces
&& !(lib.elem "flannel.1" withNode.networking.firewall.trustedInterfaces);
}
{
name = "the node runs k3s with traefik and metrics-server off and its secrets encrypted";
@ -407,6 +420,26 @@ let
&& refuses "overlap the hive bridge"
&& refuses "overlap each other";
}
{
# An agent takes the backend from its server, and `--flannel-backend` is
# a server flag that an agent refuses, so the agent's flags carry none.
# The agent is the control that the lookup reads the flag list.
name = "the server runs flannel's WireGuard backend, and the joined agent sets no backend flag";
ok =
lib.elem "--flannel-backend=wireguard-native" withNode.services.k3s.extraFlags
&& lib.elem "--flannel-backend=wireguard-native" nodeNoBridge.services.k3s.extraFlags
&& !(lib.any (lib.hasPrefix "--flannel-backend") joined.services.k3s.extraFlags)
&& lib.elem "--embedded-registry" withNode.services.k3s.extraFlags
&& joined.services.k3s.role == "agent"
&& lib.elem "flannel-wg" joined.networking.firewall.trustedInterfaces
&& !(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 names are the control that the search finds something: the swarm's
# own bao name and the hive domain are among them, and every one is in the
@ -740,7 +773,7 @@ let
&& !(hasInfix "swarm-bao-k8s-jwt-policy" off.serviceConfig.ExecStartPost)
&& hasInfix "swarm-bao-operator-viewer-policy" off.serviceConfig.ExecStartPost
&& !(noNode.networking.firewall.interfaces ? cni0)
&& !(noNode.networking.firewall.interfaces ? "flannel.1");
&& !(noNode.networking.firewall.interfaces ? "flannel-wg");
}
{
# Pods log in on a listener that asks for no client certificate, and no
@ -778,7 +811,7 @@ let
in
cni == [
"cni0"
"flannel.1"
"flannel-wg"
]
&& lib.all (i: lib.elem 8208 (portsOn i)) cni
&& lib.all (i: lib.elem i cni || !(lib.elem 8208 (portsOn i))) (lib.attrNames fw.interfaces)
@ -2807,7 +2840,7 @@ let
forNodes = address: [
(rule address "tcp" "6443")
(rule address "tcp" "10250")
(rule address "udp" "8472")
(rule address "udp" "51820")
(rule address "tcp" "5001")
];
nodeLines = lib.filter (l: hasInfix "--dport" l && hasInfix "nixos-fw -s" l) (
@ -2818,7 +2851,10 @@ let
&& lib.length nodeLines == 8
&& !(hasInfix "--dport 6443" nodeNoBridge.networking.firewall.extraCommands)
&& !(lib.elem 6443 onCluster.networking.firewall.allowedTCPPorts)
&& !(lib.elem 8472 onCluster.networking.firewall.allowedUDPPorts);
&& !(lib.elem 51820 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;
}
{
# The main node is the control for each absence.

View file

@ -365,7 +365,7 @@ pkgs.testers.runNixOSTest {
rules = machine.succeed("iptables -S nixos-fw")
port_rules = [r for r in rules.splitlines() if f"--dport {POD_PORT}" in r]
assert port_rules, rules
assert all("-i cni0 " in r or "-i flannel.1 " in r for r in port_rules), port_rules
assert all("-i cni0 " in r or "-i flannel-wg " in r for r in port_rules), port_rules
bridge_rules = [r for r in rules.splitlines() if "-i hive-br0 " in r and "--dport" in r]
assert any(f"--dport {CONTROL_PORT}" in r for r in bridge_rules), rules
assert not any(f"--dport {POD_PORT}" in r for r in bridge_rules), bridge_rules

View file

@ -10,7 +10,12 @@
# - the joining machine goes Ready, carries no `state-*`, `entry` or
# `enablelb` label, and the main node carries them;
# - the node-to-node ports are open on the main node from the joining
# machine's address only;
# machine's address only, and VXLAN's 8472 is open on neither node;
# - the pod network is flannel's WireGuard tunnel (`flannel-wg`, no `flannel.1`):
# each node holds the other's key and has shaken hands, a pod on the joining
# machine fetches a page from a pod on the main node through it, and a peer
# with a key of its own, sending from the main node's own address, gets no
# handshake and no answer;
# - a pod with the `state-ci-metrics` selector, the one the poller's pod
# carries, runs on the main node, and a pod forced onto the joining machine
# pulls its image from the main node through the embedded registry mirror
@ -47,6 +52,33 @@ let
probeRef = "${probeImage.imageName}:${probeImage.imageTag}";
missingRef = "${images.registryHost}/nobody-has-this:v1";
# A shell and `wget`, in both nodes' containerd, so a pod on each node can
# talk to the other's.
netImage = pkgs.dockerTools.buildLayeredImage {
name = "k8s-join-net";
tag = "test";
contents = [ pkgs.busybox ];
};
netPort = 8080;
netPage = "page-of-the-pod-on-main";
netPod = name: node: command: {
apiVersion = "v1";
kind = "Pod";
metadata = { inherit name; };
spec = {
nodeSelector."kubernetes.io/hostname" = node;
restartPolicy = "Never";
containers = [
{
name = "net";
image = "${netImage.imageName}:${netImage.imageTag}";
imagePullPolicy = "Never";
inherit command;
}
];
};
};
pod = name: image: selector: {
apiVersion = "v1";
kind = "Pod";
@ -116,11 +148,15 @@ pkgs.testers.runNixOSTest {
networking.hosts."127.0.0.1" = [ baoName ];
networking.firewall.allowedTCPPorts = [ baoPort ];
services.k3s.images = [ probeImage ];
services.k3s.images = [
probeImage
netImage
];
environment.systemPackages = [
pkgs.kubectl
pkgs.jq
pkgs.openssl
pkgs.wireguard-tools
];
environment.variables.KUBECONFIG = "/etc/rancher/k3s/k3s.yaml";
environment.etc = {
@ -134,6 +170,19 @@ pkgs.testers.runNixOSTest {
"k8s-join/pod-missing.json".text = builtins.toJSON (
pod "missing" missingRef { "kubernetes.io/hostname" = "joiner"; }
);
"k8s-join/pod-net-main.json".text = builtins.toJSON (
netPod "net-main" "main" [
"sh"
"-c"
"mkdir /www && echo ${netPage} > /www/index.html && exec httpd -f -p ${toString netPort} -h /www"
]
);
"k8s-join/pod-net-joiner.json".text = builtins.toJSON (
netPod "net-joiner" "joiner" [
"sleep"
"3600"
]
);
};
networking.interfaces.eth1.ipv4.addresses = lib.mkForce [
@ -185,7 +234,11 @@ pkgs.testers.runNixOSTest {
}
];
environment.systemPackages = [ pkgs.jq ];
services.k3s.images = [ netImage ];
environment.systemPackages = [
pkgs.jq
pkgs.wireguard-tools
];
virtualisation = {
memorySize = 3072;
@ -204,6 +257,7 @@ pkgs.testers.runNixOSTest {
SERVER_TOKEN = "/var/lib/rancher/k3s/server/agent-token"
JOIN_TOKEN = "/run/k3s-join/token"
JOINER_IP = "${joinIp}"
MAIN_IP = "${mainIp}"
PROBE_REF = main.succeed("cat /etc/k8s-join/probe-ref").strip()
MISSING_REF = "${missingRef}"
HOST = "${images.registryHost}"
@ -367,10 +421,14 @@ 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"), ("8472", "udp"), ("5001", "tcp")]:
for port, proto in [("6443", "tcp"), ("10250", "tcp"), ("51820", "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 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"):
main.succeed("kubectl apply -f /etc/k8s-join/pod-stateful.json")
@ -393,6 +451,63 @@ pkgs.testers.runNixOSTest {
events = kube(main, "get events --field-selector involvedObject.name=on-joiner -o json")
assert any(e["reason"] == "Pulled" for e in json.loads(events)["items"]), events
def wg_transfer(node: QemuMachine, dev: str) -> tuple[int, int]:
"""Bytes received and sent over the device's only peer."""
fields = node.succeed(f"wg show {dev} transfer").split()
assert len(fields) == 3, fields
return int(fields[1]), int(fields[2])
with subtest("the pod network is flannel's WireGuard tunnel, each node holds the other's key, and VXLAN is gone"):
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"
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")
keys[node.name] = node.succeed("wg show flannel-wg public-key").strip()
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"]]
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")
wait_pod(main, "net-main", phase="Running", ready=True, timeout=180)
wait_pod(main, "net-joiner", phase="Running", ready=True, timeout=180)
assert pod(main, "net-main")["spec"]["nodeName"] == "main"
assert pod(main, "net-joiner")["spec"]["nodeName"] == "joiner"
target = pod(main, "net-main")["status"]["podIP"]
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,
)
after = wg_transfer(joiner, "flannel-wg")
assert after[0] > before[0] and after[1] > before[1], (before, after)
for node in [main, joiner]:
stamps = [int(s) for s in node.succeed("wg show flannel-wg latest-handshakes").split()[1::2]]
assert stamps and all(s > 0 for s in stamps), stamps
with subtest("a peer with a key of its own, sending from the main node's address, gets no handshake and no answer"):
victim = pod(main, "net-joiner")["status"]["podIP"]
rogue_pub = main.succeed("wg genkey | tee /root/rogue.key | wg pubkey").strip()
assert rogue_pub not in keys.values()
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 && "
"ip addr add 10.99.0.1/32 dev rogue && ip link set rogue up && "
f"ip route add {victim}/32 dev rogue"
)
status, _ = main.execute(f"ping -I rogue -c 5 -W 2 {victim}")
assert status != 0, "a peer without a listed key got an answer"
received, sent = wg_transfer(main, "rogue")
assert sent > 0, "the control: the rogue peer sent its handshake"
assert received == 0, received
assert main.succeed("wg show rogue latest-handshakes").split()[1] == "0"
assert rogue_pub not in joiner.succeed("wg show flannel-wg peers")
main.succeed("ip link del rogue")
with subtest("an image no node holds fails to pull, naming the images' host and not docker.io"):
main.succeed("kubectl apply -f /etc/k8s-join/pod-missing.json")
main.wait_until_succeeds(

View file

@ -211,7 +211,7 @@ pkgs.testers.runNixOSTest {
with subtest("the firewall trusts the pod network and guards the other interfaces"):
rules = machine.succeed("iptables -S nixos-fw")
assert "-i cni0 " in rules, rules
assert "-i flannel.1 " in rules, rules
assert "-i flannel-wg " in rules, rules
assert "-i lo " in rules, rules
assert "-i eth0 " not in rules, rules