Files
FreedomBox/freedombox/modules/wireguard/utils.py
T
Sunil Mohan Adapa 006e3ae18a wireguard: Upgrade app to add IPv6 for server and its peers
Tests:

- Install WireGuard app without patches. Create a few clients. Both the server
and the clients don't have IPv6 addresses assigned to them. Apply the patches.
Restart FreedomBox. WireGuard app setup is run. Server gets an IPv6 address and
so do the clients.

Signed-off-by: Sunil Mohan Adapa <sunil@medhas.org>
Reviewed-by: James Valleroy <jvalleroy@mailbox.org>
2026-11-27 07:21:06 -05:00

515 lines
17 KiB
Python

# SPDX-License-Identifier: AGPL-3.0-or-later
"""Utilities for managing WireGuard."""
import datetime
import itertools
import logging
import socket
import subprocess
import time
from ipaddress import IPv4Address, IPv6Address, ip_interface
from typing import Tuple
from freedombox import app as app_module
from freedombox import network
from freedombox.utils import import_from_gi
from . import privileged
nm = import_from_gi('NM', '1.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) -> tuple[str, str]:
"""Extract IP address info from NM IPv4/IPv6 settings."""
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 '', ''
def get_nm_info():
"""Get information from network manager."""
setting_name = nm.SETTING_WIREGUARD_SETTING_NAME
client = network.get_nm_client()
connections = {}
for connection in client.get_connections():
if connection.get_connection_type() != setting_name:
continue
settings = connection.get_setting_by_name(setting_name)
secrets = connection.get_secrets(setting_name)
connection.update_secrets(setting_name, secrets)
info = {}
info['interface'] = connection.get_interface_name()
info['private_key'] = settings.get_private_key()
info['public_key'] = None
info['listen_port'] = settings.get_listen_port()
info['fwmark'] = settings.get_fwmark()
info['mtu'] = settings.get_mtu()
info['peers'] = {}
for peer_index in range(settings.get_peers_len()):
peer = settings.get_peer(peer_index)
peer_info = {
'endpoint': peer.get_endpoint(),
'public_key': peer.get_public_key(),
'preshared_key': peer.get_preshared_key(),
'persistent_keepalive': peer.get_persistent_keepalive(),
'allowed_ips': []
}
for index in range(peer.get_allowed_ips_len()):
allowed_ip = peer.get_allowed_ip(index, None)
peer_info['allowed_ips'].append(allowed_ip)
info['peers'][peer_info['public_key']] = peer_info
# This is default route when all IPs are in allowed IPs list.
info['default_route'] = False
for peer_info in info['peers'].values():
if ('0.0.0.0/0' in peer_info['allowed_ips']
and '::/0' in peer_info['allowed_ips']):
info['default_route'] = True
settings_ipv4 = connection.get_setting_ip4_config()
settings_ipv6 = connection.get_setting_ip6_config()
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['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
return connections
def get_info():
"""Return server and clients info."""
status = privileged.get_info()
nm_info = get_nm_info()
my_server_info = None
my_client_servers = {}
for interface, info in nm_info.items():
if interface == 'wg0':
my_server_info = info
else:
my_client_servers[interface] = info
# If the NM connection is not active but the device link is up, 'wg
# show' will not show any public key configured on the interface.
if interface not in status or (interface in status and
not status[interface]['public_key']):
info['public_key'] = _get_public_key_from_private_key(
info['private_key'])
continue
info['public_key'] = status[interface]['public_key']
for status_peer in status[interface]['peers']:
if status_peer['latest_handshake']:
status_peer['latest_handshake'] = \
datetime.datetime.fromtimestamp(
status_peer['latest_handshake'])
public_key = status_peer['public_key']
info_peer = info['peers'].setdefault(public_key, {})
info_peer['status'] = status_peer
return {
'my_server': my_server_info,
'my_client': {
'servers': my_client_servers,
},
}
def enable_connections(enable):
"""Activate all connections and set them to auto-connect."""
setting_name = nm.SETTING_WIREGUARD_SETTING_NAME
client = network.get_nm_client()
for connection in client.get_connections():
if connection.get_connection_type() != setting_name:
continue
network.edit_connection(connection,
{'common': {
'autoconnect': enable
}})
if enable:
network.activate_connection(connection.get_uuid())
else:
try:
network.deactivate_connection(connection.get_uuid())
except network.ConnectionNotFound:
pass # Connection is already inactive
def delete_connections():
"""Remove all WireGuard connections."""
setting_name = nm.SETTING_WIREGUARD_SETTING_NAME
client = network.get_nm_client()
for connection in client.get_connections():
if connection.get_connection_type() != setting_name:
continue
connection.delete()
def _get_public_key_from_private_key(private_key: str | None) -> str | None:
"""Return public key from private key running wg command."""
if not private_key:
return None
process = subprocess.run(['wg', 'pubkey'], check=True, capture_output=True,
input=private_key.encode())
return process.stdout.decode().strip()
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() -> 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
def _find_next_interface():
"""Find next unused wireguard interface name."""
output = subprocess.check_output(['wg', 'show',
'interfaces']).decode().strip()
interfaces = output.split()
interface_num = 1
new_interface_name = 'wg1'
while new_interface_name in interfaces:
interface_num += 1
new_interface_name = 'wg' + str(interface_num)
return new_interface_name
def add_server(settings):
"""Add information for connecting to a server."""
app = app_module.App.get('wireguard')
interface_name = _find_next_interface()
settings['common']['name'] = 'WireGuard-Client-' + interface_name
settings['common']['interface'] = interface_name
settings['common']['autoconnect'] = app.is_enabled()
if not settings['wireguard']['private_key']:
settings['wireguard']['private_key'] = _generate_private_key()
network.add_connection(settings)
# Wait upto 10 seconds for server to appear
public_key = settings['wireguard']['peer_public_key']
for _ in range(10):
info = get_info()
if info['my_client'] and info['my_client']['servers']:
found = False
for _, server in info['my_client']['servers'].items():
for _, peer in server['peers'].items():
if 'public_key' in peer and peer[
'public_key'] == public_key:
found = True
break
if found:
break
if found:
break
time.sleep(1)
else:
logging.warning('Could not add server')
def edit_server(interface, settings):
"""Edit information for connecting to a server."""
settings['common']['interface'] = interface
settings['common']['name'] = 'WireGuard-Client-' + interface
if not settings['wireguard']['private_key']:
settings['wireguard']['private_key'] = _generate_private_key()
connection = network.get_connection_by_interface_name(interface)
network.edit_connection(connection, settings)
network.reactivate_connection(connection.get_uuid())
def delete_server(interface):
"""Delete information for connecting to a server."""
connection = network.get_connection_by_interface_name(interface)
network.delete_connection(connection.get_uuid())
# Wait upto 10 seconds for server to disappear
for _ in range(10):
info = get_nm_info()
if interface not in info:
break
time.sleep(1)
else:
logging.warning('Could not delete server')
def setup_server():
"""Setup a server connection that clients can connect to."""
app = app_module.App.get('wireguard')
setting_name = nm.SETTING_WIREGUARD_SETTING_NAME
private_key = _generate_private_key()
settings = {
'common': {
'name': 'WireGuard-Server-wg0',
'type': setting_name,
'zone': 'internal',
'interface': 'wg0',
'autoconnect': app.is_enabled(),
},
'ipv4': {
'method': 'manual',
'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,
}
}
network.add_connection(settings)
logger.info('Created new WireGuard server connection')
# Wait upto 10 seconds for server to appear
for _ in range(10):
info = get_info()
if info['my_server'] and info['my_server']['public_key']:
break
time.sleep(1)
else:
logging.warning('Could not add server')
def upgrade_server():
"""Upgrade server to add IPv6 address."""
info = get_info()
if info['my_server']['ipv6_address']:
return
connection = _server_connection()
# Add an IPv6 address to server
settings_ipv6 = connection.get_setting_ip6_config()
ip_address = nm.IPAddress.new(socket.AF_INET6, str(_IPV6_ADDRESS), 128)
settings_ipv6.add_address(ip_address)
settings_ipv6.set_property(nm.SETTING_IP_CONFIG_METHOD,
nm.SETTING_IP6_CONFIG_METHOD_MANUAL)
# Add an IPv6 address to all clients
setting_name = nm.SETTING_WIREGUARD_SETTING_NAME
settings = connection.get_setting_by_name(setting_name)
for peer_index in range(settings.get_peers_len()):
peer = settings.get_peer(peer_index)
if peer.get_allowed_ips_len() == 1:
allowed_ip = ip_interface(peer.get_allowed_ip(0))
if allowed_ip.ip.version == 4:
number = int(str(allowed_ip.ip).rpartition('.')[2])
ipv6_address = _IPV6_ADDRESS + number - 1
new_peer = peer.new_clone(True)
new_peer.append_allowed_ip(str(ipv6_address), False)
settings.set_peer(new_peer, peer_index)
connection.commit_changes_async(True)
network.reactivate_connection(connection.get_uuid())
def get_next_available_ip_addresses(
settings=None) -> Tuple[IPv4Address, IPv6Address]:
"""Get the next available IPv4/IPv6 address to allocate to a client."""
if not settings:
setting_name = nm.SETTING_WIREGUARD_SETTING_NAME
connection = _server_connection()
settings = connection.get_setting_by_name(setting_name)
allocated_ips = set()
for peer_index in range(settings.get_peers_len()):
peer = settings.get_peer(peer_index)
for ip_index in range(peer.get_allowed_ips_len()):
allowed_ip = peer.get_allowed_ip(ip_index)
# We assume these are simple IP addresses but they can be subnets.
allocated_ips.add(allowed_ip)
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')
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():
"""Return a server connection."""
setting_name = nm.SETTING_WIREGUARD_SETTING_NAME
for _ in range(10):
connection = network.get_connection_by_interface_name('wg0')
if connection:
break
time.sleep(1)
if not connection:
raise RuntimeError('Unable to get a server connection.')
# Retrieve secrets so that when the connection is changed, secrets are
# preserved properly.
secrets = connection.get_secrets(setting_name)
connection.update_secrets(setting_name, secrets)
return connection
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)
peer, _ = settings.get_peer_by_public_key(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(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())
# Wait upto 10 seconds for client to appear
for _ in range(10):
info = get_info()
if info['my_server'] and info['my_server']['peers']:
found = False
for _, peer in info['my_server']['peers'].items():
if 'public_key' in peer and peer['public_key'] == public_key:
found = True
break
if found:
break
time.sleep(1)
else:
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."""
setting_name = nm.SETTING_WIREGUARD_SETTING_NAME
connection = _server_connection()
settings = connection.get_setting_by_name(setting_name)
peer, peer_index = settings.get_peer_by_public_key(public_key)
if not peer:
raise KeyError('Client not found')
settings.remove_peer(peer_index)
connection.commit_changes_async(True)
network.reactivate_connection(connection.get_uuid())
# Wait upto 10 seconds for client to disappear
for _ in range(10):
info = get_info()
if info['my_server']:
found = False
for _, peer in info['my_server']['peers'].items():
if 'public_key' in peer and peer['public_key'] == public_key:
found = True
break
if not found:
break
time.sleep(1)
else:
logging.warning('Could not remove client %s', public_key)
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']
if not server_info:
raise RuntimeError("WireGuard server not configured")
server_pubkey = server_info['public_key']
return f"""[Interface]
PrivateKey = {client_privkey}
Address = {client_ipv4}/32, {client_ipv6}/128
DNS = {server_ipv4_address}
[Peer]
PublicKey = {server_pubkey}
AllowedIPs = 0.0.0.0/0, ::0/0
Endpoint = {endpoint}
PersistentKeepalive = 25"""