From a7b294eede76dfc924436b5908042edcdf259223 Mon Sep 17 00:00:00 2001 From: Giacomo Sanchietti Date: Thu, 3 Dec 2026 17:15:16 +0100 Subject: [PATCH] feat(vpn): add a preshared key to the cluster VPN A WireGuard preshared key mixed into the handshake protects recorded cluster VPN traffic against a future quantum computer. The leader keeps one preshared key for the whole cluster, in /etc/nethserver/wg0.psk (mode 600) and in Redis at private/nodes/vpn_psk. create-cluster makes it; add-node makes it if missing. A joining node asks for it with the new add-node input vpn_psk, gets it as vpn_preshared_key and writes it in its first wg0.conf. add-node marks the node with "psk" in node//vpn. apply-vpn-routes reads the replica as the cluster user, writes the key file from Redis if it is missing or different (leader change), and sets the key on the links of flagged workers only. Nodes that do not ask for the key, like older workers and the NS7 migration tool, work as before. Assisted-by: Claude Code:claude-opus-5-5 --- .../usr/local/agent/pypkg/cluster/vpn.py | 33 +++++++++++++++++++ .../imageroot/usr/local/sbin/apply-vpn-routes | 23 +++++++++++-- .../cluster/actions/add-node/50update | 17 +++++++--- .../actions/add-node/validate-input.json | 4 +++ .../actions/add-node/validate-output.json | 5 +++ .../cluster/actions/create-cluster/50update | 5 ++- .../cluster/actions/join-cluster/50update | 3 +- .../actions/join-node/30start_replication | 4 +++ .../actions/join-node/validate-input.json | 5 +++ docs/core/database.md | 2 ++ docs/core/vpn.md | 6 ++++ 11 files changed, 99 insertions(+), 8 deletions(-) diff --git a/core/imageroot/usr/local/agent/pypkg/cluster/vpn.py b/core/imageroot/usr/local/agent/pypkg/cluster/vpn.py index cb47285f3e..5a9c4c5063 100644 --- a/core/imageroot/usr/local/agent/pypkg/cluster/vpn.py +++ b/core/imageroot/usr/local/agent/pypkg/cluster/vpn.py @@ -5,6 +5,37 @@ import os import socket +import subprocess + +PSK_PATH = '/etc/nethserver/wg0.psk' +PSK_REDIS_KEY = 'private/nodes/vpn_psk' + +def write_psk(psk, path=PSK_PATH): + """Write the cluster VPN preshared key to a root-only file""" + fd = os.open(path + '.new', os.O_WRONLY | os.O_CREAT | os.O_TRUNC, 0o600) + os.fchmod(fd, 0o600) # in case the file already existed + with os.fdopen(fd, 'w') as fpsk: + fpsk.write(psk + '\n') + os.rename(path + '.new', path) + +def read_psk(path=PSK_PATH): + """Return the cluster VPN preshared key from file, or an empty string""" + try: + with open(path) as fpsk: + return fpsk.read().strip() + except FileNotFoundError: + return '' + +def ensure_psk(rdb, path=PSK_PATH): + """Return the cluster VPN preshared key. Generate it if missing, and + store it both in Redis and in a root-only file. Leader only.""" + psk = rdb.get(PSK_REDIS_KEY) or read_psk(path) + if not psk: + psk = subprocess.run(['wg', 'genpsk'], stdout=subprocess.PIPE, text=True, check=True).stdout.strip() + if read_psk(path) != psk: + write_psk(psk, path) + rdb.setnx(PSK_REDIS_KEY, psk) + return psk def initialize_wgconf(ipaddr, listen_port=55820, peer=None): """Initialize wg0.conf to bootstrap the VPN link. The file is then @@ -40,6 +71,8 @@ def initialize_wgconf(ipaddr, listen_port=55820, peer=None): wgconf.write(f"[Peer]\n") wgconf.write(f"PublicKey = {peer['public_key']}\n") + if peer.get('preshared_key'): + wgconf.write(f"PresharedKey = {peer['preshared_key']}\n") wgconf.write(f"AllowedIPs = {peer['ip_address']}\n") wgconf.write(f"PersistentKeepalive = 25\n") wgconf.write(f"Endpoint = {peer_ep_address}:{peer_port}\n") diff --git a/core/imageroot/usr/local/sbin/apply-vpn-routes b/core/imageroot/usr/local/sbin/apply-vpn-routes index e6f68e643d..ec669c07c0 100755 --- a/core/imageroot/usr/local/sbin/apply-vpn-routes +++ b/core/imageroot/usr/local/sbin/apply-vpn-routes @@ -9,6 +9,7 @@ # routing table, update Wireguard routing (AllowedIPs) setup. import agent +import cluster.vpn import os import sys import socket @@ -19,10 +20,11 @@ import ipaddress as ipm self_id = int(os.environ['NODE_ID']) # Connect to the local Redis replica and read VPN configuration of each -# node: -with agent.redis_connect(use_replica=True) as rdb: +# node. Privileged access is required to read the VPN preshared key: +with agent.redis_connect(use_replica=True, privileged=True) as rdb: leader_id = int(rdb.hget('cluster/environment', 'NODE_ID')) cluster_network = rdb.get('cluster/network') + vpn_psk = rdb.get(cluster.vpn.PSK_REDIS_KEY) peers = {} for pkey in rdb.scan_iter('node/*/vpn'): node_id = int(pkey.removeprefix('node/').removesuffix('/vpn')) @@ -32,6 +34,22 @@ agent.assert_exp(len(peers) >= 0) agent.assert_exp(leader_id > 0) agent.assert_exp(cluster_network) +# Restore the preshared key file, e.g. after a leader change +if vpn_psk and cluster.vpn.read_psk() != vpn_psk: + print(agent.SD_NOTICE + f"Writing VPN preshared key file {cluster.vpn.PSK_PATH}", file=sys.stderr) + cluster.vpn.write_psk(vpn_psk) + +def get_psk_args(node_id): + """Return the preshared-key arguments of `wg set` for the peer node_id. + A leader-worker link uses the key if the worker node has the psk flag.""" + worker_id = node_id if self_id == leader_id else self_id + if peers.get(worker_id, {}).get('psk') != '1': + return [] # do not change the peer preshared key + if not vpn_psk: + print(agent.SD_WARNING + f"VPN preshared key for node/{node_id} not found", file=sys.stderr) + return [] + return ['preshared-key', cluster.vpn.PSK_PATH] + # Convert Redis VPN records to our VPN data model destmap = {} for node_id in peers: @@ -116,6 +134,7 @@ for node_id in destmap: 'persistent-keepalive', '25', 'allowed-ips', ','.join(allowed_ips), *(['endpoint', f"{peer_host}:{peer_port}"] if peer_host else []), # optional arguments + *get_psk_args(node_id), log_command=True, ) if wset_proc.returncode != 0: diff --git a/core/imageroot/var/lib/nethserver/cluster/actions/add-node/50update b/core/imageroot/var/lib/nethserver/cluster/actions/add-node/50update index 73237eb9dd..01fd1a30cb 100755 --- a/core/imageroot/var/lib/nethserver/cluster/actions/add-node/50update +++ b/core/imageroot/var/lib/nethserver/cluster/actions/add-node/50update @@ -28,6 +28,7 @@ import agent.tasks import ipaddress import uuid import cluster.grants +import cluster.vpn import semver # Action summary: @@ -43,6 +44,7 @@ agent.assert_exp(public_key) endpoint = request['endpoint'] agent.assert_exp(type(endpoint) is str) flags = request.get('flags', []) +vpn_psk = request.get('vpn_psk', False) # the node can set a VPN preshared key worker_version = request.get('core_version', '0.0.0') # @@ -107,12 +109,16 @@ ip_address = str(network.network_address + node_id) # # Store VPN settings of the new node # -agent.assert_exp(rdb.hset(f'node/{node_id}/vpn', mapping={ +vpn_settings = { "public_key": public_key, "ip_address": ip_address, "destinations": "", "endpoint": endpoint, -}) >= 0) +} +if vpn_psk: + vpn_preshared_key = cluster.vpn.ensure_psk(rdb) + vpn_settings["psk"] = "1" +agent.assert_exp(rdb.hset(f'node/{node_id}/vpn', mapping=vpn_settings) >= 0) # Save node flags for flag in flags: @@ -218,7 +224,7 @@ rdb.publish('cluster/event/vpn-changed', json.dumps({"node_id":node_id})) # # Return the new information to the caller # -json.dump({ +response = { "node_id": node_id, # required to set up node agent "ip_address": ip_address, # required to set up wg0 device "leader_public_key": leader_public_key, # required for VPN auth @@ -226,4 +232,7 @@ json.dump({ "leader_ip_address": leader_ip_address, # required to rewrite /etc/hosts cluster-leader "leader_endpoint": leader_endpoint, # required to reach the VPN public endpoint "leader_core_version": leader_version, # for compatibility checks -}, sys.stdout) +} +if vpn_psk: + response["vpn_preshared_key"] = vpn_preshared_key # required for VPN auth +json.dump(response, sys.stdout) diff --git a/core/imageroot/var/lib/nethserver/cluster/actions/add-node/validate-input.json b/core/imageroot/var/lib/nethserver/cluster/actions/add-node/validate-input.json index 4d6f19e992..a4a53509ed 100644 --- a/core/imageroot/var/lib/nethserver/cluster/actions/add-node/validate-input.json +++ b/core/imageroot/var/lib/nethserver/cluster/actions/add-node/validate-input.json @@ -44,6 +44,10 @@ "description": "List of node flags", "type": "array", "items": { "type": "string" } + }, + "vpn_psk": { + "description": "If true, the node supports the WireGuard VPN preshared key: it is returned in the output as `vpn_preshared_key`", + "type": "boolean" } } } diff --git a/core/imageroot/var/lib/nethserver/cluster/actions/add-node/validate-output.json b/core/imageroot/var/lib/nethserver/cluster/actions/add-node/validate-output.json index 48d238b537..93d85a7579 100644 --- a/core/imageroot/var/lib/nethserver/cluster/actions/add-node/validate-output.json +++ b/core/imageroot/var/lib/nethserver/cluster/actions/add-node/validate-output.json @@ -65,6 +65,11 @@ "my.example.com:55820", "1.2.3.4:55820" ] + }, + "vpn_preshared_key": { + "title": "VPN preshared key", + "description": "WireGuard preshared key of the cluster VPN. Returned only if the input has `vpn_psk` set to true", + "type": "string" } } } diff --git a/core/imageroot/var/lib/nethserver/cluster/actions/create-cluster/50update b/core/imageroot/var/lib/nethserver/cluster/actions/create-cluster/50update index 08368de4e7..919e044e71 100755 --- a/core/imageroot/var/lib/nethserver/cluster/actions/create-cluster/50update +++ b/core/imageroot/var/lib/nethserver/cluster/actions/create-cluster/50update @@ -60,8 +60,11 @@ rdb.hset(f'node/{NODE_ID}/vpn', mapping={ "public_key": public_key, "ip_address": ip_address, "destinations": "", - "endpoint": endpoint + "endpoint": endpoint, + "psk": "1", }) +# Generate the cluster VPN preshared key, sent to new nodes by add-node +cluster.vpn.ensure_psk(rdb) # Update the cluster-localnode record in /etc/hosts agent.run_helper('sed', '-i', diff --git a/core/imageroot/var/lib/nethserver/cluster/actions/join-cluster/50update b/core/imageroot/var/lib/nethserver/cluster/actions/join-cluster/50update index 4499f72725..1adada323d 100755 --- a/core/imageroot/var/lib/nethserver/cluster/actions/join-cluster/50update +++ b/core/imageroot/var/lib/nethserver/cluster/actions/join-cluster/50update @@ -66,6 +66,7 @@ response = agent.tasks.run( "node_pwh": node_pwh, "public_key": public_key, "endpoint": endpoint, + "vpn_psk": True, }, extra={ "title": f"add-node {endpoint}" if endpoint else "add-node", @@ -109,7 +110,7 @@ try: peer_hostname, peer_port = join_node_data['leader_endpoint'].rsplit(':', 1) socket.getaddrinfo(peer_hostname, peer_port, proto=socket.IPPROTO_UDP)[0][4][0] except Exception as ex: - print(agent.SD_ERR + "leader_endpoint error:", ex, "DATA", join_node_data, file=sys.stderr) + print(agent.SD_ERR + "leader_endpoint error:", ex, "DATA", {k: v for k, v in join_node_data.items() if k != 'vpn_preshared_key'}, file=sys.stderr) print(agent.SD_NOTICE + f"After the issue is solved, remove node {node_id} before running a new join attempt.", file=sys.stderr) raise diff --git a/core/imageroot/var/lib/nethserver/cluster/actions/join-node/30start_replication b/core/imageroot/var/lib/nethserver/cluster/actions/join-node/30start_replication index bd6b5f8cd2..2946efa012 100755 --- a/core/imageroot/var/lib/nethserver/cluster/actions/join-node/30start_replication +++ b/core/imageroot/var/lib/nethserver/cluster/actions/join-node/30start_replication @@ -33,6 +33,7 @@ node_id = int(request['node_id']) leader_ip_address = request['leader_ip_address'] leader_public_key = request['leader_public_key'] leader_endpoint = request['leader_endpoint'] +vpn_preshared_key = request.get('vpn_preshared_key', '') # Grab the node password, to initialize Redis replication credentials node_password = agent.read_envfile('/var/lib/nethserver/node/state/agent.env')["REDIS_PASSWORD"] @@ -60,10 +61,13 @@ agent.run_helper('sed', '-i', '/var/lib/nethserver/node/state/agent.env').check_returncode() # VPN bootstrap +if vpn_preshared_key: + cluster.vpn.write_psk(vpn_preshared_key) cluster.vpn.initialize_wgconf(ip_address, peer={ "ip_address": leader_ip_address, "public_key": leader_public_key, "endpoint": leader_endpoint, + "preshared_key": vpn_preshared_key, }) agent.run_helper('systemctl', 'restart', 'wg-quick@wg0.service').check_returncode() diff --git a/core/imageroot/var/lib/nethserver/cluster/actions/join-node/validate-input.json b/core/imageroot/var/lib/nethserver/cluster/actions/join-node/validate-input.json index a20e71a405..c4ab71f47f 100644 --- a/core/imageroot/var/lib/nethserver/cluster/actions/join-node/validate-input.json +++ b/core/imageroot/var/lib/nethserver/cluster/actions/join-node/validate-input.json @@ -59,6 +59,11 @@ "my.example.com:55820", "1.2.3.4:55820" ] + }, + "vpn_preshared_key": { + "title": "VPN preshared key", + "description": "Optional WireGuard preshared key of the cluster VPN, for the leader peer", + "type": "string" } } } diff --git a/docs/core/database.md b/docs/core/database.md index 9ff7809f28..2757bf185c 100644 --- a/docs/core/database.md +++ b/docs/core/database.md @@ -289,6 +289,7 @@ of the node (e.g. `node/1/...`). |node/{id}/vpn public_key |STRING |Public WireGuard VPN key| |node/{id}/vpn destinations |STRING |List of IP addresses routed through the VPN| |node/{id}/vpn endpoint |STRING |Public IP or host name of the VPN endpoint with :port suffix| +|node/{id}/vpn psk |STRING |If "1", the VPN link between the node and the leader uses the cluster preshared key `private/nodes/vpn_psk`| |node/{id}/flags |SET |Flags to mark a node. Supported flags: `nomodules`, the node can't run any module| |node/{id}/roles/{role} |SET |glob patterns matching the actions that {role} can run. {role} is one of "owner", "reader"...| |node/{id}/tcp_ports_sequence |INTEGER |Lower boundary for the next TCP_PORTS_RANGE allocation, default: `20000`| @@ -405,4 +406,5 @@ agent (read + write) and node agents (read-only). |key|type|description| |---|----|-----------| |private/nodes/backup_destination/rclone_conf | HASH | Maps a backup destination ID to its raw rclone configuration, that typically contains secret credentials | +|private/nodes/vpn_psk | STRING | WireGuard preshared key of the cluster VPN. Nodes keep a copy in `/etc/nethserver/wg0.psk` | |private/nodes/restore_uuid | HASH | Maps a destination module UUID to a source module UUID. During module restoration the destination module must read the source module backup repository and this map establish the required trust between them, which is enforced by rclone-gateway.| diff --git a/docs/core/vpn.md b/docs/core/vpn.md index 0f4de98f4b..09171247fd 100644 --- a/docs/core/vpn.md +++ b/docs/core/vpn.md @@ -104,6 +104,12 @@ peer: nvu810d2Q3LGUwJNmJawXj7u16+JUukgreQo4NCcACc= Configuration file is saved inside `/etc/wireguard/wg0.conf`, public and private keys are saved inside `/etc/nethserver/wg0.{pub,key}`. +The leader generates a WireGuard preshared key for the cluster, saved inside +`/etc/nethserver/wg0.psk` and in Redis. A node gets it when it joins the +cluster, and the link between the node and the leader uses it. Nodes that +joined before this feature have no `psk` flag in `node/{id}/vpn` and do not +use it. + The configuration file is initialized by `create-cluster` and `join-node` actions. Local modification to the configuration file can be merged into the runtime state with the following command: