mirror of
https://github.com/eduardogsilva/wireguard_webadmin.git
synced 2026-11-27 07:06:03 +01:00
Let peers connect to a remote WireGuard endpoint
This commit is contained in:
@@ -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)
|
||||
|
||||
+39
-1
@@ -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),
|
||||
}
|
||||
|
||||
+35
-2
@@ -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))
|
||||
|
||||
@@ -140,6 +140,7 @@
|
||||
|
||||
<!-- Row 2: server select (right aligned) -->
|
||||
{% if cluster_settings and servers|length > 1 %}
|
||||
<div class="w-100" id="serverSelectRow">
|
||||
<div class="d-flex w-100 mt-2">
|
||||
<div class="form-inline ml-auto">
|
||||
<label class="mr-2 mb-0" for="server_select">{% trans 'Server' %}:</label>
|
||||
@@ -150,6 +151,7 @@
|
||||
</select>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
{% endif %}
|
||||
|
||||
</div>
|
||||
|
||||
@@ -108,6 +108,8 @@
|
||||
if (data.name) {
|
||||
$('#peerPreviewModalLabel').text(data.name);
|
||||
}
|
||||
// A peer with an endpoint is a remote server: there is no client configuration to share
|
||||
$('#downloadConfigButton, #qrcodeButton, #inviteButton, #serverSelectRow').toggleClass('d-none', !!data.endpoint);
|
||||
// Check if peer has private_key and enable/disable buttons accordingly
|
||||
if (!data.private_key_exists) {
|
||||
$('#qrcodeButton').addClass('disabled').attr('aria-disabled', 'true');
|
||||
|
||||
@@ -90,6 +90,27 @@
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<!-- Endpoint -->
|
||||
<div class="form-group border-bottom pb-3">
|
||||
<label>{% trans 'Endpoint' %}</label>
|
||||
<div class="d-flex justify-content-between align-items-center">
|
||||
<span>
|
||||
{% if current_peer.endpoint %}
|
||||
<code>{{ current_peer.endpoint }}</code>
|
||||
{% if show_active_worker %}
|
||||
<br><small class="text-muted">{% trans 'Connected server' %}: {{ current_peer.active_worker.name|default:_('Primary Server') }}</small>
|
||||
{% endif %}
|
||||
{% else %}
|
||||
<span class="text-muted">{% trans 'Not set' %}</span>
|
||||
{% endif %}
|
||||
</span>
|
||||
<a href="{% url 'wireguard_peer_edit_field' %}?peer={{ current_peer.uuid }}&group=endpoint"
|
||||
class="btn btn-tool">
|
||||
<i class="fas fa-pen"></i>
|
||||
</a>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<!-- Keys Section -->
|
||||
<div class="form-group">
|
||||
<div class="d-flex justify-content-between align-items-center mb-2">
|
||||
|
||||
@@ -0,0 +1,25 @@
|
||||
# Generated by Django 5.2.19 on 2026-11-23 21:01
|
||||
|
||||
import django.db.models.deletion
|
||||
from django.db import migrations, models
|
||||
|
||||
|
||||
class Migration(migrations.Migration):
|
||||
|
||||
dependencies = [
|
||||
('cluster', '0020_workerstatus_gateway_sessions_and_more'),
|
||||
('wireguard', '0034_wireguardinstance_worker'),
|
||||
]
|
||||
|
||||
operations = [
|
||||
migrations.AddField(
|
||||
model_name='peer',
|
||||
name='active_worker',
|
||||
field=models.ForeignKey(blank=True, null=True, on_delete=django.db.models.deletion.SET_NULL, related_name='endpoint_peers', to='cluster.worker'),
|
||||
),
|
||||
migrations.AddField(
|
||||
model_name='peer',
|
||||
name='endpoint',
|
||||
field=models.CharField(blank=True, default='', max_length=255),
|
||||
),
|
||||
]
|
||||
@@ -211,6 +211,13 @@ class Peer(models.Model):
|
||||
'routing_templates.RoutingTemplate', on_delete=models.SET_NULL, blank=True, null=True, related_name='peers'
|
||||
)
|
||||
|
||||
# Remote address (host:port) for peers that this server connects to, instead of waiting for them to connect
|
||||
endpoint = models.CharField(max_length=255, blank=True, default='')
|
||||
# Cluster worker that keeps the connection of an endpoint peer in the mirror mode. Empty means the primary server.
|
||||
active_worker = models.ForeignKey(
|
||||
'cluster.Worker', on_delete=models.SET_NULL, blank=True, null=True, related_name='endpoint_peers'
|
||||
)
|
||||
|
||||
disabled_by_schedule = models.BooleanField(default=False)
|
||||
suspended = models.BooleanField(default=False)
|
||||
suspend_reason = models.TextField(blank=True, null=True)
|
||||
@@ -225,6 +232,18 @@ class Peer(models.Model):
|
||||
else:
|
||||
return self.public_key[:16] + "..."
|
||||
|
||||
@property
|
||||
def endpoint_worker(self):
|
||||
"""
|
||||
Worker that runs an endpoint peer, or None when it runs on the primary server. Only one server connects to the
|
||||
remote endpoint: in the mirror mode it is the active worker, in the distributed mode the server of the instance.
|
||||
"""
|
||||
if not self.endpoint or not ClusterSettings.cluster_enabled():
|
||||
return None
|
||||
if ClusterSettings.is_distributed():
|
||||
return self.wireguard_instance.hosting_worker
|
||||
return self.active_worker
|
||||
|
||||
@property
|
||||
def enabled(self) -> bool:
|
||||
return not self.disabled_by_schedule and not self.suspended
|
||||
|
||||
+78
-1
@@ -1,4 +1,5 @@
|
||||
import ipaddress
|
||||
import re
|
||||
from datetime import timedelta
|
||||
|
||||
from crispy_forms.bootstrap import FormActions
|
||||
@@ -11,6 +12,7 @@ from django.urls import reverse_lazy
|
||||
from django.utils import timezone
|
||||
from django.utils.translation import gettext_lazy as _
|
||||
|
||||
from cluster.models import ClusterSettings, Worker
|
||||
from scheduler.models import PeerScheduling
|
||||
from wireguard.models import NETMASK_CHOICES, Peer, PeerAllowedIP
|
||||
from wireguard_peer.functions import find_network_in_other_instance
|
||||
@@ -58,6 +60,80 @@ class PeerKeysForm(PeerModelForm):
|
||||
model = Peer
|
||||
fields = ['public_key', 'private_key', 'pre_shared_key']
|
||||
|
||||
def __init__(self, *args, **kwargs):
|
||||
super().__init__(*args, **kwargs)
|
||||
# A remote WireGuard server may not use a pre-shared key
|
||||
if self.instance.endpoint:
|
||||
self.fields['pre_shared_key'].required = False
|
||||
|
||||
|
||||
HOSTNAME_PATTERN = re.compile(r'^(?=.{1,253}$)([a-zA-Z0-9]([a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?\.)*[a-zA-Z0-9]([a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?$')
|
||||
|
||||
|
||||
def normalize_endpoint(value):
|
||||
"""Validate a WireGuard endpoint (host:port, with IPv6 addresses in brackets) and return it normalized."""
|
||||
value = (value or '').strip()
|
||||
if not value:
|
||||
return ''
|
||||
host, separator, port = value.rpartition(':')
|
||||
if not separator or not port.isdigit() or not 1 <= int(port) <= 65535:
|
||||
raise forms.ValidationError(_('Enter the endpoint as host:port, e.g. vpn.example.com:51820'))
|
||||
if host.startswith('[') and host.endswith(']'):
|
||||
try:
|
||||
ipaddress.IPv6Address(host[1:-1])
|
||||
except ValueError:
|
||||
raise forms.ValidationError(_('Enter a valid IPv6 address between brackets, e.g. [2001:db8::1]:51820'))
|
||||
return f'{host.lower()}:{int(port)}'
|
||||
try:
|
||||
ipaddress.IPv4Address(host)
|
||||
except ValueError:
|
||||
if not HOSTNAME_PATTERN.match(host):
|
||||
raise forms.ValidationError(_('Enter the endpoint as host:port, e.g. vpn.example.com:51820'))
|
||||
return f'{host.lower()}:{int(port)}'
|
||||
|
||||
|
||||
class PeerEndpointForm(PeerModelForm):
|
||||
endpoint = forms.CharField(
|
||||
label=_('Endpoint'), required=False,
|
||||
help_text=_('Address (host:port) of a remote WireGuard server. This server connects to it, instead of waiting '
|
||||
'for the peer to connect. Leave empty for a regular peer.'),
|
||||
)
|
||||
active_worker = forms.ModelChoiceField(
|
||||
queryset=Worker.objects.none(), label=_('Connected server'), required=False,
|
||||
empty_label=_('Primary Server'),
|
||||
help_text=_('Cluster server that connects to the endpoint. The networks of this peer are reachable from the '
|
||||
'clients connected to that server.'),
|
||||
)
|
||||
|
||||
class Meta:
|
||||
model = Peer
|
||||
fields = ['endpoint', 'active_worker']
|
||||
|
||||
def __init__(self, *args, **kwargs):
|
||||
super().__init__(*args, **kwargs)
|
||||
# The node of an endpoint peer is only chosen in the mirror mode; in the distributed mode it is the node of
|
||||
# the instance
|
||||
if ClusterSettings.cluster_enabled() and not ClusterSettings.is_distributed():
|
||||
self.fields['active_worker'].queryset = Worker.objects.order_by('name')
|
||||
else:
|
||||
del self.fields['active_worker']
|
||||
self.helper.layout = Layout(
|
||||
'endpoint',
|
||||
FormActions(
|
||||
Submit('save', _('Save'), css_class='btn-primary'),
|
||||
Button('cancel', _('Back'), css_class='btn-outline-secondary', onclick='window.history.back()')
|
||||
)
|
||||
)
|
||||
|
||||
def clean_endpoint(self):
|
||||
return normalize_endpoint(self.cleaned_data.get('endpoint'))
|
||||
|
||||
def clean(self):
|
||||
cleaned_data = super().clean()
|
||||
if 'active_worker' in self.fields and not cleaned_data.get('endpoint'):
|
||||
cleaned_data['active_worker'] = None
|
||||
return cleaned_data
|
||||
|
||||
|
||||
class PeerAllowedIPForm(forms.ModelForm):
|
||||
def __init__(self, *args, **kwargs):
|
||||
@@ -93,7 +169,8 @@ class PeerAllowedIPForm(forms.ModelForm):
|
||||
duplicated_ip = duplicated_ip.exclude(uuid=self.instance.uuid)
|
||||
if duplicated_ip.exists():
|
||||
raise forms.ValidationError(_("This IP is already in use by another peer."))
|
||||
if ipaddress.ip_address(allowed_ip) not in wireguard_network:
|
||||
# A peer with an endpoint is a remote server, whose tunnel address may belong to its own network
|
||||
if ipaddress.ip_address(allowed_ip) not in wireguard_network and not self.current_peer.endpoint:
|
||||
raise forms.ValidationError(_("The IP address does not belong to the Peer's WireGuard instance network range. Please check the IP address or change the priority."))
|
||||
if str(netmask) != str(32):
|
||||
raise forms.ValidationError(_("The netmask for priority 0 IP must be 32."))
|
||||
|
||||
@@ -64,6 +64,8 @@ def func_create_new_peer(
|
||||
- allowed_ip
|
||||
- default_routing_template
|
||||
- allowed_ip_netmask (defaults to 32)
|
||||
- endpoint
|
||||
- active_worker
|
||||
"""
|
||||
new_peer_data = generate_peer_default(wireguard_instance)
|
||||
|
||||
@@ -76,7 +78,15 @@ def func_create_new_peer(
|
||||
raise ValueError(f'Override not allowed: {k}')
|
||||
|
||||
if overrides.get('allowed_ip'):
|
||||
if not wireguard_instance.check_available_ip_address(overrides.get('allowed_ip')):
|
||||
if overrides.get('endpoint'):
|
||||
# A remote WireGuard server may use a tunnel address outside the network of this instance
|
||||
try:
|
||||
ipaddress.IPv4Address(str(overrides['allowed_ip']).strip())
|
||||
except ValueError:
|
||||
return None, str(_('Error creating peer|The specified IP address is not available.'))
|
||||
if PeerAllowedIP.objects.filter(config_file='server', priority=0, allowed_ip=overrides['allowed_ip']).exists():
|
||||
return None, str(_('Error creating peer|The specified IP address is not available.'))
|
||||
elif not wireguard_instance.check_available_ip_address(overrides.get('allowed_ip')):
|
||||
return None, str(_('Error creating peer|The specified IP address is not available.'))
|
||||
|
||||
# apply overrides last
|
||||
@@ -93,6 +103,8 @@ def func_create_new_peer(
|
||||
private_key=new_peer_data.get('private_key'),
|
||||
wireguard_instance=wireguard_instance,
|
||||
routing_template=new_peer_data.get('default_routing_template'),
|
||||
endpoint=new_peer_data.get('endpoint') or '',
|
||||
active_worker=new_peer_data.get('active_worker') if new_peer_data.get('endpoint') else None,
|
||||
)
|
||||
|
||||
PeerAllowedIP.objects.create(
|
||||
|
||||
+37
-4
@@ -13,8 +13,8 @@ from user_manager.models import UserAcl
|
||||
from wgwadmlibrary.tools import check_sort_order_conflict, deduplicate_sort_order, default_sort_peers, \
|
||||
user_allowed_instances, user_allowed_peers, user_has_access_to_instance, user_has_access_to_peer
|
||||
from wireguard.models import Peer, PeerAllowedIP, WireGuardInstance
|
||||
from wireguard_peer.forms import PeerAllowedIPForm, PeerNameForm, PeerKeepaliveForm, PeerKeysForm, PeerSuspensionForm, \
|
||||
PeerScheduleProfileForm
|
||||
from wireguard_peer.forms import PeerAllowedIPForm, PeerEndpointForm, PeerNameForm, PeerKeepaliveForm, PeerKeysForm, \
|
||||
PeerSuspensionForm, PeerScheduleProfileForm
|
||||
from wireguard_tools.functions import func_reload_wireguard_interface, get_config_servers
|
||||
from wireguard_tools.views import export_wireguard_configuration
|
||||
from .functions import func_create_new_peer
|
||||
@@ -30,6 +30,12 @@ def _auto_apply(request, instance):
|
||||
'id': instance.instance_id, 'worker': hosting_worker
|
||||
})
|
||||
return True
|
||||
if not ClusterSettings.primary_serves_clients():
|
||||
messages.info(request, _(
|
||||
'WireGuard is disabled on the primary server. The cluster workers apply the change on their next '
|
||||
'synchronization.'
|
||||
))
|
||||
return True
|
||||
success, message = func_reload_wireguard_interface(instance)
|
||||
if success:
|
||||
messages.info(request, _('wg%(id)s reloaded automatically.') % {'id': instance.instance_id})
|
||||
@@ -208,7 +214,8 @@ def view_wireguard_peer_manage(request):
|
||||
context = {
|
||||
'page_title': page_title, 'current_instance': current_instance, 'current_peer': current_peer,
|
||||
'peer_ip_list': peer_ip_list, 'peer_client_ip_list': peer_client_ip_list,
|
||||
'peer_scheduling': peer_scheduling
|
||||
'peer_scheduling': peer_scheduling,
|
||||
'show_active_worker': ClusterSettings.cluster_enabled() and not ClusterSettings.is_distributed(),
|
||||
}
|
||||
return render(request, 'wireguard/wireguard_manage_peer.html', context)
|
||||
|
||||
@@ -227,7 +234,8 @@ def view_wireguard_peer_edit_field(request):
|
||||
form_classes = {
|
||||
'name': PeerNameForm,
|
||||
'keepalive': PeerKeepaliveForm,
|
||||
'keys': PeerKeysForm
|
||||
'keys': PeerKeysForm,
|
||||
'endpoint': PeerEndpointForm,
|
||||
}
|
||||
|
||||
if group not in form_classes:
|
||||
@@ -251,11 +259,36 @@ def view_wireguard_peer_edit_field(request):
|
||||
page_title = _('Edit Keepalive')
|
||||
elif group == 'keys':
|
||||
page_title = _('Edit Keys')
|
||||
elif group == 'endpoint':
|
||||
page_title = _('Edit Endpoint')
|
||||
|
||||
context = {
|
||||
'page_title': page_title,
|
||||
'form': form,
|
||||
}
|
||||
if group == 'endpoint':
|
||||
context['form_description'] = {
|
||||
'size': 'col-lg-6',
|
||||
'content': _('''
|
||||
<h5>Endpoint</h5>
|
||||
<p>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: <code>vpn.example.com:51820</code>.</p>
|
||||
|
||||
<h5>Keys</h5>
|
||||
<p>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.</p>
|
||||
|
||||
<h5>Addresses</h5>
|
||||
<p>The main address of this peer may be outside the network of the instance. Add the remote networks as allowed IPs of this peer.</p>
|
||||
''')
|
||||
}
|
||||
if 'active_worker' in form.fields:
|
||||
context['form_description']['content'] += _('''
|
||||
<h5>Connected server</h5>
|
||||
<p>Only one cluster server connects to the endpoint. When empty, the primary server connects to it.</p>
|
||||
''')
|
||||
context['form_description']['content'] += _('''
|
||||
<h5>Client configuration</h5>
|
||||
<p>Peers with an endpoint have no configuration to download, QR code or VPN invite.</p>
|
||||
''')
|
||||
return render(request, 'generic_form.html', context)
|
||||
|
||||
|
||||
|
||||
@@ -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:
|
||||
|
||||
+10
-25
@@ -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
|
||||
|
||||
Reference in New Issue
Block a user