wireguard: Generate private key if needed when editing server

- Refactor code that edits the connection to server.

Signed-off-by: Sunil Mohan Adapa <sunil@medhas.org>
Reviewed-by: James Valleroy <jvalleroy@mailbox.org>
This commit is contained in:
Sunil Mohan Adapa 2020-01-18 00:05:42 -08:00 committed by James Valleroy
parent 2b9d278a95
commit 69e418ada3
No known key found for this signature in database
GPG Key ID: 77C0C75E7B650808
2 changed files with 24 additions and 9 deletions

View File

@ -114,7 +114,13 @@ def get_info():
}
def find_next_interface():
def _generate_private_key():
"""Return a private key generated by 'wg' command."""
process = subprocess.run(['wg', 'genkey'], check=True, capture_output=True)
return process.stdout.decode().strip()
def _find_next_interface():
"""Find next unused wireguard interface name."""
output = subprocess.check_output(['wg', 'show',
'interfaces']).decode().strip()
@ -130,16 +136,29 @@ def find_next_interface():
def add_server(settings):
"""Add information for connecting to a server."""
interface_name = find_next_interface()
interface_name = _find_next_interface()
settings['common']['name'] = 'WireGuard-Client-' + interface_name
settings['common']['interface'] = interface_name
if not settings['wireguard']['private_key']:
settings['wireguard']['private_key'] = _generate_private_key()
network.add_connection(settings)
def edit_server(interface, settings):
"""Edit information for a 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)
def setup_server():
"""Setup a server connection that clients can connect to."""
process = subprocess.run(['wg', 'genkey'], check=True, capture_output=True)
private_key = process.stdout.decode().strip()
private_key = _generate_private_key()
settings = {
'common': {
'name': 'WireGuard-Server-wg0',

View File

@ -239,12 +239,8 @@ class EditServerView(SuccessMessageMixin, FormView):
def form_valid(self, form):
"""Update the server."""
settings = form.get_settings()
interface = self.kwargs['interface']
settings['common']['interface'] = interface
settings['common']['name'] = 'WireGuard-Client-' + interface
connection = network.get_connection_by_interface_name(interface)
network.edit_connection(connection, settings)
utils.edit_server(interface, form.get_settings())
return super().form_valid(form)