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:
+79
-2
@@ -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
|
||||
@@ -57,7 +59,81 @@ class PeerKeysForm(PeerModelForm):
|
||||
class Meta:
|
||||
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)
|
||||
|
||||
|
||||
|
||||
Reference in New Issue
Block a user