summaryrefslogtreecommitdiff
path: root/src
diff options
context:
space:
mode:
Diffstat (limited to 'src')
-rwxr-xr-xsrc/conf_mode/policy.py73
-rwxr-xr-xsrc/op_mode/show_dhcpv6.py2
-rwxr-xr-xsrc/op_mode/wireguard_client.py118
3 files changed, 188 insertions, 5 deletions
diff --git a/src/conf_mode/policy.py b/src/conf_mode/policy.py
index f0348fe06..fb732dd81 100755
--- a/src/conf_mode/policy.py
+++ b/src/conf_mode/policy.py
@@ -25,6 +25,27 @@ from vyos import frr
from vyos import airbag
airbag.enable()
+def routing_policy_find(key, dictionary):
+ # Recursively traverse a dictionary and extract the value assigned to
+ # a given key as generator object. This is made for routing policies,
+ # thus also import/export is checked
+ for k, v in dictionary.items():
+ if k == key:
+ if isinstance(v, dict):
+ for a, b in v.items():
+ if a in ['import', 'export']:
+ yield b
+ else:
+ yield v
+ elif isinstance(v, dict):
+ for result in routing_policy_find(key, v):
+ yield result
+ elif isinstance(v, list):
+ for d in v:
+ if isinstance(d, dict):
+ for result in routing_policy_find(key, d):
+ yield result
+
def get_config(config=None):
if config:
conf = config
@@ -35,6 +56,15 @@ def get_config(config=None):
policy = conf.get_config_dict(base, key_mangling=('-', '_'), get_first_key=True,
no_tag_node_value_mangle=True)
+ # We also need some additional information from the config, prefix-lists
+ # and route-maps for instance. They will be used in verify().
+ #
+ # XXX: one MUST always call this without the key_mangling() option! See
+ # vyos.configverify.verify_common_route_maps() for more information.
+ tmp = conf.get_config_dict(['protocols'], key_mangling=('-', '_'),
+ no_tag_node_value_mangle=True)
+ # Merge policy dict into "regular" config dict
+ policy = dict_merge(tmp, policy)
return policy
def verify(policy):
@@ -64,20 +94,24 @@ def verify(policy):
if policy_type == 'access_list':
if 'source' not in rule_config:
- raise ConfigError(f'Source {mandatory_error}')
+ raise ConfigError(f'A source {mandatory_error}')
if int(instance) in range(100, 200) or int(instance) in range(2000, 2700):
if 'destination' not in rule_config:
- raise ConfigError(f'Destination {mandatory_error}')
+ raise ConfigError(f'A destination {mandatory_error}')
if policy_type == 'access_list6':
if 'source' not in rule_config:
- raise ConfigError(f'Source {mandatory_error}')
+ raise ConfigError(f'A source {mandatory_error}')
if policy_type in ['as_path_list', 'community_list', 'extcommunity_list',
'large_community_list']:
if 'regex' not in rule_config:
- raise ConfigError(f'Regex {mandatory_error}')
+ raise ConfigError(f'A regex {mandatory_error}')
+
+ if policy_type in ['prefix_list', 'prefix_list6']:
+ if 'prefix' not in rule_config:
+ raise ConfigError(f'A prefix {mandatory_error}')
# route-maps tend to be a bit more complex so they get their own verify() section
@@ -102,6 +136,37 @@ def verify(policy):
if tmp and tmp not in policy.get('large_community_list', []):
raise ConfigError(f'large-community-list {tmp} does not exist!')
+ # Specified prefix-list must exist
+ tmp = dict_search('match.ip.address.prefix_list', rule_config)
+ if tmp and tmp not in policy.get('prefix_list', []):
+ raise ConfigError(f'prefix-list {tmp} does not exist!')
+
+ # Specified prefix-list must exist
+ tmp = dict_search('match.ipv6.address.prefix_list', rule_config)
+ if tmp and tmp not in policy.get('prefix_list6', []):
+ raise ConfigError(f'prefix-list6 {tmp} does not exist!')
+
+ # When routing protocols are active some use prefix-lists, route-maps etc.
+ # to apply the systems routing policy to the learned or redistributed routes.
+ # When the "routing policy" changes and policies, route-maps etc. are deleted,
+ # it is our responsibility to verify that the policy can not be deleted if it
+ # is used by any routing protocol
+ if 'protocols' in policy:
+ for policy_type in ['access_list', 'access_list6', 'as_path_list', 'community_list',
+ 'extcommunity_list', 'large_community_list', 'prefix_list', 'route_map']:
+ if policy_type in policy:
+ for policy_name in list(set(routing_policy_find(policy_type, policy['protocols']))):
+ found = False
+ if policy_name in policy[policy_type]:
+ found = True
+ # BGP uses prefix-list for selecting both an IPv4 or IPv6 AFI related
+ # list - we need to go the extra mile here and check both prefix-lists
+ if policy_type == 'prefix_list' and 'prefix_list6' in policy and policy_name in policy['prefix_list6']:
+ found = True
+ if not found:
+ tmp = policy_type.replace('_','-')
+ raise ConfigError(f'Can not delete {tmp} "{name}", still in use!')
+
return None
def generate(policy):
diff --git a/src/op_mode/show_dhcpv6.py b/src/op_mode/show_dhcpv6.py
index ac211fb0a..f70f04298 100755
--- a/src/op_mode/show_dhcpv6.py
+++ b/src/op_mode/show_dhcpv6.py
@@ -139,7 +139,7 @@ def get_leases(config, leases, state, pool=None, sort='ip'):
# apply output/display sort
if sort == 'ip':
- leases = sorted(leases, key = lambda k: int(ip_address(k['ip'])))
+ leases = sorted(leases, key = lambda k: int(ip_address(k['ip'].split('/')[0])))
else:
leases = sorted(leases, key = lambda k: k[sort])
diff --git a/src/op_mode/wireguard_client.py b/src/op_mode/wireguard_client.py
new file mode 100755
index 000000000..7a620a01e
--- /dev/null
+++ b/src/op_mode/wireguard_client.py
@@ -0,0 +1,118 @@
+#!/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/>.
+
+import argparse
+import os
+
+from jinja2 import Template
+from ipaddress import ip_interface
+
+from vyos.ifconfig import Section
+from vyos.template import is_ipv4
+from vyos.template import is_ipv6
+from vyos.util import cmd
+from vyos.util import popen
+
+if os.geteuid() != 0:
+ exit("You need to have root privileges to run this script.\nPlease try again, this time using 'sudo'. Exiting.")
+
+server_config = """WireGuard client configuration for interface: {{ interface }}
+
+To enable this configuration on a VyOS router you can use the following commands:
+
+=== VyOS (server) configurtation ===
+
+{% 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 }}'
+"""
+
+client_config = """
+=== RoadWarrior (client) configuration ===
+
+[Interface]
+PrivateKey = {{ privkey }}
+{% if address is defined and address|length > 0 %}
+Address = {{ address | join(', ')}}
+{% endif %}
+DNS = 1.1.1.1
+
+[Peer]
+PublicKey = {{ system_pubkey }}
+Endpoint = {{ server }}:{{ port }}
+AllowedIPs = 0.0.0.0/0, ::/0
+
+"""
+
+if __name__ == '__main__':
+ parser = argparse.ArgumentParser()
+ parser.add_argument("-n", "--name", type=str, help='WireGuard peer name', required=True)
+ parser.add_argument("-i", "--interface", type=str, help='WireGuard interface the client is connecting to', required=True)
+ parser.add_argument("-s", "--server", type=str, help='WireGuard server IPv4/IPv6 address or FQDN', required=True)
+ parser.add_argument("-a", "--address", type=str, help='WireGuard client IPv4/IPv6 address', action='append')
+ args = parser.parse_args()
+
+ interface = args.interface
+ if interface not in Section.interfaces('wireguard'):
+ exit(f'WireGuard interface "{interface}" does not exist!')
+
+ wg_pubkey = cmd(f'wg show {interface} | grep "public key"').split(':')[-1].lstrip()
+ wg_port = cmd(f'wg show {interface} | grep "listening port"').split(':')[-1].lstrip()
+
+ # Generate WireGuard private key
+ privkey,_ = popen('wg genkey')
+ # Generate public key portion from given private key
+ pubkey,_ = popen('wg pubkey', input=privkey)
+
+ config = {
+ 'name' : args.name,
+ 'interface' : interface,
+ 'system_pubkey' : wg_pubkey,
+ 'privkey': privkey,
+ 'pubkey' : pubkey,
+ 'server' : args.server,
+ 'port' : wg_port,
+ 'address' : [],
+ }
+
+ if args.address:
+ v4_addr = 0
+ v6_addr = 0
+ for tmp in args.address:
+ try:
+ ip = str(ip_interface(tmp).ip)
+ if is_ipv4(tmp):
+ config['address'].append(f'{ip}/32')
+ v4_addr += 1
+ elif is_ipv6(tmp):
+ config['address'].append(f'{ip}/128')
+ v6_addr += 1
+ except:
+ print(tmp)
+ exit('Client IP address invalid!')
+
+ if (v4_addr > 1) or (v6_addr > 1):
+ exit('Client can only have one IPv4 and one IPv6 address.')
+
+ # Clear out terminal first
+ print('\x1b[2J\x1b[H')
+ server = Template(server_config, trim_blocks=True).render(config)
+ print(server)
+ client = Template(client_config, trim_blocks=True).render(config)
+ print(client)
+ qrcode,err = popen('qrencode -t ansiutf8', input=client)
+ print(qrcode)