diff --git a/freedombox/modules/wireguard/forms.py b/freedombox/modules/wireguard/forms.py index fa480c2d6..19282be13 100644 --- a/freedombox/modules/wireguard/forms.py +++ b/freedombox/modules/wireguard/forms.py @@ -5,7 +5,7 @@ Forms for wireguard module. import base64 import binascii -import ipaddress +from ipaddress import IPv4Interface, IPv6Interface, ip_interface from django import forms from django.core.exceptions import ValidationError @@ -55,12 +55,13 @@ def validate_endpoint(endpoint): raise ValidationError('Invalid endpoint.') -def validate_ip_address_with_network(value: str): +def validate_ip_addresses(value: str): """Check that value is a valid IP address with an optional network.""" try: - ipaddress.ip_interface(value) + for ip_address in value.split(','): + ip_interface(ip_address.strip()) except ValueError: - raise ValidationError(_('Not a valid IP address.')) + raise ValidationError(_('Not a valid list of IP addresses.')) class AddClientForm(forms.Form): @@ -86,16 +87,16 @@ class AddServerForm(forms.Form): 'Example: MConEJFIg6+DFHg2J1nn9SNLOSE9KR0ysdPgmPjibEs= .'), validators=[validate_key]) - ip_address_and_network = forms.CharField( - label=_('Client IP address provided by server'), strip=True, + ip_addresses = forms.CharField( + label=_('Client IP addresses provided by server'), strip=True, help_text=_( - 'IP address assigned to this machine on the VPN after connecting ' - 'to the endpoint. This value is usually provided by the server ' - 'operator. Example: 192.168.0.10 or ' + 'Comma separated list of IP addresses assigned to this machine on ' + 'the VPN after connecting to the endpoint. This value is usually ' + 'provided by server operator. Example: 192.168.0.10, ' '2a03:7c80:4b2c:91a2:5d41:ffee:9b82:7c17. You can also specify ' 'the network. This will allow reaching machines in the network. ' - 'Examples: 10.68.12.43/24 or 10.68.12.43/255.255.255.0.'), - validators=[validate_ip_address_with_network]) + 'Examples: 10.68.12.43/24, 10.68.12.43/255.255.255.0.'), + validators=[validate_ip_addresses]) private_key = forms.CharField( label=_('Private key of this machine'), strip=True, help_text=_( @@ -143,13 +144,19 @@ class AddServerForm(forms.Form): def get_settings(self) -> dict[str, dict]: """Return NM settings dict from cleaned data.""" - ip_interface = ipaddress.ip_interface( - self.cleaned_data['ip_address_and_network']) + allowed_ips: list[str] = [] + ipv4_interface: IPv4Interface | None = None + ipv6_interface: IPv6Interface | None = None + for ip in self.cleaned_data['ip_addresses'].split(','): + ip = ip_interface(ip.strip()) + allowed_ips.append(str(ip)) + if ip.ip.version == 4: + ipv4_interface = ip + else: + ipv6_interface = ip if self.cleaned_data['default_route']: allowed_ips = ['0.0.0.0/0', '::/0'] - else: - allowed_ips = [str(ip_interface)] settings = { 'common': { @@ -165,9 +172,10 @@ class AddServerForm(forms.Form): } } - if ip_interface.version == 4: - settings['ipv4'] = self._build_ipv4_settings(ip_interface) - else: - settings['ipv6'] = self._build_ipv6_settings(ip_interface) + if ipv4_interface: + settings['ipv4'] = self._build_ipv4_settings(ipv4_interface) + + if ipv6_interface: + settings['ipv6'] = self._build_ipv6_settings(ipv6_interface) return settings diff --git a/freedombox/modules/wireguard/templates/wireguard.html b/freedombox/modules/wireguard/templates/wireguard.html index ac54d721a..f6544262a 100644 --- a/freedombox/modules/wireguard/templates/wireguard.html +++ b/freedombox/modules/wireguard/templates/wireguard.html @@ -42,7 +42,15 @@ {{ box_name }} VPN IP for services {% endblocktrans %} - {{ server.ip_address }} + {{ server.ipv4_address }}, {{ server.ipv6_address }} + + + + {% blocktrans trimmed %} + {{ box_name }} DNS server + {% endblocktrans %} + + {{ server.ipv4_address }} diff --git a/freedombox/modules/wireguard/templates/wireguard_add_client.html b/freedombox/modules/wireguard/templates/wireguard_add_client.html index 909066ddd..994423228 100644 --- a/freedombox/modules/wireguard/templates/wireguard_add_client.html +++ b/freedombox/modules/wireguard/templates/wireguard_add_client.html @@ -15,14 +15,15 @@ {{ form|bootstrap }} - {% if next_ip %} + {% if next_ipv4_address and next_ipv6_address %}
-
{% endif %} diff --git a/freedombox/modules/wireguard/templates/wireguard_auto_add_client.html b/freedombox/modules/wireguard/templates/wireguard_auto_add_client.html index ffd36698c..ecb61d46d 100644 --- a/freedombox/modules/wireguard/templates/wireguard_auto_add_client.html +++ b/freedombox/modules/wireguard/templates/wireguard_auto_add_client.html @@ -60,12 +60,12 @@ {{ client_privkey }} - {% trans "Client IP Address" %} - {{ next_ip }} + {% trans "Client IP Addresses" %} + {{ ipv4_address }}, {{ ipv6_address }} {% trans "Client DNS Server" %} - 10.84.0.1 + {{ server_ipv4_address }} {% trans "Server/Peer Public Key" %} diff --git a/freedombox/modules/wireguard/templates/wireguard_show_client.html b/freedombox/modules/wireguard/templates/wireguard_show_client.html index 9a5e5ae58..f0d494b61 100644 --- a/freedombox/modules/wireguard/templates/wireguard_show_client.html +++ b/freedombox/modules/wireguard/templates/wireguard_show_client.html @@ -23,7 +23,7 @@ {{ client.public_key }} - {% trans "IP address to use for client:" %} + {% trans "IP addresses to use for client:" %} {{ client.allowed_ips|join:", " }} @@ -44,7 +44,11 @@ {% trans "Server VPN IP address for services:" %} - {{ server.ip_address }} + {{ server.ipv4_address }}, {{ server.ipv6_address }} + + + {% trans "DNS Server:" %} + {{ server.ipv4_address }} diff --git a/freedombox/modules/wireguard/templates/wireguard_show_server.html b/freedombox/modules/wireguard/templates/wireguard_show_server.html index 12adb99ec..1d31c5c50 100644 --- a/freedombox/modules/wireguard/templates/wireguard_show_server.html +++ b/freedombox/modules/wireguard/templates/wireguard_show_server.html @@ -37,9 +37,9 @@ {% trans "Public key of this machine:" %} {{ server.public_key }} - - {% trans "IP address of this machine:" %} - {{ server.ip_address_and_network }} + + {% trans "IP addresses of this machine:" %} + {{ server.ip_addresses|join:', ' }} diff --git a/freedombox/modules/wireguard/tests/test_forms.py b/freedombox/modules/wireguard/tests/test_forms.py index 7a2afae53..688c2545b 100644 --- a/freedombox/modules/wireguard/tests/test_forms.py +++ b/freedombox/modules/wireguard/tests/test_forms.py @@ -6,8 +6,9 @@ Tests for wireguard module forms. import pytest from django.core.exceptions import ValidationError -from freedombox.modules.wireguard.forms import ( - validate_endpoint, validate_ip_address_with_network, validate_key) +from freedombox.modules.wireguard.forms import (validate_endpoint, + validate_ip_addresses, + validate_key) @pytest.mark.parametrize('key', [ @@ -80,7 +81,7 @@ def test_validate_endpoint_invalid_patterns(endpoint): ]) def test_validate_ip_address_with_network_valid_patterns(value): """Test validating IPv4 address with network works for valid values.""" - validate_ip_address_with_network(value) + validate_ip_addresses(value) @pytest.mark.parametrize('value', [ @@ -101,4 +102,23 @@ def test_validate_ip_address_with_network_valid_patterns(value): def test_validate_ip_address_with_network_invalid_patterns(value): """Test validating IPv4 address with network works for invalid values.""" with pytest.raises(ValidationError): - validate_ip_address_with_network(value) + validate_ip_addresses(value) + + +@pytest.mark.parametrize('value', [ + '1.2.3.4,5.6.7.8,2001:db8::1', + '1.2.3.4, 2001:db8::1', +]) +def test_validate_ip_addresses_with_multiple_addresses(value): + """Test validating multiple IP addresses separated by comma.""" + validate_ip_addresses(value) + + +@pytest.mark.parametrize('value', [ + '1.2.3.4 2001:db8::1', + '1.2.3.4, 2001:db8::1,', +]) +def test_validate_ip_addresses_with_invalid_multiple_addresses(value): + """Test validating multiple IP addresses separated by comma.""" + with pytest.raises(ValidationError): + validate_ip_addresses(value) diff --git a/freedombox/modules/wireguard/tests/test_functional.py b/freedombox/modules/wireguard/tests/test_functional.py index 88b660862..8820f6d68 100644 --- a/freedombox/modules/wireguard/tests/test_functional.py +++ b/freedombox/modules/wireguard/tests/test_functional.py @@ -21,16 +21,21 @@ class TestWireguardApp(functional.BaseAppTests): _server = [ { - 'peer_endpoint': 'wg1.example.org:1234', - 'peer_public_key': 'HBCqZk4B93N6q19zNleJkAVs+PEfWAPgPpKnrhL/CVw=', - 'ip_address_and_network': '10.0.0.2/32', - 'private_key': '', - 'preshared_key': '' + 'peer_endpoint': + 'wg1.example.org:1234', + 'peer_public_key': + 'HBCqZk4B93N6q19zNleJkAVs+PEfWAPgPpKnrhL/CVw=', + 'ip_addresses': + '10.0.0.2/32, 2a03:7c80:4b2c:91a2:5d41:ffee:9b82:7c17/128', + 'private_key': + '', + 'preshared_key': + '' }, { 'peer_endpoint': 'wg2.example.org:5678', 'peer_public_key': 'Z/iHo0vaeSN8Ykk5KwhQ819MMU5nyzD7y7xFFthlxXI=', - 'ip_address_and_network': '192.168.0.2/24', + 'ip_addresses': '192.168.0.2/24', 'private_key': 'QC2xEZMn3bgNsSVFrU51+ALSUiUaWg6gRWigh3EeVm0=', 'preshared_key': 'AHxZ4Rr8Ij4L1aq+ceusSIgBfluqiI9Vb5I2UtQFanI=' }, @@ -60,7 +65,9 @@ class TestWireguardApp(functional.BaseAppTests): functional.nav_to_module(browser, 'wireguard') href = browser.links.find_by_href(self._get_client_href(key)) - href.first.click() + with functional.wait_for_page_update(browser): + href.first.click() + assert get_value('client-public-key') == key @staticmethod @@ -186,8 +193,7 @@ class TestWireguardApp(functional.BaseAppTests): assert get_value('peer-endpoint') == config['peer_endpoint'] assert get_value('peer-public-key') == config['peer_public_key'] - assert get_value('server-ip-address-and-network' - ) == config['ip_address_and_network'] + assert get_value('server-ip-addresses') == config['ip_addresses'] assert get_value('peer-preshared-key') == (config['preshared_key'] or 'None') @@ -201,8 +207,7 @@ class TestWireguardApp(functional.BaseAppTests): browser.find_by_id('id_peer_endpoint').fill(config['peer_endpoint']) browser.find_by_id('id_peer_public_key').fill( config['peer_public_key']) - browser.find_by_id('id_ip_address_and_network').fill( - config['ip_address_and_network']) + browser.find_by_id('id_ip_addresses').fill(config['ip_addresses']) browser.find_by_id('id_private_key').fill(config['private_key']) browser.find_by_id('id_preshared_key').fill(config['preshared_key']) functional.submit(browser, form_class='form-add-server') @@ -220,8 +225,7 @@ class TestWireguardApp(functional.BaseAppTests): browser.find_by_id('id_peer_endpoint').fill(config2['peer_endpoint']) browser.find_by_id('id_peer_public_key').fill( config2['peer_public_key']) - browser.find_by_id('id_ip_address_and_network').fill( - config2['ip_address_and_network']) + browser.find_by_id('id_ip_addresses').fill(config2['ip_addresses']) browser.find_by_id('id_private_key').fill(config2['private_key']) browser.find_by_id('id_preshared_key').fill(config2['preshared_key']) functional.submit(browser, form_class='form-edit-server') diff --git a/freedombox/modules/wireguard/utils.py b/freedombox/modules/wireguard/utils.py index c77ef1c11..881a7813f 100644 --- a/freedombox/modules/wireguard/utils.py +++ b/freedombox/modules/wireguard/utils.py @@ -2,9 +2,12 @@ """Utilities for managing WireGuard.""" import datetime +import itertools import logging import subprocess import time +from ipaddress import IPv4Address, IPv6Address +from typing import Tuple from freedombox import app as app_module from freedombox import network @@ -14,19 +17,19 @@ from . import privileged nm = import_from_gi('NM', '1.0') -IP_TEMPLATE = '10.84.0.{}' +_IPV4_ADDRESS = IPv4Address('10.84.0.1') +_IPV6_ADDRESS = IPv6Address('fd84:8484:8484::1') logger = logging.getLogger(__name__) -def _get_nm_address_info(settings_ipv4, settings_ipv6) -> tuple[str, str]: +def _get_nm_address_info(settings) -> tuple[str, str]: """Extract IP address info from NM IPv4/IPv6 settings.""" - for settings in [settings_ipv4, settings_ipv6]: - if settings and settings.get_num_addresses(): - nm_address = settings.get_address(0) - address = nm_address.get_address() - prefix = str(nm_address.get_prefix()) - return address, address + '/' + prefix + if settings and settings.get_num_addresses(): + nm_address = settings.get_address(0) + address = nm_address.get_address() + prefix = str(nm_address.get_prefix()) + return address, address + '/' + prefix return '', '' @@ -78,11 +81,24 @@ def get_nm_info(): settings_ipv4 = connection.get_setting_ip4_config() settings_ipv6 = connection.get_setting_ip6_config() - ip_address, ip_address_and_network = _get_nm_address_info( - settings_ipv4, settings_ipv6) + ipv4_address, ipv4_address_and_network = _get_nm_address_info( + settings_ipv4) + ipv6_address, ipv6_address_and_network = _get_nm_address_info( + settings_ipv6) - info['ip_address'] = ip_address - info['ip_address_and_network'] = ip_address_and_network + info['ipv4_address'] = ipv4_address + info['ipv4_address_and_network'] = ipv4_address_and_network + info['ipv6_address'] = ipv6_address + info['ipv6_address_and_network'] = ipv6_address_and_network + + ip_addresses = [] + if ipv4_address_and_network: + ip_addresses.append(ipv4_address_and_network) + + if ipv6_address_and_network: + ip_addresses.append(ipv6_address_and_network) + + info['ip_addresses'] = ip_addresses connections[info['interface']] = info @@ -171,16 +187,17 @@ def _get_public_key_from_private_key(private_key: str | None) -> str | None: return process.stdout.decode().strip() -def _generate_private_key(): +def _generate_private_key() -> str: """Return a private key generated by 'wg' command.""" process = subprocess.run(['wg', 'genkey'], check=True, capture_output=True) return process.stdout.decode().strip() -def generate_client_keypair(): +def generate_client_keypair() -> Tuple[str, str]: """Generate client private/public keypair.""" private_key = _generate_private_key() public_key = _get_public_key_from_private_key(private_key) + assert public_key return private_key, public_key @@ -277,12 +294,20 @@ def setup_server(): }, 'ipv4': { 'method': 'manual', - 'address': IP_TEMPLATE.format(1), + 'address': str(_IPV4_ADDRESS), 'netmask': '255.255.255.0', 'gateway': '', 'dns': '', 'second_dns': '', }, + 'ipv6': { + 'method': 'manual', + 'address': str(_IPV6_ADDRESS), + 'prefix': '64', + 'gateway': '', + 'dns': '', + 'second_dns': '', + }, 'wireguard': { 'private_key': private_key, 'listen_port': 51820, @@ -302,8 +327,9 @@ def setup_server(): logging.warning('Could not add server') -def _get_next_available_ip_address(settings): - """Get the next available IP address to allocate to a client.""" +def _get_next_available_ip_addresses( + settings=None) -> Tuple[IPv4Address, IPv6Address]: + """Get the next available IPv4/IPv6 address to allocate to a client.""" allocated_ips = set() for peer_index in range(settings.get_peers_len()): peer = settings.get_peer(peer_index) @@ -312,12 +338,22 @@ def _get_next_available_ip_address(settings): # We assume these are simple IP addresses but they can be subnets. allocated_ips.add(allowed_ip) - for index in range(2, 254): - ip_address = IP_TEMPLATE.format(index) - if ip_address not in allocated_ips: - return ip_address + for network_index, ip_index in itertools.product(range(0, 256), + range(1, 254)): + ipv4_address = _IPV4_ADDRESS + network_index * 256 + ip_index + if str(ipv4_address) not in allocated_ips: + break + else: + raise IndexError('Reached client limit') - raise IndexError('Reached client limit') + for index in range(1, 256 * 256): + ipv6_address = _IPV6_ADDRESS + index + if str(ipv6_address) not in allocated_ips: + break + else: + raise IndexError('Reached client limit') + + return ipv4_address, ipv6_address def _server_connection(): @@ -341,8 +377,11 @@ def _server_connection(): return connection -def add_client(public_key): - """Add a permission for a client to connect our server.""" +def add_client(public_key: str) -> Tuple[IPv4Address, IPv6Address]: + """Add a permission for a client to connect our server. + + Return the allocated IPv4 and IPv6 addresses. + """ setting_name = nm.SETTING_WIREGUARD_SETTING_NAME connection = _server_connection() settings = connection.get_setting_by_name(setting_name) @@ -350,10 +389,12 @@ def add_client(public_key): if peer: raise ValueError('Peer with public key already exists') + ipv4_address, ipv6_address = _get_next_available_ip_addresses(settings) peer = nm.WireGuardPeer.new() peer.set_public_key(public_key, False) peer.set_persistent_keepalive(25) # To keep NAT 'connections' alive - peer.append_allowed_ip(_get_next_available_ip_address(settings), False) + peer.append_allowed_ip(str(ipv4_address), False) + peer.append_allowed_ip(str(ipv6_address), False) settings.append_peer(peer) connection.commit_changes_async(True) network.reactivate_connection(connection.get_uuid()) @@ -376,6 +417,8 @@ def add_client(public_key): logging.warning('Error adding client %s', public_key) raise RuntimeError('Error adding client') + return ipv4_address, ipv6_address + def remove_client(public_key): """Remove permission for a client to connect our server.""" @@ -408,8 +451,9 @@ def remove_client(public_key): logging.warning('Could not remove client %s', public_key) -def build_client_config(client_ip: str, client_privkey: str, - client_pubkey: str, endpoint: str) -> str: +def build_client_config(client_ipv4: str, client_ipv6: str, + client_privkey: str, client_pubkey: str, endpoint: str, + server_ipv4_address: str) -> str: """Generate WireGuard client config.""" info = get_info() server_info = info['my_server'] @@ -420,8 +464,8 @@ def build_client_config(client_ip: str, client_privkey: str, return f"""[Interface] PrivateKey = {client_privkey} -Address = {client_ip}/32 -DNS = 10.84.0.1 +Address = {client_ipv4}/32, {client_ipv6}/128 +DNS = {server_ipv4_address} [Peer] PublicKey = {server_pubkey} diff --git a/freedombox/modules/wireguard/views.py b/freedombox/modules/wireguard/views.py index 17e929ced..57900ac25 100644 --- a/freedombox/modules/wireguard/views.py +++ b/freedombox/modules/wireguard/views.py @@ -66,9 +66,11 @@ class AddClientView(SuccessMessageMixin, FormView): connection = utils._server_connection() setting_name = utils.nm.SETTING_WIREGUARD_SETTING_NAME settings = connection.get_setting_by_name(setting_name) - context['next_ip'] = utils._get_next_available_ip_address(settings) + (context['next_ipv4_address'], context['next_ipv6_address'] + ) = utils._get_next_available_ip_address(settings) except Exception: - context['next_ip'] = None + context['next_ipv4_address'] = None + context['next_ipv6_address'] = None return context @@ -109,18 +111,18 @@ def auto_add_client_view(request): # Generate key pair client_privkey, client_pubkey = utils.generate_client_keypair() - # Gather information - connection = utils._server_connection() - setting_name = utils.nm.SETTING_WIREGUARD_SETTING_NAME - settings = connection.get_setting_by_name(setting_name) - next_ip = utils._get_next_available_ip_address(settings) - domains_info = {} + # Add a new client + ipv4_address, ipv6_address = utils.add_client(client_pubkey) # Prepare config and QR codes based on endpoint. + server_ipv4_address = server_info['ipv4_address'] + server_ipv6_address = server_info['ipv6_address'] + domains_info = {} for domain in domains: endpoint = f'{domain}:{port}' - config = utils.build_client_config(next_ip, client_privkey, - client_pubkey, endpoint) + config = utils.build_client_config(ipv4_address, ipv6_address, + client_privkey, client_pubkey, + endpoint, server_ipv4_address) qr_code = get_qr_code(config) domains_info[domain] = { @@ -129,17 +131,17 @@ def auto_add_client_view(request): 'config': base64.b64encode(config.encode()).decode(), } - # Add a new client - utils.add_client(client_pubkey) - return TemplateResponse( request, 'wireguard_auto_add_client.html', { 'title': _('Client Added'), 'server_pubkey': server_info['public_key'], 'client_pubkey': client_pubkey, 'client_privkey': client_privkey, - 'next_ip': next_ip, + 'ipv4_address': ipv4_address, + 'ipv6_address': ipv6_address, 'domains': domains_info, + 'server_ipv4_address': server_ipv4_address, + 'server_ipv6_address': server_ipv6_address, }) @@ -287,8 +289,7 @@ class EditServerView(SuccessMessageMixin, FormView): if not server: raise Http404 - initial['ip_address_and_network'] = server.get( - 'ip_address_and_network') + initial['ip_addresses'] = server['ip_addresses'] if server['peers']: peer = next(peer for peer in server['peers'].values()) initial['peer_endpoint'] = peer['endpoint']