diff --git a/data/templates/dhcp-server/kea-dhcp6.conf.j2 b/data/templates/dhcp-server/kea-dhcp6.conf.j2 index 3ce4e6370..3ab21551b 100644 --- a/data/templates/dhcp-server/kea-dhcp6.conf.j2 +++ b/data/templates/dhcp-server/kea-dhcp6.conf.j2 @@ -1,48 +1,52 @@ { "Dhcp6": { "interfaces-config": { +{% if listen_interface is vyos_defined %} + "interfaces": {{ listen_interface | tojson }}, +{% else %} "interfaces": [ "*" ], +{% endif %} "service-sockets-max-retries": 5, "service-sockets-retry-wait-time": 5000 }, "control-socket": { "socket-type": "unix", "socket-name": "/run/kea/dhcp6-ctrl-socket" }, "lease-database": { "type": "memfile", "persist": true, "name": "{{ lease_file }}" }, "hooks-libraries": [ { "library": "/usr/lib/{{ machine }}-linux-gnu/kea/hooks/libdhcp_lease_cmds.so", "parameters": {} } ], "option-data": [ {% if global_parameters.name_server is vyos_defined %} { "name": "dns-servers", "code": 23, "space": "dhcp6", "csv-format": true, "data": "{{ global_parameters.name_server | join(", ") }}" }{{ ',' if preference is vyos_defined else '' }} {% endif %} {% if preference is vyos_defined %} { "name": "preference", "code": 7, "space": "dhcp6", "csv-format": true, "data": "{{ preference }}" } {% endif %} ], {% if shared_network_name is vyos_defined %} "shared-networks": {{ shared_network_name | kea6_shared_network_json }} {% endif %} } } diff --git a/interface-definitions/include/dhcp/option-v6.xml.i b/interface-definitions/include/dhcp/option-v6.xml.i new file mode 100644 index 000000000..1df0c3934 --- /dev/null +++ b/interface-definitions/include/dhcp/option-v6.xml.i @@ -0,0 +1,110 @@ +<!-- include start from dhcp/option-v6.xml.i --> +<node name="option"> + <properties> + <help>DHCPv6 option</help> + </properties> + <children> + #include <include/dhcp/captive-portal.xml.i> + #include <include/dhcp/domain-search.xml.i> + #include <include/name-server-ipv6.xml.i> + <leafNode name="nis-domain"> + <properties> + <help>NIS domain name for client to use</help> + <constraint> + #include <include/constraint/alpha-numeric-hyphen-underscore-dot.xml.i> + </constraint> + <constraintErrorMessage>Invalid NIS domain name</constraintErrorMessage> + </properties> + </leafNode> + <leafNode name="nis-server"> + <properties> + <help>IPv6 address of a NIS Server</help> + <valueHelp> + <format>ipv6</format> + <description>IPv6 address of NIS server</description> + </valueHelp> + <constraint> + <validator name="ipv6-address"/> + </constraint> + <multi/> + </properties> + </leafNode> + <leafNode name="nisplus-domain"> + <properties> + <help>NIS+ domain name for client to use</help> + <constraint> + #include <include/constraint/alpha-numeric-hyphen-underscore-dot.xml.i> + </constraint> + <constraintErrorMessage>Invalid NIS+ domain name. May only contain letters, numbers and .-_</constraintErrorMessage> + </properties> + </leafNode> + <leafNode name="nisplus-server"> + <properties> + <help>IPv6 address of a NIS+ Server</help> + <valueHelp> + <format>ipv6</format> + <description>IPv6 address of NIS+ server</description> + </valueHelp> + <constraint> + <validator name="ipv6-address"/> + </constraint> + <multi/> + </properties> + </leafNode> + <leafNode name="sip-server"> + <properties> + <help>IPv6 address of SIP server</help> + <valueHelp> + <format>ipv6</format> + <description>IPv6 address of SIP server</description> + </valueHelp> + <valueHelp> + <format>hostname</format> + <description>FQDN of SIP server</description> + </valueHelp> + <constraint> + <validator name="ipv6-address"/> + <validator name="fqdn"/> + </constraint> + <multi/> + </properties> + </leafNode> + <leafNode name="sntp-server"> + <properties> + <help>IPv6 address of an SNTP server for client to use</help> + <constraint> + <validator name="ipv6-address"/> + </constraint> + <multi/> + </properties> + </leafNode> + <node name="vendor-option"> + <properties> + <help>Vendor Specific Options</help> + </properties> + <children> + <node name="cisco"> + <properties> + <help>Cisco specific parameters</help> + </properties> + <children> + <leafNode name="tftp-server"> + <properties> + <help>TFTP server name</help> + <valueHelp> + <format>ipv6</format> + <description>TFTP server IPv6 address</description> + </valueHelp> + <constraint> + <validator name="ipv6-address"/> + </constraint> + <multi/> + </properties> + </leafNode> + </children> + </node> + </children> + </node> + </children> +</node> +<!-- include end --> diff --git a/interface-definitions/service_dhcpv6-server.xml.in b/interface-definitions/service_dhcpv6-server.xml.in index 6934ceeec..07cbfc85d 100644 --- a/interface-definitions/service_dhcpv6-server.xml.in +++ b/interface-definitions/service_dhcpv6-server.xml.in @@ -1,387 +1,291 @@ <?xml version="1.0"?> <interfaceDefinition> <node name="service"> <children> <node name="dhcpv6-server" owner="${vyos_conf_scripts_dir}/service_dhcpv6-server.py"> <properties> <help>DHCP for IPv6 (DHCPv6) server</help> <priority>900</priority> </properties> <children> #include <include/generic-disable-node.xml.i> + #include <include/listen-interface-multi-broadcast.xml.i> <node name="global-parameters"> <properties> <help>Additional global parameters for DHCPv6 server</help> </properties> <children> #include <include/name-server-ipv6.xml.i> </children> </node> <leafNode name="preference"> <properties> <help>Preference of this DHCPv6 server compared with others</help> <valueHelp> <format>u32:0-255</format> <description>DHCPv6 server preference (0-255)</description> </valueHelp> <constraint> <validator name="numeric" argument="--range 0-255"/> </constraint> <constraintErrorMessage>Preference must be between 0 and 255</constraintErrorMessage> </properties> </leafNode> <tagNode name="shared-network-name"> <properties> <help>DHCPv6 shared network name</help> <constraint> #include <include/constraint/alpha-numeric-hyphen-underscore-dot.xml.i> </constraint> <constraintErrorMessage>Invalid DHCPv6 shared network name. May only contain letters, numbers and .-_</constraintErrorMessage> </properties> <children> #include <include/generic-disable-node.xml.i> #include <include/generic-description.xml.i> <leafNode name="interface"> <properties> <help>Optional interface for this shared network to accept requests from</help> <completionHelp> <script>${vyos_completion_dir}/list_interfaces</script> </completionHelp> <valueHelp> <format>txt</format> <description>Interface name</description> </valueHelp> <constraint> #include <include/constraint/interface-name.xml.i> </constraint> </properties> </leafNode> <node name="common-options"> <properties> <help>Common options to distribute to all clients, including stateless clients</help> </properties> <children> <leafNode name="info-refresh-time"> <properties> <help>Time (in seconds) that stateless clients should wait between refreshing the information they were given</help> <valueHelp> <format>u32:1-4294967295</format> <description>DHCPv6 information refresh time</description> </valueHelp> <constraint> <validator name="numeric" argument="--range 1-4294967295"/> </constraint> </properties> </leafNode> #include <include/dhcp/domain-search.xml.i> #include <include/name-server-ipv6.xml.i> </children> </node> <tagNode name="subnet"> <properties> <help>IPv6 DHCP subnet for this shared network</help> <valueHelp> <format>ipv6net</format> <description>IPv6 address and prefix length</description> </valueHelp> <constraint> <validator name="ipv6-prefix"/> </constraint> </properties> <children> - <node name="address-range"> + #include <include/dhcp/option-v6.xml.i> + <tagNode name="range"> <properties> <help>Parameters setting ranges for assigning IPv6 addresses</help> + <constraint> + #include <include/constraint/alpha-numeric-hyphen-underscore-dot.xml.i> + </constraint> + <constraintErrorMessage>Invalid range name, may only be alphanumeric, dot and hyphen</constraintErrorMessage> </properties> <children> + #include <include/dhcp/option-v6.xml.i> <leafNode name="prefix"> <properties> <help>IPv6 prefix defining range of addresses to assign</help> <valueHelp> <format>ipv6net</format> <description>IPv6 address and prefix length</description> </valueHelp> <constraint> <validator name="ipv6-prefix"/> </constraint> - <multi/> </properties> </leafNode> - <tagNode name="start"> + <leafNode name="start"> <properties> <help>First in range of consecutive IPv6 addresses to assign</help> <valueHelp> <format>ipv6</format> <description>IPv6 address</description> </valueHelp> <constraint> <validator name="ipv6-address"/> </constraint> </properties> - <children> - <leafNode name="stop"> - <properties> - <help>Last in range of consecutive IPv6 addresses</help> - <valueHelp> - <format>ipv6</format> - <description>IPv6 address</description> - </valueHelp> - <constraint> - <validator name="ipv6-address"/> - </constraint> - </properties> - </leafNode> - </children> - </tagNode> + </leafNode> + <leafNode name="stop"> + <properties> + <help>Last in range of consecutive IPv6 addresses</help> + <valueHelp> + <format>ipv6</format> + <description>IPv6 address</description> + </valueHelp> + <constraint> + <validator name="ipv6-address"/> + </constraint> + </properties> + </leafNode> </children> - </node> - #include <include/dhcp/captive-portal.xml.i> - #include <include/dhcp/domain-search.xml.i> + </tagNode> <node name="lease-time"> <properties> <help>Parameters relating to the lease time</help> </properties> <children> <leafNode name="default"> <properties> <help>Default time (in seconds) that will be assigned to a lease</help> <valueHelp> <format>u32:1-4294967295</format> <description>DHCPv6 valid lifetime</description> </valueHelp> <constraint> <validator name="numeric" argument="--range 1-4294967295"/> </constraint> </properties> </leafNode> <leafNode name="maximum"> <properties> <help>Maximum time (in seconds) that will be assigned to a lease</help> <valueHelp> <format>u32:1-4294967295</format> <description>Maximum lease time in seconds</description> </valueHelp> <constraint> <validator name="numeric" argument="--range 1-4294967295"/> </constraint> </properties> </leafNode> <leafNode name="minimum"> <properties> <help>Minimum time (in seconds) that will be assigned to a lease</help> <valueHelp> <format>u32:1-4294967295</format> <description>Minimum lease time in seconds</description> </valueHelp> <constraint> <validator name="numeric" argument="--range 1-4294967295"/> </constraint> </properties> </leafNode> </children> </node> - #include <include/name-server-ipv6.xml.i> - <leafNode name="nis-domain"> - <properties> - <help>NIS domain name for client to use</help> - <constraint> - #include <include/constraint/alpha-numeric-hyphen-underscore-dot.xml.i> - </constraint> - <constraintErrorMessage>Invalid NIS domain name</constraintErrorMessage> - </properties> - </leafNode> - <leafNode name="nis-server"> - <properties> - <help>IPv6 address of a NIS Server</help> - <valueHelp> - <format>ipv6</format> - <description>IPv6 address of NIS server</description> - </valueHelp> - <constraint> - <validator name="ipv6-address"/> - </constraint> - <multi/> - </properties> - </leafNode> - <leafNode name="nisplus-domain"> - <properties> - <help>NIS+ domain name for client to use</help> - <constraint> - #include <include/constraint/alpha-numeric-hyphen-underscore-dot.xml.i> - </constraint> - <constraintErrorMessage>Invalid NIS+ domain name. May only contain letters, numbers and .-_</constraintErrorMessage> - </properties> - </leafNode> - <leafNode name="nisplus-server"> - <properties> - <help>IPv6 address of a NIS+ Server</help> - <valueHelp> - <format>ipv6</format> - <description>IPv6 address of NIS+ server</description> - </valueHelp> - <constraint> - <validator name="ipv6-address"/> - </constraint> - <multi/> - </properties> - </leafNode> <node name="prefix-delegation"> <properties> <help>Parameters relating to IPv6 prefix delegation</help> </properties> <children> <tagNode name="prefix"> <properties> <help>IPv6 prefix to be used in prefix delegation</help> <valueHelp> <format>ipv6</format> <description>IPv6 prefix used in prefix delegation</description> </valueHelp> <constraint> <validator name="ipv6-address"/> </constraint> </properties> <children> <leafNode name="prefix-length"> <properties> <help>Length in bits of prefix</help> <valueHelp> <format>u32:32-64</format> <description>Prefix length (32-64)</description> </valueHelp> <constraint> <validator name="numeric" argument="--range 32-64"/> </constraint> <constraintErrorMessage>Prefix length must be between 32 and 64</constraintErrorMessage> </properties> </leafNode> <leafNode name="delegated-length"> <properties> <help>Length in bits of prefixes to be delegated</help> <valueHelp> <format>u32:32-64</format> <description>Delegated prefix length (32-64)</description> </valueHelp> <constraint> <validator name="numeric" argument="--range 32-96"/> </constraint> <constraintErrorMessage>Delegated prefix length must be between 32 and 96</constraintErrorMessage> </properties> </leafNode> </children> </tagNode> </children> </node> - <leafNode name="sip-server"> - <properties> - <help>IPv6 address of SIP server</help> - <valueHelp> - <format>ipv6</format> - <description>IPv6 address of SIP server</description> - </valueHelp> - <valueHelp> - <format>hostname</format> - <description>FQDN of SIP server</description> - </valueHelp> - <constraint> - <validator name="ipv6-address"/> - <validator name="fqdn"/> - </constraint> - <multi/> - </properties> - </leafNode> - <leafNode name="sntp-server"> - <properties> - <help>IPv6 address of an SNTP server for client to use</help> - <constraint> - <validator name="ipv6-address"/> - </constraint> - <multi/> - </properties> - </leafNode> <tagNode name="static-mapping"> <properties> <help>Hostname for static mapping reservation</help> <constraint> <validator name="fqdn"/> </constraint> <constraintErrorMessage>Invalid static mapping hostname</constraintErrorMessage> </properties> <children> + #include <include/dhcp/option-v6.xml.i> #include <include/generic-disable-node.xml.i> #include <include/interface/mac.xml.i> #include <include/interface/duid.xml.i> <leafNode name="ipv6-address"> <properties> <help>Client IPv6 address for this static mapping</help> <valueHelp> <format>ipv6</format> <description>IPv6 address for this static mapping</description> </valueHelp> <constraint> <validator name="ipv6-address"/> </constraint> </properties> </leafNode> <leafNode name="ipv6-prefix"> <properties> <help>Client IPv6 prefix for this static mapping</help> <valueHelp> <format>ipv6net</format> <description>IPv6 prefix for this static mapping</description> </valueHelp> <constraint> <validator name="ipv6-prefix"/> </constraint> </properties> </leafNode> </children> </tagNode> <leafNode name="subnet-id"> <properties> <help>Unique ID mapped to leases in the lease file</help> <valueHelp> <format>u32</format> <description>Unique subnet ID</description> </valueHelp> <constraint> <validator name="numeric" argument="--range 1-4294967295"/> </constraint> </properties> </leafNode> - <node name="vendor-option"> - <properties> - <help>Vendor Specific Options</help> - </properties> - <children> - <node name="cisco"> - <properties> - <help>Cisco specific parameters</help> - </properties> - <children> - <leafNode name="tftp-server"> - <properties> - <help>TFTP server name</help> - <valueHelp> - <format>ipv6</format> - <description>TFTP server IPv6 address</description> - </valueHelp> - <constraint> - <validator name="ipv6-address"/> - </constraint> - <multi/> - </properties> - </leafNode> - </children> - </node> - </children> - </node> </children> </tagNode> </children> </tagNode> </children> </node> </children> </node> </interfaceDefinition> diff --git a/python/vyos/kea.py b/python/vyos/kea.py index aa4fb7ae5..fb5afc2ce 100644 --- a/python/vyos/kea.py +++ b/python/vyos/kea.py @@ -1,361 +1,358 @@ # Copyright 2023 VyOS maintainers and contributors <maintainers@vyos.io> # # This library is free software; you can redistribute it and/or # modify it under the terms of the GNU Lesser General Public # License as published by the Free Software Foundation; either # version 2.1 of the License, or (at your option) any later version. # # This library 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 # Lesser General Public License for more details. # # You should have received a copy of the GNU Lesser General Public # License along with this library. If not, see <http://www.gnu.org/licenses/>. import json import os import socket from datetime import datetime from vyos.template import is_ipv6 from vyos.template import isc_static_route from vyos.template import netmask_from_cidr from vyos.utils.dict import dict_search_args from vyos.utils.file import file_permissions from vyos.utils.file import read_file from vyos.utils.process import run kea4_options = { 'name_server': 'domain-name-servers', 'domain_name': 'domain-name', 'domain_search': 'domain-search', 'ntp_server': 'ntp-servers', 'pop_server': 'pop-server', 'smtp_server': 'smtp-server', 'time_server': 'time-servers', 'wins_server': 'netbios-name-servers', 'default_router': 'routers', 'server_identifier': 'dhcp-server-identifier', 'tftp_server_name': 'tftp-server-name', 'bootfile_size': 'boot-size', 'time_offset': 'time-offset', 'wpad_url': 'wpad-url', 'ipv6_only_preferred': 'v6-only-preferred', 'captive_portal': 'v4-captive-portal' } kea6_options = { 'info_refresh_time': 'information-refresh-time', 'name_server': 'dns-servers', 'domain_search': 'domain-search', 'nis_domain': 'nis-domain-name', 'nis_server': 'nis-servers', 'nisplus_domain': 'nisp-domain-name', 'nisplus_server': 'nisp-servers', 'sntp_server': 'sntp-servers', 'captive_portal': 'v6-captive-portal' } def kea_parse_options(config): options = [] for node, option_name in kea4_options.items(): if node not in config: continue value = ", ".join(config[node]) if isinstance(config[node], list) else config[node] options.append({'name': option_name, 'data': value}) if 'client_prefix_length' in config: options.append({'name': 'subnet-mask', 'data': netmask_from_cidr('0.0.0.0/' + config['client_prefix_length'])}) if 'ip_forwarding' in config: options.append({'name': 'ip-forwarding', 'data': "true"}) if 'static_route' in config: default_route = '' if 'default_router' in config: default_route = isc_static_route('0.0.0.0/0', config['default_router']) routes = [isc_static_route(route, route_options['next_hop']) for route, route_options in config['static_route'].items()] options.append({'name': 'rfc3442-static-route', 'data': ", ".join(routes if not default_route else routes + [default_route])}) options.append({'name': 'windows-static-route', 'data': ", ".join(routes)}) if 'time_zone' in config: with open("/usr/share/zoneinfo/" + config['time_zone'], "rb") as f: tz_string = f.read().split(b"\n")[-2].decode("utf-8") options.append({'name': 'pcode', 'data': tz_string}) options.append({'name': 'tcode', 'data': config['time_zone']}) unifi_controller = dict_search_args(config, 'vendor_option', 'ubiquiti', 'unifi_controller') if unifi_controller: options.append({ 'name': 'unifi-controller', 'data': unifi_controller, 'space': 'ubnt' }) return options def kea_parse_subnet(subnet, config): out = {'subnet': subnet, 'id': int(config['subnet_id'])} options = [] if 'option' in config: out['option-data'] = kea_parse_options(config['option']) if 'bootfile_name' in config['option']: out['boot-file-name'] = config['option']['bootfile_name'] if 'bootfile_server' in config['option']: out['next-server'] = config['option']['bootfile_server'] if 'lease' in config: out['valid-lifetime'] = int(config['lease']) out['max-valid-lifetime'] = int(config['lease']) if 'range' in config: pools = [] for num, range_config in config['range'].items(): start, stop = range_config['start'], range_config['stop'] pool = { 'pool': f'{start} - {stop}' } if 'option' in range_config: pool['option-data'] = kea_parse_options(range_config['option']) if 'bootfile_name' in range_config['option']: pool['boot-file-name'] = range_config['option']['bootfile_name'] if 'bootfile_server' in range_config['option']: pool['next-server'] = range_config['option']['bootfile_server'] pools.append(pool) out['pools'] = pools if 'static_mapping' in config: reservations = [] for host, host_config in config['static_mapping'].items(): if 'disable' in host_config: continue reservation = { 'hostname': host, } if 'mac' in host_config: reservation['hw-address'] = host_config['mac'] if 'duid' in host_config: reservation['duid'] = host_config['duid'] if 'ip_address' in host_config: reservation['ip-address'] = host_config['ip_address'] if 'option' in host_config: reservation['option-data'] = kea_parse_options(host_config['option']) if 'bootfile_name' in host_config['option']: reservation['boot-file-name'] = host_config['option']['bootfile_name'] if 'bootfile_server' in host_config['option']: reservation['next-server'] = host_config['option']['bootfile_server'] reservations.append(reservation) out['reservations'] = reservations return out def kea6_parse_options(config): options = [] - if 'common_options' in config: - common_opt = config['common_options'] - - for node, option_name in kea6_options.items(): - if node not in common_opt: - continue - - value = ", ".join(common_opt[node]) if isinstance(common_opt[node], list) else common_opt[node] - options.append({'name': option_name, 'data': value}) - for node, option_name in kea6_options.items(): if node not in config: continue value = ", ".join(config[node]) if isinstance(config[node], list) else config[node] options.append({'name': option_name, 'data': value}) if 'sip_server' in config: sip_servers = config['sip_server'] addrs = [] hosts = [] for server in sip_servers: if is_ipv6(server): addrs.append(server) else: hosts.append(server) if addrs: options.append({'name': 'sip-server-addr', 'data': ", ".join(addrs)}) if hosts: options.append({'name': 'sip-server-dns', 'data': ", ".join(hosts)}) cisco_tftp = dict_search_args(config, 'vendor_option', 'cisco', 'tftp-server') if cisco_tftp: options.append({'name': 'tftp-servers', 'code': 2, 'space': 'cisco', 'data': cisco_tftp}) return options def kea6_parse_subnet(subnet, config): out = {'subnet': subnet, 'id': int(config['subnet_id'])} - options = kea6_parse_options(config) - if 'address_range' in config: - addr_range = config['address_range'] + if 'option' in config: + out['option-data'] = kea6_parse_options(config['option']) + + if 'range' in config: pools = [] + for num, range_config in config['range'].items(): + pool = {} - if 'prefix' in addr_range: - for prefix in addr_range['prefix']: - pools.append({'pool': prefix}) + if 'prefix' in range_config: + pool['pool'] = range_config['prefix'] - if 'start' in addr_range: - for start, range_conf in addr_range['start'].items(): - stop = range_conf['stop'] - pools.append({'pool': f'{start} - {stop}'}) + if 'start' in range_config: + start = range_config['start'] + stop = range_config['stop'] + pool['pool'] = f'{start} - {stop}' + + if 'option' in range_config: + pool['option-data'] = kea6_parse_options(range_config['option']) + + pools.append(pool) out['pools'] = pools if 'prefix_delegation' in config: pd_pools = [] if 'prefix' in config['prefix_delegation']: for prefix, pd_conf in config['prefix_delegation']['prefix'].items(): pd_pools.append({ 'prefix': prefix, 'prefix-len': int(pd_conf['prefix_length']), 'delegated-len': int(pd_conf['delegated_length']) }) out['pd-pools'] = pd_pools if 'lease_time' in config: if 'default' in config['lease_time']: out['valid-lifetime'] = int(config['lease_time']['default']) if 'maximum' in config['lease_time']: out['max-valid-lifetime'] = int(config['lease_time']['maximum']) if 'minimum' in config['lease_time']: out['min-valid-lifetime'] = int(config['lease_time']['minimum']) if 'static_mapping' in config: reservations = [] for host, host_config in config['static_mapping'].items(): if 'disable' in host_config: continue reservation = { 'hostname': host } if 'mac' in host_config: reservation['hw-address'] = host_config['mac'] if 'duid' in host_config: reservation['duid'] = host_config['duid'] if 'ipv6_address' in host_config: reservation['ip-addresses'] = [ host_config['ipv6_address'] ] if 'ipv6_prefix' in host_config: reservation['prefixes'] = [ host_config['ipv6_prefix'] ] + if 'option' in host_config: + reservation['option-data'] = kea6_parse_options(host_config['option']) + reservations.append(reservation) out['reservations'] = reservations - if options: - out['option-data'] = options - return out def kea_parse_leases(lease_path): contents = read_file(lease_path) lines = contents.split("\n") output = [] if len(lines) < 2: return output headers = lines[0].split(",") for line in lines[1:]: line_out = dict(zip(headers, line.split(","))) lifetime = int(line_out['valid_lifetime']) expiry = int(line_out['expire']) line_out['start_timestamp'] = datetime.utcfromtimestamp(expiry - lifetime) line_out['expire_timestamp'] = datetime.utcfromtimestamp(expiry) if expiry else None output.append(line_out) return output def _ctrl_socket_command(path, command, args=None): if not os.path.exists(path): return None if file_permissions(path) != '0775': run(f'sudo chmod 775 {path}') with socket.socket(socket.AF_UNIX, socket.SOCK_STREAM) as sock: sock.connect(path) payload = {'command': command} if args: payload['arguments'] = args sock.send(bytes(json.dumps(payload), 'utf-8')) result = b'' while True: data = sock.recv(4096) result += data if len(data) < 4096: break return json.loads(result.decode('utf-8')) def kea_get_active_config(inet): ctrl_socket = f'/run/kea/dhcp{inet}-ctrl-socket' config = _ctrl_socket_command(ctrl_socket, 'config-get') if not config or 'result' not in config or config['result'] != 0: return None return config def kea_get_pool_from_subnet_id(config, inet, subnet_id): shared_networks = dict_search_args(config, 'arguments', f'Dhcp{inet}', 'shared-networks') if not shared_networks: return None for network in shared_networks: if f'subnet{inet}' not in network: continue for subnet in network[f'subnet{inet}']: if 'id' in subnet and int(subnet['id']) == int(subnet_id): return network['name'] return None diff --git a/python/vyos/template.py b/python/vyos/template.py index 1368f1f61..456239568 100644 --- a/python/vyos/template.py +++ b/python/vyos/template.py @@ -1,963 +1,962 @@ # Copyright 2019-2023 VyOS maintainers and contributors <maintainers@vyos.io> # # This library is free software; you can redistribute it and/or # modify it under the terms of the GNU Lesser General Public # License as published by the Free Software Foundation; either # version 2.1 of the License, or (at your option) any later version. # # This library 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 # Lesser General Public License for more details. # # You should have received a copy of the GNU Lesser General Public # License along with this library. If not, see <http://www.gnu.org/licenses/>. import functools import os from jinja2 import Environment from jinja2 import FileSystemLoader from jinja2 import ChainableUndefined from vyos.defaults import directories from vyos.utils.dict import dict_search_args from vyos.utils.file import makedir from vyos.utils.permission import chmod from vyos.utils.permission import chown # Holds template filters registered via register_filter() _FILTERS = {} _TESTS = {} # reuse Environments with identical settings to improve performance @functools.lru_cache(maxsize=2) def _get_environment(location=None): if location is None: loc_loader=FileSystemLoader(directories["templates"]) else: loc_loader=FileSystemLoader(location) env = Environment( # Don't check if template files were modified upon re-rendering auto_reload=False, # Cache up to this number of templates for quick re-rendering cache_size=100, loader=loc_loader, trim_blocks=True, undefined=ChainableUndefined, extensions=['jinja2.ext.loopcontrols'] ) env.filters.update(_FILTERS) env.tests.update(_TESTS) return env def register_filter(name, func=None): """Register a function to be available as filter in templates under given name. It can also be used as a decorator, see below in this module for examples. :raise RuntimeError: when trying to register a filter after a template has been rendered already :raise ValueError: when trying to register a name which was taken already """ if func is None: return functools.partial(register_filter, name) if _get_environment.cache_info().currsize: raise RuntimeError( "Filters can only be registered before rendering the first template" ) if name in _FILTERS: raise ValueError(f"A filter with name {name!r} was registered already") _FILTERS[name] = func return func def register_test(name, func=None): """Register a function to be available as test in templates under given name. It can also be used as a decorator, see below in this module for examples. :raise RuntimeError: when trying to register a test after a template has been rendered already :raise ValueError: when trying to register a name which was taken already """ if func is None: return functools.partial(register_test, name) if _get_environment.cache_info().currsize: raise RuntimeError( "Tests can only be registered before rendering the first template" ) if name in _TESTS: raise ValueError(f"A test with name {name!r} was registered already") _TESTS[name] = func return func def render_to_string(template, content, formater=None, location=None): """Render a template from the template directory, raise on any errors. :param template: the path to the template relative to the template folder :param content: the dictionary of variables to put into rendering context :param formater: if given, it has to be a callable the rendered string is passed through The parsed template files are cached, so rendering the same file multiple times does not cause as too much overhead. If used everywhere, it could be changed to load the template from Python environment variables from an importable Python module generated when the Debian package is build (recovering the load time and overhead caused by having the file out of the code). """ template = _get_environment(location).get_template(template) rendered = template.render(content) if formater is not None: rendered = formater(rendered) return rendered def render( destination, template, content, formater=None, permission=None, user=None, group=None, location=None, ): """Render a template from the template directory to a file, raise on any errors. :param destination: path to the file to save the rendered template in :param permission: permission bitmask to set for the output file :param user: user to own the output file :param group: group to own the output file All other parameters are as for :func:`render_to_string`. """ # Create the directory if it does not exist folder = os.path.dirname(destination) makedir(folder, user, group) # As we are opening the file with 'w', we are performing the rendering before # calling open() to not accidentally erase the file if rendering fails rendered = render_to_string(template, content, formater, location) # Write to file with open(destination, "w") as file: chmod(file.fileno(), permission) chown(file.fileno(), user, group) file.write(rendered) ################################## # Custom template filters follow # ################################## @register_filter('force_to_list') def force_to_list(value): """ Convert scalars to single-item lists and leave lists untouched """ if isinstance(value, list): return value else: return [value] @register_filter('seconds_to_human') def seconds_to_human(seconds, separator=""): """ Convert seconds to human-readable values like 1d6h15m23s """ from vyos.utils.convert import seconds_to_human return seconds_to_human(seconds, separator=separator) @register_filter('bytes_to_human') def bytes_to_human(bytes, initial_exponent=0, precision=2): """ Convert bytes to human-readable values like 1.44M """ from vyos.utils.convert import bytes_to_human return bytes_to_human(bytes, initial_exponent=initial_exponent, precision=precision) @register_filter('human_to_bytes') def human_to_bytes(value): """ Convert a data amount with a unit suffix to bytes, like 2K to 2048 """ from vyos.utils.convert import human_to_bytes return human_to_bytes(value) @register_filter('ip_from_cidr') def ip_from_cidr(prefix): """ Take an IPv4/IPv6 CIDR host and strip cidr mask. Example: 192.0.2.1/24 -> 192.0.2.1, 2001:db8::1/64 -> 2001:db8::1 """ from ipaddress import ip_interface return str(ip_interface(prefix).ip) @register_filter('address_from_cidr') def address_from_cidr(prefix): """ Take an IPv4/IPv6 CIDR prefix and convert the network to an "address". Example: 192.0.2.0/24 -> 192.0.2.0, 2001:db8::/48 -> 2001:db8:: """ from ipaddress import ip_network return str(ip_network(prefix).network_address) @register_filter('bracketize_ipv6') def bracketize_ipv6(address): """ Place a passed IPv6 address into [] brackets, do nothing for IPv4 """ if is_ipv6(address): return f'[{address}]' return address @register_filter('dot_colon_to_dash') def dot_colon_to_dash(text): """ Replace dot and colon to dash for string Example: 192.0.2.1 => 192-0-2-1, 2001:db8::1 => 2001-db8--1 """ text = text.replace(":", "-") text = text.replace(".", "-") return text @register_filter('generate_uuid4') def generate_uuid4(text): """ Generate random unique ID Example: % uuid4() UUID('958ddf6a-ef14-4e81-8cfb-afb12456d1c5') """ from uuid import uuid4 return uuid4() @register_filter('netmask_from_cidr') def netmask_from_cidr(prefix): """ Take CIDR prefix and convert the prefix length to a "subnet mask". Example: - 192.0.2.0/24 -> 255.255.255.0 - 2001:db8::/48 -> ffff:ffff:ffff:: """ from ipaddress import ip_network return str(ip_network(prefix).netmask) @register_filter('netmask_from_ipv4') def netmask_from_ipv4(address): """ Take IP address and search all attached interface IP addresses for the given one. After address has been found, return the associated netmask. Example: - 172.18.201.10 -> 255.255.255.128 """ from netifaces import interfaces from netifaces import ifaddresses from netifaces import AF_INET for interface in interfaces(): tmp = ifaddresses(interface) if AF_INET in tmp: for af_addr in tmp[AF_INET]: if 'addr' in af_addr: if af_addr['addr'] == address: return af_addr['netmask'] raise ValueError @register_filter('is_ip_network') def is_ip_network(addr): """ Take IP(v4/v6) address and validate if the passed argument is a network or a host address. Example: - 192.0.2.0 -> False - 192.0.2.10/24 -> False - 192.0.2.0/24 -> True - 2001:db8:: -> False - 2001:db8::100 -> False - 2001:db8::/48 -> True - 2001:db8:1000::/64 -> True """ try: from ipaddress import ip_network # input variables must contain a / to indicate its CIDR notation if len(addr.split('/')) != 2: raise ValueError() ip_network(addr) return True except: return False @register_filter('network_from_ipv4') def network_from_ipv4(address): """ Take IP address and search all attached interface IP addresses for the given one. After address has been found, return the associated network address. Example: - 172.18.201.10 has mask 255.255.255.128 -> network is 172.18.201.0 """ netmask = netmask_from_ipv4(address) from ipaddress import ip_interface cidr_prefix = ip_interface(f'{address}/{netmask}').network return address_from_cidr(cidr_prefix) @register_filter('is_interface') def is_interface(interface): """ Check if parameter is a valid local interface name """ return os.path.exists(f'/sys/class/net/{interface}') @register_filter('is_ip') def is_ip(addr): """ Check addr if it is an IPv4 or IPv6 address """ return is_ipv4(addr) or is_ipv6(addr) @register_filter('is_ipv4') def is_ipv4(text): """ Filter IP address, return True on IPv4 address, False otherwise """ from ipaddress import ip_interface try: return ip_interface(text).version == 4 except: return False @register_filter('is_ipv6') def is_ipv6(text): """ Filter IP address, return True on IPv6 address, False otherwise """ from ipaddress import ip_interface try: return ip_interface(text).version == 6 except: return False @register_filter('first_host_address') def first_host_address(prefix): """ Return first usable (host) IP address from given prefix. Example: - 10.0.0.0/24 -> 10.0.0.1 - 2001:db8::/64 -> 2001:db8:: """ from ipaddress import ip_interface tmp = ip_interface(prefix).network return str(tmp.network_address +1) @register_filter('last_host_address') def last_host_address(text): """ Return first usable IP address from given prefix. Example: - 10.0.0.0/24 -> 10.0.0.254 - 2001:db8::/64 -> 2001:db8::ffff:ffff:ffff:ffff """ from ipaddress import ip_interface from ipaddress import IPv4Network from ipaddress import IPv6Network addr = ip_interface(text) if addr.version == 4: return str(IPv4Network(addr).broadcast_address - 1) return str(IPv6Network(addr).broadcast_address) @register_filter('inc_ip') def inc_ip(address, increment): """ Increment given IP address by 'increment' Example (inc by 2): - 10.0.0.0/24 -> 10.0.0.2 - 2001:db8::/64 -> 2001:db8::2 """ from ipaddress import ip_interface return str(ip_interface(address).ip + int(increment)) @register_filter('dec_ip') def dec_ip(address, decrement): """ Decrement given IP address by 'decrement' Example (inc by 2): - 10.0.0.0/24 -> 10.0.0.2 - 2001:db8::/64 -> 2001:db8::2 """ from ipaddress import ip_interface return str(ip_interface(address).ip - int(decrement)) @register_filter('compare_netmask') def compare_netmask(netmask1, netmask2): """ Compare two IP netmask if they have the exact same size. compare_netmask('10.0.0.0/8', '20.0.0.0/8') -> True compare_netmask('10.0.0.0/8', '20.0.0.0/16') -> False """ from ipaddress import ip_network try: return ip_network(netmask1).netmask == ip_network(netmask2).netmask except: return False @register_filter('isc_static_route') def isc_static_route(subnet, router): # https://ercpe.de/blog/pushing-static-routes-with-isc-dhcp-server # Option format is: # <netmask>, <network-byte1>, <network-byte2>, <network-byte3>, <router-byte1>, <router-byte2>, <router-byte3> # where bytes with the value 0 are omitted. from ipaddress import ip_network net = ip_network(subnet) # add netmask string = str(net.prefixlen) + ',' # add network bytes if net.prefixlen: width = net.prefixlen // 8 if net.prefixlen % 8: width += 1 string += ','.join(map(str,tuple(net.network_address.packed)[:width])) + ',' # add router bytes string += ','.join(router.split('.')) return string @register_filter('is_file') def is_file(filename): if os.path.exists(filename): return os.path.isfile(filename) return False @register_filter('get_dhcp_router') def get_dhcp_router(interface): """ Static routes can point to a router received by a DHCP reply. This helper is used to get the current default router from the DHCP reply. Returns False of no router is found, returns the IP address as string if a router is found. """ lease_file = directories['isc_dhclient_dir'] + f'/dhclient_{interface}.leases' if not os.path.exists(lease_file): return None from vyos.utils.file import read_file for line in read_file(lease_file).splitlines(): if 'option routers' in line: (_, _, address) = line.split() return address.rstrip(';') @register_filter('natural_sort') def natural_sort(iterable): import re from jinja2.runtime import Undefined if isinstance(iterable, Undefined) or iterable is None: return list() def convert(text): return int(text) if text.isdigit() else text.lower() def alphanum_key(key): return [convert(c) for c in re.split('([0-9]+)', str(key))] return sorted(iterable, key=alphanum_key) @register_filter('get_ipv4') def get_ipv4(interface): """ Get interface IPv4 addresses""" from vyos.ifconfig import Interface return Interface(interface).get_addr_v4() @register_filter('get_ipv6') def get_ipv6(interface): """ Get interface IPv6 addresses""" from vyos.ifconfig import Interface return Interface(interface).get_addr_v6() @register_filter('get_ip') def get_ip(interface): """ Get interface IP addresses""" from vyos.ifconfig import Interface return Interface(interface).get_addr() def get_first_ike_dh_group(ike_group): if ike_group and 'proposal' in ike_group: for priority, proposal in ike_group['proposal'].items(): if 'dh_group' in proposal: return 'dh-group' + proposal['dh_group'] return 'dh-group2' # Fallback on dh-group2 @register_filter('get_esp_ike_cipher') def get_esp_ike_cipher(group_config, ike_group=None): pfs_lut = { 'dh-group1' : 'modp768', 'dh-group2' : 'modp1024', 'dh-group5' : 'modp1536', 'dh-group14' : 'modp2048', 'dh-group15' : 'modp3072', 'dh-group16' : 'modp4096', 'dh-group17' : 'modp6144', 'dh-group18' : 'modp8192', 'dh-group19' : 'ecp256', 'dh-group20' : 'ecp384', 'dh-group21' : 'ecp521', 'dh-group22' : 'modp1024s160', 'dh-group23' : 'modp2048s224', 'dh-group24' : 'modp2048s256', 'dh-group25' : 'ecp192', 'dh-group26' : 'ecp224', 'dh-group27' : 'ecp224bp', 'dh-group28' : 'ecp256bp', 'dh-group29' : 'ecp384bp', 'dh-group30' : 'ecp512bp', 'dh-group31' : 'curve25519', 'dh-group32' : 'curve448' } ciphers = [] if 'proposal' in group_config: for priority, proposal in group_config['proposal'].items(): # both encryption and hash need to be specified for a proposal if not {'encryption', 'hash'} <= set(proposal): continue tmp = '{encryption}-{hash}'.format(**proposal) if 'prf' in proposal: tmp += '-' + proposal['prf'] if 'dh_group' in proposal: tmp += '-' + pfs_lut[ 'dh-group' + proposal['dh_group'] ] elif 'pfs' in group_config and group_config['pfs'] != 'disable': group = group_config['pfs'] if group_config['pfs'] == 'enable': group = get_first_ike_dh_group(ike_group) tmp += '-' + pfs_lut[group] ciphers.append(tmp) return ciphers @register_filter('get_uuid') def get_uuid(interface): """ Get interface IP addresses""" from uuid import uuid1 return uuid1() openvpn_translate = { 'des': 'des-cbc', '3des': 'des-ede3-cbc', 'bf128': 'bf-cbc', 'bf256': 'bf-cbc', 'aes128gcm': 'aes-128-gcm', 'aes128': 'aes-128-cbc', 'aes192gcm': 'aes-192-gcm', 'aes192': 'aes-192-cbc', 'aes256gcm': 'aes-256-gcm', 'aes256': 'aes-256-cbc' } @register_filter('openvpn_cipher') def get_openvpn_cipher(cipher): if cipher in openvpn_translate: return openvpn_translate[cipher].upper() return cipher.upper() @register_filter('openvpn_ncp_ciphers') def get_openvpn_ncp_ciphers(ciphers): out = [] for cipher in ciphers: if cipher in openvpn_translate: out.append(openvpn_translate[cipher]) else: out.append(cipher) return ':'.join(out).upper() @register_filter('snmp_auth_oid') def snmp_auth_oid(type): if type not in ['md5', 'sha', 'aes', 'des', 'none']: raise ValueError() OIDs = { 'md5' : '.1.3.6.1.6.3.10.1.1.2', 'sha' : '.1.3.6.1.6.3.10.1.1.3', 'aes' : '.1.3.6.1.6.3.10.1.2.4', 'des' : '.1.3.6.1.6.3.10.1.2.2', 'none': '.1.3.6.1.6.3.10.1.2.1' } return OIDs[type] @register_filter('nft_action') def nft_action(vyos_action): if vyos_action == 'accept': return 'return' return vyos_action @register_filter('nft_rule') def nft_rule(rule_conf, fw_hook, fw_name, rule_id, ip_name='ip'): from vyos.firewall import parse_rule return parse_rule(rule_conf, fw_hook, fw_name, rule_id, ip_name) @register_filter('nft_default_rule') def nft_default_rule(fw_conf, fw_name, family): output = ['counter'] default_action = fw_conf['default_action'] #family = 'ipv6' if ipv6 else 'ipv4' if 'default_log' in fw_conf: action_suffix = default_action[:1].upper() output.append(f'log prefix "[{family}-{fw_name[:19]}-default-{action_suffix}]"') #output.append(nft_action(default_action)) output.append(f'{default_action}') if 'default_jump_target' in fw_conf: target = fw_conf['default_jump_target'] def_suffix = '6' if family == 'ipv6' else '' output.append(f'NAME{def_suffix}_{target}') output.append(f'comment "{fw_name} default-action {default_action}"') return " ".join(output) @register_filter('nft_state_policy') def nft_state_policy(conf, state): out = [f'ct state {state}'] if 'log' in conf: log_state = state[:3].upper() log_action = (conf['action'] if 'action' in conf else 'accept')[:1].upper() out.append(f'log prefix "[STATE-POLICY-{log_state}-{log_action}]"') if 'log_level' in conf: log_level = conf['log_level'] out.append(f'level {log_level}') out.append('counter') if 'action' in conf: out.append(conf['action']) return " ".join(out) @register_filter('nft_intra_zone_action') def nft_intra_zone_action(zone_conf, ipv6=False): if 'intra_zone_filtering' in zone_conf: intra_zone = zone_conf['intra_zone_filtering'] fw_name = 'ipv6_name' if ipv6 else 'name' name_prefix = 'NAME6_' if ipv6 else 'NAME_' if 'action' in intra_zone: if intra_zone['action'] == 'accept': return 'return' return intra_zone['action'] elif dict_search_args(intra_zone, 'firewall', fw_name): name = dict_search_args(intra_zone, 'firewall', fw_name) return f'jump {name_prefix}{name}' return 'return' @register_filter('nft_nested_group') def nft_nested_group(out_list, includes, groups, key): if not vyos_defined(out_list): out_list = [] def add_includes(name): if key in groups[name]: for item in groups[name][key]: if item in out_list: continue out_list.append(item) if 'include' in groups[name]: for name_inc in groups[name]['include']: add_includes(name_inc) for name in includes: add_includes(name) return out_list @register_filter('nat_rule') def nat_rule(rule_conf, rule_id, nat_type, ipv6=False): from vyos.nat import parse_nat_rule return parse_nat_rule(rule_conf, rule_id, nat_type, ipv6) @register_filter('nat_static_rule') def nat_static_rule(rule_conf, rule_id, nat_type): from vyos.nat import parse_nat_static_rule return parse_nat_static_rule(rule_conf, rule_id, nat_type) @register_filter('conntrack_rule') def conntrack_rule(rule_conf, rule_id, action, ipv6=False): ip_prefix = 'ip6' if ipv6 else 'ip' def_suffix = '6' if ipv6 else '' output = [] if 'inbound_interface' in rule_conf: ifname = rule_conf['inbound_interface'] if ifname != 'any': output.append(f'iifname {ifname}') if 'protocol' in rule_conf: if action != 'timeout': proto = rule_conf['protocol'] else: for protocol, protocol_config in rule_conf['protocol'].items(): proto = protocol output.append(f'meta l4proto {proto}') tcp_flags = dict_search_args(rule_conf, 'tcp', 'flags') if tcp_flags and action != 'timeout': from vyos.firewall import parse_tcp_flags output.append(parse_tcp_flags(tcp_flags)) for side in ['source', 'destination']: if side in rule_conf: side_conf = rule_conf[side] prefix = side[0] if 'address' in side_conf: address = side_conf['address'] operator = '' if address[0] == '!': operator = '!=' address = address[1:] output.append(f'{ip_prefix} {prefix}addr {operator} {address}') if 'port' in side_conf: port = side_conf['port'] operator = '' if port[0] == '!': operator = '!=' port = port[1:] output.append(f'th {prefix}port {operator} {port}') if 'group' in side_conf: group = side_conf['group'] if 'address_group' in group: group_name = group['address_group'] operator = '' if group_name[0] == '!': operator = '!=' group_name = group_name[1:] output.append(f'{ip_prefix} {prefix}addr {operator} @A{def_suffix}_{group_name}') # Generate firewall group domain-group elif 'domain_group' in group: group_name = group['domain_group'] operator = '' if group_name[0] == '!': operator = '!=' group_name = group_name[1:] output.append(f'{ip_prefix} {prefix}addr {operator} @D_{group_name}') elif 'network_group' in group: group_name = group['network_group'] operator = '' if group_name[0] == '!': operator = '!=' group_name = group_name[1:] output.append(f'{ip_prefix} {prefix}addr {operator} @N{def_suffix}_{group_name}') if 'port_group' in group: group_name = group['port_group'] if proto == 'tcp_udp': proto = 'th' operator = '' if group_name[0] == '!': operator = '!=' group_name = group_name[1:] output.append(f'{proto} {prefix}port {operator} @P_{group_name}') if action == 'ignore': output.append('counter notrack') output.append(f'comment "ignore-{rule_id}"') else: output.append(f'counter ct timeout set ct-timeout-{rule_id}') output.append(f'comment "timeout-{rule_id}"') return " ".join(output) @register_filter('conntrack_ct_policy') def conntrack_ct_policy(protocol_conf): output = [] for item in protocol_conf: item_value = protocol_conf[item] output.append(f'{item}: {item_value}') return ", ".join(output) @register_filter('range_to_regex') def range_to_regex(num_range): """Convert range of numbers or list of ranges to regex % range_to_regex('11-12') '(1[1-2])' % range_to_regex(['11-12', '14-15']) '(1[1-2]|1[4-5])' """ from vyos.range_regex import range_to_regex if isinstance(num_range, list): data = [] for entry in num_range: if '-' not in entry: data.append(entry) else: data.append(range_to_regex(entry)) return f'({"|".join(data)})' if '-' not in num_range: return num_range regex = range_to_regex(num_range) return f'({regex})' @register_filter('kea_address_json') def kea_address_json(addresses): from json import dumps from vyos.utils.network import is_addr_assigned out = [] for address in addresses: ifname = is_addr_assigned(address, return_ifname=True) if not ifname: continue out.append(f'{ifname}/{address}') return dumps(out) @register_filter('kea_failover_json') def kea_failover_json(config): from json import dumps source_addr = config['source_address'] remote_addr = config['remote'] data = { 'this-server-name': os.uname()[1], 'mode': 'hot-standby', 'heartbeat-delay': 10000, 'max-response-delay': 10000, 'max-ack-delay': 5000, 'max-unacked-clients': 0, 'peers': [ { 'name': os.uname()[1], 'url': f'http://{source_addr}:647/', 'role': 'standby' if config['status'] == 'secondary' else 'primary', 'auto-failover': True }, { 'name': config['name'], 'url': f'http://{remote_addr}:647/', 'role': 'primary' if config['status'] == 'secondary' else 'standby', 'auto-failover': True }] } if 'ca_cert_file' in config: data['trust-anchor'] = config['ca_cert_file'] if 'cert_file' in config: data['cert-file'] = config['cert_file'] if 'cert_key_file' in config: data['key-file'] = config['cert_key_file'] return dumps(data) @register_filter('kea_shared_network_json') def kea_shared_network_json(shared_networks): from vyos.kea import kea_parse_options from vyos.kea import kea_parse_subnet from json import dumps out = [] for name, config in shared_networks.items(): if 'disable' in config: continue network = { 'name': name, 'authoritative': ('authoritative' in config), 'subnet4': [] } if 'option' in config: network['option-data'] = kea_parse_options(config['option']) if 'bootfile_name' in config['option']: network['boot-file-name'] = config['option']['bootfile_name'] if 'bootfile_server' in config['option']: network['next-server'] = config['option']['bootfile_server'] if 'subnet' in config: for subnet, subnet_config in config['subnet'].items(): if 'disable' in subnet_config: continue network['subnet4'].append(kea_parse_subnet(subnet, subnet_config)) out.append(network) return dumps(out, indent=4) @register_filter('kea6_shared_network_json') def kea6_shared_network_json(shared_networks): from vyos.kea import kea6_parse_options from vyos.kea import kea6_parse_subnet from json import dumps out = [] for name, config in shared_networks.items(): if 'disable' in config: continue network = { 'name': name, 'subnet6': [] } - options = kea6_parse_options(config) + + if 'common_options' in config: + network['option-data'] = kea6_parse_options(config['common_options']) if 'interface' in config: network['interface'] = config['interface'] if 'subnet' in config: for subnet, subnet_config in config['subnet'].items(): network['subnet6'].append(kea6_parse_subnet(subnet, subnet_config)) - if options: - network['option-data'] = options - out.append(network) return dumps(out, indent=4) @register_test('vyos_defined') def vyos_defined(value, test_value=None, var_type=None): """ Jinja2 plugin to test if a variable is defined and not none - vyos_defined will test value if defined and is not none and return true or false. If test_value is supplied, the value must also pass == test_value to return true. If var_type is supplied, the value must also be of the specified class/type Examples: 1. Test if var is defined and not none: {% if foo is vyos_defined %} ... {% endif %} 2. Test if variable is defined, not none and has value "something" {% if bar is vyos_defined("something") %} ... {% endif %} Parameters ---------- value : any Value to test from ansible test_value : any, optional Value to test in addition of defined and not none, by default None var_type : ['float', 'int', 'str', 'list', 'dict', 'tuple', 'bool'], optional Type or Class to test for Returns ------- boolean True if variable matches criteria, False in other cases. Implementation inspired and re-used from https://github.com/aristanetworks/ansible-avd/ """ from jinja2 import Undefined if isinstance(value, Undefined) or value is None: # Invalid value - return false return False elif test_value is not None and value != test_value: # Valid value but not matching the optional argument return False elif str(var_type).lower() in ['float', 'int', 'str', 'list', 'dict', 'tuple', 'bool'] and str(var_type).lower() != type(value).__name__: # Invalid class - return false return False else: # Valid value and is matching optional argument if provided - return true return True diff --git a/smoketest/configs/basic-vyos b/smoketest/configs/basic-vyos index fca4964bf..c42f14841 100644 --- a/smoketest/configs/basic-vyos +++ b/smoketest/configs/basic-vyos @@ -1,200 +1,205 @@ interfaces { ethernet eth0 { address 192.168.0.1/24 address fe88::1/56 duplex auto smp-affinity auto speed auto } ethernet eth1 { duplex auto smp-affinity auto speed auto } ethernet eth2 { duplex auto smp-affinity auto speed auto vif 100 { address 100.100.0.1/24 } vif-s 200 { address 100.64.200.254/24 vif-c 201 { address 100.64.201.254/24 } vif-c 202 { address 100.64.202.254/24 } } } loopback lo { } } protocols { static { arp 192.168.0.20 { hwaddr 00:50:00:00:00:20 } arp 192.168.0.30 { hwaddr 00:50:00:00:00:30 } arp 192.168.0.40 { hwaddr 00:50:00:00:00:40 } arp 100.100.0.2 { hwaddr 00:50:00:00:02:02 } arp 100.100.0.3 { hwaddr 00:50:00:00:02:03 } arp 100.100.0.4 { hwaddr 00:50:00:00:02:04 } arp 100.64.200.1 { hwaddr 00:50:00:00:00:01 } arp 100.64.200.2 { hwaddr 00:50:00:00:00:02 } arp 100.64.201.10 { hwaddr 00:50:00:00:00:10 } arp 100.64.201.20 { hwaddr 00:50:00:00:00:20 } arp 100.64.202.30 { hwaddr 00:50:00:00:00:30 } arp 100.64.202.40 { hwaddr 00:50:00:00:00:40 } route 0.0.0.0/0 { next-hop 100.64.0.1 { } } } } service { dhcp-server { shared-network-name LAN { authoritative subnet 192.168.0.0/24 { default-router 192.168.0.1 dns-server 192.168.0.1 domain-name vyos.net domain-search vyos.net range LANDynamic { start 192.168.0.20 stop 192.168.0.240 } } } } dhcpv6-server { shared-network-name LAN6 { subnet fe88::/56 { address-range { - prefix fe88::/56 { + prefix fe88::/60 { temporary } + start fe88:0000:0000:fe:: { + stop fe88:0000:0000:ff:: + } } + domain-search vyos.net + name-server fe88::1 prefix-delegation { start fe88:0000:0000:0001:: { prefix-length 64 stop fe88:0000:0000:0010:: } } } } } dns { forwarding { allow-from 192.168.0.0/16 cache-size 10000 dnssec off listen-address 192.168.0.1 } } ssh { ciphers aes128-ctr,aes192-ctr,aes256-ctr ciphers chacha20-poly1305@openssh.com,rijndael-cbc@lysator.liu.se listen-address 192.168.0.1 key-exchange curve25519-sha256@libssh.org key-exchange diffie-hellman-group1-sha1,diffie-hellman-group-exchange-sha1,diffie-hellman-group-exchange-sha256 port 22 } } system { config-management { commit-revisions 100 } console { device ttyS0 { speed 115200 } } conntrack { ignore { rule 1 { destination { address 192.0.2.2 } source { address 192.0.2.1 } } } } host-name vyos login { user vyos { authentication { encrypted-password $6$O5gJRlDYQpj$MtrCV9lxMnZPMbcxlU7.FI793MImNHznxGoMFgm3Q6QP3vfKJyOSRCt3Ka/GzFQyW1yZS4NS616NLHaIPPFHc0 plaintext-password "" } } } name-server 192.168.0.1 syslog { console { facility all { level emerg } facility mail { level info } } global { facility all { level info } facility protocols { level debug } facility security { level info } preserve-fqdn } host syslog.vyos.net { facility local7 { level notice } facility protocols { level alert } facility security { level warning } format { octet-counted } port 8000 } } time-zone Europe/Berlin } /* Warning: Do not remove the following line. */ /* === vyatta-config-version: "broadcast-relay@1:cluster@1:config-management@1:conntrack-sync@1:conntrack@1:dhcp-relay@2:dhcp-server@5:dns-forwarding@1:firewall@5:ipsec@5:l2tp@1:mdns@1:nat@4:ntp@1:pptp@1:qos@1:quagga@6:snmp@1:ssh@1:system@9:vrrp@2:wanloadbalance@3:webgui@1:webproxy@1:webproxy@2:zone-policy@1" === */ /* Release version: 1.2.6 */ diff --git a/smoketest/scripts/cli/test_service_dhcpv6-server.py b/smoketest/scripts/cli/test_service_dhcpv6-server.py index fcbfeb7be..dcce30f55 100755 --- a/smoketest/scripts/cli/test_service_dhcpv6-server.py +++ b/smoketest/scripts/cli/test_service_dhcpv6-server.py @@ -1,275 +1,277 @@ #!/usr/bin/env python3 # # Copyright (C) 2020-2023 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 unittest from json import loads from base_vyostest_shim import VyOSUnitTestSHIM from vyos.configsession import ConfigSessionError from vyos.template import inc_ip from vyos.utils.process import process_named_running from vyos.utils.file import read_file PROCESS_NAME = 'kea-dhcp6' KEA6_CONF = '/run/kea/kea-dhcp6.conf' base_path = ['service', 'dhcpv6-server'] subnet = '2001:db8:f00::/64' dns_1 = '2001:db8::1' dns_2 = '2001:db8::2' domain = 'vyos.net' nis_servers = ['2001:db8:ffff::1', '2001:db8:ffff::2'] interface = 'eth0' interface_addr = inc_ip(subnet, 1) + '/64' class TestServiceDHCPv6Server(VyOSUnitTestSHIM.TestCase): @classmethod def setUpClass(cls): super(TestServiceDHCPv6Server, cls).setUpClass() # Clear out current configuration to allow running this test on a live system cls.cli_delete(cls, base_path) cls.cli_set(cls, ['interfaces', 'ethernet', interface, 'address', interface_addr]) @classmethod def tearDownClass(cls): cls.cli_delete(cls, ['interfaces', 'ethernet', interface, 'address', interface_addr]) cls.cli_commit(cls) super(TestServiceDHCPv6Server, cls).tearDownClass() def tearDown(self): self.cli_delete(base_path) self.cli_commit() def walk_path(self, obj, path): current = obj for i, key in enumerate(path): if isinstance(key, str): self.assertTrue(isinstance(current, dict), msg=f'Failed path: {path}') self.assertTrue(key in current, msg=f'Failed path: {path}') elif isinstance(key, int): self.assertTrue(isinstance(current, list), msg=f'Failed path: {path}') self.assertTrue(0 <= key < len(current), msg=f'Failed path: {path}') else: assert False, "Invalid type" current = current[key] return current def verify_config_object(self, obj, path, value): base_obj = self.walk_path(obj, path) self.assertTrue(isinstance(base_obj, list)) self.assertTrue(any(True for v in base_obj if v == value)) def verify_config_value(self, obj, path, key, value): base_obj = self.walk_path(obj, path) if isinstance(base_obj, list): self.assertTrue(any(True for v in base_obj if key in v and v[key] == value)) elif isinstance(base_obj, dict): self.assertTrue(key in base_obj) self.assertEqual(base_obj[key], value) def test_single_pool(self): shared_net_name = 'SMOKE-1' search_domains = ['foo.vyos.net', 'bar.vyos.net'] lease_time = '1200' max_lease_time = '72000' min_lease_time = '600' preference = '10' sip_server = 'sip.vyos.net' sntp_server = inc_ip(subnet, 100) range_start = inc_ip(subnet, 256) # ::100 range_stop = inc_ip(subnet, 65535) # ::ffff pool = base_path + ['shared-network-name', shared_net_name, 'subnet', subnet] self.cli_set(base_path + ['preference', preference]) self.cli_set(pool + ['subnet-id', '1']) # we use the first subnet IP address as default gateway - self.cli_set(pool + ['name-server', dns_1]) - self.cli_set(pool + ['name-server', dns_2]) - self.cli_set(pool + ['name-server', dns_2]) self.cli_set(pool + ['lease-time', 'default', lease_time]) self.cli_set(pool + ['lease-time', 'maximum', max_lease_time]) self.cli_set(pool + ['lease-time', 'minimum', min_lease_time]) - self.cli_set(pool + ['nis-domain', domain]) - self.cli_set(pool + ['nisplus-domain', domain]) - self.cli_set(pool + ['sip-server', sip_server]) - self.cli_set(pool + ['sntp-server', sntp_server]) - self.cli_set(pool + ['address-range', 'start', range_start, 'stop', range_stop]) + self.cli_set(pool + ['option', 'name-server', dns_1]) + self.cli_set(pool + ['option', 'name-server', dns_2]) + self.cli_set(pool + ['option', 'name-server', dns_2]) + self.cli_set(pool + ['option', 'nis-domain', domain]) + self.cli_set(pool + ['option', 'nisplus-domain', domain]) + self.cli_set(pool + ['option', 'sip-server', sip_server]) + self.cli_set(pool + ['option', 'sntp-server', sntp_server]) + self.cli_set(pool + ['range', '1', 'start', range_start]) + self.cli_set(pool + ['range', '1', 'stop', range_stop]) for server in nis_servers: - self.cli_set(pool + ['nis-server', server]) - self.cli_set(pool + ['nisplus-server', server]) + self.cli_set(pool + ['option', 'nis-server', server]) + self.cli_set(pool + ['option', 'nisplus-server', server]) for search in search_domains: - self.cli_set(pool + ['domain-search', search]) + self.cli_set(pool + ['option', 'domain-search', search]) client_base = 1 for client in ['client1', 'client2', 'client3']: duid = f'00:01:00:01:12:34:56:78:aa:bb:cc:dd:ee:{client_base:02}' self.cli_set(pool + ['static-mapping', client, 'duid', duid]) self.cli_set(pool + ['static-mapping', client, 'ipv6-address', inc_ip(subnet, client_base)]) self.cli_set(pool + ['static-mapping', client, 'ipv6-prefix', inc_ip(subnet, client_base << 64) + '/64']) client_base += 1 # cannot have both mac-address and duid set with self.assertRaises(ConfigSessionError): self.cli_set(pool + ['static-mapping', 'client1', 'mac', '00:50:00:00:00:11']) self.cli_commit() self.cli_delete(pool + ['static-mapping', 'client1', 'mac']) # commit changes self.cli_commit() config = read_file(KEA6_CONF) obj = loads(config) self.verify_config_value(obj, ['Dhcp6', 'shared-networks'], 'name', shared_net_name) self.verify_config_value(obj, ['Dhcp6', 'shared-networks', 0, 'subnet6'], 'subnet', subnet) self.verify_config_value(obj, ['Dhcp6', 'shared-networks', 0, 'subnet6'], 'id', 1) self.verify_config_value(obj, ['Dhcp6', 'shared-networks', 0, 'subnet6'], 'valid-lifetime', int(lease_time)) self.verify_config_value(obj, ['Dhcp6', 'shared-networks', 0, 'subnet6'], 'min-valid-lifetime', int(min_lease_time)) self.verify_config_value(obj, ['Dhcp6', 'shared-networks', 0, 'subnet6'], 'max-valid-lifetime', int(max_lease_time)) # Verify options self.verify_config_object( obj, ['Dhcp6', 'shared-networks', 0, 'subnet6', 0, 'option-data'], {'name': 'dns-servers', 'data': f'{dns_1}, {dns_2}'}) self.verify_config_object( obj, ['Dhcp6', 'shared-networks', 0, 'subnet6', 0, 'option-data'], {'name': 'domain-search', 'data': ", ".join(search_domains)}) self.verify_config_object( obj, ['Dhcp6', 'shared-networks', 0, 'subnet6', 0, 'option-data'], {'name': 'nis-domain-name', 'data': domain}) self.verify_config_object( obj, ['Dhcp6', 'shared-networks', 0, 'subnet6', 0, 'option-data'], {'name': 'nis-servers', 'data': ", ".join(nis_servers)}) self.verify_config_object( obj, ['Dhcp6', 'shared-networks', 0, 'subnet6', 0, 'option-data'], {'name': 'nisp-domain-name', 'data': domain}) self.verify_config_object( obj, ['Dhcp6', 'shared-networks', 0, 'subnet6', 0, 'option-data'], {'name': 'nisp-servers', 'data': ", ".join(nis_servers)}) self.verify_config_object( obj, ['Dhcp6', 'shared-networks', 0, 'subnet6', 0, 'option-data'], {'name': 'sntp-servers', 'data': sntp_server}) self.verify_config_object( obj, ['Dhcp6', 'shared-networks', 0, 'subnet6', 0, 'option-data'], {'name': 'sip-server-dns', 'data': sip_server}) # Verify pools self.verify_config_object( obj, ['Dhcp6', 'shared-networks', 0, 'subnet6', 0, 'pools'], {'pool': f'{range_start} - {range_stop}'}) client_base = 1 for client in ['client1', 'client2', 'client3']: duid = f'00:01:00:01:12:34:56:78:aa:bb:cc:dd:ee:{client_base:02}' ip = inc_ip(subnet, client_base) prefix = inc_ip(subnet, client_base << 64) + '/64' self.verify_config_object( obj, ['Dhcp6', 'shared-networks', 0, 'subnet6', 0, 'reservations'], {'hostname': client, 'duid': duid, 'ip-addresses': [ip], 'prefixes': [prefix]}) client_base += 1 # Check for running process self.assertTrue(process_named_running(PROCESS_NAME)) def test_prefix_delegation(self): shared_net_name = 'SMOKE-2' range_start = inc_ip(subnet, 256) # ::100 range_stop = inc_ip(subnet, 65535) # ::ffff delegate_start = '2001:db8:ee::' delegate_len = '64' prefix_len = '56' pool = base_path + ['shared-network-name', shared_net_name, 'subnet', subnet] self.cli_set(pool + ['subnet-id', '1']) - self.cli_set(pool + ['address-range', 'start', range_start, 'stop', range_stop]) + self.cli_set(pool + ['range', '1', 'start', range_start]) + self.cli_set(pool + ['range', '1', 'stop', range_stop]) self.cli_set(pool + ['prefix-delegation', 'prefix', delegate_start, 'delegated-length', delegate_len]) self.cli_set(pool + ['prefix-delegation', 'prefix', delegate_start, 'prefix-length', prefix_len]) # commit changes self.cli_commit() config = read_file(KEA6_CONF) obj = loads(config) self.verify_config_value(obj, ['Dhcp6', 'shared-networks'], 'name', shared_net_name) self.verify_config_value(obj, ['Dhcp6', 'shared-networks', 0, 'subnet6'], 'subnet', subnet) # Verify pools self.verify_config_object( obj, ['Dhcp6', 'shared-networks', 0, 'subnet6', 0, 'pools'], {'pool': f'{range_start} - {range_stop}'}) self.verify_config_object( obj, ['Dhcp6', 'shared-networks', 0, 'subnet6', 0, 'pd-pools'], {'prefix': delegate_start, 'prefix-len': int(prefix_len), 'delegated-len': int(delegate_len)}) # Check for running process self.assertTrue(process_named_running(PROCESS_NAME)) def test_global_nameserver(self): shared_net_name = 'SMOKE-3' ns_global_1 = '2001:db8::1111' ns_global_2 = '2001:db8::2222' self.cli_set(base_path + ['global-parameters', 'name-server', ns_global_1]) self.cli_set(base_path + ['global-parameters', 'name-server', ns_global_2]) self.cli_set(base_path + ['shared-network-name', shared_net_name, 'subnet', subnet, 'subnet-id', '1']) # commit changes self.cli_commit() config = read_file(KEA6_CONF) obj = loads(config) self.verify_config_value(obj, ['Dhcp6', 'shared-networks'], 'name', shared_net_name) self.verify_config_value(obj, ['Dhcp6', 'shared-networks', 0, 'subnet6'], 'subnet', subnet) self.verify_config_value(obj, ['Dhcp6', 'shared-networks', 0, 'subnet6'], 'id', 1) self.verify_config_object( obj, ['Dhcp6', 'option-data'], {'name': 'dns-servers', "code": 23, "space": "dhcp6", "csv-format": True, 'data': f'{ns_global_1}, {ns_global_2}'}) # Check for running process self.assertTrue(process_named_running(PROCESS_NAME)) if __name__ == '__main__': unittest.main(verbosity=2) diff --git a/src/conf_mode/service_dhcpv6-server.py b/src/conf_mode/service_dhcpv6-server.py index 7cd801cdd..214531904 100755 --- a/src/conf_mode/service_dhcpv6-server.py +++ b/src/conf_mode/service_dhcpv6-server.py @@ -1,231 +1,239 @@ #!/usr/bin/env python3 # # Copyright (C) 2018-2023 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 os from ipaddress import ip_address from ipaddress import ip_network from sys import exit from vyos.config import Config from vyos.template import render from vyos.utils.process import call from vyos.utils.file import chmod_775 from vyos.utils.file import makedir from vyos.utils.file import write_file from vyos.utils.dict import dict_search from vyos.utils.network import is_subnet_connected from vyos import ConfigError from vyos import airbag airbag.enable() config_file = '/run/kea/kea-dhcp6.conf' ctrl_socket = '/run/kea/dhcp6-ctrl-socket' lease_file = '/config/dhcp/dhcp6-leases.csv' user_group = '_kea' def get_config(config=None): if config: conf = config else: conf = Config() base = ['service', 'dhcpv6-server'] if not conf.exists(base): return None dhcpv6 = conf.get_config_dict(base, key_mangling=('-', '_'), get_first_key=True, no_tag_node_value_mangle=True) return dhcpv6 def verify(dhcpv6): # bail out early - looks like removal from running config if not dhcpv6 or 'disable' in dhcpv6: return None # If DHCP is enabled we need one share-network if 'shared_network_name' not in dhcpv6: raise ConfigError('No DHCPv6 shared networks configured. At least '\ 'one DHCPv6 shared network must be configured.') # Inspect shared-network/subnet subnets = [] subnet_ids = [] listen_ok = False for network, network_config in dhcpv6['shared_network_name'].items(): # A shared-network requires a subnet definition if 'subnet' not in network_config: raise ConfigError(f'No DHCPv6 lease subnets configured for "{network}". '\ 'At least one lease subnet must be configured for '\ 'each shared network!') for subnet, subnet_config in network_config['subnet'].items(): if 'subnet_id' not in subnet_config: raise ConfigError(f'Unique subnet ID not specified for subnet "{subnet}"') if subnet_config['subnet_id'] in subnet_ids: raise ConfigError(f'Subnet ID for subnet "{subnet}" is not unique') subnet_ids.append(subnet_config['subnet_id']) - if 'address_range' in subnet_config: - if 'start' in subnet_config['address_range']: - range6_start = [] - range6_stop = [] - for start, start_config in subnet_config['address_range']['start'].items(): - if 'stop' not in start_config: - raise ConfigError(f'address-range stop address for start "{start}" is not defined!') - stop = start_config['stop'] + if 'range' in subnet_config: + range6_start = [] + range6_stop = [] + + for num, range_config in subnet_config['range'].items(): + if 'start' in range_config: + start = range_config['start'] + + if 'stop' not in range_config: + raise ConfigError(f'Range stop address for start "{start}" is not defined!') + stop = range_config['stop'] # Start address must be inside network if not ip_address(start) in ip_network(subnet): - raise ConfigError(f'address-range start address "{start}" is not in subnet "{subnet}"!') + raise ConfigError(f'Range start address "{start}" is not in subnet "{subnet}"!') # Stop address must be inside network if not ip_address(stop) in ip_network(subnet): - raise ConfigError(f'address-range stop address "{stop}" is not in subnet "{subnet}"!') + raise ConfigError(f'Range stop address "{stop}" is not in subnet "{subnet}"!') # Stop address must be greater or equal to start address if not ip_address(stop) >= ip_address(start): - raise ConfigError(f'address-range stop address "{stop}" must be greater then or equal ' \ + raise ConfigError(f'Range stop address "{stop}" must be greater then or equal ' \ f'to the range start address "{start}"!') # DHCPv6 range start address must be unique - two ranges can't # start with the same address - makes no sense if start in range6_start: raise ConfigError(f'Conflicting DHCPv6 lease range: '\ f'Pool start address "{start}" defined multipe times!') + range6_start.append(start) # DHCPv6 range stop address must be unique - two ranges can't # end with the same address - makes no sense if stop in range6_stop: raise ConfigError(f'Conflicting DHCPv6 lease range: '\ f'Pool stop address "{stop}" defined multipe times!') + range6_stop.append(stop) - if 'prefix' in subnet_config: - for prefix in subnet_config['prefix']: - if ip_network(prefix) not in ip_network(subnet): - raise ConfigError(f'address-range prefix "{prefix}" is not in subnet "{subnet}""') + if 'prefix' in range_config: + prefix = range_config['prefix'] + + if not ip_network(prefix).subnet_of(ip_network(subnet)): + raise ConfigError(f'Range prefix "{prefix}" is not in subnet "{subnet}"') # Prefix delegation sanity checks if 'prefix_delegation' in subnet_config: if 'prefix' not in subnet_config['prefix_delegation']: raise ConfigError('prefix-delegation prefix not defined!') for prefix, prefix_config in subnet_config['prefix_delegation']['prefix'].items(): if 'delegated_length' not in prefix_config: raise ConfigError(f'Delegated IPv6 prefix length for "{prefix}" '\ f'must be configured') if 'prefix_length' not in prefix_config: raise ConfigError('Length of delegated IPv6 prefix must be configured') if prefix_config['prefix_length'] > prefix_config['delegated_length']: raise ConfigError('Length of delegated IPv6 prefix must be within parent prefix') # Static mappings don't require anything (but check if IP is in subnet if it's set) if 'static_mapping' in subnet_config: for mapping, mapping_config in subnet_config['static_mapping'].items(): if 'ipv6_address' in mapping_config: # Static address must be in subnet if ip_address(mapping_config['ipv6_address']) not in ip_network(subnet): raise ConfigError(f'static-mapping address for mapping "{mapping}" is not in subnet "{subnet}"!') if ('mac' not in mapping_config and 'duid' not in mapping_config) or \ ('mac' in mapping_config and 'duid' in mapping_config): raise ConfigError(f'Either MAC address or Client identifier (DUID) is required for ' f'static mapping "{mapping}" within shared-network "{network}, {subnet}"!') - if 'vendor_option' in subnet_config: - if len(dict_search('vendor_option.cisco.tftp_server', subnet_config)) > 2: - raise ConfigError(f'No more then two Cisco tftp-servers should be defined for subnet "{subnet}"!') + if 'option' in subnet_config: + if 'vendor_option' in subnet_config['option']: + if len(dict_search('option.vendor_option.cisco.tftp_server', subnet_config)) > 2: + raise ConfigError(f'No more then two Cisco tftp-servers should be defined for subnet "{subnet}"!') # Subnets must be unique if subnet in subnets: raise ConfigError(f'DHCPv6 subnets must be unique! Subnet {subnet} defined multiple times!') + subnets.append(subnet) # DHCPv6 requires at least one configured address range or one static mapping # (FIXME: is not actually checked right now?) # There must be one subnet connected to a listen interface if network is not disabled. if 'disable' not in network_config: if is_subnet_connected(subnet): listen_ok = True # DHCPv6 subnet must not overlap. ISC DHCP also complains about overlapping # subnets: "Warning: subnet 2001:db8::/32 overlaps subnet 2001:db8:1::/32" net = ip_network(subnet) for n in subnets: net2 = ip_network(n) if (net != net2): if net.overlaps(net2): raise ConfigError('DHCPv6 conflicting subnet ranges: {0} overlaps {1}'.format(net, net2)) if not listen_ok: raise ConfigError('None of the DHCPv6 subnets are connected to a subnet6 on '\ 'this machine. At least one subnet6 must be connected such that '\ 'DHCPv6 listens on an interface!') return None def generate(dhcpv6): # bail out early - looks like removal from running config if not dhcpv6 or 'disable' in dhcpv6: return None dhcpv6['lease_file'] = lease_file dhcpv6['machine'] = os.uname().machine # Create directory for lease file if necessary lease_dir = os.path.dirname(lease_file) if not os.path.isdir(lease_dir): makedir(lease_dir, group='vyattacfg') chmod_775(lease_dir) # Create lease file if necessary and let kea own it - 'kea-lfc' expects it that way if not os.path.exists(lease_file): write_file(lease_file, '', user=user_group, group=user_group, mode=0o644) render(config_file, 'dhcp-server/kea-dhcp6.conf.j2', dhcpv6, user=user_group, group=user_group) return None def apply(dhcpv6): # bail out early - looks like removal from running config service_name = 'kea-dhcp6-server.service' if not dhcpv6 or 'disable' in dhcpv6: # DHCP server is removed in the commit call(f'systemctl stop {service_name}') if os.path.exists(config_file): os.unlink(config_file) return None call(f'systemctl restart {service_name}') return None if __name__ == '__main__': try: c = get_config() verify(c) generate(c) apply(c) except ConfigError as e: print(e) exit(1) diff --git a/src/migration-scripts/dhcpv6-server/3-to-4 b/src/migration-scripts/dhcpv6-server/3-to-4 index c065e3d43..4747ebd60 100755 --- a/src/migration-scripts/dhcpv6-server/3-to-4 +++ b/src/migration-scripts/dhcpv6-server/3-to-4 @@ -1,55 +1,90 @@ #!/usr/bin/env python3 # # Copyright (C) 2024 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/>. # T3316: # - Add subnet IDs to existing subnets +# - Move options to option node +# - Migrate address-range to range tagNode import sys import re from vyos.configtree import ConfigTree if len(sys.argv) < 2: print("Must specify file name!") sys.exit(1) file_name = sys.argv[1] with open(file_name, 'r') as f: config_file = f.read() base = ['service', 'dhcpv6-server', 'shared-network-name'] config = ConfigTree(config_file) if not config.exists(base): # Nothing to do sys.exit(0) +option_nodes = ['captive-portal', 'domain-search', 'name-server', + 'nis-domain', 'nis-server', 'nisplus-domain', 'nisplus-server', + 'sip-server', 'sntp-server', 'vendor-option'] + subnet_id = 1 for network in config.list_nodes(base): if config.exists(base + [network, 'subnet']): for subnet in config.list_nodes(base + [network, 'subnet']): base_subnet = base + [network, 'subnet', subnet] + if config.exists(base_subnet + ['address-range']): + config.set(base_subnet + ['range']) + config.set_tag(base_subnet + ['range']) + + range_id = 1 + + if config.exists(base_subnet + ['address-range', 'prefix']): + for prefix in config.return_values(base_subnet + ['address-range', 'prefix']): + config.set(base_subnet + ['range', range_id, 'prefix'], value=prefix) + + range_id += 1 + + if config.exists(base_subnet + ['address-range', 'start']): + for start in config.list_nodes(base_subnet + ['address-range', 'start']): + stop = config.return_value(base_subnet + ['address-range', 'start', start, 'stop']) + + config.set(base_subnet + ['range', range_id, 'start'], value=start) + config.set(base_subnet + ['range', range_id, 'stop'], value=stop) + + range_id += 1 + + config.delete(base_subnet + ['address-range']) + + for option in option_nodes: + if config.exists(base_subnet + [option]): + config.set(base_subnet + ['option']) + config.copy(base_subnet + [option], base_subnet + ['option', option]) + config.delete(base_subnet + [option]) + config.set(base_subnet + ['subnet-id'], value=subnet_id) subnet_id += 1 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)) exit(1) diff --git a/src/op_mode/dhcp.py b/src/op_mode/dhcp.py index 02f4d5bbb..a64acec31 100755 --- a/src/op_mode/dhcp.py +++ b/src/op_mode/dhcp.py @@ -1,399 +1,396 @@ #!/usr/bin/env python3 # # Copyright (C) 2022-2023 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 os import sys import typing from datetime import datetime from glob import glob from ipaddress import ip_address from tabulate import tabulate import vyos.opmode from vyos.base import Warning from vyos.configquery import ConfigTreeQuery from vyos.kea import kea_get_active_config from vyos.kea import kea_get_pool_from_subnet_id from vyos.kea import kea_parse_leases from vyos.utils.process import is_systemd_service_running time_string = "%a %b %d %H:%M:%S %Z %Y" config = ConfigTreeQuery() lease_valid_states = ['all', 'active', 'free', 'expired', 'released', 'abandoned', 'reset', 'backup'] sort_valid_inet = ['end', 'mac', 'hostname', 'ip', 'pool', 'remaining', 'start', 'state'] sort_valid_inet6 = ['end', 'iaid_duid', 'ip', 'last_communication', 'pool', 'remaining', 'state', 'type'] ArgFamily = typing.Literal['inet', 'inet6'] ArgState = typing.Literal['all', 'active', 'free', 'expired', 'released', 'abandoned', 'reset', 'backup'] ArgOrigin = typing.Literal['local', 'remote'] def _utc_to_local(utc_dt): return datetime.fromtimestamp((datetime.fromtimestamp(utc_dt) - datetime(1970, 1, 1)).total_seconds()) def _format_hex_string(in_str): out_str = "" # if input is divisible by 2, add : every 2 chars if len(in_str) > 0 and len(in_str) % 2 == 0: out_str = ':'.join(a+b for a,b in zip(in_str[::2], in_str[1::2])) else: out_str = in_str return out_str def _find_list_of_dict_index(lst, key='ip', value='') -> int: """ Find the index entry of list of dict matching the dict value Exampe: % lst = [{'ip': '192.0.2.1'}, {'ip': '192.0.2.2'}] % _find_list_of_dict_index(lst, key='ip', value='192.0.2.2') % 1 """ idx = next((index for (index, d) in enumerate(lst) if d[key] == value), None) return idx def _get_raw_server_leases(family='inet', pool=None, sorted=None, state=[], origin=None) -> list: """ Get DHCP server leases :return list """ inet_suffix = '6' if family == 'inet6' else '4' lease_file = f'/config/dhcp/dhcp{inet_suffix}-leases.csv' leases = kea_parse_leases(lease_file) if pool is None: pool = _get_dhcp_pools(family=family) else: pool = [pool] active_config = kea_get_active_config(inet_suffix) data = [] for lease in leases: data_lease = {} data_lease['ip'] = lease['address'] lease_state_long = {'0': 'active', '1': 'rejected', '2': 'expired'} data_lease['state'] = lease_state_long[lease['state']] data_lease['pool'] = kea_get_pool_from_subnet_id(active_config, inet_suffix, lease['subnet_id']) if active_config else '-' data_lease['end'] = lease['expire_timestamp'].timestamp() if lease['expire_timestamp'] else None data_lease['origin'] = 'local' # TODO: Determine remote in HA if family == 'inet': data_lease['mac'] = lease['hwaddr'] data_lease['start'] = lease['start_timestamp'].timestamp() data_lease['hostname'] = lease['hostname'] if family == 'inet6': data_lease['last_communication'] = lease['start_timestamp'].timestamp() data_lease['iaid_duid'] = _format_hex_string(lease['duid']) lease_types_long = {'0': 'non-temporary', '1': 'temporary', '2': 'prefix delegation'} data_lease['type'] = lease_types_long[lease['lease_type']] data_lease['remaining'] = '-' if lease['expire']: data_lease['remaining'] = lease['expire_timestamp'] - datetime.utcnow() if data_lease['remaining'].days >= 0: # substraction gives us a timedelta object which can't be formatted with strftime # so we use str(), split gets rid of the microseconds data_lease['remaining'] = str(data_lease["remaining"]).split('.')[0] # Do not add old leases if data_lease['remaining'] != '' and data_lease['pool'] in pool and data_lease['state'] != 'free': if not state or state == 'all' or data_lease['state'] in state: data.append(data_lease) # deduplicate checked = [] for entry in data: addr = entry.get('ip') if addr not in checked: checked.append(addr) else: idx = _find_list_of_dict_index(data, key='ip', value=addr) data.pop(idx) if sorted: if sorted == 'ip': data.sort(key = lambda x:ip_address(x['ip'])) else: data.sort(key = lambda x:x[sorted]) return data def _get_formatted_server_leases(raw_data, family='inet'): data_entries = [] if family == 'inet': for lease in raw_data: ipaddr = lease.get('ip') hw_addr = lease.get('mac') state = lease.get('state') start = lease.get('start') start = _utc_to_local(start).strftime('%Y/%m/%d %H:%M:%S') end = lease.get('end') end = _utc_to_local(end).strftime('%Y/%m/%d %H:%M:%S') if end else '-' remain = lease.get('remaining') pool = lease.get('pool') hostname = lease.get('hostname') origin = lease.get('origin') data_entries.append([ipaddr, hw_addr, state, start, end, remain, pool, hostname, origin]) headers = ['IP Address', 'MAC address', 'State', 'Lease start', 'Lease expiration', 'Remaining', 'Pool', 'Hostname', 'Origin'] if family == 'inet6': for lease in raw_data: ipaddr = lease.get('ip') state = lease.get('state') start = lease.get('last_communication') start = _utc_to_local(start).strftime('%Y/%m/%d %H:%M:%S') end = lease.get('end') end = _utc_to_local(end).strftime('%Y/%m/%d %H:%M:%S') remain = lease.get('remaining') lease_type = lease.get('type') pool = lease.get('pool') host_identifier = lease.get('iaid_duid') data_entries.append([ipaddr, state, start, end, remain, lease_type, pool, host_identifier]) headers = ['IPv6 address', 'State', 'Last communication', 'Lease expiration', 'Remaining', 'Type', 'Pool', 'IAID_DUID'] output = tabulate(data_entries, headers, numalign='left') return output def _get_dhcp_pools(family='inet') -> list: v = 'v6' if family == 'inet6' else '' pools = config.list_nodes(f'service dhcp{v}-server shared-network-name') return pools def _get_pool_size(pool, family='inet'): v = 'v6' if family == 'inet6' else '' base = f'service dhcp{v}-server shared-network-name {pool}' size = 0 subnets = config.list_nodes(f'{base} subnet') for subnet in subnets: - if family == 'inet6': - ranges = config.list_nodes(f'{base} subnet {subnet} address-range start') - else: - ranges = config.list_nodes(f'{base} subnet {subnet} range') + ranges = config.list_nodes(f'{base} subnet {subnet} range') for range in ranges: if family == 'inet6': - start = config.list_nodes(f'{base} subnet {subnet} address-range start')[0] - stop = config.value(f'{base} subnet {subnet} address-range start {start} stop') + start = config.value(f'{base} subnet {subnet} range {range} start') + stop = config.value(f'{base} subnet {subnet} range {range} stop') else: start = config.value(f'{base} subnet {subnet} range {range} start') stop = config.value(f'{base} subnet {subnet} range {range} stop') # Add +1 because both range boundaries are inclusive size += int(ip_address(stop)) - int(ip_address(start)) + 1 return size def _get_raw_pool_statistics(family='inet', pool=None): if pool is None: pool = _get_dhcp_pools(family=family) else: pool = [pool] v = 'v6' if family == 'inet6' else '' stats = [] for p in pool: subnet = config.list_nodes(f'service dhcp{v}-server shared-network-name {p} subnet') size = _get_pool_size(family=family, pool=p) leases = len(_get_raw_server_leases(family=family, pool=p)) use_percentage = round(leases / size * 100) if size != 0 else 0 pool_stats = {'pool': p, 'size': size, 'leases': leases, 'available': (size - leases), 'use_percentage': use_percentage, 'subnet': subnet} stats.append(pool_stats) return stats def _get_formatted_pool_statistics(pool_data, family='inet'): data_entries = [] for entry in pool_data: pool = entry.get('pool') size = entry.get('size') leases = entry.get('leases') available = entry.get('available') use_percentage = entry.get('use_percentage') use_percentage = f'{use_percentage}%' data_entries.append([pool, size, leases, available, use_percentage]) headers = ['Pool', 'Size','Leases', 'Available', 'Usage'] output = tabulate(data_entries, headers, numalign='left') return output def _verify(func): """Decorator checks if DHCP(v6) config exists""" from functools import wraps @wraps(func) def _wrapper(*args, **kwargs): config = ConfigTreeQuery() family = kwargs.get('family') v = 'v6' if family == 'inet6' else '' unconf_message = f'DHCP{v} server is not configured' # Check if config does not exist if not config.exists(f'service dhcp{v}-server'): raise vyos.opmode.UnconfiguredSubsystem(unconf_message) return func(*args, **kwargs) return _wrapper @_verify def show_pool_statistics(raw: bool, family: ArgFamily, pool: typing.Optional[str]): pool_data = _get_raw_pool_statistics(family=family, pool=pool) if raw: return pool_data else: return _get_formatted_pool_statistics(pool_data, family=family) @_verify def show_server_leases(raw: bool, family: ArgFamily, pool: typing.Optional[str], sorted: typing.Optional[str], state: typing.Optional[ArgState], origin: typing.Optional[ArgOrigin] ): # if dhcp server is down, inactive leases may still be shown as active, so warn the user. v = '6' if family == 'inet6' else '4' if not is_systemd_service_running(f'kea-dhcp{v}-server.service'): Warning('DHCP server is configured but not started. Data may be stale.') v = 'v6' if family == 'inet6' else '' if pool and pool not in _get_dhcp_pools(family=family): raise vyos.opmode.IncorrectValue(f'DHCP{v} pool "{pool}" does not exist!') if state and state not in lease_valid_states: raise vyos.opmode.IncorrectValue(f'DHCP{v} state "{state}" is invalid!') sort_valid = sort_valid_inet6 if family == 'inet6' else sort_valid_inet if sorted and sorted not in sort_valid: raise vyos.opmode.IncorrectValue(f'DHCP{v} sort "{sorted}" is invalid!') lease_data = _get_raw_server_leases(family=family, pool=pool, sorted=sorted, state=state, origin=origin) if raw: return lease_data else: return _get_formatted_server_leases(lease_data, family=family) def _get_raw_client_leases(family='inet', interface=None): from time import mktime from datetime import datetime from vyos.defaults import directories from vyos.utils.network import get_interface_vrf lease_dir = directories['isc_dhclient_dir'] lease_files = [] lease_data = [] if interface: tmp = f'{lease_dir}/dhclient_{interface}.lease' if os.path.exists(tmp): lease_files.append(tmp) else: # All DHCP leases lease_files = glob(f'{lease_dir}/dhclient_*.lease') for lease in lease_files: tmp = {} with open(lease, 'r') as f: for line in f.readlines(): line = line.rstrip() if 'last_update' not in tmp: # ISC dhcp client contains least_update timestamp in human readable # format this makes less sense for an API and also the expiry # timestamp is provided in UNIX time. Convert string (e.g. Sun Jul # 30 18:13:44 CEST 2023) to UNIX time (1690733624) tmp.update({'last_update' : int(mktime(datetime.strptime(line, time_string).timetuple()))}) continue k, v = line.split('=') tmp.update({k : v.replace("'", "")}) if 'interface' in tmp: vrf = get_interface_vrf(tmp['interface']) if vrf: tmp.update({'vrf' : vrf}) lease_data.append(tmp) return lease_data def _get_formatted_client_leases(lease_data, family): from time import localtime from time import strftime from vyos.utils.network import is_intf_addr_assigned data_entries = [] for lease in lease_data: if not lease.get('new_ip_address'): continue data_entries.append(["Interface", lease['interface']]) if 'new_ip_address' in lease: tmp = '[Active]' if is_intf_addr_assigned(lease['interface'], lease['new_ip_address']) else '[Inactive]' data_entries.append(["IP address", lease['new_ip_address'], tmp]) if 'new_subnet_mask' in lease: data_entries.append(["Subnet Mask", lease['new_subnet_mask']]) if 'new_domain_name' in lease: data_entries.append(["Domain Name", lease['new_domain_name']]) if 'new_routers' in lease: data_entries.append(["Router", lease['new_routers']]) if 'new_domain_name_servers' in lease: data_entries.append(["Name Server", lease['new_domain_name_servers']]) if 'new_dhcp_server_identifier' in lease: data_entries.append(["DHCP Server", lease['new_dhcp_server_identifier']]) if 'new_dhcp_lease_time' in lease: data_entries.append(["DHCP Server", lease['new_dhcp_lease_time']]) if 'vrf' in lease: data_entries.append(["VRF", lease['vrf']]) if 'last_update' in lease: tmp = strftime(time_string, localtime(int(lease['last_update']))) data_entries.append(["Last Update", tmp]) if 'new_expiry' in lease: tmp = strftime(time_string, localtime(int(lease['new_expiry']))) data_entries.append(["Expiry", tmp]) # Add empty marker data_entries.append(['']) output = tabulate(data_entries, tablefmt='plain') return output def show_client_leases(raw: bool, family: ArgFamily, interface: typing.Optional[str]): lease_data = _get_raw_client_leases(family=family, interface=interface) if raw: return lease_data else: return _get_formatted_client_leases(lease_data, family=family) if __name__ == '__main__': try: res = vyos.opmode.run(sys.modules[__name__]) if res: print(res) except (ValueError, vyos.opmode.Error) as e: print(e) sys.exit(1)