wireguard: Allow attaching a name to a client

- Store the names locally in FreedomBox interface as Network Manager does not
support adding a name to a client.

- Auto-generate names for ones that currently don't have names and when
auto-adding a client.

- Allow editing the client name on edit page and manual add page.

- Show name in:
  - WireGuard page
  - Add client page.
  - Auto-add client page.
  - Delete client page.
  - Show client page.

- Link to show client page from name instead of public key in WireGuard.

- Add Edit/Delete buttons in auto-add client page.

- Style delete client page differently.

- Forget all client names when app is uninstalled.

Tests:

- Unit and functional tests work.

- When editing a client, name field is shown. Changing the name works. Changing
the public key and name also works.

- When adding a client manually, name field is shown. Setting a default name
works. Setting a non-default name works.

- On the WireGuard main page, name of client is shown and has link to show
client page. Links works. There is no link on the pubic key.

- When adding a client manually, the name is shown at the top of the page along
with the name field at the bottom.

- When auto-adding a client. Name is shown in the success notice message. Edit
and delete buttons are shown and they work.

- On delete client page, information is shown as table. Name and public key are
shown.

- On show client page, name of the client is shown.

- When clients are added without the patches and patches are applied, when
viewing WireGuard page, all existing clients are given a name automatically.

- After app is uninstalled, the freedombox sqlite3 database does not contain the
key 'wireguard_client_names' in 'freedombox_kvstore' table. Uninstalling without
any clients does not lead to an error.

Reviewed-by: James Valleroy <jvalleroy@mailbox.org>
This commit is contained in:
Sunil Mohan Adapa authored and James Valleroy committed 2026-11-27 07:21:22 -05:00
1 parent 005bed01a3
commit bbd3c59910
9 files changed
+160 -22

No files matched your search

