diff --git a/api/views.py b/api/views.py index e1d7cf0..44b9a9e 100644 --- a/api/views.py +++ b/api/views.py @@ -141,6 +141,7 @@ def peer_info(request): 'public_key': str(peer.public_key), 'uuid': str(peer.uuid), 'private_key_exists': bool(peer.private_key), + 'endpoint': peer.endpoint, 'is_route_policy_restricted': peer.is_route_policy_restricted, } return JsonResponse(data) diff --git a/api_v2/views_api.py b/api_v2/views_api.py index ae3f252..a83f951 100644 --- a/api_v2/views_api.py +++ b/api_v2/views_api.py @@ -4,6 +4,7 @@ import re from functools import wraps from typing import List, Optional, Tuple +from django import forms from django.conf import settings as django_settings from django.core.exceptions import ValidationError from django.db import transaction @@ -19,6 +20,7 @@ from dns.models import DNSSettings, StaticHost from dns.views import export_dns_configuration from routing_templates.models import RoutingTemplate from wireguard.models import Peer, PeerAllowedIP, WireGuardInstance +from wireguard_peer.forms import normalize_endpoint from wireguard_peer.functions import find_network_in_other_instance, func_create_new_peer from wireguard_tools.functions import ( func_reload_wireguard_interface, running_wireguard_interfaces, start_primary_interfaces, stop_primary_interfaces, @@ -243,6 +245,13 @@ def _validate_dns_hostname(hostname: str) -> Tuple[Optional[str], Optional[str]] "description": "Suspend/unsuspend a peer (update)."}, {"name": "suspend_reason", "in": "json", "type": "string", "required": False, "description": "Suspend reason (update). Can be cleared by sending null/empty string."}, + {"name": "endpoint", "in": "json", "type": "string", "required": False, "example": "vpn.example.com:51820", + "description": "Address (host:port) of a remote WireGuard server that this server connects to (create/update). " + "Cleared by sending an empty string. A peer with an endpoint may use a main address outside " + "the instance network."}, + {"name": "active_worker_uuid", "in": "json", "type": "string", "required": False, + "description": "Cluster worker that connects to the endpoint in the mirror mode (create/update). Null or " + "empty means the primary server."}, ], returns=[ {"status": 200, "body": {"status": "success", "message": "Peer updated successfully.", "peer_uuid": "...", "public_key": "...", "main_addresses": ["..."], "reload": {"success": True, "message": "..."}}}, @@ -329,6 +338,22 @@ def api_v2_manage_peer(request): if client_route_error: return JsonResponse({"status": "error", "error_message": client_route_error}, status=400) + new_endpoint = None + if "endpoint" in payload: + try: + new_endpoint = normalize_endpoint(str(payload.get("endpoint") or "")) + except forms.ValidationError as error: + return JsonResponse({"status": "error", "error_message": f"Invalid endpoint: {error.messages[0]}"}, status=400) + + new_active_worker = None + if payload.get("active_worker_uuid"): + try: + new_active_worker = Worker.objects.filter(uuid=payload.get("active_worker_uuid")).first() + except (ValidationError, ValueError): + new_active_worker = None + if not new_active_worker: + return JsonResponse({"status": "error", "error_message": "Invalid active_worker_uuid."}, status=400) + with transaction.atomic(): # CREATE if request.method == "POST": @@ -358,6 +383,9 @@ def api_v2_manage_peer(request): create_overrides["persistent_keepalive"] = peer_persistent_keepalive if peer_allowed_ip: create_overrides["allowed_ip"] = str(peer_allowed_ip).strip() + if new_endpoint: + create_overrides["endpoint"] = new_endpoint + create_overrides["active_worker"] = new_active_worker if routing_template is not None: create_overrides["default_routing_template"] = routing_template @@ -459,6 +487,13 @@ def api_v2_manage_peer(request): if "suspend_reason" in payload: peer_for_action.suspend_reason = new_suspend_reason + if new_endpoint is not None: + peer_for_action.endpoint = new_endpoint + if "active_worker_uuid" in payload: + peer_for_action.active_worker = new_active_worker + if not peer_for_action.endpoint: + peer_for_action.active_worker = None + peer_for_action.save() _sync_allowed_ips(peer_for_action, announced_pairs, config_file="server") @@ -737,6 +772,7 @@ def api_v2_peer_list(request): "suspend_reason": current_peer.suspend_reason or "", "disabled_by_schedule": bool(current_peer.disabled_by_schedule), "main_addresses": current_peer.main_addresses, + "endpoint": current_peer.endpoint, }) return JsonResponse( @@ -763,7 +799,7 @@ def api_v2_peer_list(request): "description": "Peer public key selector."}, ], returns=[ - {"status": 200, "body": {"status": "success", "peer": {"uuid": "...", "name": "...", "public_key": "...", "pre_shared_key": "...", "private_key": "...", "persistent_keepalive": 25, "routing_template_uuid": "...", "suspended": False, "suspend_reason": "...", "disabled_by_schedule": False, "enabled": True, "main_addresses": ["..."], "announced_networks": ["..."], "client_routes": ["..."], "instance": "...", "instance_uuid": "..."}}}, + {"status": 200, "body": {"status": "success", "peer": {"uuid": "...", "name": "...", "public_key": "...", "pre_shared_key": "...", "private_key": "...", "persistent_keepalive": 25, "routing_template_uuid": "...", "suspended": False, "suspend_reason": "...", "disabled_by_schedule": False, "enabled": True, "main_addresses": ["..."], "announced_networks": ["..."], "client_routes": ["..."], "endpoint": "", "active_worker_uuid": "", "instance": "...", "instance_uuid": "..."}}}, {"status": 400, "body": {"status": "error", "error_message": "Missing peer selector (peer_uuid or peer_public_key)."}}, {"status": 404, "body": {"status": "error", "error_message": "Peer not found."}}, {"status": 403, "body": {"status": "error", "error_message": "Invalid API key."}}, @@ -839,6 +875,8 @@ def api_v2_peer_detail(request): "main_addresses": current_peer.main_addresses, "announced_networks": current_peer.announced_networks, "client_routes": current_peer.client_routes, + "endpoint": current_peer.endpoint, + "active_worker_uuid": str(current_peer.active_worker.uuid) if current_peer.active_worker else "", "instance": f"wg{wireguard_instance.instance_id}", "instance_uuid": str(wireguard_instance.uuid), } diff --git a/cluster/sync.py b/cluster/sync.py index 8ccb1db..4eecdae 100644 --- a/cluster/sync.py +++ b/cluster/sync.py @@ -5,6 +5,7 @@ import os from datetime import timedelta from django.conf import settings +from django.db.models import Prefetch from django.utils import timezone from django.utils.dateparse import parse_datetime @@ -16,8 +17,10 @@ from dns.functions import generate_dnsmasq_config from dns.models import DNSFilterList from firewall.tools import generate_firewall_script from gatekeeper.sessions import REVOKED_SESSIONS_FILE, build_revoked_sessions_data -from wireguard.models import WireGuardInstance -from wireguard_tools.functions import CLUSTER_WIREGUARD_CONFIG_DIR, WIREGUARD_CONFIG_DIR +from wireguard.models import Peer, PeerAllowedIP, WireGuardInstance +from wireguard_tools.functions import ( + CLUSTER_WIREGUARD_CONFIG_DIR, ENDPOINT_PEER_TITLE, WIREGUARD_CONFIG_DIR, peer_config_lines, remove_endpoint_peers +) DNSMASQ_CONFIG_DIR = '/etc/dnsmasq' DNSMASQ_MAIN_CONFIG = 'wireguard_webadmin_dns.conf' @@ -81,10 +84,40 @@ def build_wireguard_section(worker): if not os.path.isfile(config_path): continue content, content_sha256 = _read_file(config_path) + if not ClusterSettings.is_distributed(): + content, content_sha256 = _mirror_endpoint_peers( + content, content_sha256, os.path.basename(config_path), worker + ) section.add_file(os.path.basename(config_path), content, content_sha256) return section +def _mirror_endpoint_peers(content, content_sha256, filename, worker): + """ + In the mirror mode only one server connects to the remote endpoint of a peer: the configuration of the primary + server is sent without its endpoint peers, plus the endpoint peers that run on this worker. + """ + try: + instance_id = int(filename[len('wg'):-len('.conf')]) + except ValueError: + return content, content_sha256 + endpoint_peers = ( + Peer.objects.filter( + wireguard_instance__instance_id=instance_id, active_worker=worker, + suspended=False, disabled_by_schedule=False, + ) + .exclude(endpoint='') + .prefetch_related(Prefetch('peerallowedip_set', queryset=PeerAllowedIP.objects.filter(config_file='server'))) + ) + worker_lines = [line for peer in endpoint_peers for line in peer_config_lines(peer)] + if not worker_lines and ENDPOINT_PEER_TITLE not in content: + return content, content_sha256 + content = remove_endpoint_peers(content) + if worker_lines: + content = content.rstrip("\n") + "\n\n" + "\n".join(worker_lines) + return content, None + + def build_firewall_section(worker): section = Section() section.add_file('wg-firewall.sh', generate_firewall_script(cluster_node=True, worker=worker)) diff --git a/templates/wireguard/peer_list/peer_preview_modal.html b/templates/wireguard/peer_list/peer_preview_modal.html index 4a163e3..347d55e 100644 --- a/templates/wireguard/peer_list/peer_preview_modal.html +++ b/templates/wireguard/peer_list/peer_preview_modal.html @@ -140,14 +140,16 @@ {% if cluster_settings and servers|length > 1 %} -
{{ current_peer.endpoint }}
+ {% if show_active_worker %}
+ When an endpoint is set, this server connects to a remote WireGuard server instead of waiting for the peer to connect. Use it to reach the networks behind a router or another server. Example: vpn.example.com:51820.
The public key of this peer is the public key of the remote server. The remote server must have the public key of this instance configured. The pre-shared key is optional.
+ +The main address of this peer may be outside the network of the instance. Add the remote networks as allowed IPs of this peer.
+ ''') + } + if 'active_worker' in form.fields: + context['form_description']['content'] += _(''' +Only one cluster server connects to the endpoint. When empty, the primary server connects to it.
+ ''') + context['form_description']['content'] += _(''' +Peers with an endpoint have no configuration to download, QR code or VPN invite.
+ ''') return render(request, 'generic_form.html', context) diff --git a/wireguard_tools/functions.py b/wireguard_tools/functions.py index 1945f5d..a71c103 100644 --- a/wireguard_tools/functions.py +++ b/wireguard_tools/functions.py @@ -16,6 +16,49 @@ WIREGUARD_CONFIG_DIR = '/etc/wireguard' CLUSTER_WIREGUARD_CONFIG_DIR = '/etc/wireguard/cluster' +# Title of the configuration block of a peer with an endpoint. Mirror workers remove these blocks from the configuration +# of the primary server and receive only the endpoint peers they run. +ENDPOINT_PEER_TITLE = '# Endpoint peer: ' + + +def peer_config_lines(peer) -> list: + """[Peer] block of a peer, using its prefetched server allowed IPs. Ends with an empty line.""" + allowed_ips = [ip for ip in peer.peerallowedip_set.all() if ip.config_file == 'server'] + allowed_ips.sort(key=lambda ip: ip.priority) + if not allowed_ips: + prepend_line = "# " + peer_title = f"# WARNING: No Allowed IPs set for peer {peer}. " + allowed_ips_line = "# AllowedIPs = (missing)" + else: + prepend_line = "" + peer_title = f"{ENDPOINT_PEER_TITLE if peer.endpoint else '# Peer: '}{peer}" + allowed_ips_line = "AllowedIPs = " + ", ".join(f"{ip.allowed_ip}/{ip.netmask}" for ip in allowed_ips) + + lines = [peer_title, f"{prepend_line}[Peer]", f"{prepend_line}PublicKey = {peer.public_key}"] + if peer.pre_shared_key: + lines.append(f"{prepend_line}PresharedKey = {peer.pre_shared_key}") + if peer.endpoint: + lines.append(f"{prepend_line}Endpoint = {peer.endpoint}") + lines.append(f"{prepend_line}PersistentKeepalive = {peer.persistent_keepalive}") + lines.append(allowed_ips_line) + lines.append("") + return lines + + +def remove_endpoint_peers(config_content: str) -> str: + """Remove the blocks of endpoint peers from a configuration written by export_wireguard_configuration.""" + lines = [] + skipping = False + for line in config_content.split("\n"): + if line.startswith(ENDPOINT_PEER_TITLE): + skipping = True + if not skipping: + lines.append(line) + if skipping and line == "": + skipping = False + return "\n".join(lines) + + def get_instance_config_dir(instance: WireGuardInstance) -> str: return CLUSTER_WIREGUARD_CONFIG_DIR if instance.hosting_worker else WIREGUARD_CONFIG_DIR @@ -159,6 +202,9 @@ def reload_wireguard_interface(target: Union[str, WireGuardInstance], config_dir if target.hosting_worker: # The worker applies the new configuration on its next synchronization return True, f"wg{target.instance_id} runs on {target.hosting_worker} and is updated by the cluster" + if not ClusterSettings.primary_serves_clients(): + # The interfaces of the primary server are stopped; the workers apply it on their next synchronization + return True, f"wg{target.instance_id} is updated by the cluster workers" interface_name = f"wg{target.instance_id}" conf_filename = f"{interface_name}.conf" else: diff --git a/wireguard_tools/views.py b/wireguard_tools/views.py index 122bb36..690117d 100644 --- a/wireguard_tools/views.py +++ b/wireguard_tools/views.py @@ -23,8 +23,8 @@ from vpn_invite.models import PeerInvite from wgwadmlibrary.tools import user_has_access_to_peer from wireguard.models import Peer, PeerAllowedIP, WireGuardInstance from wireguard_tools.functions import ( - CLUSTER_WIREGUARD_CONFIG_DIR, WIREGUARD_CONFIG_DIR, get_instance_config_dir, stop_primary_interfaces, - sync_interface_routes, + CLUSTER_WIREGUARD_CONFIG_DIR, WIREGUARD_CONFIG_DIR, get_instance_config_dir, peer_config_lines, + stop_primary_interfaces, sync_interface_routes, ) @@ -206,29 +206,10 @@ def export_wireguard_configuration(instance_only: WireGuardInstance = None): ) for peer in peers: - allowed_ips = list(peer.peerallowedip_set.all()) - - if not allowed_ips: - prepend_line = "# " - peer_title = f"# WARNING: No Allowed IPs set for peer {peer}. " - allowed_ips_line = "# AllowedIPs = (missing)" - else: - prepend_line = "" - peer_title = f"# Peer: {peer}" - allowed_ips_line = prepend_line + "AllowedIPs = " + ", ".join(f"{ip.allowed_ip}/{ip.netmask}" for ip in allowed_ips) - - peer_lines = [ - peer_title, - f"{prepend_line}[Peer]", - f"{prepend_line}PublicKey = {peer.public_key}", - ] - - if peer.pre_shared_key: - peer_lines.append(f"{prepend_line}PresharedKey = {peer.pre_shared_key}") - peer_lines.append(f"{prepend_line}PersistentKeepalive = {peer.persistent_keepalive}") - peer_lines.append(allowed_ips_line) - config_lines.extend(peer_lines) - config_lines.append("") + # Only one server connects to the remote endpoint of a peer + if peer.endpoint and peer.endpoint_worker != instance.hosting_worker: + continue + config_lines.extend(peer_config_lines(peer)) config_content = "\n".join(config_lines) config_path = os.path.join(config_dirs[instance.uuid], f"wg{instance.instance_id}.conf") @@ -278,6 +259,10 @@ def download_config_or_qrcode(request): if not user_has_access_to_peer(user_acl, peer): raise Http404 + # A peer with an endpoint is a remote server that this server connects to: it has no client configuration + if peer.endpoint: + raise Http404 + format_type = request.GET.get('format', 'conf') worker_uuid = request.GET.get('worker') server_address = None