diff --git a/python/vyos/ifconfig/bond.py b/python/vyos/ifconfig/bond.py index 8ba481728..a659b9bd2 100644 --- a/python/vyos/ifconfig/bond.py +++ b/python/vyos/ifconfig/bond.py @@ -1,509 +1,511 @@ # Copyright 2019-2024 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 os from vyos.ifconfig.interface import Interface from vyos.utils.dict import dict_search from vyos.utils.assertion import assert_list from vyos.utils.assertion import assert_mac from vyos.utils.assertion import assert_positive @Interface.register class BondIf(Interface): """ The Linux bonding driver provides a method for aggregating multiple network interfaces into a single logical "bonded" interface. The behavior of the bonded interfaces depends upon the mode; generally speaking, modes provide either hot standby or load balancing services. Additionally, link integrity monitoring may be performed. """ - iftype = 'bond' definition = { **Interface.definition, ** { 'section': 'bonding', 'prefixes': ['bond', ], 'broadcast': True, 'bridgeable': True, }, } _sysfs_set = {**Interface._sysfs_set, **{ 'bond_hash_policy': { 'validate': lambda v: assert_list(v, ['layer2', 'layer2+3', 'layer3+4', 'encap2+3', 'encap3+4']), 'location': '/sys/class/net/{ifname}/bonding/xmit_hash_policy', }, 'bond_min_links': { 'validate': assert_positive, 'location': '/sys/class/net/{ifname}/bonding/min_links', }, 'bond_lacp_rate': { 'validate': lambda v: assert_list(v, ['slow', 'fast']), 'location': '/sys/class/net/{ifname}/bonding/lacp_rate', }, 'bond_system_mac': { 'validate': lambda v: assert_mac(v, test_all_zero=False), 'location': '/sys/class/net/{ifname}/bonding/ad_actor_system', }, 'bond_miimon': { 'validate': assert_positive, 'location': '/sys/class/net/{ifname}/bonding/miimon' }, 'bond_arp_interval': { 'validate': assert_positive, 'location': '/sys/class/net/{ifname}/bonding/arp_interval' }, 'bond_arp_ip_target': { # XXX: no validation of the IP 'location': '/sys/class/net/{ifname}/bonding/arp_ip_target', }, 'bond_add_port': { 'location': '/sys/class/net/{ifname}/bonding/slaves', }, 'bond_del_port': { 'location': '/sys/class/net/{ifname}/bonding/slaves', }, 'bond_primary': { 'convert': lambda name: name if name else '\0', 'location': '/sys/class/net/{ifname}/bonding/primary', }, 'bond_mode': { 'validate': lambda v: assert_list(v, ['balance-rr', 'active-backup', 'balance-xor', 'broadcast', '802.3ad', 'balance-tlb', 'balance-alb']), 'location': '/sys/class/net/{ifname}/bonding/mode', }, }} _sysfs_get = {**Interface._sysfs_get, **{ 'bond_arp_ip_target': { 'location': '/sys/class/net/{ifname}/bonding/arp_ip_target', }, 'bond_mode': { 'location': '/sys/class/net/{ifname}/bonding/mode', } }} @staticmethod def get_inherit_bond_options() -> list: """ Returns list of option which are inherited from bond interface to member interfaces :return: List of interface options :rtype: list """ options = [ 'mtu' ] return options + def _create(self): + super()._create('bond') + def remove(self): """ Remove interface from operating system. Removing the interface deconfigures all assigned IP addresses and clear possible DHCP(v6) client processes. Example: >>> from vyos.ifconfig import Interface >>> i = Interface('eth0') >>> i.remove() """ # when a bond member gets deleted, all members are placed in A/D state # even when they are enabled inside CLI. This will make the config # and system look async. slave_list = [] for s in self.get_slaves(): slave = { 'ifname': s, 'state': Interface(s).get_admin_state() } slave_list.append(slave) # remove bond master which places members in disabled state super().remove() # replicate previous interface state before bond destruction back to # physical interface for slave in slave_list: i = Interface(slave['ifname']) i.set_admin_state(slave['state']) def set_hash_policy(self, mode): """ Selects the transmit hash policy to use for slave selection in balance-xor, 802.3ad, and tlb modes. Possible values are: layer2, layer2+3, layer3+4, encap2+3, encap3+4. The default value is layer2 Example: >>> from vyos.ifconfig import BondIf >>> BondIf('bond0').set_hash_policy('layer2+3') """ self.set_interface('bond_hash_policy', mode) def set_min_links(self, number): """ Specifies the minimum number of links that must be active before asserting carrier. It is similar to the Cisco EtherChannel min-links feature. This allows setting the minimum number of member ports that must be up (link-up state) before marking the bond device as up (carrier on). This is useful for situations where higher level services such as clustering want to ensure a minimum number of low bandwidth links are active before switchover. This option only affect 802.3ad mode. The default value is 0. This will cause carrier to be asserted (for 802.3ad mode) whenever there is an active aggregator, regardless of the number of available links in that aggregator. Note that, because an aggregator cannot be active without at least one available link, setting this option to 0 or to 1 has the exact same effect. Example: >>> from vyos.ifconfig import BondIf >>> BondIf('bond0').set_min_links('0') """ self.set_interface('bond_min_links', number) def set_lacp_rate(self, slow_fast): """ Option specifying the rate in which we'll ask our link partner to transmit LACPDU packets in 802.3ad mode. Possible values are: slow or 0 Request partner to transmit LACPDUs every 30 seconds fast or 1 Request partner to transmit LACPDUs every 1 second The default is slow. Example: >>> from vyos.ifconfig import BondIf >>> BondIf('bond0').set_lacp_rate('slow') """ self.set_interface('bond_lacp_rate', slow_fast) def set_miimon_interval(self, interval): """ Specifies the MII link monitoring frequency in milliseconds. This determines how often the link state of each slave is inspected for link failures. A value of zero disables MII link monitoring. A value of 100 is a good starting point. The default value is 0. Example: >>> from vyos.ifconfig import BondIf >>> BondIf('bond0').set_miimon_interval('100') """ return self.set_interface('bond_miimon', interval) def set_arp_interval(self, interval): """ Specifies the ARP link monitoring frequency in milliseconds. The ARP monitor works by periodically checking the slave devices to determine whether they have sent or received traffic recently (the precise criteria depends upon the bonding mode, and the state of the slave). Regular traffic is generated via ARP probes issued for the addresses specified by the arp_ip_target option. If ARP monitoring is used in an etherchannel compatible mode (modes 0 and 2), the switch should be configured in a mode that evenly distributes packets across all links. If the switch is configured to distribute the packets in an XOR fashion, all replies from the ARP targets will be received on the same link which could cause the other team members to fail. value of 0 disables ARP monitoring. The default value is 0. Example: >>> from vyos.ifconfig import BondIf >>> BondIf('bond0').set_arp_interval('100') """ return self.set_interface('bond_arp_interval', interval) def get_arp_ip_target(self): """ Specifies the IP addresses to use as ARP monitoring peers when arp_interval is > 0. These are the targets of the ARP request sent to determine the health of the link to the targets. Specify these values in ddd.ddd.ddd.ddd format. Multiple IP addresses must be separated by a comma. At least one IP address must be given for ARP monitoring to function. The maximum number of targets that can be specified is 16. The default value is no IP addresses. Example: >>> from vyos.ifconfig import BondIf >>> BondIf('bond0').get_arp_ip_target() '192.0.2.1' """ # As this function might also be called from update() of a VLAN interface # we must check if the bond_arp_ip_target retrieval worked or not - as this # can not be set for a bond vif interface try: return self.get_interface('bond_arp_ip_target') except FileNotFoundError: return '' def set_arp_ip_target(self, target): """ Specifies the IP addresses to use as ARP monitoring peers when arp_interval is > 0. These are the targets of the ARP request sent to determine the health of the link to the targets. Specify these values in ddd.ddd.ddd.ddd format. Multiple IP addresses must be separated by a comma. At least one IP address must be given for ARP monitoring to function. The maximum number of targets that can be specified is 16. The default value is no IP addresses. Example: >>> from vyos.ifconfig import BondIf >>> BondIf('bond0').set_arp_ip_target('192.0.2.1') >>> BondIf('bond0').get_arp_ip_target() '192.0.2.1' """ return self.set_interface('bond_arp_ip_target', target) def add_port(self, interface): """ Enslave physical interface to bond. Example: >>> from vyos.ifconfig import BondIf >>> BondIf('bond0').add_port('eth0') >>> BondIf('bond0').add_port('eth1') """ # From drivers/net/bonding/bond_main.c: # ... # bond_set_slave_link_state(new_slave, # BOND_LINK_UP, # BOND_SLAVE_NOTIFY_NOW); # ... # # The kernel will ALWAYS place new bond members in "up" state regardless # what the CLI will tell us! # Physical interface must be in admin down state before they can be # enslaved. If this is not the case an error will be shown: # bond0: eth0 is up - this may be due to an out of date ifenslave slave = Interface(interface) slave_state = slave.get_admin_state() if slave_state == 'up': slave.set_admin_state('down') ret = self.set_interface('bond_add_port', f'+{interface}') # The kernel will ALWAYS place new bond members in "up" state regardless # what the LI is configured for - thus we place the interface in its # desired state slave.set_admin_state(slave_state) return ret def del_port(self, interface): """ Remove physical port from bond Example: >>> from vyos.ifconfig import BondIf >>> BondIf('bond0').del_port('eth1') """ return self.set_interface('bond_del_port', f'-{interface}') def get_slaves(self): """ Return a list with all configured slave interfaces on this bond. Example: >>> from vyos.ifconfig import BondIf >>> BondIf('bond0').get_slaves() ['eth1', 'eth2'] """ enslaved_ifs = [] # retrieve real enslaved interfaces from OS kernel sysfs_bond = '/sys/class/net/{}'.format(self.config['ifname']) if os.path.isdir(sysfs_bond): for directory in os.listdir(sysfs_bond): if 'lower_' in directory: enslaved_ifs.append(directory.replace('lower_', '')) return enslaved_ifs def get_mode(self): """ Return bond operation mode. Example: >>> from vyos.ifconfig import BondIf >>> BondIf('bond0').get_mode() '802.3ad' """ mode = self.get_interface('bond_mode') # mode is now "802.3ad 4", we are only interested in "802.3ad" return mode.split()[0] def set_primary(self, interface): """ A string (eth0, eth2, etc) specifying which slave is the primary device. The specified device will always be the active slave while it is available. Only when the primary is off-line will alternate devices be used. This is useful when one slave is preferred over another, e.g., when one slave has higher throughput than another. The primary option is only valid for active-backup, balance-tlb and balance-alb mode. Example: >>> from vyos.ifconfig import BondIf >>> BondIf('bond0').set_primary('eth2') """ return self.set_interface('bond_primary', interface) def set_mode(self, mode): """ Specifies one of the bonding policies. The default is balance-rr (round robin). Possible values are: balance-rr, active-backup, balance-xor, broadcast, 802.3ad, balance-tlb, balance-alb NOTE: the bonding mode can not be changed when the bond itself has slaves Example: >>> from vyos.ifconfig import BondIf >>> BondIf('bond0').set_mode('802.3ad') """ return self.set_interface('bond_mode', mode) def set_system_mac(self, mac): """ In an AD system, this specifies the mac-address for the actor in protocol packet exchanges (LACPDUs). The value cannot be NULL or multicast. It is preferred to have the local-admin bit set for this mac but driver does not enforce it. If the value is not given then system defaults to using the masters' mac address as actors' system address. This parameter has effect only in 802.3ad mode and is available through SysFs interface. Example: >>> from vyos.ifconfig import BondIf >>> BondIf('bond0').set_system_mac('00:50:ab:cd:ef:01') """ return self.set_interface('bond_system_mac', mac) def update(self, config): """ General helper function which works on a dictionary retrived by get_config_dict(). It's main intention is to consolidate the scattered interface setup code and provide a single point of entry when workin on any interface. """ # use ref-counting function to place an interface into admin down state. # set_admin_state_up() must be called the same amount of times else the # interface won't come up. This can/should be used to prevent link flapping # when changing interface parameters require the interface to be down. # We will disable it once before reconfiguration and enable it afterwards. if 'shutdown_required' in config: self.set_admin_state('down') # Specifies the MII link monitoring frequency in milliseconds value = config.get('mii_mon_interval') self.set_miimon_interval(value) # Bonding transmit hash policy value = config.get('hash_policy') if value: self.set_hash_policy(value) # Minimum number of member interfaces value = config.get('min_links') if value: self.set_min_links(value) # Some interface options can only be changed if the interface is # administratively down if self.get_admin_state() == 'down': # Remove ALL bond member interfaces for interface in self.get_slaves(): self.del_port(interface) # Restore correct interface status based on config if dict_search(f'member.interface.{interface}.disable', config) is not None or \ dict_search(f'member.interface_remove.{interface}.disable', config) is not None: Interface(interface).set_admin_state('down') else: Interface(interface).set_admin_state('up') # Bonding policy/mode - default value, always present self.set_mode(config['mode']) # LACPDU transmission rate - default value if config['mode'] == '802.3ad': self.set_lacp_rate(config.get('lacp_rate')) if config['mode'] not in ['802.3ad', 'balance-tlb', 'balance-alb']: tmp = dict_search('arp_monitor.interval', config) value = tmp if (tmp != None) else '0' self.set_arp_interval(value) # ARP monitor targets need to be synchronized between sysfs and CLI. # Unfortunately an address can't be send twice to sysfs as this will # result in the following exception: OSError: [Errno 22] Invalid argument. # # We remove ALL addresses prior to adding new ones, this will remove # addresses manually added by the user too - but as we are limited to 16 adresses # from the kernel side this looks valid to me. We won't run into an error # when a user added manual adresses which would result in having more # then 16 adresses in total. arp_tgt_addr = list(map(str, self.get_arp_ip_target().split())) for addr in arp_tgt_addr: self.set_arp_ip_target('-' + addr) # Add configured ARP target addresses value = dict_search('arp_monitor.target', config) if isinstance(value, str): value = [value] if value: for addr in value: self.set_arp_ip_target('+' + addr) # Add (enslave) interfaces to bond value = dict_search('member.interface', config) for interface in (value or []): # if we've come here we already verified the interface # does not have an addresses configured so just flush # any remaining ones Interface(interface).flush_addrs() self.add_port(interface) # Add system mac address for 802.3ad - default address is all zero # mode is always present (defaultValue) if config['mode'] == '802.3ad': mac = '00:00:00:00:00:00' if 'system_mac' in config: mac = config['system_mac'] self.set_system_mac(mac) # Primary device interface - must be set after 'mode' value = config.get('primary') if value: self.set_primary(value) # call base class first super().update(config) # enable/disable EAPoL (Extensible Authentication Protocol over Local Area Network) self.set_eapol() diff --git a/python/vyos/ifconfig/bridge.py b/python/vyos/ifconfig/bridge.py index 917f962b7..d534dade7 100644 --- a/python/vyos/ifconfig/bridge.py +++ b/python/vyos/ifconfig/bridge.py @@ -1,413 +1,415 @@ # Copyright 2019-2024 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/>. from vyos.ifconfig.interface import Interface from vyos.utils.assertion import assert_boolean from vyos.utils.assertion import assert_list from vyos.utils.assertion import assert_positive from vyos.utils.dict import dict_search from vyos.utils.network import interface_exists from vyos.configdict import get_vlan_ids from vyos.configdict import list_diff @Interface.register class BridgeIf(Interface): """ A bridge is a way to connect two Ethernet segments together in a protocol independent way. Packets are forwarded based on Ethernet address, rather than IP address (like a router). Since forwarding is done at Layer 2, all protocols can go transparently through a bridge. The Linux bridge code implements a subset of the ANSI/IEEE 802.1d standard. """ - iftype = 'bridge' definition = { **Interface.definition, **{ 'section': 'bridge', 'prefixes': ['br', ], 'broadcast': True, 'vlan': True, }, } _sysfs_get = { **Interface._sysfs_get,**{ 'vlan_filter': { 'location': '/sys/class/net/{ifname}/bridge/vlan_filtering' } } } _sysfs_set = {**Interface._sysfs_set, **{ 'ageing_time': { 'validate': assert_positive, 'convert': lambda t: int(t) * 100, 'location': '/sys/class/net/{ifname}/bridge/ageing_time', }, 'forward_delay': { 'validate': assert_positive, 'convert': lambda t: int(t) * 100, 'location': '/sys/class/net/{ifname}/bridge/forward_delay', }, 'hello_time': { 'validate': assert_positive, 'convert': lambda t: int(t) * 100, 'location': '/sys/class/net/{ifname}/bridge/hello_time', }, 'max_age': { 'validate': assert_positive, 'convert': lambda t: int(t) * 100, 'location': '/sys/class/net/{ifname}/bridge/max_age', }, 'priority': { 'validate': assert_positive, 'location': '/sys/class/net/{ifname}/bridge/priority', }, 'stp': { 'validate': assert_boolean, 'location': '/sys/class/net/{ifname}/bridge/stp_state', }, 'vlan_filter': { 'validate': assert_boolean, 'location': '/sys/class/net/{ifname}/bridge/vlan_filtering', }, 'vlan_protocol': { 'validate': lambda v: assert_list(v, ['0x88a8', '0x8100']), 'location': '/sys/class/net/{ifname}/bridge/vlan_protocol', }, 'multicast_querier': { 'validate': assert_boolean, 'location': '/sys/class/net/{ifname}/bridge/multicast_querier', }, 'multicast_snooping': { 'validate': assert_boolean, 'location': '/sys/class/net/{ifname}/bridge/multicast_snooping', }, }} _command_set = {**Interface._command_set, **{ 'add_port': { 'shellcmd': 'ip link set dev {value} master {ifname}', }, 'del_port': { 'shellcmd': 'ip link set dev {value} nomaster', }, }} + def _create(self): + super()._create('bridge') + def get_vlan_filter(self): """ Get the status of the bridge VLAN filter """ return self.get_interface('vlan_filter') def set_ageing_time(self, time): """ Set bridge interface MAC address aging time in seconds. Internal kernel representation is in centiseconds. Kernel default is 300 seconds. Example: >>> from vyos.ifconfig import BridgeIf >>> BridgeIf('br0').ageing_time(2) """ self.set_interface('ageing_time', time) def set_forward_delay(self, time): """ Set bridge forwarding delay in seconds. Internal Kernel representation is in centiseconds. Example: >>> from vyos.ifconfig import BridgeIf >>> BridgeIf('br0').forward_delay(15) """ self.set_interface('forward_delay', time) def set_hello_time(self, time): """ Set bridge hello time in seconds. Internal Kernel representation is in centiseconds. Example: >>> from vyos.ifconfig import BridgeIf >>> BridgeIf('br0').set_hello_time(2) """ self.set_interface('hello_time', time) def set_max_age(self, time): """ Set bridge max message age in seconds. Internal Kernel representation is in centiseconds. Example: >>> from vyos.ifconfig import Interface >>> BridgeIf('br0').set_max_age(30) """ self.set_interface('max_age', time) def set_priority(self, priority): """ Set bridge max aging time in seconds. Example: >>> from vyos.ifconfig import BridgeIf >>> BridgeIf('br0').set_priority(8192) """ self.set_interface('priority', priority) def set_stp(self, state): """ Set bridge STP (Spanning Tree) state. 0 -> STP disabled, 1 -> STP enabled Example: >>> from vyos.ifconfig import BridgeIf >>> BridgeIf('br0').set_stp(1) """ self.set_interface('stp', state) def set_vlan_filter(self, state): """ Set bridge Vlan Filter state. 0 -> Vlan Filter disabled, 1 -> Vlan Filter enabled Example: >>> from vyos.ifconfig import BridgeIf >>> BridgeIf('br0').set_vlan_filter(1) """ self.set_interface('vlan_filter', state) # VLAN of bridge parent interface is always 1 # VLAN 1 is the default VLAN for all unlabeled packets cmd = f'bridge vlan add dev {self.ifname} vid 1 pvid untagged self' self._cmd(cmd) def set_multicast_querier(self, enable): """ Sets whether the bridge actively runs a multicast querier or not. When a bridge receives a 'multicast host membership' query from another network host, that host is tracked based on the time that the query was received plus the multicast query interval time. Use enable=1 to enable or enable=0 to disable Example: >>> from vyos.ifconfig import Interface >>> BridgeIf('br0').set_multicast_querier(1) """ self.set_interface('multicast_querier', enable) def set_multicast_snooping(self, enable): """ Enable or disable multicast snooping on the bridge. Use enable=1 to enable or enable=0 to disable Example: >>> from vyos.ifconfig import Interface >>> BridgeIf('br0').set_multicast_snooping(1) """ self.set_interface('multicast_snooping', enable) def add_port(self, interface): """ Add physical interface to bridge (member port) Example: >>> from vyos.ifconfig import Interface >>> BridgeIf('br0').add_port('eth0') >>> BridgeIf('br0').add_port('eth1') """ # Bridge port handling of wireless interfaces is done by hostapd. if 'wlan' in interface: return try: return self.set_interface('add_port', interface) except: from vyos import ConfigError raise ConfigError('Error: Device does not allow enslaving to a bridge.') def del_port(self, interface): """ Remove member port from bridge instance. Example: >>> from vyos.ifconfig import Interface >>> BridgeIf('br0').del_port('eth1') """ return self.set_interface('del_port', interface) def set_vlan_protocol(self, protocol): """ Set protocol used for VLAN filtering. The valid values are 0x8100(802.1q) or 0x88A8(802.1ad). Example: >>> from vyos.ifconfig import Interface >>> BridgeIf('br0').del_port('eth1') """ if protocol not in ['802.1q', '802.1ad']: raise ValueError() map = { '802.1ad': '0x88a8', '802.1q' : '0x8100' } return self.set_interface('vlan_protocol', map[protocol]) def update(self, config): """ General helper function which works on a dictionary retrived by get_config_dict(). It's main intention is to consolidate the scattered interface setup code and provide a single point of entry when workin on any interface. """ # Set ageing time value = config.get('aging') self.set_ageing_time(value) # set bridge forward delay value = config.get('forwarding_delay') self.set_forward_delay(value) # set hello time value = config.get('hello_time') self.set_hello_time(value) # set max message age value = config.get('max_age') self.set_max_age(value) # set bridge priority value = config.get('priority') self.set_priority(value) # enable/disable spanning tree value = '1' if 'stp' in config else '0' self.set_stp(value) # enable or disable multicast snooping tmp = dict_search('igmp.snooping', config) value = '1' if (tmp != None) else '0' self.set_multicast_snooping(value) # enable or disable IGMP querier tmp = dict_search('igmp.querier', config) value = '1' if (tmp != None) else '0' self.set_multicast_querier(value) # remove interface from bridge tmp = dict_search('member.interface_remove', config) for member in (tmp or []): if interface_exists(member): self.del_port(member) # enable/disable VLAN Filter tmp = '1' if 'enable_vlan' in config else '0' self.set_vlan_filter(tmp) tmp = config.get('protocol') self.set_vlan_protocol(tmp) # add VLAN interfaces to local 'parent' bridge to allow forwarding if 'enable_vlan' in config: for vlan in config.get('vif_remove', {}): # Remove old VLANs from the bridge cmd = f'bridge vlan del dev {self.ifname} vid {vlan} self' self._cmd(cmd) for vlan in config.get('vif', {}): cmd = f'bridge vlan add dev {self.ifname} vid {vlan} self' self._cmd(cmd) # VLAN of bridge parent interface is always 1. VLAN 1 is the default # VLAN for all unlabeled packets cmd = f'bridge vlan add dev {self.ifname} vid 1 pvid untagged self' self._cmd(cmd) tmp = dict_search('member.interface', config) if tmp: for interface, interface_config in tmp.items(): # if interface does yet not exist bail out early and # add it later if not interface_exists(interface): continue # Bridge lower "physical" interface lower = Interface(interface) # If we've come that far we already verified the interface does # not have any addresses configured by CLI so just flush any # remaining ones lower.flush_addrs() # enslave interface port to bridge self.add_port(interface) if not interface.startswith('wlan'): # always set private-vlan/port isolation - this can not be # done when lower link is a wifi link, as it will trigger: # RTNETLINK answers: Operation not supported tmp = dict_search('isolated', interface_config) value = 'on' if (tmp != None) else 'off' lower.set_port_isolation(value) # set bridge port path cost if 'cost' in interface_config: lower.set_path_cost(interface_config['cost']) # set bridge port path priority if 'priority' in interface_config: lower.set_path_priority(interface_config['priority']) if 'enable_vlan' in config: add_vlan = [] native_vlan_id = None allowed_vlan_ids= [] cur_vlan_ids = get_vlan_ids(interface) if 'native_vlan' in interface_config: vlan_id = interface_config['native_vlan'] add_vlan.append(vlan_id) native_vlan_id = vlan_id if 'allowed_vlan' in interface_config: for vlan in interface_config['allowed_vlan']: vlan_range = vlan.split('-') if len(vlan_range) == 2: for vlan_add in range(int(vlan_range[0]),int(vlan_range[1]) + 1): add_vlan.append(str(vlan_add)) allowed_vlan_ids.append(str(vlan_add)) else: add_vlan.append(vlan) allowed_vlan_ids.append(vlan) # Remove redundant VLANs from the system for vlan in list_diff(cur_vlan_ids, add_vlan): cmd = f'bridge vlan del dev {interface} vid {vlan} master' self._cmd(cmd) for vlan in allowed_vlan_ids: cmd = f'bridge vlan add dev {interface} vid {vlan} master' self._cmd(cmd) # Setting native VLAN to system if native_vlan_id: cmd = f'bridge vlan add dev {interface} vid {native_vlan_id} pvid untagged master' self._cmd(cmd) super().update(config) diff --git a/python/vyos/ifconfig/dummy.py b/python/vyos/ifconfig/dummy.py index d45769931..29a1965a3 100644 --- a/python/vyos/ifconfig/dummy.py +++ b/python/vyos/ifconfig/dummy.py @@ -1,33 +1,34 @@ # Copyright 2019-2021 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/>. from vyos.ifconfig.interface import Interface @Interface.register class DummyIf(Interface): """ A dummy interface is entirely virtual like, for example, the loopback interface. The purpose of a dummy interface is to provide a device to route packets through without actually transmitting them. """ - - iftype = 'dummy' definition = { **Interface.definition, **{ 'section': 'dummy', 'prefixes': ['dum', ], }, } + + def _create(self): + super()._create('dummy') diff --git a/python/vyos/ifconfig/ethernet.py b/python/vyos/ifconfig/ethernet.py index d0c03dbe0..93727bdf6 100644 --- a/python/vyos/ifconfig/ethernet.py +++ b/python/vyos/ifconfig/ethernet.py @@ -1,535 +1,537 @@ # 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 os from glob import glob from vyos.base import Warning from vyos.ethtool import Ethtool from vyos.ifconfig import Section from vyos.ifconfig.interface import Interface from vyos.utils.dict import dict_search from vyos.utils.file import read_file from vyos.utils.process import run from vyos.utils.assertion import assert_list @Interface.register class EthernetIf(Interface): """ Abstraction of a Linux Ethernet Interface """ - iftype = 'ethernet' definition = { **Interface.definition, **{ 'section': 'ethernet', 'prefixes': ['lan', 'eth', 'eno', 'ens', 'enp', 'enx'], 'bondable': True, 'broadcast': True, 'bridgeable': True, 'eternal': '(lan|eth|eno|ens|enp|enx)[0-9]+$', }, } @staticmethod def feature(ifname, option, value): run(f'ethtool --features {ifname} {option} {value}') return False _command_set = { **Interface._command_set, **{ 'gro': { 'validate': lambda v: assert_list(v, ['on', 'off']), 'possible': lambda i, v: EthernetIf.feature(i, 'gro', v), }, 'gso': { 'validate': lambda v: assert_list(v, ['on', 'off']), 'possible': lambda i, v: EthernetIf.feature(i, 'gso', v), }, 'hw-tc-offload': { 'validate': lambda v: assert_list(v, ['on', 'off']), 'possible': lambda i, v: EthernetIf.feature(i, 'hw-tc-offload', v), }, 'lro': { 'validate': lambda v: assert_list(v, ['on', 'off']), 'possible': lambda i, v: EthernetIf.feature(i, 'lro', v), }, 'sg': { 'validate': lambda v: assert_list(v, ['on', 'off']), 'possible': lambda i, v: EthernetIf.feature(i, 'sg', v), }, 'tso': { 'validate': lambda v: assert_list(v, ['on', 'off']), 'possible': lambda i, v: EthernetIf.feature(i, 'tso', v), }, }, } @staticmethod def get_bond_member_allowed_options() -> list: """ Return list of options which are allowed for changing, when interface is a bond member :return: List of interface options :rtype: list """ bond_allowed_sections = [ 'description', 'disable', 'disable_flow_control', 'disable_link_detect', 'duplex', 'eapol.ca_certificate', 'eapol.certificate', 'eapol.passphrase', 'mirror.egress', 'mirror.ingress', 'offload.gro', 'offload.gso', 'offload.lro', 'offload.rfs', 'offload.rps', 'offload.sg', 'offload.tso', 'redirect', 'ring_buffer.rx', 'ring_buffer.tx', 'speed', 'hw_id', ] return bond_allowed_sections def __init__(self, ifname, **kargs): super().__init__(ifname, **kargs) self.ethtool = Ethtool(ifname) + def _create(self): + pass + def remove(self): """ Remove interface from config. Removing the interface deconfigures all assigned IP addresses. Example: >>> from vyos.ifconfig import WWANIf >>> i = EthernetIf('eth0') >>> i.remove() """ if self.exists(self.ifname): # interface is placed in A/D state when removed from config! It # will remain visible for the operating system. self.set_admin_state('down') # Remove all VLAN subinterfaces - filter with the VLAN dot for vlan in [ x - for x in Section.interfaces(self.iftype) + for x in Section.interfaces('ethernet') if x.startswith(f'{self.ifname}.') ]: Interface(vlan).remove() super().remove() def set_flow_control(self, enable): """ Changes the pause parameters of the specified Ethernet device. @param enable: true -> enable pause frames, false -> disable pause frames Example: >>> from vyos.ifconfig import EthernetIf >>> i = EthernetIf('eth0') >>> i.set_flow_control(True) """ ifname = self.config['ifname'] if enable not in ['on', 'off']: raise ValueError('Value out of range') if not self.ethtool.check_flow_control(): self._debug_msg( 'NIC driver does not support changing flow control settings!' ) return False current = self.ethtool.get_flow_control() if current != enable: # Assemble command executed on system. Unfortunately there is no way # to change this setting via sysfs cmd = f'ethtool --pause {ifname} autoneg {enable} tx {enable} rx {enable}' output, code = self._popen(cmd) if code: Warning(f'could not change "{ifname}" flow control setting!') return output return None def set_speed_duplex(self, speed, duplex): """ Set link speed in Mbit/s and duplex. @speed can be any link speed in MBit/s, e.g. 10, 100, 1000 auto @duplex can be half, full, auto Example: >>> from vyos.ifconfig import EthernetIf >>> i = EthernetIf('eth0') >>> i.set_speed_duplex('auto', 'auto') """ ifname = self.config['ifname'] if speed not in [ 'auto', '10', '100', '1000', '2500', '5000', '10000', '25000', '40000', '50000', '100000', '400000', ]: raise ValueError('Value out of range (speed)') if duplex not in ['auto', 'full', 'half']: raise ValueError('Value out of range (duplex)') if not self.ethtool.check_speed_duplex(speed, duplex): Warning(f'changing speed/duplex setting on "{ifname}" is unsupported!') return if not self.ethtool.check_auto_negotiation_supported(): Warning(f'changing auto-negotiation setting on "{ifname}" is unsupported!') return # Get current speed and duplex settings: ifname = self.config['ifname'] if self.ethtool.get_auto_negotiation(): if speed == 'auto' and duplex == 'auto': # bail out early as nothing is to change return else: # XXX: read in current speed and duplex settings # There are some "nice" NICs like AX88179 which do not support # reading the speed thus we simply fallback to the supplied speed # to not cause any change here and raise an exception. cur_speed = read_file(f'/sys/class/net/{ifname}/speed', speed) cur_duplex = read_file(f'/sys/class/net/{ifname}/duplex', duplex) if (cur_speed == speed) and (cur_duplex == duplex): # bail out early as nothing is to change return cmd = f'ethtool --change {ifname}' try: if speed == 'auto' or duplex == 'auto': cmd += ' autoneg on' else: cmd += f' speed {speed} duplex {duplex} autoneg off' return self._cmd(cmd) except PermissionError: # Some NICs do not tell that they don't suppport settings speed/duplex, # but they do not actually support it either. # In that case it's probably better to ignore the error # than end up with a broken config. print( 'Warning: could not set speed/duplex settings: operation not permitted!' ) def set_gro(self, state): """ Enable Generic Receive Offload. State can be either True or False. Example: >>> from vyos.ifconfig import EthernetIf >>> i = EthernetIf('eth0') >>> i.set_gro(True) """ if not isinstance(state, bool): raise ValueError('Value out of range') enabled, fixed = self.ethtool.get_generic_receive_offload() if enabled != state: if not fixed: return self.set_interface('gro', 'on' if state else 'off') else: print( 'Adapter does not support changing generic-receive-offload settings!' ) return False def set_gso(self, state): """ Enable Generic Segmentation offload. State can be either True or False. Example: >>> from vyos.ifconfig import EthernetIf >>> i = EthernetIf('eth0') >>> i.set_gso(True) """ if not isinstance(state, bool): raise ValueError('Value out of range') enabled, fixed = self.ethtool.get_generic_segmentation_offload() if enabled != state: if not fixed: return self.set_interface('gso', 'on' if state else 'off') else: print( 'Adapter does not support changing generic-segmentation-offload settings!' ) return False def set_hw_tc_offload(self, state): """ Enable hardware TC flow offload. State can be either True or False. Example: >>> from vyos.ifconfig import EthernetIf >>> i = EthernetIf('eth0') >>> i.set_hw_tc_offload(True) """ if not isinstance(state, bool): raise ValueError('Value out of range') enabled, fixed = self.ethtool.get_hw_tc_offload() if enabled != state: if not fixed: return self.set_interface('hw-tc-offload', 'on' if state else 'off') else: print('Adapter does not support changing hw-tc-offload settings!') return False def set_lro(self, state): """ Enable Large Receive offload. State can be either True or False. Example: >>> from vyos.ifconfig import EthernetIf >>> i = EthernetIf('eth0') >>> i.set_lro(True) """ if not isinstance(state, bool): raise ValueError('Value out of range') enabled, fixed = self.ethtool.get_large_receive_offload() if enabled != state: if not fixed: return self.set_interface('lro', 'on' if state else 'off') else: print( 'Adapter does not support changing large-receive-offload settings!' ) return False def set_rps(self, state): if not isinstance(state, bool): raise ValueError('Value out of range') rps_cpus = 0 queues = len(glob(f'/sys/class/net/{self.ifname}/queues/rx-*')) if state: cpu_count = os.cpu_count() # Enable RPS on all available CPUs except CPU0 which we will not # utilize so the system has one spare core when it's under high # preasure to server other means. Linux sysfs excepts a bitmask # representation of the CPUs which should participate on RPS, we # can enable more CPUs that are physically present on the system, # Linux will clip that internally! rps_cpus = (1 << cpu_count) - 1 # XXX: we should probably reserve one core when the system is under # high preasure so we can still have a core left for housekeeping. # This is done by masking out the lowst bit so CPU0 is spared from # receive packet steering. rps_cpus &= ~1 # Convert the bitmask to hexadecimal chunks of 32 bits # Split the bitmask into chunks of up to 32 bits each hex_chunks = [] for i in range(0, cpu_count, 32): # Extract the next 32-bit chunk chunk = (rps_cpus >> i) & 0xFFFFFFFF hex_chunks.append(f'{chunk:08x}') # Join the chunks with commas rps_cpus = ','.join(hex_chunks) for i in range(queues): self._write_sysfs( f'/sys/class/net/{self.ifname}/queues/rx-{i}/rps_cpus', rps_cpus ) # send bitmask representation as hex string without leading '0x' return True def set_rfs(self, state): rfs_flow = 0 queues = len(glob(f'/sys/class/net/{self.ifname}/queues/rx-*')) if state: global_rfs_flow = 32768 rfs_flow = int(global_rfs_flow / queues) for i in range(0, queues): self._write_sysfs( f'/sys/class/net/{self.ifname}/queues/rx-{i}/rps_flow_cnt', rfs_flow, ) return True def set_sg(self, state): """ Enable Scatter-Gather support. State can be either True or False. Example: >>> from vyos.ifconfig import EthernetIf >>> i = EthernetIf('eth0') >>> i.set_sg(True) """ if not isinstance(state, bool): raise ValueError('Value out of range') enabled, fixed = self.ethtool.get_scatter_gather() if enabled != state: if not fixed: return self.set_interface('sg', 'on' if state else 'off') else: print('Adapter does not support changing scatter-gather settings!') return False def set_tso(self, state): """ Enable TCP segmentation offloading. State can be either True or False. Example: >>> from vyos.ifconfig import EthernetIf >>> i = EthernetIf('eth0') >>> i.set_tso(False) """ if not isinstance(state, bool): raise ValueError('Value out of range') enabled, fixed = self.ethtool.get_tcp_segmentation_offload() if enabled != state: if not fixed: return self.set_interface('tso', 'on' if state else 'off') else: print( 'Adapter does not support changing tcp-segmentation-offload settings!' ) return False def set_ring_buffer(self, rx_tx, size): """ Example: >>> from vyos.ifconfig import EthernetIf >>> i = EthernetIf('eth0') >>> i.set_ring_buffer('rx', '4096') """ current_size = self.ethtool.get_ring_buffer(rx_tx) if current_size == size: # bail out early if nothing is about to change return None ifname = self.config['ifname'] cmd = f'ethtool --set-ring {ifname} {rx_tx} {size}' output, code = self._popen(cmd) # ethtool error codes: # 80 - value already setted # 81 - does not possible to set value if code and code != 80: print(f'could not set "{rx_tx}" ring-buffer for {ifname}') return output def set_switchdev(self, enable): ifname = self.config['ifname'] addr, code = self._popen( f"ethtool -i {ifname} | grep bus-info | awk '{{print $2}}'" ) if code != 0: print(f'could not resolve PCIe address of {ifname}') return enabled = False state, code = self._popen( f"/sbin/devlink dev eswitch show pci/{addr} | awk '{{print $3}}'" ) if code == 0 and state == 'switchdev': enabled = True if enable and not enabled: output, code = self._popen( f'/sbin/devlink dev eswitch set pci/{addr} mode switchdev' ) if code != 0: print(f'{ifname} does not support switchdev mode') elif not enable and enabled: self._cmd(f'/sbin/devlink dev eswitch set pci/{addr} mode legacy') def update(self, config): """General helper function which works on a dictionary retrived by get_config_dict(). It's main intention is to consolidate the scattered interface setup code and provide a single point of entry when workin on any interface.""" # disable ethernet flow control (pause frames) value = 'off' if 'disable_flow_control' in config else 'on' self.set_flow_control(value) # GRO (generic receive offload) self.set_gro(dict_search('offload.gro', config) is not None) # GSO (generic segmentation offload) self.set_gso(dict_search('offload.gso', config) is not None) # GSO (generic segmentation offload) self.set_hw_tc_offload(dict_search('offload.hw_tc_offload', config) is not None) # LRO (large receive offload) self.set_lro(dict_search('offload.lro', config) is not None) # RPS - Receive Packet Steering self.set_rps(dict_search('offload.rps', config) is not None) # RFS - Receive Flow Steering self.set_rfs(dict_search('offload.rfs', config) is not None) # scatter-gather option self.set_sg(dict_search('offload.sg', config) is not None) # TSO (TCP segmentation offloading) self.set_tso(dict_search('offload.tso', config) is not None) # Set physical interface speed and duplex if 'speed_duplex_changed' in config: if {'speed', 'duplex'} <= set(config): speed = config.get('speed') duplex = config.get('duplex') self.set_speed_duplex(speed, duplex) # Set interface ring buffer if 'ring_buffer' in config: for rx_tx, size in config['ring_buffer'].items(): self.set_ring_buffer(rx_tx, size) self.set_switchdev('switchdev' in config) # call base class last super().update(config) # enable/disable EAPoL (Extensible Authentication Protocol over Local Area Network) self.set_eapol() diff --git a/python/vyos/ifconfig/geneve.py b/python/vyos/ifconfig/geneve.py index fbb261a35..f7fddb812 100644 --- a/python/vyos/ifconfig/geneve.py +++ b/python/vyos/ifconfig/geneve.py @@ -1,65 +1,64 @@ # Copyright 2019-2021 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/>. from vyos.ifconfig import Interface from vyos.utils.dict import dict_search @Interface.register class GeneveIf(Interface): """ Geneve: Generic Network Virtualization Encapsulation For more information please refer to: https://tools.ietf.org/html/draft-gross-geneve-00 https://www.redhat.com/en/blog/what-geneve https://developers.redhat.com/blog/2019/05/17/an-introduction-to-linux-virtual-interfaces-tunnels/#geneve https://lwn.net/Articles/644938/ """ - iftype = 'geneve' definition = { **Interface.definition, **{ 'section': 'geneve', 'prefixes': ['gnv', ], 'bridgeable': True, } } def _create(self): # This table represents a mapping from VyOS internal config dict to # arguments used by iproute2. For more information please refer to: # - https://man7.org/linux/man-pages/man8/ip-link.8.html mapping = { 'parameters.ip.df' : 'df', 'parameters.ip.tos' : 'tos', 'parameters.ip.ttl' : 'ttl', 'parameters.ip.innerproto' : 'innerprotoinherit', 'parameters.ipv6.flowlabel' : 'flowlabel', } - cmd = 'ip link add name {ifname} type {type} id {vni} remote {remote}' + cmd = 'ip link add name {ifname} type geneve id {vni} remote {remote}' for vyos_key, iproute2_key in mapping.items(): # dict_search will return an empty dict "{}" for valueless nodes like # "parameters.nolearning" - thus we need to test the nodes existence # by using isinstance() tmp = dict_search(vyos_key, self.config) if isinstance(tmp, dict): cmd += f' {iproute2_key}' elif tmp != None: cmd += f' {iproute2_key} {tmp}' self._cmd(cmd.format(**self.config)) # interface is always A/D down. It needs to be enabled explicitly self.set_admin_state('down') diff --git a/python/vyos/ifconfig/input.py b/python/vyos/ifconfig/input.py index 3e5f5790d..201d3cacb 100644 --- a/python/vyos/ifconfig/input.py +++ b/python/vyos/ifconfig/input.py @@ -1,36 +1,37 @@ # 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/>. from vyos.ifconfig.interface import Interface @Interface.register class InputIf(Interface): """ The Intermediate Functional Block (ifb) pseudo network interface acts as a QoS concentrator for multiple different sources of traffic. Packets from or to other interfaces have to be redirected to it using the mirred action in order to be handled, regularly routed traffic will be dropped. This way, a single stack of qdiscs, classes and filters can be shared between multiple interfaces. """ - - iftype = 'ifb' definition = { **Interface.definition, **{ 'section': 'input', 'prefixes': ['ifb', ], }, } + + def _create(self): + super()._create('ifb') diff --git a/python/vyos/ifconfig/interface.py b/python/vyos/ifconfig/interface.py index de821ab60..07075fd1b 100644 --- a/python/vyos/ifconfig/interface.py +++ b/python/vyos/ifconfig/interface.py @@ -1,2005 +1,1990 @@ # Copyright 2019-2024 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 os import re import json import jmespath from copy import deepcopy from glob import glob from ipaddress import IPv4Network from netifaces import ifaddresses # this is not the same as socket.AF_INET/INET6 from netifaces import AF_INET from netifaces import AF_INET6 from netaddr import EUI from netaddr import mac_unix_expanded -from vyos.base import ConfigError from vyos.configdict import list_diff from vyos.configdict import dict_merge from vyos.configdict import get_vlan_ids from vyos.defaults import directories from vyos.pki import find_chain from vyos.pki import encode_certificate from vyos.pki import load_certificate from vyos.pki import wrap_private_key from vyos.template import is_ipv4 from vyos.template import is_ipv6 from vyos.template import render from vyos.utils.network import mac2eui64 from vyos.utils.dict import dict_search from vyos.utils.network import get_interface_config from vyos.utils.network import get_interface_address from vyos.utils.network import get_interface_namespace from vyos.utils.network import get_vrf_tableid from vyos.utils.network import is_netns_interface from vyos.utils.process import is_systemd_service_active from vyos.utils.process import run from vyos.utils.file import read_file from vyos.utils.file import write_file from vyos.utils.network import is_intf_addr_assigned from vyos.utils.network import is_ipv6_link_local from vyos.utils.assertion import assert_boolean from vyos.utils.assertion import assert_list from vyos.utils.assertion import assert_mac from vyos.utils.assertion import assert_mtu from vyos.utils.assertion import assert_positive from vyos.utils.assertion import assert_range from vyos.ifconfig.control import Control from vyos.ifconfig.vrrp import VRRP from vyos.ifconfig.operational import Operational from vyos.ifconfig import Section link_local_prefix = 'fe80::/64' class Interface(Control): # This is the class which will be used to create # self.operational, it allows subclasses, such as # WireGuard to modify their display behaviour OperationalClass = Operational options = ['debug', 'create'] - required = [] default = { 'debug': True, 'create': True, } definition = { 'section': '', 'prefixes': [], 'vlan': False, 'bondable': False, 'broadcast': False, 'bridgeable': False, 'eternal': '', } _command_get = { 'admin_state': { 'shellcmd': 'ip -json link show dev {ifname}', 'format': lambda j: 'up' if 'UP' in jmespath.search('[*].flags | [0]', json.loads(j)) else 'down', }, 'alias': { 'shellcmd': 'ip -json -detail link list dev {ifname}', 'format': lambda j: jmespath.search('[*].ifalias | [0]', json.loads(j)) or '', }, 'ifindex': { 'shellcmd': 'ip -json -detail link list dev {ifname}', 'format': lambda j: jmespath.search('[*].ifindex | [0]', json.loads(j)) or '', }, 'mac': { 'shellcmd': 'ip -json -detail link list dev {ifname}', 'format': lambda j: jmespath.search('[*].address | [0]', json.loads(j)), }, 'min_mtu': { 'shellcmd': 'ip -json -detail link list dev {ifname}', 'format': lambda j: jmespath.search('[*].min_mtu | [0]', json.loads(j)), }, 'max_mtu': { 'shellcmd': 'ip -json -detail link list dev {ifname}', 'format': lambda j: jmespath.search('[*].max_mtu | [0]', json.loads(j)), }, 'mtu': { 'shellcmd': 'ip -json -detail link list dev {ifname}', 'format': lambda j: jmespath.search('[*].mtu | [0]', json.loads(j)), }, 'oper_state': { 'shellcmd': 'ip -json -detail link list dev {ifname}', 'format': lambda j: jmespath.search('[*].operstate | [0]', json.loads(j)), }, 'vrf': { 'shellcmd': 'ip -json -detail link list dev {ifname}', 'format': lambda j: jmespath.search('[?linkinfo.info_slave_kind == `vrf`].master | [0]', json.loads(j)), }, } _command_set = { 'admin_state': { 'validate': lambda v: assert_list(v, ['up', 'down']), 'shellcmd': 'ip link set dev {ifname} {value}', }, 'alias': { 'convert': lambda name: name if name else '', 'shellcmd': 'ip link set dev {ifname} alias "{value}"', }, 'bridge_port_isolation': { 'validate': lambda v: assert_list(v, ['on', 'off']), 'shellcmd': 'bridge link set dev {ifname} isolated {value}', }, 'mac': { 'validate': assert_mac, 'shellcmd': 'ip link set dev {ifname} address {value}', }, 'mtu': { 'validate': assert_mtu, 'shellcmd': 'ip link set dev {ifname} mtu {value}', }, 'vrf': { 'convert': lambda v: f'master {v}' if v else 'nomaster', 'shellcmd': 'ip link set dev {ifname} {value}', }, } _sysfs_set = { 'arp_cache_tmo': { 'location': '/proc/sys/net/ipv4/neigh/{ifname}/base_reachable_time_ms', }, 'arp_filter': { 'validate': assert_boolean, 'location': '/proc/sys/net/ipv4/conf/{ifname}/arp_filter', }, 'arp_accept': { 'validate': lambda arp: assert_range(arp,0,2), 'location': '/proc/sys/net/ipv4/conf/{ifname}/arp_accept', }, 'arp_announce': { 'validate': assert_boolean, 'location': '/proc/sys/net/ipv4/conf/{ifname}/arp_announce', }, 'arp_ignore': { 'validate': assert_boolean, 'location': '/proc/sys/net/ipv4/conf/{ifname}/arp_ignore', }, 'ipv4_forwarding': { 'validate': assert_boolean, 'location': '/proc/sys/net/ipv4/conf/{ifname}/forwarding', }, 'ipv4_directed_broadcast': { 'validate': assert_boolean, 'location': '/proc/sys/net/ipv4/conf/{ifname}/bc_forwarding', }, 'ipv6_accept_ra': { 'validate': lambda ara: assert_range(ara,0,3), 'location': '/proc/sys/net/ipv6/conf/{ifname}/accept_ra', }, 'ipv6_autoconf': { 'validate': lambda aco: assert_range(aco,0,2), 'location': '/proc/sys/net/ipv6/conf/{ifname}/autoconf', }, 'ipv6_forwarding': { 'validate': lambda fwd: assert_range(fwd,0,2), 'location': '/proc/sys/net/ipv6/conf/{ifname}/forwarding', }, 'ipv6_accept_dad': { 'validate': lambda dad: assert_range(dad,0,3), 'location': '/proc/sys/net/ipv6/conf/{ifname}/accept_dad', }, 'ipv6_dad_transmits': { 'validate': assert_positive, 'location': '/proc/sys/net/ipv6/conf/{ifname}/dad_transmits', }, 'ipv6_cache_tmo': { 'location': '/proc/sys/net/ipv6/neigh/{ifname}/base_reachable_time_ms', }, 'path_cost': { # XXX: we should set a maximum 'validate': assert_positive, 'location': '/sys/class/net/{ifname}/brport/path_cost', 'errormsg': '{ifname} is not a bridge port member' }, 'path_priority': { # XXX: we should set a maximum 'validate': assert_positive, 'location': '/sys/class/net/{ifname}/brport/priority', 'errormsg': '{ifname} is not a bridge port member' }, 'proxy_arp': { 'validate': assert_boolean, 'location': '/proc/sys/net/ipv4/conf/{ifname}/proxy_arp', }, 'proxy_arp_pvlan': { 'validate': assert_boolean, 'location': '/proc/sys/net/ipv4/conf/{ifname}/proxy_arp_pvlan', }, # link_detect vs link_filter name weirdness 'link_detect': { 'validate': lambda link: assert_range(link,0,3), 'location': '/proc/sys/net/ipv4/conf/{ifname}/link_filter', }, 'per_client_thread': { 'validate': assert_boolean, 'location': '/sys/class/net/{ifname}/threaded', }, } _sysfs_get = { 'arp_cache_tmo': { 'location': '/proc/sys/net/ipv4/neigh/{ifname}/base_reachable_time_ms', }, 'arp_filter': { 'location': '/proc/sys/net/ipv4/conf/{ifname}/arp_filter', }, 'arp_accept': { 'location': '/proc/sys/net/ipv4/conf/{ifname}/arp_accept', }, 'arp_announce': { 'location': '/proc/sys/net/ipv4/conf/{ifname}/arp_announce', }, 'arp_ignore': { 'location': '/proc/sys/net/ipv4/conf/{ifname}/arp_ignore', }, 'ipv4_forwarding': { 'location': '/proc/sys/net/ipv4/conf/{ifname}/forwarding', }, 'ipv4_directed_broadcast': { 'location': '/proc/sys/net/ipv4/conf/{ifname}/bc_forwarding', }, 'ipv6_accept_ra': { 'location': '/proc/sys/net/ipv6/conf/{ifname}/accept_ra', }, 'ipv6_autoconf': { 'location': '/proc/sys/net/ipv6/conf/{ifname}/autoconf', }, 'ipv6_forwarding': { 'location': '/proc/sys/net/ipv6/conf/{ifname}/forwarding', }, 'ipv6_accept_dad': { 'location': '/proc/sys/net/ipv6/conf/{ifname}/accept_dad', }, 'ipv6_dad_transmits': { 'location': '/proc/sys/net/ipv6/conf/{ifname}/dad_transmits', }, 'ipv6_cache_tmo': { 'location': '/proc/sys/net/ipv6/neigh/{ifname}/base_reachable_time_ms', }, 'proxy_arp': { 'location': '/proc/sys/net/ipv4/conf/{ifname}/proxy_arp', }, 'proxy_arp_pvlan': { 'location': '/proc/sys/net/ipv4/conf/{ifname}/proxy_arp_pvlan', }, 'link_detect': { 'location': '/proc/sys/net/ipv4/conf/{ifname}/link_filter', }, 'per_client_thread': { 'validate': assert_boolean, 'location': '/sys/class/net/{ifname}/threaded', }, } @classmethod def exists(cls, ifname: str, netns: str=None) -> bool: cmd = f'ip link show dev {ifname}' if netns: cmd = f'ip netns exec {netns} {cmd}' return run(cmd) == 0 @classmethod def get_config(cls): """ Some but not all interfaces require a configuration when they are added using iproute2. This method will provide the configuration dictionary used by this class. """ return deepcopy(cls.default) def __init__(self, ifname, **kargs): """ This is the base interface class which supports basic IP/MAC address operations as well as DHCP(v6). Other interface which represent e.g. and ethernet bridge are implemented as derived classes adding all additional functionality. For creation you will need to provide the interface type, otherwise the existing interface is used DEBUG: This class has embedded debugging (print) which can be enabled by creating the following file: vyos@vyos# touch /tmp/vyos.ifconfig.debug Example: >>> from vyos.ifconfig import Interface >>> i = Interface('eth0') """ self.config = deepcopy(kargs) self.config['ifname'] = self.ifname = ifname self._admin_state_down_cnt = 0 # we must have updated config before initialising the Interface super().__init__(**kargs) if not self.exists(ifname): - # Any instance of Interface, such as Interface('eth0') can be used - # safely to access the generic function in this class as 'type' is - # unset, the class can not be created - if not hasattr(self, 'iftype'): - raise ConfigError(f'Interface "{ifname}" has no "iftype" attribute defined!') - self.config['type'] = self.iftype - # Should an Instance of a child class (EthernetIf, DummyIf, ..) # be required, then create should be set to False to not accidentally create it. # In case a subclass does not define it, we use get to set the default to True - if self.config.get('create',True): - for k in self.required: - if k not in kargs: - name = self.default['type'] - raise ConfigError(f'missing required option {k} for {name} {ifname} creation') - + if self.config.get('create', True): self._create() # If we can not connect to the interface then let the caller know # as the class could not be correctly initialised else: raise Exception(f'interface "{ifname}" not found!') # temporary list of assigned IP addresses self._addr = [] self.operational = self.OperationalClass(ifname) self.vrrp = VRRP(ifname) - def _create(self): + def _create(self, type: str=''): # Do not create interface that already exist or exists in netns netns = self.config.get('netns', None) if self.exists(f'{self.ifname}', netns=netns): return - cmd = 'ip link add dev {ifname} type {type}'.format(**self.config) + cmd = f'ip link add dev {self.ifname}' + if type: cmd += f' type {type}' if 'netns' in self.config: cmd = f'ip netns exec {netns} {cmd}' self._cmd(cmd) def remove(self): """ Remove interface from operating system. Removing the interface deconfigures all assigned IP addresses and clear possible DHCP(v6) client processes. Example: >>> from vyos.ifconfig import Interface >>> i = Interface('eth0') >>> i.remove() """ # Stop WPA supplicant if EAPoL was in use if is_systemd_service_active(f'wpa_supplicant-wired@{self.ifname}'): self._cmd(f'systemctl stop wpa_supplicant-wired@{self.ifname}') # remove all assigned IP addresses from interface - this is a bit redundant # as the kernel will remove all addresses on interface deletion, but we # can not delete ALL interfaces, see below self.flush_addrs() # remove interface from conntrack VRF interface map self._del_interface_from_ct_iface_map() # --------------------------------------------------------------------- # Any class can define an eternal regex in its definition # interface matching the regex will not be deleted eternal = self.definition['eternal'] if not eternal: self._delete() elif not re.match(eternal, self.ifname): self._delete() def _delete(self): # NOTE (Improvement): # after interface removal no other commands should be allowed # to be called and instead should raise an Exception: cmd = 'ip link del dev {ifname}'.format(**self.config) # for delete we can't get data from self.config{'netns'} netns = get_interface_namespace(self.ifname) if netns: cmd = f'ip netns exec {netns} {cmd}' return self._cmd(cmd) def _nft_check_and_run(self, nft_command): # Check if deleting is possible first to avoid raising errors _, err = self._popen(f'nft --check {nft_command}') if not err: # Remove map element self._cmd(f'nft {nft_command}') def _del_interface_from_ct_iface_map(self): nft_command = f'delete element inet vrf_zones ct_iface_map {{ "{self.ifname}" }}' self._nft_check_and_run(nft_command) def _add_interface_to_ct_iface_map(self, vrf_table_id: int): nft_command = f'add element inet vrf_zones ct_iface_map {{ "{self.ifname}" : {vrf_table_id} }}' self._nft_check_and_run(nft_command) def get_ifindex(self): """ Get interface index by name Example: >>> from vyos.ifconfig import Interface >>> Interface('eth0').get_ifindex() '2' """ return int(self.get_interface('ifindex')) def get_min_mtu(self): """ Get hardware minimum supported MTU Example: >>> from vyos.ifconfig import Interface >>> Interface('eth0').get_min_mtu() '60' """ return int(self.get_interface('min_mtu')) def get_max_mtu(self): """ Get hardware maximum supported MTU Example: >>> from vyos.ifconfig import Interface >>> Interface('eth0').get_max_mtu() '9000' """ return int(self.get_interface('max_mtu')) def get_mtu(self): """ Get/set interface mtu in bytes. Example: >>> from vyos.ifconfig import Interface >>> Interface('eth0').get_mtu() '1500' """ return int(self.get_interface('mtu')) def set_mtu(self, mtu): """ Get/set interface mtu in bytes. Example: >>> from vyos.ifconfig import Interface >>> Interface('eth0').set_mtu(1400) >>> Interface('eth0').get_mtu() '1400' """ tmp = self.get_interface('mtu') if str(tmp) == mtu: return None return self.set_interface('mtu', mtu) def get_mac(self): """ Get current interface MAC (Media Access Contrl) address used. Example: >>> from vyos.ifconfig import Interface >>> Interface('eth0').get_mac() '00:50:ab:cd:ef:00' """ return self.get_interface('mac') def get_mac_synthetic(self): """ Get a synthetic MAC address. This is a common method which can be called from derived classes to overwrite the get_mac() call in a generic way. NOTE: Tunnel interfaces have no "MAC" address by default. The content of the 'address' file in /sys/class/net/device contains the local-ip thus we generate a random MAC address instead Example: >>> from vyos.ifconfig import Interface >>> Interface('eth0').get_mac() '00:50:ab:cd:ef:00' """ from hashlib import sha256 # Get processor ID number cpu_id = self._cmd('sudo dmidecode -t 4 | grep ID | head -n1 | sed "s/.*ID://;s/ //g"') # XXX: T3894 - it seems not all systems have eth0 - get a list of all # available Ethernet interfaces on the system (without VLAN subinterfaces) # and then take the first one. all_eth_ifs = Section.interfaces('ethernet', vlan=False) first_mac = Interface(all_eth_ifs[0]).get_mac() sha = sha256() # Calculate SHA256 sum based on the CPU ID number, eth0 mac address and # this interface identifier - this is as predictable as an interface # MAC address and thus can be used in the same way sha.update(cpu_id.encode()) sha.update(first_mac.encode()) sha.update(self.ifname.encode()) # take the most significant 48 bits from the SHA256 string tmp = sha.hexdigest()[:12] # Convert pseudo random string into EUI format which now represents a # MAC address tmp = EUI(tmp).value # set locally administered bit in MAC address tmp |= 0xf20000000000 # convert integer to "real" MAC address representation mac = EUI(hex(tmp).split('x')[-1]) # change dialect to use : as delimiter instead of - mac.dialect = mac_unix_expanded return str(mac) def set_mac(self, mac): """ Set interface MAC (Media Access Contrl) address to given value. Example: >>> from vyos.ifconfig import Interface >>> Interface('eth0').set_mac('00:50:ab:cd:ef:01') """ # If MAC is unchanged, bail out early if mac == self.get_mac(): return None # MAC address can only be changed if interface is in 'down' state prev_state = self.get_admin_state() if prev_state == 'up': self.set_admin_state('down') self.set_interface('mac', mac) # Turn an interface to the 'up' state if it was changed to 'down' by this fucntion if prev_state == 'up': self.set_admin_state('up') def del_netns(self, netns: str) -> bool: """ Remove interface from given network namespace """ # If network namespace does not exist then there is nothing to delete if not os.path.exists(f'/run/netns/{netns}'): return False # Check if interface exists in network namespace if is_netns_interface(self.ifname, netns): self._cmd(f'ip netns exec {netns} ip link del dev {self.ifname}') return True return False def set_netns(self, netns: str) -> bool: """ Add interface from given network namespace Example: >>> from vyos.ifconfig import Interface >>> Interface('dum0').set_netns('foo') """ self._cmd(f'ip link set dev {self.ifname} netns {netns}') return True def get_vrf(self): """ Get VRF from interface Example: >>> from vyos.ifconfig import Interface >>> Interface('eth0').get_vrf() """ return self.get_interface('vrf') def set_vrf(self, vrf: str) -> bool: """ Add/Remove interface from given VRF instance. Example: >>> from vyos.ifconfig import Interface >>> Interface('eth0').set_vrf('foo') >>> Interface('eth0').set_vrf() """ # Don't allow for netns yet if 'netns' in self.config: return False tmp = self.get_interface('vrf') if tmp == vrf: return False # Get current VRF table ID old_vrf_tableid = get_vrf_tableid(self.ifname) self.set_interface('vrf', vrf) if vrf: # Get routing table ID number for VRF vrf_table_id = get_vrf_tableid(vrf) # Add map element with interface and zone ID if vrf_table_id: # delete old table ID from nftables if it has changed, e.g. interface moved to a different VRF if old_vrf_tableid and old_vrf_tableid != int(vrf_table_id): self._del_interface_from_ct_iface_map() self._add_interface_to_ct_iface_map(vrf_table_id) else: self._del_interface_from_ct_iface_map() return True def set_arp_cache_tmo(self, tmo): """ Set ARP cache timeout value in seconds. Internal Kernel representation is in milliseconds. Example: >>> from vyos.ifconfig import Interface >>> Interface('eth0').set_arp_cache_tmo(40) """ tmo = str(int(tmo) * 1000) tmp = self.get_interface('arp_cache_tmo') if tmp == tmo: return None return self.set_interface('arp_cache_tmo', tmo) def set_ipv6_cache_tmo(self, tmo): """ Set IPv6 cache timeout value in seconds. Internal Kernel representation is in milliseconds. Example: >>> from vyos.ifconfig import Interface >>> Interface('eth0').set_ipv6_cache_tmo(40) """ tmo = str(int(tmo) * 1000) tmp = self.get_interface('ipv6_cache_tmo') if tmp == tmo: return None return self.set_interface('ipv6_cache_tmo', tmo) def _cleanup_mss_rules(self, table, ifname): commands = [] results = self._cmd(f'nft -a list chain {table} VYOS_TCP_MSS').split("\n") for line in results: if f'oifname "{ifname}"' in line: handle_search = re.search('handle (\d+)', line) if handle_search: self._cmd(f'nft delete rule {table} VYOS_TCP_MSS handle {handle_search[1]}') def set_tcp_ipv4_mss(self, mss): """ Set IPv4 TCP MSS value advertised when TCP SYN packets leave this interface. Value is in bytes. A value of 0 will disable the MSS adjustment Example: >>> from vyos.ifconfig import Interface >>> Interface('eth0').set_tcp_ipv4_mss(1340) """ # Don't allow for netns yet if 'netns' in self.config: return None self._cleanup_mss_rules('raw', self.ifname) nft_prefix = 'nft add rule raw VYOS_TCP_MSS' base_cmd = f'oifname "{self.ifname}" tcp flags & (syn|rst) == syn' if mss == 'clamp-mss-to-pmtu': self._cmd(f"{nft_prefix} '{base_cmd} tcp option maxseg size set rt mtu'") elif int(mss) > 0: low_mss = str(int(mss) + 1) self._cmd(f"{nft_prefix} '{base_cmd} tcp option maxseg size {low_mss}-65535 tcp option maxseg size set {mss}'") def set_tcp_ipv6_mss(self, mss): """ Set IPv6 TCP MSS value advertised when TCP SYN packets leave this interface. Value is in bytes. A value of 0 will disable the MSS adjustment Example: >>> from vyos.ifconfig import Interface >>> Interface('eth0').set_tcp_mss(1320) """ # Don't allow for netns yet if 'netns' in self.config: return None self._cleanup_mss_rules('ip6 raw', self.ifname) nft_prefix = 'nft add rule ip6 raw VYOS_TCP_MSS' base_cmd = f'oifname "{self.ifname}" tcp flags & (syn|rst) == syn' if mss == 'clamp-mss-to-pmtu': self._cmd(f"{nft_prefix} '{base_cmd} tcp option maxseg size set rt mtu'") elif int(mss) > 0: low_mss = str(int(mss) + 1) self._cmd(f"{nft_prefix} '{base_cmd} tcp option maxseg size {low_mss}-65535 tcp option maxseg size set {mss}'") def set_arp_filter(self, arp_filter): """ Filter ARP requests 1 - Allows you to have multiple network interfaces on the same subnet, and have the ARPs for each interface be answered based on whether or not the kernel would route a packet from the ARP'd IP out that interface (therefore you must use source based routing for this to work). In other words it allows control of which cards (usually 1) will respond to an arp request. 0 - (default) The kernel can respond to arp requests with addresses from other interfaces. This may seem wrong but it usually makes sense, because it increases the chance of successful communication. IP addresses are owned by the complete host on Linux, not by particular interfaces. Only for more complex setups like load- balancing, does this behaviour cause problems. """ tmp = self.get_interface('arp_filter') if tmp == arp_filter: return None return self.set_interface('arp_filter', arp_filter) def set_arp_accept(self, arp_accept): """ Define behavior for gratuitous ARP frames who's IP is not already present in the ARP table: 0 - don't create new entries in the ARP table 1 - create new entries in the ARP table Both replies and requests type gratuitous arp will trigger the ARP table to be updated, if this setting is on. If the ARP table already contains the IP address of the gratuitous arp frame, the arp table will be updated regardless if this setting is on or off. """ tmp = self.get_interface('arp_accept') if tmp == arp_accept: return None return self.set_interface('arp_accept', arp_accept) def set_arp_announce(self, arp_announce): """ Define different restriction levels for announcing the local source IP address from IP packets in ARP requests sent on interface: 0 - (default) Use any local address, configured on any interface 1 - Try to avoid local addresses that are not in the target's subnet for this interface. This mode is useful when target hosts reachable via this interface require the source IP address in ARP requests to be part of their logical network configured on the receiving interface. When we generate the request we will check all our subnets that include the target IP and will preserve the source address if it is from such subnet. Increasing the restriction level gives more chance for receiving answer from the resolved target while decreasing the level announces more valid sender's information. """ tmp = self.get_interface('arp_announce') if tmp == arp_announce: return None return self.set_interface('arp_announce', arp_announce) def set_arp_ignore(self, arp_ignore): """ Define different modes for sending replies in response to received ARP requests that resolve local target IP addresses: 0 - (default): reply for any local target IP address, configured on any interface 1 - reply only if the target IP address is local address configured on the incoming interface """ tmp = self.get_interface('arp_ignore') if tmp == arp_ignore: return None return self.set_interface('arp_ignore', arp_ignore) def set_ipv4_forwarding(self, forwarding): """ Configure IPv4 forwarding. """ tmp = self.get_interface('ipv4_forwarding') if tmp == forwarding: return None return self.set_interface('ipv4_forwarding', forwarding) def set_ipv4_directed_broadcast(self, forwarding): """ Configure IPv4 directed broadcast forwarding. """ tmp = self.get_interface('ipv4_directed_broadcast') if tmp == forwarding: return None return self.set_interface('ipv4_directed_broadcast', forwarding) def _cleanup_ipv4_source_validation_rules(self, ifname): results = self._cmd(f'nft -a list chain ip raw vyos_rpfilter').split("\n") for line in results: if f'iifname "{ifname}"' in line: handle_search = re.search('handle (\d+)', line) if handle_search: self._cmd(f'nft delete rule ip raw vyos_rpfilter handle {handle_search[1]}') def set_ipv4_source_validation(self, mode): """ Set IPv4 reverse path validation Example: >>> from vyos.ifconfig import Interface >>> Interface('eth0').set_ipv4_source_validation('strict') """ # Don't allow for netns yet if 'netns' in self.config: return None self._cleanup_ipv4_source_validation_rules(self.ifname) nft_prefix = f'nft insert rule ip raw vyos_rpfilter iifname "{self.ifname}"' if mode in ['strict', 'loose']: self._cmd(f"{nft_prefix} counter return") if mode == 'strict': self._cmd(f"{nft_prefix} fib saddr . iif oif 0 counter drop") elif mode == 'loose': self._cmd(f"{nft_prefix} fib saddr oif 0 counter drop") def _cleanup_ipv6_source_validation_rules(self, ifname): results = self._cmd(f'nft -a list chain ip6 raw vyos_rpfilter').split("\n") for line in results: if f'iifname "{ifname}"' in line: handle_search = re.search('handle (\d+)', line) if handle_search: self._cmd(f'nft delete rule ip6 raw vyos_rpfilter handle {handle_search[1]}') def set_ipv6_source_validation(self, mode): """ Set IPv6 reverse path validation Example: >>> from vyos.ifconfig import Interface >>> Interface('eth0').set_ipv6_source_validation('strict') """ # Don't allow for netns yet if 'netns' in self.config: return None self._cleanup_ipv6_source_validation_rules(self.ifname) nft_prefix = f'nft insert rule ip6 raw vyos_rpfilter iifname "{self.ifname}"' if mode in ['strict', 'loose']: self._cmd(f"{nft_prefix} counter return") if mode == 'strict': self._cmd(f"{nft_prefix} fib saddr . iif oif 0 counter drop") elif mode == 'loose': self._cmd(f"{nft_prefix} fib saddr oif 0 counter drop") def set_ipv6_accept_ra(self, accept_ra): """ Accept Router Advertisements; autoconfigure using them. It also determines whether or not to transmit Router Solicitations. If and only if the functional setting is to accept Router Advertisements, Router Solicitations will be transmitted. 0 - Do not accept Router Advertisements. 1 - (default) Accept Router Advertisements if forwarding is disabled. 2 - Overrule forwarding behaviour. Accept Router Advertisements even if forwarding is enabled. """ tmp = self.get_interface('ipv6_accept_ra') if tmp == accept_ra: return None return self.set_interface('ipv6_accept_ra', accept_ra) def set_ipv6_autoconf(self, autoconf): """ Autoconfigure addresses using Prefix Information in Router Advertisements. """ tmp = self.get_interface('ipv6_autoconf') if tmp == autoconf: return None return self.set_interface('ipv6_autoconf', autoconf) def add_ipv6_eui64_address(self, prefix): """ Extended Unique Identifier (EUI), as per RFC2373, allows a host to assign itself a unique IPv6 address based on a given IPv6 prefix. Calculate the EUI64 from the interface's MAC, then assign it with the given prefix to the interface. """ # T2863: only add a link-local IPv6 address if the interface returns # a MAC address. This is not the case on e.g. WireGuard interfaces. mac = self.get_mac() if mac: eui64 = mac2eui64(mac, prefix) prefixlen = prefix.split('/')[1] self.add_addr(f'{eui64}/{prefixlen}') def del_ipv6_eui64_address(self, prefix): """ Delete the address based on the interface's MAC-based EUI64 combined with the prefix address. """ if is_ipv6(prefix): eui64 = mac2eui64(self.get_mac(), prefix) prefixlen = prefix.split('/')[1] self.del_addr(f'{eui64}/{prefixlen}') def set_ipv6_forwarding(self, forwarding): """ Configure IPv6 interface-specific Host/Router behaviour. False: By default, Host behaviour is assumed. This means: 1. IsRouter flag is not set in Neighbour Advertisements. 2. If accept_ra is TRUE (default), transmit Router Solicitations. 3. If accept_ra is TRUE (default), accept Router Advertisements (and do autoconfiguration). 4. If accept_redirects is TRUE (default), accept Redirects. True: If local forwarding is enabled, Router behaviour is assumed. This means exactly the reverse from the above: 1. IsRouter flag is set in Neighbour Advertisements. 2. Router Solicitations are not sent unless accept_ra is 2. 3. Router Advertisements are ignored unless accept_ra is 2. 4. Redirects are ignored. """ tmp = self.get_interface('ipv6_forwarding') if tmp == forwarding: return None return self.set_interface('ipv6_forwarding', forwarding) def set_ipv6_dad_accept(self, dad): """Whether to accept DAD (Duplicate Address Detection)""" tmp = self.get_interface('ipv6_accept_dad') if tmp == dad: return None return self.set_interface('ipv6_accept_dad', dad) def set_ipv6_dad_messages(self, dad): """ The amount of Duplicate Address Detection probes to send. Default: 1 """ tmp = self.get_interface('ipv6_dad_transmits') if tmp == dad: return None return self.set_interface('ipv6_dad_transmits', dad) def set_link_detect(self, link_filter): """ Configure kernel response in packets received on interfaces that are 'down' 0 - Allow packets to be received for the address on this interface even if interface is disabled or no carrier. 1 - Ignore packets received if interface associated with the incoming address is down. 2 - Ignore packets received if interface associated with the incoming address is down or has no carrier. Default value is 0. Note that some distributions enable it in startup scripts. Example: >>> from vyos.ifconfig import Interface >>> Interface('eth0').set_link_detect(1) """ tmp = self.get_interface('link_detect') if tmp == link_filter: return None return self.set_interface('link_detect', link_filter) def get_alias(self): """ Get interface alias name used by e.g. SNMP Example: >>> Interface('eth0').get_alias() 'interface description as set by user' """ return self.get_interface('alias') def set_alias(self, ifalias=''): """ Set interface alias name used by e.g. SNMP Example: >>> from vyos.ifconfig import Interface >>> Interface('eth0').set_alias('VyOS upstream interface') to clear alias e.g. delete it use: >>> Interface('eth0').set_ifalias('') """ tmp = self.get_interface('alias') if tmp == ifalias: return None self.set_interface('alias', ifalias) def get_admin_state(self): """ Get interface administrative state. Function will return 'up' or 'down' Example: >>> from vyos.ifconfig import Interface >>> Interface('eth0').get_admin_state() 'up' """ return self.get_interface('admin_state') def set_admin_state(self, state): """ Set interface administrative state to be 'up' or 'down' Example: >>> from vyos.ifconfig import Interface >>> Interface('eth0').set_admin_state('down') >>> Interface('eth0').get_admin_state() 'down' """ if state == 'up': self._admin_state_down_cnt -= 1 if self._admin_state_down_cnt < 1: return self.set_interface('admin_state', state) else: self._admin_state_down_cnt += 1 return self.set_interface('admin_state', state) def set_path_cost(self, cost): """ Set interface path cost, only relevant for STP enabled interfaces Example: >>> from vyos.ifconfig import Interface >>> Interface('eth0').set_path_cost(4) """ self.set_interface('path_cost', cost) def set_path_priority(self, priority): """ Set interface path priority, only relevant for STP enabled interfaces Example: >>> from vyos.ifconfig import Interface >>> Interface('eth0').set_path_priority(4) """ self.set_interface('path_priority', priority) def set_port_isolation(self, on_or_off): """ Controls whether a given port will be isolated, which means it will be able to communicate with non-isolated ports only. By default this flag is off. Use enable=1 to enable or enable=0 to disable Example: >>> from vyos.ifconfig import Interface >>> Interface('eth1').set_port_isolation('on') """ self.set_interface('bridge_port_isolation', on_or_off) def set_proxy_arp(self, enable): """ Set per interface proxy ARP configuration Example: >>> from vyos.ifconfig import Interface >>> Interface('eth0').set_proxy_arp(1) """ tmp = self.get_interface('proxy_arp') if tmp == enable: return None self.set_interface('proxy_arp', enable) def set_proxy_arp_pvlan(self, enable): """ Private VLAN proxy arp. Basically allow proxy arp replies back to the same interface (from which the ARP request/solicitation was received). This is done to support (ethernet) switch features, like RFC 3069, where the individual ports are NOT allowed to communicate with each other, but they are allowed to talk to the upstream router. As described in RFC 3069, it is possible to allow these hosts to communicate through the upstream router by proxy_arp'ing. Don't need to be used together with proxy_arp. This technology is known by different names: In RFC 3069 it is called VLAN Aggregation. Cisco and Allied Telesyn call it Private VLAN. Hewlett-Packard call it Source-Port filtering or port-isolation. Ericsson call it MAC-Forced Forwarding (RFC Draft). Example: >>> from vyos.ifconfig import Interface >>> Interface('eth0').set_proxy_arp_pvlan(1) """ tmp = self.get_interface('proxy_arp_pvlan') if tmp == enable: return None self.set_interface('proxy_arp_pvlan', enable) def get_addr_v4(self): """ Retrieve assigned IPv4 addresses from given interface. This is done using the netifaces and ipaddress python modules. Example: >>> from vyos.ifconfig import Interface >>> Interface('eth0').get_addr_v4() ['172.16.33.30/24'] """ ipv4 = [] if AF_INET in ifaddresses(self.config['ifname']): for v4_addr in ifaddresses(self.config['ifname'])[AF_INET]: # we need to manually assemble a list of IPv4 address/prefix prefix = '/' + \ str(IPv4Network('0.0.0.0/' + v4_addr['netmask']).prefixlen) ipv4.append(v4_addr['addr'] + prefix) return ipv4 def get_addr_v6(self): """ Retrieve assigned IPv6 addresses from given interface. This is done using the netifaces and ipaddress python modules. Example: >>> from vyos.ifconfig import Interface >>> Interface('eth0').get_addr_v6() ['fe80::20c:29ff:fe11:a174/64'] """ ipv6 = [] if AF_INET6 in ifaddresses(self.config['ifname']): for v6_addr in ifaddresses(self.config['ifname'])[AF_INET6]: # Note that currently expanded netmasks are not supported. That means # 2001:db00::0/24 is a valid argument while 2001:db00::0/ffff:ff00:: not. # see https://docs.python.org/3/library/ipaddress.html prefix = '/' + v6_addr['netmask'].split('/')[-1] # we alsoneed to remove the interface suffix on link local # addresses v6_addr['addr'] = v6_addr['addr'].split('%')[0] ipv6.append(v6_addr['addr'] + prefix) return ipv6 def get_addr(self): """ Retrieve assigned IPv4 and IPv6 addresses from given interface. Example: >>> from vyos.ifconfig import Interface >>> Interface('eth0').get_addr() ['172.16.33.30/24', 'fe80::20c:29ff:fe11:a174/64'] """ return self.get_addr_v4() + self.get_addr_v6() def add_addr(self, addr): """ Add IP(v6) address to interface. Address is only added if it is not already assigned to that interface. Address format must be validated and compressed/normalized before calling this function. addr: can be an IPv4 address, IPv6 address, dhcp or dhcpv6! IPv4: add IPv4 address to interface IPv6: add IPv6 address to interface dhcp: start dhclient (IPv4) on interface dhcpv6: start WIDE DHCPv6 (IPv6) on interface Returns False if address is already assigned and wasn't re-added. Example: >>> from vyos.ifconfig import Interface >>> j = Interface('eth0') >>> j.add_addr('192.0.2.1/24') >>> j.add_addr('2001:db8::ffff/64') >>> j.get_addr() ['192.0.2.1/24', '2001:db8::ffff/64'] """ # XXX: normalize/compress with ipaddress if calling functions don't? # is subnet mask always passed, and in the same way? # do not add same address twice if addr in self._addr: return False # get interface network namespace if specified netns = self.config.get('netns', None) # add to interface if addr == 'dhcp': self.set_dhcp(True) elif addr == 'dhcpv6': self.set_dhcpv6(True) elif not is_intf_addr_assigned(self.ifname, addr, netns=netns): netns_cmd = f'ip netns exec {netns}' if netns else '' tmp = f'{netns_cmd} ip addr add {addr} dev {self.ifname}' # Add broadcast address for IPv4 if is_ipv4(addr): tmp += ' brd +' self._cmd(tmp) else: return False # add to cache self._addr.append(addr) return True def del_addr(self, addr): """ Delete IP(v6) address from interface. Address is only deleted if it is assigned to that interface. Address format must be exactly the same as was used when adding the address. addr: can be an IPv4 address, IPv6 address, dhcp or dhcpv6! IPv4: delete IPv4 address from interface IPv6: delete IPv6 address from interface dhcp: stop dhclient (IPv4) on interface dhcpv6: stop dhclient (IPv6) on interface Returns False if address isn't already assigned and wasn't deleted. Example: >>> from vyos.ifconfig import Interface >>> j = Interface('eth0') >>> j.add_addr('2001:db8::ffff/64') >>> j.add_addr('192.0.2.1/24') >>> j.get_addr() ['192.0.2.1/24', '2001:db8::ffff/64'] >>> j.del_addr('192.0.2.1/24') >>> j.get_addr() ['2001:db8::ffff/64'] """ if not addr: raise ValueError() # get interface network namespace if specified netns = self.config.get('netns', None) # remove from interface if addr == 'dhcp': self.set_dhcp(False) elif addr == 'dhcpv6': self.set_dhcpv6(False) elif is_intf_addr_assigned(self.ifname, addr, netns=netns): netns_cmd = f'ip netns exec {netns}' if netns else '' self._cmd(f'{netns_cmd} ip addr del {addr} dev {self.ifname}') else: return False # remove from cache if addr in self._addr: self._addr.remove(addr) return True def flush_addrs(self): """ Flush all addresses from an interface, including DHCP. Will raise an exception on error. """ # stop DHCP(v6) if running self.set_dhcp(False) self.set_dhcpv6(False) netns = get_interface_namespace(self.ifname) netns_cmd = f'ip netns exec {netns}' if netns else '' cmd = f'{netns_cmd} ip addr flush dev {self.ifname}' # flush all addresses self._cmd(cmd) def add_to_bridge(self, bridge_dict): """ Adds the interface to the bridge with the passed port config. Returns False if bridge doesn't exist. """ # drop all interface addresses first self.flush_addrs() ifname = self.ifname for bridge, bridge_config in bridge_dict.items(): # add interface to bridge - use Section.klass to get BridgeIf class Section.klass(bridge)(bridge, create=True).add_port(self.ifname) # set bridge port path cost if 'cost' in bridge_config: self.set_path_cost(bridge_config['cost']) # set bridge port path priority if 'priority' in bridge_config: self.set_path_cost(bridge_config['priority']) bridge_vlan_filter = Section.klass(bridge)(bridge, create=True).get_vlan_filter() if int(bridge_vlan_filter): cur_vlan_ids = get_vlan_ids(ifname) add_vlan = [] native_vlan_id = None allowed_vlan_ids= [] if 'native_vlan' in bridge_config: vlan_id = bridge_config['native_vlan'] add_vlan.append(vlan_id) native_vlan_id = vlan_id if 'allowed_vlan' in bridge_config: for vlan in bridge_config['allowed_vlan']: vlan_range = vlan.split('-') if len(vlan_range) == 2: for vlan_add in range(int(vlan_range[0]),int(vlan_range[1]) + 1): add_vlan.append(str(vlan_add)) allowed_vlan_ids.append(str(vlan_add)) else: add_vlan.append(vlan) allowed_vlan_ids.append(vlan) # Remove redundant VLANs from the system for vlan in list_diff(cur_vlan_ids, add_vlan): cmd = f'bridge vlan del dev {ifname} vid {vlan} master' self._cmd(cmd) for vlan in allowed_vlan_ids: cmd = f'bridge vlan add dev {ifname} vid {vlan} master' self._cmd(cmd) # Setting native VLAN to system if native_vlan_id: cmd = f'bridge vlan add dev {ifname} vid {native_vlan_id} pvid untagged master' self._cmd(cmd) def set_dhcp(self, enable): """ Enable/Disable DHCP client on a given interface. """ if enable not in [True, False]: raise ValueError() config_base = directories['isc_dhclient_dir'] + '/dhclient' dhclient_config_file = f'{config_base}_{self.ifname}.conf' dhclient_lease_file = f'{config_base}_{self.ifname}.leases' systemd_override_file = f'/run/systemd/system/dhclient@{self.ifname}.service.d/10-override.conf' systemd_service = f'dhclient@{self.ifname}.service' # Rendered client configuration files require the apsolute config path self.config['isc_dhclient_dir'] = directories['isc_dhclient_dir'] # 'up' check is mandatory b/c even if the interface is A/D, as soon as # the DHCP client is started the interface will be placed in u/u state. # This is not what we intended to do when disabling an interface. if enable and 'disable' not in self.config: if dict_search('dhcp_options.host_name', self.config) == None: # read configured system hostname. # maybe change to vyos-hostsd client ??? hostname = 'vyos' hostname_file = '/etc/hostname' if os.path.isfile(hostname_file): hostname = read_file(hostname_file) tmp = {'dhcp_options' : { 'host_name' : hostname}} self.config = dict_merge(tmp, self.config) render(systemd_override_file, 'dhcp-client/override.conf.j2', self.config) render(dhclient_config_file, 'dhcp-client/ipv4.j2', self.config) # Reload systemd unit definitons as some options are dynamically generated self._cmd('systemctl daemon-reload') # When the DHCP client is restarted a brief outage will occur, as # the old lease is released a new one is acquired (T4203). We will # only restart DHCP client if it's option changed, or if it's not # running, but it should be running (e.g. on system startup) if 'dhcp_options_changed' in self.config or not is_systemd_service_active(systemd_service): return self._cmd(f'systemctl restart {systemd_service}') else: if is_systemd_service_active(systemd_service): self._cmd(f'systemctl stop {systemd_service}') # Smoketests occationally fail if the lease is not removed from the Kernel fast enough: # AssertionError: 2 unexpectedly found in {17: [{'addr': '52:54:00:00:00:00', # 'broadcast': 'ff:ff:ff:ff:ff:ff'}], 2: [{'addr': '192.0.2.103', 'netmask': '255.255.255.0', # # We will force removal of any dynamic IPv4 address from the interface tmp = get_interface_address(self.ifname) if tmp and 'addr_info' in tmp: for address_dict in tmp['addr_info']: if address_dict['family'] == 'inet': # Only remove dynamic assigned addresses if 'dynamic' not in address_dict: continue address = address_dict['local'] prefixlen = address_dict['prefixlen'] self.del_addr(f'{address}/{prefixlen}') # cleanup old config files for file in [dhclient_config_file, systemd_override_file, dhclient_lease_file]: if os.path.isfile(file): os.remove(file) return None def set_dhcpv6(self, enable): """ Enable/Disable DHCPv6 client on a given interface. """ if enable not in [True, False]: raise ValueError() ifname = self.ifname config_base = directories['dhcp6_client_dir'] config_file = f'{config_base}/dhcp6c.{ifname}.conf' script_file = f'/etc/wide-dhcpv6/dhcp6c.{ifname}.script' # can not live under /run b/c of noexec mount option systemd_override_file = f'/run/systemd/system/dhcp6c@{ifname}.service.d/10-override.conf' systemd_service = f'dhcp6c@{ifname}.service' # Rendered client configuration files require additional settings config = deepcopy(self.config) config['dhcp6_client_dir'] = directories['dhcp6_client_dir'] config['dhcp6_script_file'] = script_file if enable and 'disable' not in config: render(systemd_override_file, 'dhcp-client/ipv6.override.conf.j2', config) render(config_file, 'dhcp-client/ipv6.j2', config) render(script_file, 'dhcp-client/dhcp6c-script.j2', config, permission=0o755) # Reload systemd unit definitons as some options are dynamically generated self._cmd('systemctl daemon-reload') # We must ignore any return codes. This is required to enable # DHCPv6-PD for interfaces which are yet not up and running. return self._popen(f'systemctl restart {systemd_service}') else: if is_systemd_service_active(systemd_service): self._cmd(f'systemctl stop {systemd_service}') if os.path.isfile(config_file): os.remove(config_file) if os.path.isfile(script_file): os.remove(script_file) return None def set_mirror_redirect(self): # Please refer to the document for details # - https://man7.org/linux/man-pages/man8/tc.8.html # - https://man7.org/linux/man-pages/man8/tc-mirred.8.html # Depening if we are the source or the target interface of the port # mirror we need to setup some variables. # Don't allow for netns yet if 'netns' in self.config: return None source_if = self.config['ifname'] mirror_config = None if 'mirror' in self.config: mirror_config = self.config['mirror'] if 'is_mirror_intf' in self.config: source_if = next(iter(self.config['is_mirror_intf'])) mirror_config = self.config['is_mirror_intf'][source_if].get('mirror', None) redirect_config = None # clear existing ingess - ignore errors (e.g. "Error: Cannot find specified # qdisc on specified device") - we simply cleanup all stuff here if not 'traffic_policy' in self.config: self._popen(f'tc qdisc del dev {source_if} parent ffff: 2>/dev/null'); self._popen(f'tc qdisc del dev {source_if} parent 1: 2>/dev/null'); # Apply interface mirror policy if mirror_config: for direction, target_if in mirror_config.items(): if direction == 'ingress': handle = 'ffff: ingress' parent = 'ffff:' elif direction == 'egress': handle = '1: root prio' parent = '1:' # Mirror egress traffic mirror_cmd = f'tc qdisc add dev {source_if} handle {handle}; ' # Export the mirrored traffic to the interface mirror_cmd += f'tc filter add dev {source_if} parent {parent} protocol '\ f'all prio 10 u32 match u32 0 0 flowid 1:1 action mirred '\ f'egress mirror dev {target_if}' _, err = self._popen(mirror_cmd) if err: print('tc qdisc(filter for mirror port failed') # Apply interface traffic redirection policy elif 'redirect' in self.config: _, err = self._popen(f'tc qdisc add dev {source_if} handle ffff: ingress') if err: print(f'tc qdisc add for redirect failed!') target_if = self.config['redirect'] _, err = self._popen(f'tc filter add dev {source_if} parent ffff: protocol '\ f'all prio 10 u32 match u32 0 0 flowid 1:1 action mirred '\ f'egress redirect dev {target_if}') if err: print('tc filter add for redirect failed') def set_per_client_thread(self, enable): """ Per-device control to enable/disable the threaded mode for all the napi instances of the given network device, without the need for a device up/down. User sets it to 1 or 0 to enable or disable threaded mode. Example: >>> from vyos.ifconfig import Interface >>> Interface('wg1').set_per_client_thread(1) """ # In the case of a "virtual" interface like wireguard, the sysfs # node is only created once there is a peer configured. We can now # add a verify() code-path for this or make this dynamic without # nagging the user tmp = self._sysfs_get['per_client_thread']['location'] if not os.path.exists(tmp): return None tmp = self.get_interface('per_client_thread') if tmp == enable: return None self.set_interface('per_client_thread', enable) def set_eapol(self) -> None: """ Take care about EAPoL supplicant daemon """ # XXX: wpa_supplicant works on the source interface cfg_dir = '/run/wpa_supplicant' wpa_supplicant_conf = f'{cfg_dir}/{self.ifname}.conf' eapol_action='stop' if 'eapol' in self.config: # The default is a fallback to hw_id which is not present for any interface # other then an ethernet interface. Thus we emulate hw_id by reading back the # Kernel assigned MAC address if 'hw_id' not in self.config: self.config['hw_id'] = read_file(f'/sys/class/net/{self.ifname}/address') render(wpa_supplicant_conf, 'ethernet/wpa_supplicant.conf.j2', self.config) cert_file_path = os.path.join(cfg_dir, f'{self.ifname}_cert.pem') cert_key_path = os.path.join(cfg_dir, f'{self.ifname}_cert.key') cert_name = self.config['eapol']['certificate'] pki_cert = self.config['pki']['certificate'][cert_name] loaded_pki_cert = load_certificate(pki_cert['certificate']) loaded_ca_certs = {load_certificate(c['certificate']) for c in self.config['pki']['ca'].values()} if 'ca' in self.config['pki'] else {} cert_full_chain = find_chain(loaded_pki_cert, loaded_ca_certs) write_file(cert_file_path, '\n'.join(encode_certificate(c) for c in cert_full_chain)) write_file(cert_key_path, wrap_private_key(pki_cert['private']['key'])) if 'ca_certificate' in self.config['eapol']: ca_cert_file_path = os.path.join(cfg_dir, f'{self.ifname}_ca.pem') ca_chains = [] for ca_cert_name in self.config['eapol']['ca_certificate']: pki_ca_cert = self.config['pki']['ca'][ca_cert_name] loaded_ca_cert = load_certificate(pki_ca_cert['certificate']) ca_full_chain = find_chain(loaded_ca_cert, loaded_ca_certs) ca_chains.append( '\n'.join(encode_certificate(c) for c in ca_full_chain)) write_file(ca_cert_file_path, '\n'.join(ca_chains)) eapol_action='reload-or-restart' # start/stop WPA supplicant service self._cmd(f'systemctl {eapol_action} wpa_supplicant-wired@{self.ifname}') if 'eapol' not in self.config: # delete configuration on interface removal if os.path.isfile(wpa_supplicant_conf): os.unlink(wpa_supplicant_conf) def update(self, config): """ General helper function which works on a dictionary retrived by get_config_dict(). It's main intention is to consolidate the scattered interface setup code and provide a single point of entry when workin on any interface. """ if self.debug: import pprint pprint.pprint(config) # Cache the configuration - it will be reused inside e.g. DHCP handler # XXX: maybe pass the option via __init__ in the future and rename this # method to apply()? self.config = config # Change interface MAC address - re-set to real hardware address (hw-id) # if custom mac is removed. Skip if bond member. if 'is_bond_member' not in config: mac = config.get('hw_id') if 'mac' in config: mac = config.get('mac') if mac: self.set_mac(mac) # If interface is connected to NETNS we don't have to check all other # settings like MTU/IPv6/sysctl values, etc. # Since the interface is pushed onto a separate logical stack # Configure NETNS if dict_search('netns', config) != None: if not is_netns_interface(self.ifname, self.config['netns']): self.set_netns(config.get('netns', '')) else: self.del_netns(config.get('netns', '')) # Update interface description self.set_alias(config.get('description', '')) # Ignore link state changes value = '2' if 'disable_link_detect' in config else '1' self.set_link_detect(value) # Configure assigned interface IP addresses. No longer # configured addresses will be removed first new_addr = config.get('address', []) # always ensure DHCP client is stopped (when not configured explicitly) if 'dhcp' not in new_addr: self.del_addr('dhcp') # always ensure DHCPv6 client is stopped (when not configured as client # for IPv6 address or prefix delegation) dhcpv6pd = dict_search('dhcpv6_options.pd', config) dhcpv6pd = dhcpv6pd != None and len(dhcpv6pd) != 0 if 'dhcpv6' not in new_addr and not dhcpv6pd: self.del_addr('dhcpv6') # determine IP addresses which are assigned to the interface and build a # list of addresses which are no longer in the dict so they can be removed if 'address_old' in config: for addr in list_diff(config['address_old'], new_addr): # we will delete all interface specific IP addresses if they are not # explicitly configured on the CLI if is_ipv6_link_local(addr): eui64 = mac2eui64(self.get_mac(), link_local_prefix) if addr != f'{eui64}/64': self.del_addr(addr) else: self.del_addr(addr) # start DHCPv6 client when only PD was configured if dhcpv6pd: self.set_dhcpv6(True) # XXX: Bind interface to given VRF or unbind it if vrf is not set. Unbinding # will call 'ip link set dev eth0 nomaster' which will also drop the # interface out of any bridge or bond - thus this is checked before. if 'is_bond_member' in config: bond_if = next(iter(config['is_bond_member'])) tmp = get_interface_config(config['ifname']) if 'master' in tmp and tmp['master'] != bond_if: self.set_vrf('') elif 'is_bridge_member' in config: bridge_if = next(iter(config['is_bridge_member'])) tmp = get_interface_config(config['ifname']) if 'master' in tmp and tmp['master'] != bridge_if: self.set_vrf('') else: self.set_vrf(config.get('vrf', '')) # Add this section after vrf T4331 for addr in new_addr: self.add_addr(addr) # Configure MSS value for IPv4 TCP connections tmp = dict_search('ip.adjust_mss', config) value = tmp if (tmp != None) else '0' self.set_tcp_ipv4_mss(value) # Configure ARP cache timeout in milliseconds - has default value tmp = dict_search('ip.arp_cache_timeout', config) value = tmp if (tmp != None) else '30' self.set_arp_cache_tmo(value) # Configure ARP filter configuration tmp = dict_search('ip.disable_arp_filter', config) value = '0' if (tmp != None) else '1' self.set_arp_filter(value) # Configure ARP accept tmp = dict_search('ip.enable_arp_accept', config) value = '1' if (tmp != None) else '0' self.set_arp_accept(value) # Configure ARP announce tmp = dict_search('ip.enable_arp_announce', config) value = '1' if (tmp != None) else '0' self.set_arp_announce(value) # Configure ARP ignore tmp = dict_search('ip.enable_arp_ignore', config) value = '1' if (tmp != None) else '0' self.set_arp_ignore(value) # Enable proxy-arp on this interface tmp = dict_search('ip.enable_proxy_arp', config) value = '1' if (tmp != None) else '0' self.set_proxy_arp(value) # Enable private VLAN proxy ARP on this interface tmp = dict_search('ip.proxy_arp_pvlan', config) value = '1' if (tmp != None) else '0' self.set_proxy_arp_pvlan(value) # IPv4 forwarding tmp = dict_search('ip.disable_forwarding', config) value = '0' if (tmp != None) else '1' self.set_ipv4_forwarding(value) # IPv4 directed broadcast forwarding tmp = dict_search('ip.enable_directed_broadcast', config) value = '1' if (tmp != None) else '0' self.set_ipv4_directed_broadcast(value) # IPv4 source-validation tmp = dict_search('ip.source_validation', config) value = tmp if (tmp != None) else '0' self.set_ipv4_source_validation(value) # IPv6 source-validation tmp = dict_search('ipv6.source_validation', config) value = tmp if (tmp != None) else '0' self.set_ipv6_source_validation(value) # MTU - Maximum Transfer Unit has a default value. It must ALWAYS be set # before mangling any IPv6 option. If MTU is less then 1280 IPv6 will be # automatically disabled by the kernel. Also MTU must be increased before # configuring any IPv6 address on the interface. if 'mtu' in config and dict_search('dhcp_options.mtu', config) == None: self.set_mtu(config.get('mtu')) # Configure MSS value for IPv6 TCP connections tmp = dict_search('ipv6.adjust_mss', config) value = tmp if (tmp != None) else '0' self.set_tcp_ipv6_mss(value) # IPv6 forwarding tmp = dict_search('ipv6.disable_forwarding', config) value = '0' if (tmp != None) else '1' self.set_ipv6_forwarding(value) # IPv6 router advertisements tmp = dict_search('ipv6.address.autoconf', config) value = '2' if (tmp != None) else '1' if 'dhcpv6' in new_addr: value = '2' self.set_ipv6_accept_ra(value) # IPv6 address autoconfiguration tmp = dict_search('ipv6.address.autoconf', config) value = '1' if (tmp != None) else '0' self.set_ipv6_autoconf(value) # Whether to accept IPv6 DAD (Duplicate Address Detection) packets tmp = dict_search('ipv6.accept_dad', config) # Not all interface types got this CLI option, but if they do, there # is an XML defaultValue available if (tmp != None): self.set_ipv6_dad_accept(tmp) # IPv6 DAD tries tmp = dict_search('ipv6.dup_addr_detect_transmits', config) # Not all interface types got this CLI option, but if they do, there # is an XML defaultValue available if (tmp != None): self.set_ipv6_dad_messages(tmp) # Delete old IPv6 EUI64 addresses before changing MAC for addr in (dict_search('ipv6.address.eui64_old', config) or []): self.del_ipv6_eui64_address(addr) # Manage IPv6 link-local addresses if dict_search('ipv6.address.no_default_link_local', config) != None: self.del_ipv6_eui64_address(link_local_prefix) else: self.add_ipv6_eui64_address(link_local_prefix) # Add IPv6 EUI-based addresses tmp = dict_search('ipv6.address.eui64', config) if tmp: for addr in tmp: self.add_ipv6_eui64_address(addr) # Configure IPv6 base time in milliseconds - has default value tmp = dict_search('ipv6.base_reachable_time', config) value = tmp if (tmp != None) else '30' self.set_ipv6_cache_tmo(value) # re-add ourselves to any bridge we might have fallen out of if 'is_bridge_member' in config: tmp = config.get('is_bridge_member') self.add_to_bridge(tmp) # configure interface mirror or redirection target self.set_mirror_redirect() # enable/disable NAPI threading mode tmp = dict_search('per_client_thread', config) value = '1' if (tmp != None) else '0' self.set_per_client_thread(value) # Enable/Disable of an interface must always be done at the end of the # derived class to make use of the ref-counting set_admin_state() # function. We will only enable the interface if 'up' was called as # often as 'down'. This is required by some interface implementations # as certain parameters can only be changed when the interface is # in admin-down state. This ensures the link does not flap during # reconfiguration. state = 'down' if 'disable' in config else 'up' self.set_admin_state(state) # remove no longer required 802.1ad (Q-in-Q VLANs) ifname = config['ifname'] for vif_s_id in config.get('vif_s_remove', {}): vif_s_ifname = f'{ifname}.{vif_s_id}' VLANIf(vif_s_ifname).remove() # create/update 802.1ad (Q-in-Q VLANs) for vif_s_id, vif_s_config in config.get('vif_s', {}).items(): tmp = deepcopy(VLANIf.get_config()) tmp['protocol'] = vif_s_config['protocol'] tmp['source_interface'] = ifname tmp['vlan_id'] = vif_s_id # It is not possible to change the VLAN encapsulation protocol # "on-the-fly". For this "quirk" we need to actively delete and # re-create the VIF-S interface. vif_s_ifname = f'{ifname}.{vif_s_id}' if self.exists(vif_s_ifname): cur_cfg = get_interface_config(vif_s_ifname) protocol = dict_search('linkinfo.info_data.protocol', cur_cfg).lower() if protocol != vif_s_config['protocol']: VLANIf(vif_s_ifname).remove() s_vlan = VLANIf(vif_s_ifname, **tmp) s_vlan.update(vif_s_config) # remove no longer required client VLAN (vif-c) for vif_c_id in vif_s_config.get('vif_c_remove', {}): vif_c_ifname = f'{vif_s_ifname}.{vif_c_id}' VLANIf(vif_c_ifname).remove() # create/update client VLAN (vif-c) interface for vif_c_id, vif_c_config in vif_s_config.get('vif_c', {}).items(): tmp = deepcopy(VLANIf.get_config()) tmp['source_interface'] = vif_s_ifname tmp['vlan_id'] = vif_c_id vif_c_ifname = f'{vif_s_ifname}.{vif_c_id}' c_vlan = VLANIf(vif_c_ifname, **tmp) c_vlan.update(vif_c_config) # remove no longer required 802.1q VLAN interfaces for vif_id in config.get('vif_remove', {}): vif_ifname = f'{ifname}.{vif_id}' VLANIf(vif_ifname).remove() # create/update 802.1q VLAN interfaces for vif_id, vif_config in config.get('vif', {}).items(): vif_ifname = f'{ifname}.{vif_id}' tmp = deepcopy(VLANIf.get_config()) tmp['source_interface'] = ifname tmp['vlan_id'] = vif_id # We need to ensure that the string format is consistent, and we need to exclude redundant spaces. sep = ' ' if 'egress_qos' in vif_config: # Unwrap strings into arrays egress_qos_array = vif_config['egress_qos'].split() # The split array is spliced according to the fixed format tmp['egress_qos'] = sep.join(egress_qos_array) if 'ingress_qos' in vif_config: # Unwrap strings into arrays ingress_qos_array = vif_config['ingress_qos'].split() # The split array is spliced according to the fixed format tmp['ingress_qos'] = sep.join(ingress_qos_array) # Since setting the QoS control parameters in the later stage will # not completely delete the old settings, # we still need to delete the VLAN encapsulation interface in order to # ensure that the changed settings are effective. cur_cfg = get_interface_config(vif_ifname) qos_str = '' tmp2 = dict_search('linkinfo.info_data.ingress_qos', cur_cfg) if 'ingress_qos' in tmp and tmp2: for item in tmp2: from_key = item['from'] to_key = item['to'] qos_str += f'{from_key}:{to_key} ' if qos_str != tmp['ingress_qos']: if self.exists(vif_ifname): VLANIf(vif_ifname).remove() qos_str = '' tmp2 = dict_search('linkinfo.info_data.egress_qos', cur_cfg) if 'egress_qos' in tmp and tmp2: for item in tmp2: from_key = item['from'] to_key = item['to'] qos_str += f'{from_key}:{to_key} ' if qos_str != tmp['egress_qos']: if self.exists(vif_ifname): VLANIf(vif_ifname).remove() vlan = VLANIf(vif_ifname, **tmp) vlan.update(vif_config) class VLANIf(Interface): """ Specific class which abstracts 802.1q and 802.1ad (Q-in-Q) VLAN interfaces """ - iftype = 'vlan' - def _create(self): # bail out early if interface already exists if self.exists(f'{self.ifname}'): return # If source_interface or vlan_id was not explicitly defined (e.g. when # calling VLANIf('eth0.1').remove() we can define source_interface and # vlan_id here, as it's quiet obvious that it would be eth0 in that case. if 'source_interface' not in self.config: self.config['source_interface'] = '.'.join(self.ifname.split('.')[:-1]) if 'vlan_id' not in self.config: self.config['vlan_id'] = self.ifname.split('.')[-1] cmd = 'ip link add link {source_interface} name {ifname} type vlan id {vlan_id}' if 'protocol' in self.config: cmd += ' protocol {protocol}' if 'ingress_qos' in self.config: cmd += ' ingress-qos-map {ingress_qos}' if 'egress_qos' in self.config: cmd += ' egress-qos-map {egress_qos}' self._cmd(cmd.format(**self.config)) # interface is always A/D down. It needs to be enabled explicitly self.set_admin_state('down') def set_admin_state(self, state): """ Set interface administrative state to be 'up' or 'down' Example: >>> from vyos.ifconfig import Interface >>> Interface('eth0.10').set_admin_state('down') >>> Interface('eth0.10').get_admin_state() 'down' """ # A VLAN interface can only be placed in admin up state when # the lower interface is up, too lower_interface = glob(f'/sys/class/net/{self.ifname}/lower*/flags')[0] with open(lower_interface, 'r') as f: flags = f.read() # If parent is not up - bail out as we can not bring up the VLAN. # Flags are defined in kernel source include/uapi/linux/if.h if not int(flags, 16) & 1: return None return super().set_admin_state(state) diff --git a/python/vyos/ifconfig/l2tpv3.py b/python/vyos/ifconfig/l2tpv3.py index c1f2803ee..dfaa006aa 100644 --- a/python/vyos/ifconfig/l2tpv3.py +++ b/python/vyos/ifconfig/l2tpv3.py @@ -1,113 +1,112 @@ # 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/>. from time import sleep from time import time from vyos.utils.process import run from vyos.ifconfig.interface import Interface def wait_for_add_l2tpv3(timeout=10, sleep_interval=1, cmd=None): ''' In some cases, we need to wait until local address is assigned. And only then can the l2tpv3 tunnel be configured. For example when ipv6 address in tentative state or we wait for some routing daemon for remote address. ''' start_time = time() test_command = cmd while True: if (start_time + timeout) < time(): return None result = run(test_command) if result == 0: return True sleep(sleep_interval) @Interface.register class L2TPv3If(Interface): """ The Linux bonding driver provides a method for aggregating multiple network interfaces into a single logical "bonded" interface. The behavior of the bonded interfaces depends upon the mode; generally speaking, modes provide either hot standby or load balancing services. Additionally, link integrity monitoring may be performed. """ - iftype = 'l2tp' definition = { **Interface.definition, **{ 'section': 'l2tpeth', 'prefixes': ['l2tpeth', ], 'bridgeable': True, } } def _create(self): # create tunnel interface cmd = 'ip l2tp add tunnel tunnel_id {tunnel_id}' cmd += ' peer_tunnel_id {peer_tunnel_id}' cmd += ' udp_sport {source_port}' cmd += ' udp_dport {destination_port}' cmd += ' encap {encapsulation}' cmd += ' local {source_address}' cmd += ' remote {remote}' c = cmd.format(**self.config) # wait until the local/remote address is available, but no more 10 sec. wait_for_add_l2tpv3(cmd=c) # setup session cmd = 'ip l2tp add session name {ifname}' cmd += ' tunnel_id {tunnel_id}' cmd += ' session_id {session_id}' cmd += ' peer_session_id {peer_session_id}' self._cmd(cmd.format(**self.config)) # No need for interface shut down. There exist no function to permanently enable tunnel. # But you can disable interface permanently with shutdown/disable command. self.set_admin_state('up') def remove(self): """ Remove interface from operating system. Removing the interface deconfigures all assigned IP addresses. Example: >>> from vyos.ifconfig import L2TPv3If >>> i = L2TPv3If('l2tpeth0') >>> i.remove() """ if self.exists(self.ifname): self.set_admin_state('down') # remove all assigned IP addresses from interface - this is a bit redundant # as the kernel will remove all addresses on interface deletion self.flush_addrs() # remove interface from conntrack VRF interface map, here explicitly and do not # rely on the base class implementation as the interface will # vanish as soon as the l2tp session is deleted self._del_interface_from_ct_iface_map() if {'tunnel_id', 'session_id'} <= set(self.config): cmd = 'ip l2tp del session tunnel_id {tunnel_id}' cmd += ' session_id {session_id}' self._cmd(cmd.format(**self.config)) if 'tunnel_id' in self.config: cmd = 'ip l2tp del tunnel tunnel_id {tunnel_id}' self._cmd(cmd.format(**self.config)) # No need to call the baseclass as the interface is now already gone diff --git a/python/vyos/ifconfig/loopback.py b/python/vyos/ifconfig/loopback.py index e1d041839..13e8a2c50 100644 --- a/python/vyos/ifconfig/loopback.py +++ b/python/vyos/ifconfig/loopback.py @@ -1,70 +1,74 @@ # Copyright 2019-2022 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/>. from vyos.ifconfig.interface import Interface @Interface.register class LoopbackIf(Interface): """ The loopback device is a special, virtual network interface that your router uses to communicate with itself. """ _persistent_addresses = ['127.0.0.1/8', '::1/128'] - iftype = 'loopback' definition = { **Interface.definition, **{ 'section': 'loopback', 'prefixes': ['lo', ], 'bridgeable': True, + 'eternal': 'lo$', } } + def _create(self): + # we can not create this interface as it is managed by the Kernel + pass + def remove(self): """ Loopback interface can not be deleted from operating system. We can only remove all assigned IP addresses. Example: >>> from vyos.ifconfig import Interface >>> i = LoopbackIf('lo').remove() """ # remove all assigned IP addresses from interface for addr in self.get_addr(): if addr in self._persistent_addresses: # Do not allow deletion of the default loopback addresses as # this will cause weird system behavior like snmp/ssh no longer # operating as expected, see https://vyos.dev/T2034. continue self.del_addr(addr) def update(self, config): """ General helper function which works on a dictionary retrived by get_config_dict(). It's main intention is to consolidate the scattered interface setup code and provide a single point of entry when workin on any interface. """ address = config.get('address', []) # We must ensure that the loopback addresses are never deleted from the system for tmp in self._persistent_addresses: if tmp not in address: address.append(tmp) # Update IP address entry in our dictionary config.update({'address' : address}) # call base class super().update(config) diff --git a/python/vyos/ifconfig/macsec.py b/python/vyos/ifconfig/macsec.py index 383905814..3b4dc223f 100644 --- a/python/vyos/ifconfig/macsec.py +++ b/python/vyos/ifconfig/macsec.py @@ -1,74 +1,73 @@ # Copyright 2020-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/>. from vyos.ifconfig.interface import Interface @Interface.register class MACsecIf(Interface): """ MACsec is an IEEE standard (IEEE 802.1AE) for MAC security, introduced in 2006. It defines a way to establish a protocol independent connection between two hosts with data confidentiality, authenticity and/or integrity, using GCM-AES-128. MACsec operates on the Ethernet layer and as such is a layer 2 protocol, which means it's designed to secure traffic within a layer 2 network, including DHCP or ARP requests. It does not compete with other security solutions such as IPsec (layer 3) or TLS (layer 4), as all those solutions are used for their own specific use cases. """ - iftype = 'macsec' definition = { **Interface.definition, **{ 'section': 'macsec', 'prefixes': ['macsec', ], }, } def _create(self): """ Create MACsec interface in OS kernel. Interface is administrative down by default. """ # create tunnel interface - cmd = 'ip link add link {source_interface} {ifname} type {type}'.format(**self.config) + cmd = 'ip link add link {source_interface} {ifname} type macsec'.format(**self.config) cmd += f' cipher {self.config["security"]["cipher"]}' if 'encrypt' in self.config["security"]: cmd += ' encrypt on' self._cmd(cmd) # Check if using static keys if 'static' in self.config["security"]: # Set static TX key cmd = 'ip macsec add {ifname} tx sa 0 pn 1 on key 00'.format(**self.config) cmd += f' {self.config["security"]["static"]["key"]}' self._cmd(cmd) for peer, peer_config in self.config["security"]["static"]["peer"].items(): if 'disable' in peer_config: continue # Create the address cmd = 'ip macsec add {ifname} rx port 1 address'.format(**self.config) cmd += f' {peer_config["mac"]}' self._cmd(cmd) # Add the encryption key to the address cmd += f' sa 0 pn 1 on key 01 {peer_config["key"]}' self._cmd(cmd) # interface is always A/D down. It needs to be enabled explicitly self.set_admin_state('down') diff --git a/python/vyos/ifconfig/macvlan.py b/python/vyos/ifconfig/macvlan.py index fb7f1d298..fe948b920 100644 --- a/python/vyos/ifconfig/macvlan.py +++ b/python/vyos/ifconfig/macvlan.py @@ -1,46 +1,45 @@ # Copyright 2019-2024 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/>. from vyos.ifconfig.interface import Interface @Interface.register class MACVLANIf(Interface): """ Abstraction of a Linux MACvlan interface """ - iftype = 'macvlan' definition = { **Interface.definition, **{ 'section': 'pseudo-ethernet', 'prefixes': ['peth', ], }, } def _create(self): """ Create MACvlan interface in OS kernel. Interface is administrative down by default. """ # please do not change the order when assembling the command - cmd = 'ip link add {ifname} link {source_interface} type {type} mode {mode}' + cmd = 'ip link add {ifname} link {source_interface} type macvlan mode {mode}' self._cmd(cmd.format(**self.config)) # interface is always A/D down. It needs to be enabled explicitly self.set_admin_state('down') def set_mode(self, mode): - cmd = f'ip link set dev {self.ifname} type {self.iftype} mode {mode}' + cmd = f'ip link set dev {self.ifname} type macvlan mode {mode}' return self._cmd(cmd) diff --git a/python/vyos/ifconfig/pppoe.py b/python/vyos/ifconfig/pppoe.py index f80a68d4f..85ca3877e 100644 --- a/python/vyos/ifconfig/pppoe.py +++ b/python/vyos/ifconfig/pppoe.py @@ -1,142 +1,141 @@ # Copyright 2020-2022 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/>. from vyos.ifconfig.interface import Interface from vyos.utils.assertion import assert_range from vyos.utils.network import get_interface_config @Interface.register class PPPoEIf(Interface): - iftype = 'pppoe' definition = { **Interface.definition, **{ 'section': 'pppoe', 'prefixes': ['pppoe', ], }, } _sysfs_get = { **Interface._sysfs_get,**{ 'accept_ra_defrtr': { 'location': '/proc/sys/net/ipv6/conf/{ifname}/accept_ra_defrtr', } } } _sysfs_set = {**Interface._sysfs_set, **{ 'accept_ra_defrtr': { 'validate': lambda value: assert_range(value, 0, 2), 'location': '/proc/sys/net/ipv6/conf/{ifname}/accept_ra_defrtr', }, }} def _remove_routes(self, vrf=None): # Always delete default routes when interface is removed vrf_cmd = '' if vrf: vrf_cmd = f'-c "vrf {vrf}"' self._cmd(f'vtysh -c "conf t" {vrf_cmd} -c "no ip route 0.0.0.0/0 {self.ifname} tag 210"') self._cmd(f'vtysh -c "conf t" {vrf_cmd} -c "no ipv6 route ::/0 {self.ifname} tag 210"') def remove(self): """ Remove interface from operating system. Removing the interface deconfigures all assigned IP addresses and clear possible DHCP(v6) client processes. Example: >>> from vyos.ifconfig import Interface >>> i = Interface('pppoe0') >>> i.remove() """ vrf = None tmp = get_interface_config(self.ifname) if 'master' in tmp: vrf = tmp['master'] self._remove_routes(vrf) # remove bond master which places members in disabled state super().remove() def _create(self): # we can not create this interface as it is managed outside pass def _delete(self): # we can not create this interface as it is managed outside pass def del_addr(self, addr): # we can not create this interface as it is managed outside pass def get_mac(self): """ Get a synthetic MAC address. """ return self.get_mac_synthetic() def set_accept_ra_defrtr(self, enable): """ Learn default router in Router Advertisement. 1: enabled 0: disable Example: >>> from vyos.ifconfig import PPPoEIf >>> PPPoEIf('pppoe1').set_accept_ra_defrtr(0) """ tmp = self.get_interface('accept_ra_defrtr') if tmp == enable: return None self.set_interface('accept_ra_defrtr', enable) def update(self, config): """ General helper function which works on a dictionary retrived by get_config_dict(). It's main intention is to consolidate the scattered interface setup code and provide a single point of entry when workin on any interface. """ # Cache the configuration - it will be reused inside e.g. DHCP handler # XXX: maybe pass the option via __init__ in the future and rename this # method to apply()? # # We need to copy this from super().update() as we utilize self.set_dhcpv6() # before this is done by the base class. self._config = config # DHCPv6 PD handling is a bit different on PPPoE interfaces, as we do # not require an 'address dhcpv6' CLI option as with other interfaces if 'dhcpv6_options' in config and 'pd' in config['dhcpv6_options']: self.set_dhcpv6(True) else: self.set_dhcpv6(False) super().update(config) # generate proper configuration string when VRFs are in use vrf = '' if 'vrf' in config: tmp = config['vrf'] vrf = f'-c "vrf {tmp}"' # learn default router in Router Advertisement. tmp = '0' if 'no_default_route' in config else '1' self.set_accept_ra_defrtr(tmp) if 'no_default_route' not in config: # Set default route(s) pointing to PPPoE interface distance = config['default_route_distance'] self._cmd(f'vtysh -c "conf t" {vrf} -c "ip route 0.0.0.0/0 {self.ifname} tag 210 {distance}"') if 'ipv6' in config: self._cmd(f'vtysh -c "conf t" {vrf} -c "ipv6 route ::/0 {self.ifname} tag 210 {distance}"') diff --git a/python/vyos/ifconfig/sstpc.py b/python/vyos/ifconfig/sstpc.py index 50fc6ee6b..d92ef23dc 100644 --- a/python/vyos/ifconfig/sstpc.py +++ b/python/vyos/ifconfig/sstpc.py @@ -1,40 +1,39 @@ # Copyright 2022 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/>. from vyos.ifconfig.interface import Interface @Interface.register class SSTPCIf(Interface): - iftype = 'sstpc' definition = { **Interface.definition, **{ 'section': 'sstpc', 'prefixes': ['sstpc', ], 'eternal': 'sstpc[0-9]+$', }, } def _create(self): # we can not create this interface as it is managed outside pass def _delete(self): # we can not create this interface as it is managed outside pass def get_mac(self): """ Get a synthetic MAC address. """ return self.get_mac_synthetic() diff --git a/python/vyos/ifconfig/tunnel.py b/python/vyos/ifconfig/tunnel.py index 9ba7b31a6..df904f7d5 100644 --- a/python/vyos/ifconfig/tunnel.py +++ b/python/vyos/ifconfig/tunnel.py @@ -1,178 +1,177 @@ # Copyright 2019-2021 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/>. # https://developers.redhat.com/blog/2019/05/17/an-introduction-to-linux-virtual-interfaces-tunnels/ # https://community.hetzner.com/tutorials/linux-setup-gre-tunnel from vyos.ifconfig.interface import Interface from vyos.utils.dict import dict_search from vyos.utils.assertion import assert_list def enable_to_on(value): if value == 'enable': return 'on' if value == 'disable': return 'off' raise ValueError(f'expect enable or disable but got "{value}"') @Interface.register class TunnelIf(Interface): """ Tunnel: private base class for tunnels https://git.kernel.org/pub/scm/network/iproute2/iproute2.git/tree/ip/tunnel.c https://git.kernel.org/pub/scm/network/iproute2/iproute2.git/tree/ip/ip6tunnel.c """ definition = { **Interface.definition, **{ 'section': 'tunnel', 'prefixes': ['tun',], 'bridgeable': True, }, } # This table represents a mapping from VyOS internal config dict to # arguments used by iproute2. For more information please refer to: # - https://man7.org/linux/man-pages/man8/ip-link.8.html # - https://man7.org/linux/man-pages/man8/ip-tunnel.8.html mapping = { 'source_address' : 'local', 'source_interface' : 'dev', 'remote' : 'remote', 'parameters.ip.key' : 'key', 'parameters.ip.tos' : 'tos', 'parameters.ip.ttl' : 'ttl', } mapping_ipv4 = { 'parameters.ip.key' : 'key', 'parameters.ip.no_pmtu_discovery' : 'nopmtudisc', 'parameters.ip.ignore_df' : 'ignore-df', 'parameters.ip.tos' : 'tos', 'parameters.ip.ttl' : 'ttl', 'parameters.erspan.direction' : 'erspan_dir', 'parameters.erspan.hw_id' : 'erspan_hwid', 'parameters.erspan.index' : 'erspan', 'parameters.erspan.version' : 'erspan_ver', } mapping_ipv6 = { 'parameters.ipv6.encaplimit' : 'encaplimit', 'parameters.ipv6.flowlabel' : 'flowlabel', 'parameters.ipv6.hoplimit' : 'hoplimit', 'parameters.ipv6.tclass' : 'tclass', } # TODO: This is surely used for more than tunnels # TODO: could be refactored elsewhere _command_set = { **Interface._command_set, **{ 'multicast': { 'validate': lambda v: assert_list(v, ['enable', 'disable']), 'convert': enable_to_on, 'shellcmd': 'ip link set dev {ifname} multicast {value}', }, } } def __init__(self, ifname, **kargs): # T3357: we do not have the 'encapsulation' in kargs when calling this # class from op-mode like "show interfaces tunnel" if 'encapsulation' in kargs: - self.iftype = kargs['encapsulation'] # The gretap interface has the possibility to act as L2 bridge - if self.iftype in ['gretap', 'ip6gretap']: + if kargs['encapsulation'] in ['gretap', 'ip6gretap']: # no multicast, ttl or tos for gretap self.definition = { **TunnelIf.definition, **{ 'bridgeable': True, }, } super().__init__(ifname, **kargs) def _create(self): if self.config['encapsulation'] in ['ipip6', 'ip6ip6', 'ip6gre']: mapping = { **self.mapping, **self.mapping_ipv6 } else: mapping = { **self.mapping, **self.mapping_ipv4 } cmd = 'ip tunnel add {ifname} mode {encapsulation}' - if self.iftype in ['gretap', 'ip6gretap', 'erspan', 'ip6erspan']: + if self.config['encapsulation'] in ['gretap', 'ip6gretap', 'erspan', 'ip6erspan']: cmd = 'ip link add name {ifname} type {encapsulation}' # ERSPAN requires the serialisation of packets - if self.iftype in ['erspan', 'ip6erspan']: + if self.config['encapsulation'] in ['erspan', 'ip6erspan']: cmd += ' seq' for vyos_key, iproute2_key in mapping.items(): # dict_search will return an empty dict "{}" for valueless nodes like # "parameters.nolearning" - thus we need to test the nodes existence # by using isinstance() tmp = dict_search(vyos_key, self.config) if isinstance(tmp, dict): cmd += f' {iproute2_key}' elif tmp != None: cmd += f' {iproute2_key} {tmp}' self._cmd(cmd.format(**self.config)) self.set_admin_state('down') def _change_options(self): # gretap interfaces do not support changing any parameter - if self.iftype in ['gretap', 'ip6gretap', 'erspan', 'ip6erspan']: + if self.config['encapsulation'] in ['gretap', 'ip6gretap', 'erspan', 'ip6erspan']: return if self.config['encapsulation'] in ['ipip6', 'ip6ip6', 'ip6gre']: mapping = { **self.mapping, **self.mapping_ipv6 } else: mapping = { **self.mapping, **self.mapping_ipv4 } cmd = 'ip tunnel change {ifname} mode {encapsulation}' for vyos_key, iproute2_key in mapping.items(): # dict_search will return an empty dict "{}" for valueless nodes like # "parameters.nolearning" - thus we need to test the nodes existence # by using isinstance() tmp = dict_search(vyos_key, self.config) if isinstance(tmp, dict): cmd += f' {iproute2_key}' elif tmp != None: cmd += f' {iproute2_key} {tmp}' self._cmd(cmd.format(**self.config)) def get_mac(self): """ Get a synthetic MAC address. """ return self.get_mac_synthetic() def set_multicast(self, enable): """ Change the MULTICAST flag on the device """ return self.set_interface('multicast', enable) def update(self, config): """ General helper function which works on a dictionary retrived by get_config_dict(). It's main intention is to consolidate the scattered interface setup code and provide a single point of entry when workin on any interface. """ # Adjust iproute2 tunnel parameters if necessary self._change_options() # IP Multicast tmp = dict_search('enable_multicast', config) value = 'enable' if (tmp != None) else 'disable' self.set_multicast(value) # call base class first super().update(config) diff --git a/python/vyos/ifconfig/veth.py b/python/vyos/ifconfig/veth.py index aafbf226a..2c8709d20 100644 --- a/python/vyos/ifconfig/veth.py +++ b/python/vyos/ifconfig/veth.py @@ -1,54 +1,53 @@ # Copyright 2022 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/>. from vyos.ifconfig.interface import Interface @Interface.register class VethIf(Interface): """ Abstraction of a Linux veth interface """ - iftype = 'veth' definition = { **Interface.definition, **{ 'section': 'virtual-ethernet', 'prefixes': ['veth', ], 'bridgeable': True, }, } def _create(self): """ Create veth interface in OS kernel. Interface is administrative down by default. """ # check before create, as we have 2 veth interfaces in our CLI # interface virtual-ethernet veth0 peer-name 'veth1' # interface virtual-ethernet veth1 peer-name 'veth0' # # but iproute2 creates the pair with one command: # ip link add vet0 type veth peer name veth1 if self.exists(self.config['peer_name']): return # create virtual-ethernet interface - cmd = 'ip link add {ifname} type {type}'.format(**self.config) + cmd = f'ip link add {self.ifname} type veth' cmd += f' peer name {self.config["peer_name"]}' self._cmd(cmd) # interface is always A/D down. It needs to be enabled explicitly self.set_admin_state('down') diff --git a/python/vyos/ifconfig/vrrp.py b/python/vyos/ifconfig/vrrp.py index a3657370f..3ee22706c 100644 --- a/python/vyos/ifconfig/vrrp.py +++ b/python/vyos/ifconfig/vrrp.py @@ -1,172 +1,169 @@ # Copyright 2019-2024 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 os import json import signal from time import time from tabulate import tabulate from vyos.configquery import ConfigTreeQuery from vyos.utils.convert import seconds_to_human from vyos.utils.file import read_file from vyos.utils.file import wait_for_file_write_complete from vyos.utils.process import process_running - class VRRPError(Exception): pass - class VRRPNoData(VRRPError): pass - class VRRP(object): _vrrp_prefix = '00:00:5E:00:01:' location = { 'pid': '/run/keepalived/keepalived.pid', 'fifo': '/run/keepalived/keepalived_notify_fifo', 'state': '/tmp/keepalived.data', 'stats': '/tmp/keepalived.stats', 'json': '/tmp/keepalived.json', 'daemon': '/etc/default/keepalived', 'config': '/run/keepalived/keepalived.conf', } _signal = { 'state': signal.SIGUSR1, 'stats': signal.SIGUSR2, 'json': signal.SIGRTMIN + 2, } _name = { 'state': 'information', 'stats': 'statistics', 'json': 'data', } state = { 0: 'INIT', 1: 'BACKUP', 2: 'MASTER', 3: 'FAULT', # UNKNOWN } def __init__(self, ifname): self.ifname = ifname def enabled(self): return self.ifname in self.active_interfaces() @classmethod def active_interfaces(cls): if not os.path.exists(cls.location['pid']): return [] data = cls.collect('json') return [group['data']['ifp_ifname'] for group in json.loads(data)] @classmethod def decode_state(cls, code): return cls.state.get(code, 'UNKNOWN') # used in conf mode @classmethod def is_running(cls): if not os.path.exists(cls.location['pid']): return False return process_running(cls.location['pid']) @classmethod def collect(cls, what): fname = cls.location[what] try: # send signal to generate the configuration file pid = read_file(cls.location['pid']) wait_for_file_write_complete( fname, pre_hook=(lambda: os.kill(int(pid), cls._signal[what])), timeout=30, ) return read_file(fname) except FileNotFoundError: raise VRRPNoData( 'VRRP data is not available (process not running or no active groups)' ) except OSError: # raised by vyos.utils.file.read_file raise VRRPNoData('VRRP data is not available (wait time exceeded)') except Exception: name = cls._name[what] raise VRRPError(f'VRRP {name} is not available') finally: if os.path.exists(fname): os.remove(fname) @classmethod def disabled(cls): disabled = [] base = ['high-availability', 'vrrp'] conf = ConfigTreeQuery() if conf.exists(base): # Read VRRP configuration directly from CLI vrrp_config_dict = conf.get_config_dict( base, key_mangling=('-', '_'), get_first_key=True ) # add disabled groups to the list if 'group' in vrrp_config_dict: for group, group_config in vrrp_config_dict['group'].items(): if 'disable' not in group_config: continue disabled.append( [ group, group_config['interface'], group_config['vrid'], 'DISABLED', '', ] ) # return list with disabled instances return disabled @classmethod def format(cls, data): headers = ['Name', 'Interface', 'VRID', 'State', 'Priority', 'Last Transition'] groups = [] data = json.loads(data) if isinstance(data, str) else data for group in data: data = group['data'] name = data['iname'] intf = data['ifp_ifname'] vrid = data['vrid'] state = cls.decode_state(data['state']) priority = data['effective_priority'] since = int(time() - float(data['last_transition'])) last = seconds_to_human(since) groups.append([name, intf, vrid, state, priority, last]) # add to the active list disabled instances groups.extend(cls.disabled()) return tabulate(groups, headers) diff --git a/python/vyos/ifconfig/vti.py b/python/vyos/ifconfig/vti.py index 251cbeb36..78f5895f8 100644 --- a/python/vyos/ifconfig/vti.py +++ b/python/vyos/ifconfig/vti.py @@ -1,80 +1,79 @@ # Copyright 2021-2024 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/>. from vyos.ifconfig.interface import Interface from vyos.utils.dict import dict_search from vyos.utils.vti_updown_db import vti_updown_db_exists, open_vti_updown_db_readonly @Interface.register class VTIIf(Interface): - iftype = 'vti' definition = { **Interface.definition, **{ 'section': 'vti', 'prefixes': ['vti', ], }, } def __init__(self, ifname, **kwargs): self.bypass_vti_updown_db = kwargs.pop("bypass_vti_updown_db", False) super().__init__(ifname, **kwargs) def _create(self): # This table represents a mapping from VyOS internal config dict to # arguments used by iproute2. For more information please refer to: # - https://man7.org/linux/man-pages/man8/ip-link.8.html # - https://man7.org/linux/man-pages/man8/ip-tunnel.8.html mapping = { 'source_interface' : 'dev', } if_id = self.ifname.lstrip('vti') # The key defaults to 0 and will match any policies which similarly do # not have a lookup key configuration - thus we shift the key by one # to also support a vti0 interface if_id = str(int(if_id) +1) cmd = f'ip link add {self.ifname} type xfrm if_id {if_id}' for vyos_key, iproute2_key in mapping.items(): # dict_search will return an empty dict "{}" for valueless nodes like # "parameters.nolearning" - thus we need to test the nodes existence # by using isinstance() tmp = dict_search(vyos_key, self.config) if isinstance(tmp, dict): cmd += f' {iproute2_key}' elif tmp != None: cmd += f' {iproute2_key} {tmp}' self._cmd(cmd.format(**self.config)) # interface is always A/D down. It needs to be enabled explicitly self.set_interface('admin_state', 'down') def set_admin_state(self, state): """ Set interface administrative state to be 'up' or 'down'. The interface will only be brought 'up' if ith is attached to an active ipsec site-to-site connection or remote access connection. """ if state == 'down' or self.bypass_vti_updown_db: super().set_admin_state(state) elif vti_updown_db_exists(): with open_vti_updown_db_readonly() as db: if db.wantsInterfaceUp(self.ifname): super().set_admin_state(state) def get_mac(self): """ Get a synthetic MAC address. """ return self.get_mac_synthetic() diff --git a/python/vyos/ifconfig/vtun.py b/python/vyos/ifconfig/vtun.py index 6fb414e56..ee790f275 100644 --- a/python/vyos/ifconfig/vtun.py +++ b/python/vyos/ifconfig/vtun.py @@ -1,49 +1,48 @@ # Copyright 2020-2021 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/>. from vyos.ifconfig.interface import Interface @Interface.register class VTunIf(Interface): - iftype = 'vtun' definition = { **Interface.definition, **{ 'section': 'openvpn', 'prefixes': ['vtun', ], 'bridgeable': True, }, } def _create(self): """ Depending on OpenVPN operation mode the interface is created immediately (e.g. Server mode) or once the connection to the server is established (client mode). The latter will only be brought up once the server can be reached, thus we might need to create this interface in advance for the service to be operational. """ try: cmd = 'openvpn --mktun --dev-type {device_type} --dev {ifname}'.format(**self.config) return self._cmd(cmd) except PermissionError: # interface created by OpenVPN daemon in the meantime ... pass def add_addr(self, addr): # IP addresses are managed by OpenVPN daemon pass def del_addr(self, addr): # IP addresses are managed by OpenVPN daemon pass diff --git a/python/vyos/ifconfig/vxlan.py b/python/vyos/ifconfig/vxlan.py index 1023c58d1..58844885b 100644 --- a/python/vyos/ifconfig/vxlan.py +++ b/python/vyos/ifconfig/vxlan.py @@ -1,211 +1,209 @@ # Copyright 2019-2024 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/>. from vyos.configdict import list_diff from vyos.ifconfig import Interface from vyos.utils.assertion import assert_list from vyos.utils.dict import dict_search from vyos.utils.network import get_interface_config from vyos.utils.network import get_vxlan_vlan_tunnels from vyos.utils.network import get_vxlan_vni_filter @Interface.register class VXLANIf(Interface): """ The VXLAN protocol is a tunnelling protocol designed to solve the problem of limited VLAN IDs (4096) in IEEE 802.1q. With VXLAN the size of the identifier is expanded to 24 bits (16777216). VXLAN is described by IETF RFC 7348, and has been implemented by a number of vendors. The protocol runs over UDP using a single destination port. This document describes the Linux kernel tunnel device, there is also a separate implementation of VXLAN for Openvswitch. Unlike most tunnels, a VXLAN is a 1 to N network, not just point to point. A VXLAN device can learn the IP address of the other endpoint either dynamically in a manner similar to a learning bridge, or make use of statically-configured forwarding entries. For more information please refer to: https://www.kernel.org/doc/Documentation/networking/vxlan.txt """ - - iftype = 'vxlan' definition = { **Interface.definition, **{ 'section': 'vxlan', 'prefixes': ['vxlan', ], 'bridgeable': True, } } _command_set = {**Interface._command_set, **{ 'neigh_suppress': { 'validate': lambda v: assert_list(v, ['on', 'off']), 'shellcmd': 'bridge link set dev {ifname} neigh_suppress {value} learning off', }, 'vlan_tunnel': { 'validate': lambda v: assert_list(v, ['on', 'off']), 'shellcmd': 'bridge link set dev {ifname} vlan_tunnel {value}', }, }} def _create(self): # This table represents a mapping from VyOS internal config dict to # arguments used by iproute2. For more information please refer to: # - https://man7.org/linux/man-pages/man8/ip-link.8.html mapping = { 'group' : 'group', 'gpe' : 'gpe', 'parameters.external' : 'external', 'parameters.ip.df' : 'df', 'parameters.ip.tos' : 'tos', 'parameters.ip.ttl' : 'ttl', 'parameters.ipv6.flowlabel' : 'flowlabel', 'parameters.nolearning' : 'nolearning', 'parameters.vni_filter' : 'vnifilter', 'remote' : 'remote', 'source_address' : 'local', 'source_interface' : 'dev', 'vni' : 'id', } # IPv6 flowlabels can only be used on IPv6 tunnels, thus we need to # ensure that at least the first remote IP address is passed to the # tunnel creation command. Subsequent tunnel remote addresses can later # be added to the FDB remote_list = None if 'remote' in self.config: # skip first element as this is already configured as remote remote_list = self.config['remote'][1:] self.config['remote'] = self.config['remote'][0] - cmd = 'ip link add {ifname} type {type} dstport {port}' + cmd = 'ip link add {ifname} type vxlan dstport {port}' for vyos_key, iproute2_key in mapping.items(): # dict_search will return an empty dict "{}" for valueless nodes like # "parameters.nolearning" - thus we need to test the nodes existence # by using isinstance() tmp = dict_search(vyos_key, self.config) if isinstance(tmp, dict): cmd += f' {iproute2_key}' elif tmp != None: cmd += f' {iproute2_key} {tmp}' self._cmd(cmd.format(**self.config)) # interface is always A/D down. It needs to be enabled explicitly self.set_admin_state('down') # VXLAN tunnel is always recreated on any change - see interfaces_vxlan.py if remote_list: for remote in remote_list: cmd = f'bridge fdb append to 00:00:00:00:00:00 dst {remote} ' \ 'port {port} dev {ifname}' self._cmd(cmd.format(**self.config)) def set_neigh_suppress(self, state): """ Controls whether neigh discovery (arp and nd) proxy and suppression is enabled on the port. By default this flag is off. """ # Determine current OS Kernel neigh_suppress setting - only adjust when needed tmp = get_interface_config(self.ifname) cur_state = 'on' if dict_search(f'linkinfo.info_slave_data.neigh_suppress', tmp) == True else 'off' new_state = 'on' if state else 'off' if cur_state != new_state: self.set_interface('neigh_suppress', state) def set_vlan_vni_mapping(self, state): """ Controls whether vlan to tunnel mapping is enabled on the port. By default this flag is off. """ def range_to_dict(vlan_to_vni): """ Converts dict of ranges to dict """ result_dict = {} for vlan, vlan_conf in vlan_to_vni.items(): vni = vlan_conf['vni'] vlan_range, vni_range = vlan.split('-'), vni.split('-') if len(vlan_range) > 1: vlan_range = range(int(vlan_range[0]), int(vlan_range[1]) + 1) vni_range = range(int(vni_range[0]), int(vni_range[1]) + 1) dict_to_add = {str(k): {'vni': str(v)} for k, v in zip(vlan_range, vni_range)} result_dict.update(dict_to_add) return result_dict if not isinstance(state, bool): raise ValueError('Value out of range') if 'vlan_to_vni_removed' in self.config: cur_vni_filter = None if dict_search('parameters.vni_filter', self.config) != None: cur_vni_filter = get_vxlan_vni_filter(self.ifname) for vlan, vlan_config in range_to_dict(self.config['vlan_to_vni_removed']).items(): # If VNI filtering is enabled, remove matching VNI filter if cur_vni_filter != None: vni = vlan_config['vni'] if vni in cur_vni_filter: self._cmd(f'bridge vni delete dev {self.ifname} vni {vni}') self._cmd(f'bridge vlan del dev {self.ifname} vid {vlan}') # Determine current OS Kernel vlan_tunnel setting - only adjust when needed tmp = get_interface_config(self.ifname) cur_state = 'on' if dict_search(f'linkinfo.info_slave_data.vlan_tunnel', tmp) == True else 'off' new_state = 'on' if state else 'off' if cur_state != new_state: self.set_interface('vlan_tunnel', new_state) if 'vlan_to_vni' in self.config: # Determine current OS Kernel configured VLANs vlan_vni_mapping = range_to_dict(self.config['vlan_to_vni']) os_configured_vlan_ids = get_vxlan_vlan_tunnels(self.ifname) add_vlan = list_diff(list(vlan_vni_mapping.keys()), os_configured_vlan_ids) for vlan, vlan_config in vlan_vni_mapping.items(): # VLAN mapping already exists - skip if vlan not in add_vlan: continue vni = vlan_config['vni'] # The following commands must be run one after another, # they can not be combined with linux 6.1 and iproute2 6.1 self._cmd(f'bridge vlan add dev {self.ifname} vid {vlan}') self._cmd(f'bridge vlan add dev {self.ifname} vid {vlan} tunnel_info id {vni}') # If VNI filtering is enabled, install matching VNI filter if dict_search('parameters.vni_filter', self.config) != None: self._cmd(f'bridge vni add dev {self.ifname} vni {vni}') def update(self, config): """ General helper function which works on a dictionary retrived by get_config_dict(). It's main intention is to consolidate the scattered interface setup code and provide a single point of entry when workin on any interface. """ # call base class last super().update(config) # Enable/Disable VLAN tunnel mapping # This is only possible after the interface was assigned to the bridge self.set_vlan_vni_mapping(dict_search('vlan_to_vni', config) != None) # Enable/Disable neighbor suppression and learning, there is no need to # explicitly "disable" it, as VXLAN interface will be recreated if anything # under "parameters" changes. if dict_search('parameters.neighbor_suppress', config) != None: self.set_neigh_suppress('on') diff --git a/python/vyos/ifconfig/wireguard.py b/python/vyos/ifconfig/wireguard.py index cccac361d..519012625 100644 --- a/python/vyos/ifconfig/wireguard.py +++ b/python/vyos/ifconfig/wireguard.py @@ -1,246 +1,245 @@ # Copyright 2019-2024 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 os import time from datetime import timedelta from tempfile import NamedTemporaryFile from hurry.filesize import size from hurry.filesize import alternative from vyos.ifconfig import Interface from vyos.ifconfig import Operational from vyos.template import is_ipv6 - class WireGuardOperational(Operational): def _dump(self): """Dump wireguard data in a python friendly way.""" last_device = None output = {} # Dump wireguard connection data _f = self._cmd('wg show all dump') for line in _f.split('\n'): if not line: # Skip empty lines and last line continue items = line.split('\t') if last_device != items[0]: # We are currently entering a new node device, private_key, public_key, listen_port, fw_mark = items last_device = device output[device] = { 'private_key': None if private_key == '(none)' else private_key, 'public_key': None if public_key == '(none)' else public_key, 'listen_port': int(listen_port), 'fw_mark': None if fw_mark == 'off' else int(fw_mark), 'peers': {}, } else: # We are entering a peer ( device, public_key, preshared_key, endpoint, allowed_ips, latest_handshake, transfer_rx, transfer_tx, persistent_keepalive, ) = items if allowed_ips == '(none)': allowed_ips = [] else: allowed_ips = allowed_ips.split('\t') output[device]['peers'][public_key] = { 'preshared_key': None if preshared_key == '(none)' else preshared_key, 'endpoint': None if endpoint == '(none)' else endpoint, 'allowed_ips': allowed_ips, 'latest_handshake': None if latest_handshake == '0' else int(latest_handshake), 'transfer_rx': int(transfer_rx), 'transfer_tx': int(transfer_tx), 'persistent_keepalive': None if persistent_keepalive == 'off' else int(persistent_keepalive), } return output def show_interface(self): from vyos.config import Config c = Config() wgdump = self._dump().get(self.config['ifname'], None) c.set_level(['interfaces', 'wireguard', self.config['ifname']]) description = c.return_effective_value(['description']) ips = c.return_effective_values(['address']) answer = 'interface: {}\n'.format(self.config['ifname']) if description: answer += ' description: {}\n'.format(description) if ips: answer += ' address: {}\n'.format(', '.join(ips)) answer += ' public key: {}\n'.format(wgdump['public_key']) answer += ' private key: (hidden)\n' answer += ' listening port: {}\n'.format(wgdump['listen_port']) answer += '\n' for peer in c.list_effective_nodes(['peer']): if wgdump['peers']: pubkey = c.return_effective_value(['peer', peer, 'public-key']) if pubkey in wgdump['peers']: wgpeer = wgdump['peers'][pubkey] answer += ' peer: {}\n'.format(peer) answer += ' public key: {}\n'.format(pubkey) """ figure out if the tunnel is recently active or not """ status = 'inactive' if wgpeer['latest_handshake'] is None: """ no handshake ever """ status = 'inactive' else: if int(wgpeer['latest_handshake']) > 0: delta = timedelta( seconds=int(time.time() - wgpeer['latest_handshake']) ) answer += ' latest handshake: {}\n'.format(delta) if time.time() - int(wgpeer['latest_handshake']) < (60 * 5): """ Five minutes and the tunnel is still active """ status = 'active' else: """ it's been longer than 5 minutes """ status = 'inactive' elif int(wgpeer['latest_handshake']) == 0: """ no handshake ever """ status = 'inactive' answer += ' status: {}\n'.format(status) if wgpeer['endpoint'] is not None: answer += ' endpoint: {}\n'.format(wgpeer['endpoint']) if wgpeer['allowed_ips'] is not None: answer += ' allowed ips: {}\n'.format( ','.join(wgpeer['allowed_ips']).replace(',', ', ') ) if wgpeer['transfer_rx'] > 0 or wgpeer['transfer_tx'] > 0: rx_size = size(wgpeer['transfer_rx'], system=alternative) tx_size = size(wgpeer['transfer_tx'], system=alternative) answer += ' transfer: {} received, {} sent\n'.format( rx_size, tx_size ) if wgpeer['persistent_keepalive'] is not None: answer += ' persistent keepalive: every {} seconds\n'.format( wgpeer['persistent_keepalive'] ) answer += '\n' return answer @Interface.register class WireGuardIf(Interface): OperationalClass = WireGuardOperational - iftype = 'wireguard' definition = { **Interface.definition, **{ 'section': 'wireguard', - 'prefixes': [ - 'wg', - ], + 'prefixes': ['wg', ], 'bridgeable': False, }, } + def _create(self): + super()._create('wireguard') + def get_mac(self): """Get a synthetic MAC address.""" return self.get_mac_synthetic() def update(self, config): """General helper function which works on a dictionary retrived by get_config_dict(). It's main intention is to consolidate the scattered interface setup code and provide a single point of entry when workin on any interface.""" tmp_file = NamedTemporaryFile('w') tmp_file.write(config['private_key']) tmp_file.flush() # Wireguard base command is identical for every peer base_cmd = 'wg set {ifname}' if 'port' in config: base_cmd += ' listen-port {port}' if 'fwmark' in config: base_cmd += ' fwmark {fwmark}' base_cmd += f' private-key {tmp_file.name}' base_cmd = base_cmd.format(**config) # T6490: execute command to ensure interface configured self._cmd(base_cmd) if 'peer' in config: for peer, peer_config in config['peer'].items(): # T4702: No need to configure this peer when it was explicitly # marked as disabled - also active sessions are terminated as # the public key was already removed when entering this method! if 'disable' in peer_config: continue # start of with a fresh 'wg' command cmd = base_cmd + ' peer {public_key}' # If no PSK is given remove it by using /dev/null - passing keys via # the shell (usually bash) is considered insecure, thus we use a file no_psk_file = '/dev/null' psk_file = no_psk_file if 'preshared_key' in peer_config: psk_file = '/tmp/tmp.wireguard.psk' with open(psk_file, 'w') as f: f.write(peer_config['preshared_key']) cmd += f' preshared-key {psk_file}' # Persistent keepalive is optional if 'persistent_keepalive' in peer_config: cmd += ' persistent-keepalive {persistent_keepalive}' # Multiple allowed-ip ranges can be defined - ensure we are always # dealing with a list if isinstance(peer_config['allowed_ips'], str): peer_config['allowed_ips'] = [peer_config['allowed_ips']] cmd += ' allowed-ips ' + ','.join(peer_config['allowed_ips']) # Endpoint configuration is optional if {'address', 'port'} <= set(peer_config): if is_ipv6(peer_config['address']): cmd += ' endpoint [{address}]:{port}' else: cmd += ' endpoint {address}:{port}' self._cmd(cmd.format(**peer_config)) # PSK key file is not required to be stored persistently as its backed by CLI if psk_file != no_psk_file and os.path.exists(psk_file): os.remove(psk_file) # call base class super().update(config) diff --git a/python/vyos/ifconfig/wireless.py b/python/vyos/ifconfig/wireless.py index 88eaa772b..121f56bd5 100644 --- a/python/vyos/ifconfig/wireless.py +++ b/python/vyos/ifconfig/wireless.py @@ -1,65 +1,64 @@ # Copyright 2020-2021 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/>. from vyos.ifconfig.interface import Interface @Interface.register class WiFiIf(Interface): """ Handle WIFI/WLAN interfaces. """ - iftype = 'wifi' definition = { **Interface.definition, **{ 'section': 'wireless', 'prefixes': ['wlan', ], 'bridgeable': True, } } def _create(self): # all interfaces will be added in monitor mode cmd = 'iw phy {physical_device} interface add {ifname} type monitor' self._cmd(cmd.format(**self.config)) # wireless interface is administratively down by default self.set_admin_state('down') def _delete(self): cmd = 'iw dev {ifname} del' \ .format(**self.config) self._cmd(cmd) def update(self, config): """ General helper function which works on a dictionary retrived by get_config_dict(). It's main intention is to consolidate the scattered interface setup code and provide a single point of entry when workin on any interface. """ # We can not call add_to_bridge() until wpa_supplicant is running, thus # we will remove the key from the config dict and react to this special # case in this derived class. # re-add ourselves to any bridge we might have fallen out of bridge_member = None if 'is_bridge_member' in config: bridge_member = config['is_bridge_member'] del config['is_bridge_member'] # call base class first super().update(config) # re-add ourselves to any bridge we might have fallen out of if bridge_member: self.add_to_bridge(bridge_member) diff --git a/python/vyos/ifconfig/wwan.py b/python/vyos/ifconfig/wwan.py index 845c9bef9..004a64b39 100644 --- a/python/vyos/ifconfig/wwan.py +++ b/python/vyos/ifconfig/wwan.py @@ -1,45 +1,44 @@ # Copyright 2021 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/>. from vyos.ifconfig.interface import Interface @Interface.register class WWANIf(Interface): - iftype = 'wwan' definition = { **Interface.definition, **{ 'section': 'wwan', 'prefixes': ['wwan', ], 'eternal': 'wwan[0-9]+$', }, } def remove(self): """ Remove interface from config. Removing the interface deconfigures all assigned IP addresses. Example: >>> from vyos.ifconfig import WWANIf >>> i = WWANIf('wwan0') >>> i.remove() """ if self.exists(self.ifname): # interface is placed in A/D state when removed from config! It # will remain visible for the operating system. self.set_admin_state('down') super().remove()