+1
View File
@@ -104,4 +104,5 @@ class WireguardApp(app_module.App):
def uninstall(self):
"""De-configure and uninstall the app."""
utils.delete_connections()
utils.client_remove_all_names()
super().uninstall()
+4
View File
@@ -66,6 +66,10 @@ def validate_ip_addresses(value: str):
class AddClientForm(forms.Form):
"""Form to add client."""
name = forms.CharField(
label=_('Name'), strip=True,
help_text=_('A memorable name to associate with the client.'))
public_key = forms.CharField(
label=_('Public Key'), strip=True, help_text=_(
'Public key of the client to add. Use the provided value or '
@@ -26,6 +26,7 @@
<div class="table-responsive">
<table class="table" id="server-peers-list">
<tr>
<th>{% trans "Name" %}</th>
<th>{% trans "Public Key" %}</th>
<th>{% trans "Client IP addresses" %}</th>
<th>{% trans "Last Connected Time" %}</th>
@@ -36,9 +37,10 @@
<tr>
<td>
<a href="{% url 'wireguard:show-client' peer.public_key|urlencode:'' %}">
{{ peer.public_key }}
{{ peer.name }}
</a>
</td>
<td>{{ peer.public_key }}</td>
<td>{{ peer.allowed_ips|join:", " }}</td>
<td>{{ peer.status.latest_handshake|default:'' }}</td>
</tr>
@@ -22,6 +22,12 @@
<tr>
<td colspan="2" class="fs-4">{% trans "Client" %}</td>
</tr>
<tr>
<th>{% trans "Name" %}</th>
<td class="client-name">{{ client_name }}<br>
{% trans "(Use this or set one yourself)" %}
</td>
</tr>
<tr>
<th>{% trans "Public Key" %}</th>
<td class="client-public-key">{{ client_pubkey }}<br>
@@ -12,7 +12,22 @@
<h3>{{ title }}</h3>
<div class="alert alert-info alert-client-added">
{% trans "New client added with public key:" %} {{ client_pubkey }}
{% blocktrans trimmed %}
New client '{{ client_name }}' added with public key: {{ client_pubkey }}
{% endblocktrans %}
</div>
<div class="btn-toolbar">
<a class="btn btn-default btn-edit-client"
href="{% url 'wireguard:edit-client' client_pubkey|urlencode:'' %}">
{% icon 'pencil-square-o' %}
{% trans "Edit" %}
</a>
<a class="btn btn-default btn-delete-client"
href="{% url 'wireguard:delete-client' client_pubkey|urlencode:'' %}">
{% icon 'trash-o' %}
{% trans "Delete" %}
</a>
</div>
<p>
@@ -13,9 +13,18 @@
<p>
{% trans "Are you sure that you want to delete this client?" %}
</p>
<p>
<b>{{ public_key }}</b>
</p>
<table class="table">
<tbody>
<tr class="client-name">
<th>{% trans "Name" %}</th>
<td>{{ name }}</td>
</tr>
<tr class="client-public-key">
<th>{% trans "Public Key" %}</th>
<td>{{ public_key }}</td>
</tr>
</tbody>
</table>
<form class="form form-delete-client" method="post">
{% csrf_token %}
@@ -21,6 +21,10 @@
<tr>
<td colspan="2" class="fs-4">{% trans "Client" %}</td>
</tr>
<tr class="client-name">
<th>{% trans "Name" %}</th>
<td>{{ client.name }}</td>
</tr>
<tr class="client-public-key">
<th>{% trans "Public Key" %}</th>
<td>{{ client.public_key }}</td>
+85 -12
View File
@@ -3,6 +3,7 @@
import datetime
import itertools
import json
import logging
import socket
import subprocess
@@ -10,8 +11,10 @@ import time
from ipaddress import IPv4Address, IPv6Address, ip_interface
from typing import Tuple
from django.utils.translation import gettext_lazy as _
from freedombox import app as app_module
from freedombox import network
from freedombox import kvstore, network
from freedombox.utils import import_from_gi
from . import privileged
@@ -23,6 +26,70 @@ _IPV6_ADDRESS = IPv6Address('fd84:8484:8484::1')
logger = logging.getLogger(__name__)
_CLIENT_NAMES_KEY = 'wireguard_client_names'
def _client_load_names() -> dict[str, str]:
"""Return client names as a dictionary of public keys to names."""
return json.loads(kvstore.get_default(_CLIENT_NAMES_KEY, '{}'))
def _client_save_names(names: dict[str, str]):
"""Save the dict of public keys to client names."""
kvstore.set(_CLIENT_NAMES_KEY, json.dumps(names))
def client_get_free_name() -> str:
"""Return an unused client name."""
client_names = _client_load_names()
client_names_set = set(client_names.values())
for index in range(1, 10000):
client_name = _('Client') + ' ' + str(index)
if client_name not in client_names_set:
return client_name
else:
raise Exception('Client limit reached')
def client_get_name(public_key: str) -> str:
"""Return a client's name, automatically setting one if not present."""
client_names = _client_load_names()
try:
return client_names[public_key]
except KeyError:
client_names_set = set(client_names.values())
for index in range(1, 10000):
client_name = _('Client') + ' ' + str(index)
if client_name not in client_names_set:
client_names[public_key] = client_name
_client_save_names(client_names)
return client_name
else:
raise Exception('Client limit reached')
def client_set_name(public_key: str, name: str):
"""Set a name for a client or remove it."""
client_names = _client_load_names()
client_names[public_key] = name
_client_save_names(client_names)
def _client_remove_name(public_key: str):
"""Remove a name stored for a client."""
client_names = _client_load_names()
try:
del client_names[public_key]
except KeyError:
return
_client_save_names(client_names)
def client_remove_all_names():
"""Remove all client names."""
kvstore.delete(_CLIENT_NAMES_KEY, ignore_missing=True)
def _get_nm_address_info(settings) -> tuple[str, str]:
"""Extract IP address info from NM IPv4/IPv6 settings."""
@@ -59,12 +126,14 @@ def get_nm_info():
info['peers'] = {}
for peer_index in range(settings.get_peers_len()):
peer = settings.get_peer(peer_index)
public_key = peer.get_public_key()
peer_info = {
'endpoint': peer.get_endpoint(),
'public_key': peer.get_public_key(),
'public_key': public_key,
'preshared_key': peer.get_preshared_key(),
'persistent_keepalive': peer.get_persistent_keepalive(),
'allowed_ips': []
'allowed_ips': [],
'name': client_get_name(public_key)
}
for index in range(peer.get_allowed_ips_len()):
allowed_ip = peer.get_allowed_ip(index, None)
@@ -230,12 +299,12 @@ def add_server(settings):
# Wait upto 10 seconds for server to appear
public_key = settings['wireguard']['peer_public_key']
for _ in range(10):
for _index 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():
for _server_index, server in info['my_client']['servers'].items():
for _public_key, peer in server['peers'].items():
if 'public_key' in peer and peer[
'public_key'] == public_key:
found = True
@@ -270,7 +339,7 @@ def delete_server(interface):
network.delete_connection(connection.get_uuid())
# Wait upto 10 seconds for server to disappear
for _ in range(10):
for _index in range(10):
info = get_nm_info()
if interface not in info:
break
@@ -318,7 +387,7 @@ def setup_server():
logger.info('Created new WireGuard server connection')
# Wait upto 10 seconds for server to appear
for _ in range(10):
for _index in range(10):
info = get_info()
if info['my_server'] and info['my_server']['public_key']:
break
@@ -399,7 +468,7 @@ def get_next_available_ip_addresses(
def _server_connection():
"""Return a server connection."""
setting_name = nm.SETTING_WIREGUARD_SETTING_NAME
for _ in range(10):
for _index in range(10):
connection = network.get_connection_by_interface_name('wg0')
if connection:
break
@@ -417,11 +486,13 @@ def _server_connection():
return connection
def add_client(public_key: str) -> Tuple[IPv4Address, IPv6Address]:
def add_client(public_key: str, name: str) -> Tuple[IPv4Address, IPv6Address]:
"""Add a permission for a client to connect our server.
Return the allocated IPv4 and IPv6 addresses.
"""
client_set_name(public_key, name)
setting_name = nm.SETTING_WIREGUARD_SETTING_NAME
connection = _server_connection()
settings = connection.get_setting_by_name(setting_name)
@@ -462,6 +533,8 @@ def add_client(public_key: str) -> Tuple[IPv4Address, IPv6Address]:
def remove_client(public_key):
"""Remove permission for a client to connect our server."""
_client_remove_name(public_key)
setting_name = nm.SETTING_WIREGUARD_SETTING_NAME
connection = _server_connection()
settings = connection.get_setting_by_name(setting_name)
@@ -474,11 +547,11 @@ def remove_client(public_key):
network.reactivate_connection(connection.get_uuid())
# Wait upto 10 seconds for client to disappear
for _ in range(10):
for _index in range(10):
info = get_info()
if info['my_server']:
found = False
for _, peer in info['my_server']['peers'].items():
for _public_key, peer in info['my_server']['peers'].items():
if 'public_key' in peer and peer['public_key'] == public_key:
found = True
break
+29 -5
View File
@@ -58,6 +58,7 @@ class AddClientView(SuccessMessageMixin, FormView):
success_message = _('Added new client.')
_public_key: str | None = None
_private_key: str | None = None
_name: str | None = None
def _get_client_key_pair(self) -> Tuple[str, str]:
"""Return a newly generated public/private key pair."""
@@ -67,6 +68,13 @@ class AddClientView(SuccessMessageMixin, FormView):
return self._private_key, self._public_key
def _get_name(self) -> str:
"""Return a name for the client."""
if not self._name:
self._name = utils.client_get_free_name()
return self._name
def get_context_data(self, **kwargs):
"""Return additional context for rendering the template."""
context = super().get_context_data(**kwargs)
@@ -75,6 +83,9 @@ class AddClientView(SuccessMessageMixin, FormView):
# Server information
context['server'] = utils.get_info()['my_server']
# Get name
context['client_name'] = self._get_name()
# Generate key pair
(context['client_privkey'],
context['client_pubkey']) = self._get_client_key_pair()
@@ -92,14 +103,16 @@ class AddClientView(SuccessMessageMixin, FormView):
def get_initial(self):
"""Return initial form data."""
initial = super().get_initial()
initial['name'] = self._get_name()
initial['public_key'] = self._get_client_key_pair()[1]
return initial
def form_valid(self, form):
"""Add the client."""
name = form.cleaned_data.get('name')
public_key = form.cleaned_data.get('public_key')
try:
utils.add_client(public_key)
utils.add_client(public_key, name)
except ValueError:
messages.warning(self.request,
_('Client with public key already exists'))
@@ -133,7 +146,8 @@ def auto_add_client_view(request):
client_privkey, client_pubkey = utils.generate_client_keypair()
# Add a new client
ipv4_address, ipv6_address = utils.add_client(client_pubkey)
client_name = utils.client_get_free_name()
ipv4_address, ipv6_address = utils.add_client(client_pubkey, client_name)
# Prepare config and QR codes based on endpoint.
server_ipv4_address = server_info['ipv4_address']
@@ -156,6 +170,7 @@ def auto_add_client_view(request):
request, 'wireguard_auto_add_client.html', {
'title': _('Client Added'),
'server_pubkey': server_info['public_key'],
'client_name': client_name,
'client_pubkey': client_pubkey,
'client_privkey': client_privkey,
'ipv4_address': ipv4_address,
@@ -206,22 +221,29 @@ class EditClientView(SuccessMessageMixin, FormView):
def get_initial(self):
"""Get initial form data."""
initial = super().get_initial()
initial['public_key'] = urllib.parse.unquote(self.kwargs['public_key'])
public_key = urllib.parse.unquote(self.kwargs['public_key'])
initial['public_key'] = public_key
initial['name'] = utils.client_get_name(public_key)
return initial
def form_valid(self, form):
"""Update the client."""
old_name = form.initial['name']
name = form.cleaned_data.get('name')
old_public_key = form.initial['public_key']
public_key = form.cleaned_data.get('public_key')
if old_public_key != public_key:
try:
utils.add_client(public_key)
utils.add_client(public_key, name)
except ValueError:
messages.warning(self.request,
_('Client with public key already exists'))
utils.remove_client(old_public_key)
elif old_name != name:
utils.client_set_name(public_key, name)
return super().form_valid(form)
@@ -234,7 +256,9 @@ class DeleteClientView(SuccessMessageMixin, TemplateView):
"""Return additional context data for rendering the template."""
context = super().get_context_data(**kwargs)
context['title'] = _('Delete Client')
context['public_key'] = urllib.parse.unquote(self.kwargs['public_key'])
public_key = urllib.parse.unquote(self.kwargs['public_key'])
context['public_key'] = public_key
context['name'] = utils.client_get_name(public_key)
return context
def post(self, request, public_key):