Skip to content
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
33 changes: 33 additions & 0 deletions core/imageroot/usr/local/agent/pypkg/cluster/vpn.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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")
Expand Down
23 changes: 21 additions & 2 deletions core/imageroot/usr/local/sbin/apply-vpn-routes
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@
# routing table, update Wireguard routing (AllowedIPs) setup.

import agent
import cluster.vpn
import os
import sys
import socket
Expand All @@ -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'))
Expand All @@ -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:
Expand Down Expand Up @@ -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:
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -28,6 +28,7 @@ import agent.tasks
import ipaddress
import uuid
import cluster.grants
import cluster.vpn
import semver

# Action summary:
Expand All @@ -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')

#
Expand Down Expand Up @@ -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:
Expand Down Expand Up @@ -218,12 +224,15 @@ 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
"network": str(network), # required to set up route table
"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)
Original file line number Diff line number Diff line change
Expand Up @@ -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"
}
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -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"
}
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -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',
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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",
Expand Down Expand Up @@ -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

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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"]
Expand Down Expand Up @@ -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()

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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"
}
}
}
2 changes: 2 additions & 0 deletions docs/core/database.md
Original file line number Diff line number Diff line change
Expand Up @@ -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`|
Expand Down Expand Up @@ -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.|
6 changes: 6 additions & 0 deletions docs/core/vpn.md
Original file line number Diff line number Diff line change
Expand Up @@ -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:
Expand Down
Loading