summaryrefslogtreecommitdiff
diff options
context:
space:
mode:
-rw-r--r--interface-definitions/interfaces-wireguard.xml.in12
-rw-r--r--op-mode-definitions/wireguard.xml.in41
-rw-r--r--python/vyos/ifconfig/wireguard.py12
-rwxr-xr-xsmoketest/scripts/cli/test_interfaces_wireguard.py16
-rwxr-xr-xsrc/conf_mode/interfaces-wireguard.py16
-rwxr-xr-xsrc/migration-scripts/interfaces/22-to-2366
-rwxr-xr-xsrc/op_mode/pki.py2
-rwxr-xr-xsrc/op_mode/wireguard.py154
-rwxr-xr-xsrc/op_mode/wireguard_client.py2
9 files changed, 146 insertions, 175 deletions
diff --git a/interface-definitions/interfaces-wireguard.xml.in b/interface-definitions/interfaces-wireguard.xml.in
index 378251fed..773bde09c 100644
--- a/interface-definitions/interfaces-wireguard.xml.in
+++ b/interface-definitions/interfaces-wireguard.xml.in
@@ -42,12 +42,12 @@
</leafNode>
<leafNode name="private-key">
<properties>
- <help>Private key to use on that interface</help>
- <completionHelp>
- <script>${vyos_op_scripts_dir}/wireguard.py --listkdir</script>
- </completionHelp>
+ <help>Base64 encoded private key</help>
+ <constraint>
+ <regex>[0-9a-zA-Z\+/]{43}=$</regex>
+ </constraint>
+ <constraintErrorMessage>Key is not valid 44-character (32-bytes) base64</constraintErrorMessage>
</properties>
- <defaultValue>default</defaultValue>
</leafNode>
<tagNode name="peer">
<properties>
@@ -59,7 +59,7 @@
</properties>
<children>
#include <include/generic-disable-node.xml.i>
- <leafNode name="pubkey">
+ <leafNode name="public-key">
<properties>
<help>base64 encoded public key</help>
<constraint>
diff --git a/op-mode-definitions/wireguard.xml.in b/op-mode-definitions/wireguard.xml.in
index a84980b44..ac3daa3b8 100644
--- a/op-mode-definitions/wireguard.xml.in
+++ b/op-mode-definitions/wireguard.xml.in
@@ -8,24 +8,6 @@
<help>Generate Wireguard keys</help>
</properties>
<children>
- <leafNode name="default-keypair">
- <properties>
- <help>Generate the default Wireguard keypair</help>
- </properties>
- <command>sudo ${vyos_op_scripts_dir}/wireguard.py --genkey</command>
- </leafNode>
- <leafNode name="preshared-key">
- <properties>
- <help>Generate a Wireguard preshared key</help>
- </properties>
- <command>${vyos_op_scripts_dir}/wireguard.py --genpsk</command>
- </leafNode>
- <tagNode name="named-keypairs">
- <properties>
- <help>Generate specified Wireguard keypairs</help>
- </properties>
- <command>sudo ${vyos_op_scripts_dir}/wireguard.py --genkey --location "$4"</command>
- </tagNode>
<tagNode name="client-config">
<properties>
<help>Generate Client config QR code</help>
@@ -94,25 +76,20 @@
<help>Show Wireguard keys</help>
</properties>
<children>
- <tagNode name="pubkey">
+ <leafNode name="pubkey">
<properties>
- <help>Show specified Wireguard public key</help>
- <completionHelp>
- <script>${vyos_op_scripts_dir}/wireguard.py --listkdir</script>
- </completionHelp>
+ <help>Show Wireguard public keys</help>
</properties>
- <command>${vyos_op_scripts_dir}/wireguard.py --showpub --location "$5"</command>
- </tagNode>
- <tagNode name="privkey">
+ <command>${vyos_op_scripts_dir}/wireguard.py --showpub</command>
+ </leafNode>
+ <leafNode name="privkey">
<properties>
- <help>Show specified Wireguard private key</help>
- <completionHelp>
- <script>${vyos_op_scripts_dir}/wireguard.py --listkdir</script>
- </completionHelp>
+ <help>Show Wireguard private keys</help>
</properties>
- <command>${vyos_op_scripts_dir}/wireguard.py --showpriv --location "$5"</command>
- </tagNode>
+ <command>${vyos_op_scripts_dir}/wireguard.py --showpriv</command>
+ </leafNode>
</children>
+ <command>${vyos_op_scripts_dir}/wireguard.py --showpub --showpriv</command>
</node>
</children>
</node>
diff --git a/python/vyos/ifconfig/wireguard.py b/python/vyos/ifconfig/wireguard.py
index e5b9c4408..c4cf2fbbf 100644
--- a/python/vyos/ifconfig/wireguard.py
+++ b/python/vyos/ifconfig/wireguard.py
@@ -95,7 +95,7 @@ class WireGuardOperational(Operational):
for peer in c.list_effective_nodes(["peer"]):
if wgdump['peers']:
- pubkey = c.return_effective_value(["peer", peer, "pubkey"])
+ pubkey = c.return_effective_value(["peer", peer, "public_key"])
if pubkey in wgdump['peers']:
wgpeer = wgdump['peers'][pubkey]
@@ -194,11 +194,15 @@ class WireGuardIf(Interface):
peer = config['peer_remove'][tmp]
peer['ifname'] = config['ifname']
- cmd = 'wg set {ifname} peer {pubkey} remove'
+ cmd = 'wg set {ifname} peer {public_key} remove'
self._cmd(cmd.format(**peer))
+ config['private_key_file'] = '/tmp/tmp.wireguard.key'
+ with open(config['private_key_file'], 'w') as f:
+ f.write(config['private_key'])
+
# Wireguard base command is identical for every peer
- base_cmd = 'wg set {ifname} private-key {private_key}'
+ base_cmd = 'wg set {ifname} private-key {private_key_file}'
if 'port' in config:
base_cmd += ' listen-port {port}'
if 'fwmark' in config:
@@ -210,7 +214,7 @@ class WireGuardIf(Interface):
peer = config['peer'][tmp]
# start of with a fresh 'wg' command
- cmd = base_cmd + ' peer {pubkey}'
+ cmd = base_cmd + ' peer {public_key}'
# If no PSK is given remove it by using /dev/null - passing keys via
# the shell (usually bash) is considered insecure, thus we use a file
diff --git a/smoketest/scripts/cli/test_interfaces_wireguard.py b/smoketest/scripts/cli/test_interfaces_wireguard.py
index d31ec0332..3707eaac3 100755
--- a/smoketest/scripts/cli/test_interfaces_wireguard.py
+++ b/smoketest/scripts/cli/test_interfaces_wireguard.py
@@ -21,11 +21,6 @@ from base_vyostest_shim import VyOSUnitTestSHIM
from vyos.configsession import ConfigSession
from vyos.configsession import ConfigSessionError
-
-# Generate WireGuard default keypair
-if not os.path.isdir('/config/auth/wireguard/default'):
- os.system('sudo /usr/libexec/vyos/op_mode/wireguard.py --genkey')
-
base_path = ['interfaces', 'wireguard']
class WireGuardInterfaceTest(VyOSUnitTestSHIM.TestCase):
@@ -42,12 +37,15 @@ class WireGuardInterfaceTest(VyOSUnitTestSHIM.TestCase):
# Create WireGuard interfaces with associated peers
for intf in self._interfaces:
peer = 'foo-' + intf
+ privkey = '6ISOkASm6VhHOOSz/5iIxw+Q9adq9zA17iMM4X40dlc='
psk = 'u2xdA70hkz0S1CG0dZlOh0aq2orwFXRIVrKo4DCvHgM='
pubkey = 'n6ZZL7ph/QJUJSUUTyu19c77my1dRCDHkMzFQUO9Z3A='
for addr in self._test_addr:
self.cli_set(base_path + [intf, 'address', addr])
+ self.cli_set(base_path + [intf, 'private-key', privkey])
+
self.cli_set(base_path + [intf, 'peer', peer, 'address', '127.0.0.1'])
self.cli_set(base_path + [intf, 'peer', peer, 'port', '1337'])
@@ -57,7 +55,7 @@ class WireGuardInterfaceTest(VyOSUnitTestSHIM.TestCase):
self.cli_set(base_path + [intf, 'peer', peer, 'allowed-ips', ip])
self.cli_set(base_path + [intf, 'peer', peer, 'preshared-key', psk])
- self.cli_set(base_path + [intf, 'peer', peer, 'pubkey', pubkey])
+ self.cli_set(base_path + [intf, 'peer', peer, 'public-key', pubkey])
self.cli_commit()
self.assertTrue(os.path.isdir(f'/sys/class/net/{intf}'))
@@ -68,17 +66,19 @@ class WireGuardInterfaceTest(VyOSUnitTestSHIM.TestCase):
# Remove one of the configured peers.
interface = 'wg0'
port = '12345'
+ privkey = '6ISOkASm6VhHOOSz/5iIxw+Q9adq9zA17iMM4X40dlc='
pubkey_1 = 'n1CUsmR0M2LUUsyicBd6blZICwUqqWWHbu4ifZ2/9gk='
pubkey_2 = 'ebFx/1G0ti8tvuZd94sEIosAZZIznX+dBAKG/8DFm0I='
self.cli_set(base_path + [interface, 'address', '172.16.0.1/24'])
+ self.cli_set(base_path + [interface, 'private-key', privkey])
- self.cli_set(base_path + [interface, 'peer', 'PEER01', 'pubkey', pubkey_1])
+ self.cli_set(base_path + [interface, 'peer', 'PEER01', 'public-key', pubkey_1])
self.cli_set(base_path + [interface, 'peer', 'PEER01', 'port', port])
self.cli_set(base_path + [interface, 'peer', 'PEER01', 'allowed-ips', '10.205.212.10/32'])
self.cli_set(base_path + [interface, 'peer', 'PEER01', 'address', '192.0.2.1'])
- self.cli_set(base_path + [interface, 'peer', 'PEER02', 'pubkey', pubkey_2])
+ self.cli_set(base_path + [interface, 'peer', 'PEER02', 'public-key', pubkey_2])
self.cli_set(base_path + [interface, 'peer', 'PEER02', 'port', port])
self.cli_set(base_path + [interface, 'peer', 'PEER02', 'allowed-ips', '10.205.212.11/32'])
self.cli_set(base_path + [interface, 'peer', 'PEER02', 'address', '192.0.2.2'])
diff --git a/src/conf_mode/interfaces-wireguard.py b/src/conf_mode/interfaces-wireguard.py
index 024ab8f59..4c566a5ad 100755
--- a/src/conf_mode/interfaces-wireguard.py
+++ b/src/conf_mode/interfaces-wireguard.py
@@ -46,17 +46,14 @@ def get_config(config=None):
base = ['interfaces', 'wireguard']
wireguard = get_interface_dict(conf, base)
- # Mangle private key - it has a default so its always valid
- wireguard['private_key'] = '/config/auth/wireguard/{private_key}/private.key'.format(**wireguard)
-
# Determine which Wireguard peer has been removed.
# Peers can only be removed with their public key!
dict = {}
tmp = node_changed(conf, ['peer'], key_mangling=('-', '_'))
for peer in (tmp or []):
- pubkey = leaf_node_changed(conf, ['peer', peer, 'pubkey'])
- if pubkey:
- dict = dict_merge({'peer_remove' : {peer : {'pubkey' : pubkey[0]}}}, dict)
+ public_key = leaf_node_changed(conf, ['peer', peer, 'public_key'])
+ if public_key:
+ dict = dict_merge({'peer_remove' : {peer : {'public_key' : public_key[0]}}}, dict)
wireguard.update(dict)
return wireguard
@@ -70,9 +67,8 @@ def verify(wireguard):
verify_address(wireguard)
verify_vrf(wireguard)
- if not os.path.exists(wireguard['private_key']):
- raise ConfigError('Wireguard private-key not found! Execute: ' \
- '"run generate wireguard [default-keypair|named-keypairs]"')
+ if 'private_key' not in wireguard:
+ raise ConfigError('Wireguard private-key not defined')
if 'peer' not in wireguard:
raise ConfigError('At least one Wireguard peer is required!')
@@ -84,7 +80,7 @@ def verify(wireguard):
if 'allowed_ips' not in peer:
raise ConfigError(f'Wireguard allowed-ips required for peer "{tmp}"!')
- if 'pubkey' not in peer:
+ if 'public_key' not in peer:
raise ConfigError(f'Wireguard public-key required for peer "{tmp}"!')
if ('address' in peer and 'port' not in peer) or ('port' in peer and 'address' not in peer):
diff --git a/src/migration-scripts/interfaces/22-to-23 b/src/migration-scripts/interfaces/22-to-23
new file mode 100755
index 000000000..c52a26908
--- /dev/null
+++ b/src/migration-scripts/interfaces/22-to-23
@@ -0,0 +1,66 @@
+#!/usr/bin/env python3
+#
+# Copyright (C) 2021 VyOS maintainers and contributors
+#
+# This program is free software; you can redistribute it and/or modify
+# it under the terms of the GNU General Public License version 2 or later as
+# published by the Free Software Foundation.
+#
+# This program is distributed in the hope that it will be useful,
+# but WITHOUT ANY WARRANTY; without even the implied warranty of
+# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+# GNU General Public License for more details.
+#
+# You should have received a copy of the GNU General Public License
+# along with this program. If not, see <http://www.gnu.org/licenses/>.
+
+# A VTI interface also requires an IPSec configuration - VyOS 1.2 supported
+# having a VTI interface in the CLI but no IPSec configuration - drop VTI
+# configuration if this is the case for VyOS 1.4
+
+import os
+import sys
+from vyos.configtree import ConfigTree
+
+if __name__ == '__main__':
+ if (len(sys.argv) < 1):
+ print("Must specify file name!")
+ sys.exit(1)
+
+ file_name = sys.argv[1]
+
+ with open(file_name, 'r') as f:
+ config_file = f.read()
+
+ config = ConfigTree(config_file)
+ base = ['interfaces', 'wireguard']
+ if not config.exists(base):
+ # Nothing to do
+ sys.exit(0)
+
+ for interface in config.list_nodes(base):
+ private_key_path = base + [interface, 'private-key']
+
+ key_file = 'default'
+ if config.exists(private_key_path):
+ key_file = config.return_value(private_key_path)
+
+ full_key_path = f'/config/auth/wireguard/{key_file}/private.key'
+
+ if not os.path.exists(full_key_path):
+ print(f'Could not find wireguard private key for migration on interface "{interface}"')
+ continue
+
+ with open(full_key_path, 'r') as f:
+ key_data = f.read().strip()
+ config.set(private_key_path, value=key_data)
+
+ for peer in config.list_nodes(base + [interface, 'peer']):
+ config.rename(base + [interface, 'peer', peer, 'pubkey'], 'public-key')
+
+ try:
+ with open(file_name, 'w') as f:
+ f.write(config.to_string())
+ except OSError as e:
+ print("Failed to save the modified config: {}".format(e))
+ sys.exit(1)
diff --git a/src/op_mode/pki.py b/src/op_mode/pki.py
index 7dbeb4097..b4a68b31c 100755
--- a/src/op_mode/pki.py
+++ b/src/op_mode/pki.py
@@ -215,7 +215,7 @@ def install_wireguard_key(name, private_key, public_key):
print("")
print("Public key for use on peer configuration: " + public_key)
else:
- print("set interfaces wireguard [INTERFACE] peer %s pubkey '%s'" % (name, public_key))
+ print("set interfaces wireguard [INTERFACE] peer %s public-key '%s'" % (name, public_key))
print("")
print("Private key for use on peer configuration: " + private_key)
diff --git a/src/op_mode/wireguard.py b/src/op_mode/wireguard.py
index e08bc983a..3ed8e17ca 100755
--- a/src/op_mode/wireguard.py
+++ b/src/op_mode/wireguard.py
@@ -1,6 +1,6 @@
#!/usr/bin/env python3
#
-# Copyright (C) 2018-2020 VyOS maintainers and contributors
+# Copyright (C) 2018-2021 VyOS maintainers and contributors
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License version 2 or later as
@@ -15,132 +15,65 @@
# along with this program. If not, see <http://www.gnu.org/licenses/>.
import argparse
-import os
import sys
-import shutil
-import syslog as sl
-import re
+import tabulate
from vyos.config import Config
from vyos.ifconfig import WireGuardIf
from vyos.util import cmd
-from vyos.util import run
-from vyos.util import check_kmod
from vyos import ConfigError
-dir = r'/config/auth/wireguard'
-psk = dir + '/preshared.key'
-
-k_mod = 'wireguard'
-
-def generate_keypair(pk, pub):
- """ generates a keypair which is stored in /config/auth/wireguard """
- old_umask = os.umask(0o027)
- if run(f'wg genkey | tee {pk} | wg pubkey > {pub}') != 0:
- raise ConfigError("wireguard key-pair generation failed")
- else:
- sl.syslog(
- sl.LOG_NOTICE, "new keypair wireguard key generated in " + dir)
- os.umask(old_umask)
-
-
-def genkey(location):
- """ helper function to check, regenerate the keypair """
- pk = "{}/private.key".format(location)
- pub = "{}/public.key".format(location)
- old_umask = os.umask(0o027)
- if os.path.exists(pk) and os.path.exists(pub):
- try:
- choice = input(
- "You already have a wireguard key-pair, do you want to re-generate? [y/n] ")
- if choice == 'y' or choice == 'Y':
- generate_keypair(pk, pub)
- except KeyboardInterrupt:
- sys.exit(0)
- else:
- """ if keypair is bing executed from a running iso """
- if not os.path.exists(location):
- run(f'sudo mkdir -p {location}')
- run(f'sudo chgrp vyattacfg {location}')
- run(f'sudo chmod 750 {location}')
- generate_keypair(pk, pub)
- os.umask(old_umask)
-
-
-def showkey(key):
- """ helper function to show privkey or pubkey """
- if os.path.exists(key):
- print (open(key).read().strip())
- else:
- print ("{} not found".format(key))
-
-
-def genpsk():
- """
- generates a preshared key and shows it on stdout,
- it's stored only in the cli config
- """
-
- psk = cmd('wg genpsk')
- print(psk)
-
-def list_key_dirs():
- """ lists all dirs under /config/auth/wireguard """
- if os.path.exists(dir):
- nks = next(os.walk(dir))[1]
- for nk in nks:
- print (nk)
-
-def del_key_dir(kname):
- """ deletes /config/auth/wireguard/<kname> """
- kdir = "{0}/{1}".format(dir,kname)
- if not os.path.isdir(kdir):
- print ("named keypair {} not found".format(kname))
- return 1
- shutil.rmtree(kdir)
-
+base = ['interfaces', 'wireguard']
+
+def get_public_keys():
+ config = Config()
+ headers = ['Interface', 'Peer', 'Public Key']
+ out = []
+ if config.exists(base):
+ wg_interfaces = config.get_config_dict(base, key_mangling=('-', '_'),
+ get_first_key=True,
+ no_tag_node_value_mangle=True)
+
+ for wg, wg_conf in wg_interfaces.items():
+ if 'peer' in wg_conf:
+ for peer, peer_conf in wg_conf['peer'].items():
+ out.append([wg, peer, peer_conf['public_key']])
+
+ print("Wireguard Public Keys:")
+ print(tabulate.tabulate(out, headers))
+
+def get_private_keys():
+ config = Config()
+ headers = ['Interface', 'Private Key', 'Public Key']
+ out = []
+ if config.exists(base):
+ wg_interfaces = config.get_config_dict(base, key_mangling=('-', '_'),
+ get_first_key=True,
+ no_tag_node_value_mangle=True)
+
+ for wg, wg_conf in wg_interfaces.items():
+ private_key = wg_conf['private_key']
+ public_key = cmd('wg pubkey', input=private_key)
+ out.append([wg, private_key, public_key])
+
+ print("Wireguard Private Keys:")
+ print(tabulate.tabulate(out, headers))
if __name__ == '__main__':
- check_kmod(k_mod)
parser = argparse.ArgumentParser(description='wireguard key management')
parser.add_argument(
- '--genkey', action="store_true", help='generate key-pair')
- parser.add_argument(
- '--showpub', action="store_true", help='shows public key')
- parser.add_argument(
- '--showpriv', action="store_true", help='shows private key')
- parser.add_argument(
- '--genpsk', action="store_true", help='generates preshared-key')
- parser.add_argument(
- '--location', action="store", help='key location within {}'.format(dir))
- parser.add_argument(
- '--listkdir', action="store_true", help='lists named keydirectories')
+ '--showpub', action="store_true", help='shows public keys')
parser.add_argument(
- '--delkdir', action="store_true", help='removes named keydirectories')
+ '--showpriv', action="store_true", help='shows private keys')
parser.add_argument(
'--showinterface', action="store", help='shows interface details')
args = parser.parse_args()
try:
- if args.genkey:
- if args.location:
- genkey("{0}/{1}".format(dir, args.location))
- else:
- genkey("{}/default".format(dir))
if args.showpub:
- if args.location:
- showkey("{0}/{1}/public.key".format(dir, args.location))
- else:
- showkey("{}/default/public.key".format(dir))
+ get_public_keys()
if args.showpriv:
- if args.location:
- showkey("{0}/{1}/private.key".format(dir, args.location))
- else:
- showkey("{}/default/private.key".format(dir))
- if args.genpsk:
- genpsk()
- if args.listkdir:
- list_key_dirs()
+ get_private_keys()
if args.showinterface:
try:
intf = WireGuardIf(args.showinterface, create=False, debug=False)
@@ -148,11 +81,6 @@ if __name__ == '__main__':
# the interface does not exists
except Exception:
pass
- if args.delkdir:
- if args.location:
- del_key_dir(args.location)
- else:
- del_key_dir("default")
except ConfigError as e:
print(e)
diff --git a/src/op_mode/wireguard_client.py b/src/op_mode/wireguard_client.py
index 7a620a01e..7661254da 100755
--- a/src/op_mode/wireguard_client.py
+++ b/src/op_mode/wireguard_client.py
@@ -38,7 +38,7 @@ To enable this configuration on a VyOS router you can use the following commands
{% for addr in address if address is defined %}
set interfaces wireguard {{ interface }} peer {{ name }} allowed-ips '{{ addr }}'
{% endfor %}
-set interfaces wireguard {{ interface }} peer {{ name }} pubkey '{{ pubkey }}'
+set interfaces wireguard {{ interface }} peer {{ name }} public-key '{{ pubkey }}'
"""
client_config = """