wireguard: Enable/disable connections along with the app

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-15 14:49:12 -08:00 committed by James Valleroy
parent 0bc097f37d
commit 318df8723a
No known key found for this signature in database
GPG Key ID: 77C0C75E7B650808
2 changed files with 31 additions and 1 deletions

View File

@ -26,6 +26,7 @@ from plinth import cfg, frontpage, menu
from plinth.modules.firewall.components import Firewall
from plinth.utils import format_lazy, import_from_gi
from . import utils
from .manifest import clients # noqa, pylint: disable=unused-import
nm = import_from_gi('NM', '1.0')
@ -89,12 +90,14 @@ class WireguardApp(app_module.App):
from plinth import kvstore
super().enable()
kvstore.set('wireguard-enabled', True)
utils.enable_connections(True)
def disable(self):
"""Disable the app by simply storing a flag in key/value store."""
from plinth import kvstore
super().disable()
kvstore.set('wireguard-enabled', False)
utils.enable_connections(False)
def is_enabled(self):
"""Return whether all leader components are enabled and flag is set."""

View File

@ -114,6 +114,27 @@ def get_info():
}
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 _generate_private_key():
"""Return a private key generated by 'wg' command."""
process = subprocess.run(['wg', 'genkey'], check=True, capture_output=True)
@ -136,9 +157,12 @@ def _find_next_interface():
def add_server(settings):
"""Add information for connecting to a server."""
from plinth.modules.wireguard import app
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()
@ -158,6 +182,8 @@ def edit_server(interface, settings):
def setup_server():
"""Setup a server connection that clients can connect to."""
from plinth.modules.wireguard import app
setting_name = nm.SETTING_WIREGUARD_SETTING_NAME
private_key = _generate_private_key()
settings = {
@ -165,7 +191,8 @@ def setup_server():
'name': 'WireGuard-Server-wg0',
'type': setting_name,
'zone': 'internal',
'interface': 'wg0'
'interface': 'wg0',
'autoconnect': app.is_enabled(),
},
'ipv4': {
'method': 'manual',