Page Menu
Home
VyOS Platform
Search
Configure Global Search
Log In
Files
F119895443
No One
Temporary
Actions
View File
Edit File
Delete File
View Transforms
Subscribe
Flag For Later
Award Token
Size
204 KB
Referenced Files
None
Subscribers
None
View Options
diff --git a/python/vyos/ifconfig/interface.py b/python/vyos/ifconfig/interface.py
index 117479ade..748830004 100644
--- a/python/vyos/ifconfig/interface.py
+++ b/python/vyos/ifconfig/interface.py
@@ -1,1900 +1,1910 @@
# 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 vyos 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.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_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.template import is_ipv4
from vyos.template import is_ipv6
from vyos.utils.file import read_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
from netaddr import EUI
from netaddr import mac_unix_expanded
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 '',
},
'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 self.iftype:
raise Exception(f'interface "{ifname}" not found')
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')
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):
# 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)
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()
"""
# 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()
# ---------------------------------------------------------------------
# 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 _set_vrf_ct_zone(self, vrf):
+ def _set_vrf_ct_zone(self, vrf, old_vrf_tableid=None):
"""
Add/Remove rules in nftables to associate traffic in VRF to an
individual conntack zone
"""
# Don't allow for netns yet
if 'netns' in self.config:
return None
+ def nft_check_and_run(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}')
+
if vrf:
# Get routing table ID for VRF
- vrf_table_id = get_interface_config(vrf).get('linkinfo', {}).get(
- 'info_data', {}).get('table')
+ 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):
+ nft_del_element = f'delete element inet vrf_zones ct_iface_map {{ "{self.ifname}" }}'
+ nft_check_and_run(nft_del_element)
+
self._cmd(f'nft add element inet vrf_zones ct_iface_map {{ "{self.ifname}" : {vrf_table_id} }}')
else:
nft_del_element = f'delete element inet vrf_zones ct_iface_map {{ "{self.ifname}" }}'
- # Check if deleting is possible first to avoid raising errors
- _, err = self._popen(f'nft --check {nft_del_element}')
- if not err:
- # Remove map element
- self._cmd(f'nft {nft_del_element}')
+ nft_check_and_run(nft_del_element)
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()
"""
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)
- self._set_vrf_ct_zone(vrf)
+ self._set_vrf_ct_zone(vrf, old_vrf_tableid)
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()
ifname = self.ifname
config_base = directories['isc_dhclient_dir'] + '/dhclient'
dhclient_config_file = f'{config_base}_{ifname}.conf'
dhclient_lease_file = f'{config_base}_{ifname}.leases'
systemd_override_file = f'/run/systemd/system/dhclient@{ifname}.service.d/10-override.conf'
systemd_service = f'dhclient@{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}')
# 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 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/utils/network.py b/python/vyos/utils/network.py
index 829124b57..8406a5638 100644
--- a/python/vyos/utils/network.py
+++ b/python/vyos/utils/network.py
@@ -1,558 +1,571 @@
# 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/>.
def _are_same_ip(one, two):
from socket import AF_INET
from socket import AF_INET6
from socket import inet_pton
from vyos.template import is_ipv4
# compare the binary representation of the IP
f_one = AF_INET if is_ipv4(one) else AF_INET6
s_two = AF_INET if is_ipv4(two) else AF_INET6
return inet_pton(f_one, one) == inet_pton(f_one, two)
def get_protocol_by_name(protocol_name):
"""Get protocol number by protocol name
% get_protocol_by_name('tcp')
% 6
"""
import socket
try:
protocol_number = socket.getprotobyname(protocol_name)
return protocol_number
except socket.error:
return protocol_name
def interface_exists(interface) -> bool:
import os
return os.path.exists(f'/sys/class/net/{interface}')
def is_netns_interface(interface, netns):
from vyos.utils.process import rc_cmd
rc, out = rc_cmd(f'sudo ip netns exec {netns} ip link show dev {interface}')
if rc == 0:
return True
return False
def get_netns_all() -> list:
from json import loads
from vyos.utils.process import cmd
tmp = loads(cmd('ip --json netns ls'))
return [ netns['name'] for netns in tmp ]
def get_vrf_members(vrf: str) -> list:
"""
Get list of interface VRF members
:param vrf: str
:return: list
"""
import json
from vyos.utils.process import cmd
interfaces = []
try:
if not interface_exists(vrf):
raise ValueError(f'VRF "{vrf}" does not exist!')
output = cmd(f'ip --json --brief link show vrf {vrf}')
answer = json.loads(output)
for data in answer:
if 'ifname' in data:
interfaces.append(data.get('ifname'))
except:
pass
return interfaces
def get_interface_vrf(interface):
""" Returns VRF of given interface """
from vyos.utils.dict import dict_search
from vyos.utils.network import get_interface_config
tmp = get_interface_config(interface)
if dict_search('linkinfo.info_slave_kind', tmp) == 'vrf':
return tmp['master']
return 'default'
+def get_vrf_tableid(interface: str):
+ """ Return VRF table ID for given interface name or None """
+ from vyos.utils.dict import dict_search
+ table = None
+ tmp = get_interface_config(interface)
+ # Check if we are "the" VRF interface
+ if dict_search('linkinfo.info_kind', tmp) == 'vrf':
+ table = tmp['linkinfo']['info_data']['table']
+ # or an interface bound to a VRF
+ elif dict_search('linkinfo.info_slave_kind', tmp) == 'vrf':
+ table = tmp['linkinfo']['info_slave_data']['table']
+ return table
+
def get_interface_config(interface):
""" Returns the used encapsulation protocol for given interface.
If interface does not exist, None is returned.
"""
if not interface_exists(interface):
return None
from json import loads
from vyos.utils.process import cmd
tmp = loads(cmd(f'ip --detail --json link show dev {interface}'))[0]
return tmp
def get_interface_address(interface):
""" Returns the used encapsulation protocol for given interface.
If interface does not exist, None is returned.
"""
if not interface_exists(interface):
return None
from json import loads
from vyos.utils.process import cmd
tmp = loads(cmd(f'ip --detail --json addr show dev {interface}'))[0]
return tmp
def get_interface_namespace(interface: str):
"""
Returns wich netns the interface belongs to
"""
from json import loads
from vyos.utils.process import cmd
# Bail out early if netns does not exist
tmp = cmd(f'ip --json netns ls')
if not tmp: return None
for ns in loads(tmp):
netns = f'{ns["name"]}'
# Search interface in each netns
data = loads(cmd(f'ip netns exec {netns} ip --json link show'))
for tmp in data:
if interface == tmp["ifname"]:
return netns
def is_ipv6_tentative(iface: str, ipv6_address: str) -> bool:
"""Check if IPv6 address is in tentative state.
This function checks if an IPv6 address on a specific network interface is
in the tentative state. IPv6 tentative addresses are not fully configured
and are undergoing Duplicate Address Detection (DAD) to ensure they are
unique on the network.
Args:
iface (str): The name of the network interface.
ipv6_address (str): The IPv6 address to check.
Returns:
bool: True if the IPv6 address is tentative, False otherwise.
"""
import json
from vyos.utils.process import rc_cmd
rc, out = rc_cmd(f'ip -6 --json address show dev {iface}')
if rc:
return False
data = json.loads(out)
for addr_info in data[0]['addr_info']:
if (
addr_info.get('local') == ipv6_address and
addr_info.get('tentative', False)
):
return True
return False
def is_wwan_connected(interface):
""" Determine if a given WWAN interface, e.g. wwan0 is connected to the
carrier network or not """
import json
from vyos.utils.dict import dict_search
from vyos.utils.process import cmd
from vyos.utils.process import is_systemd_service_active
if not interface.startswith('wwan'):
raise ValueError(f'Specified interface "{interface}" is not a WWAN interface')
# ModemManager is required for connection(s) - if service is not running,
# there won't be any connection at all!
if not is_systemd_service_active('ModemManager.service'):
return False
modem = interface.lstrip('wwan')
tmp = cmd(f'mmcli --modem {modem} --output-json')
tmp = json.loads(tmp)
# return True/False if interface is in connected state
return dict_search('modem.generic.state', tmp) == 'connected'
def get_bridge_fdb(interface):
""" Returns the forwarding database entries for a given interface """
if not interface_exists(interface):
return None
from json import loads
from vyos.utils.process import cmd
tmp = loads(cmd(f'bridge -j fdb show dev {interface}'))
return tmp
def get_all_vrfs():
""" Return a dictionary of all system wide known VRF instances """
from json import loads
from vyos.utils.process import cmd
tmp = loads(cmd('ip --json vrf list'))
# Result is of type [{"name":"red","table":1000},{"name":"blue","table":2000}]
# so we will re-arrange it to a more nicer representation:
# {'red': {'table': 1000}, 'blue': {'table': 2000}}
data = {}
for entry in tmp:
name = entry.pop('name')
data[name] = entry
return data
def interface_list() -> list:
from vyos.ifconfig import Section
"""
Get list of interfaces in system
:rtype: list
"""
return Section.interfaces()
def vrf_list() -> list:
"""
Get list of VRFs in system
:rtype: list
"""
return list(get_all_vrfs().keys())
def mac2eui64(mac, prefix=None):
"""
Convert a MAC address to a EUI64 address or, with prefix provided, a full
IPv6 address.
Thankfully copied from https://gist.github.com/wido/f5e32576bb57b5cc6f934e177a37a0d3
"""
import re
from ipaddress import ip_network
# http://tools.ietf.org/html/rfc4291#section-2.5.1
eui64 = re.sub(r'[.:-]', '', mac).lower()
eui64 = eui64[0:6] + 'fffe' + eui64[6:]
eui64 = hex(int(eui64[0:2], 16) ^ 2)[2:].zfill(2) + eui64[2:]
if prefix is None:
return ':'.join(re.findall(r'.{4}', eui64))
else:
try:
net = ip_network(prefix, strict=False)
euil = int('0x{0}'.format(eui64), 16)
return str(net[euil])
except: # pylint: disable=bare-except
return
def check_port_availability(ipaddress, port, protocol):
"""
Check if port is available and not used by any service
Return False if a port is busy or IP address does not exists
Should be used carefully for services that can start listening
dynamically, because IP address may be dynamic too
"""
from socketserver import TCPServer, UDPServer
from ipaddress import ip_address
# verify arguments
try:
ipaddress = ip_address(ipaddress).compressed
except:
raise ValueError(f'The {ipaddress} is not a valid IPv4 or IPv6 address')
if port not in range(1, 65536):
raise ValueError(f'The port number {port} is not in the 1-65535 range')
if protocol not in ['tcp', 'udp']:
raise ValueError(f'The protocol {protocol} is not supported. Only tcp and udp are allowed')
# check port availability
try:
if protocol == 'tcp':
server = TCPServer((ipaddress, port), None, bind_and_activate=True)
if protocol == 'udp':
server = UDPServer((ipaddress, port), None, bind_and_activate=True)
server.server_close()
except Exception as e:
# errno.h:
#define EADDRINUSE 98 /* Address already in use */
if e.errno == 98:
return False
return True
def is_listen_port_bind_service(port: int, service: str) -> bool:
"""Check if listen port bound to expected program name
:param port: Bind port
:param service: Program name
:return: bool
Example:
% is_listen_port_bind_service(443, 'nginx')
True
% is_listen_port_bind_service(443, 'ocserv-main')
False
"""
from psutil import net_connections as connections
from psutil import Process as process
for connection in connections():
addr = connection.laddr
pid = connection.pid
pid_name = process(pid).name()
pid_port = addr.port
if service == pid_name and port == pid_port:
return True
return False
def is_ipv6_link_local(addr):
""" Check if addrsss is an IPv6 link-local address. Returns True/False """
from ipaddress import ip_interface
from vyos.template import is_ipv6
addr = addr.split('%')[0]
if is_ipv6(addr):
if ip_interface(addr).is_link_local:
return True
return False
def is_addr_assigned(ip_address, vrf=None, return_ifname=False, include_vrf=False) -> bool | str:
""" Verify if the given IPv4/IPv6 address is assigned to any interface """
from netifaces import interfaces
from vyos.utils.network import get_interface_config
from vyos.utils.dict import dict_search
for interface in interfaces():
# Check if interface belongs to the requested VRF, if this is not the
# case there is no need to proceed with this data set - continue loop
# with next element
tmp = get_interface_config(interface)
if dict_search('master', tmp) != vrf and not include_vrf:
continue
if is_intf_addr_assigned(interface, ip_address):
return interface if return_ifname else True
return False
def is_intf_addr_assigned(ifname: str, addr: str, netns: str=None) -> bool:
"""
Verify if the given IPv4/IPv6 address is assigned to specific interface.
It can check both a single IP address (e.g. 192.0.2.1 or a assigned CIDR
address 192.0.2.1/24.
"""
import json
import jmespath
from vyos.utils.process import rc_cmd
from ipaddress import ip_interface
netns_cmd = f'ip netns exec {netns}' if netns else ''
rc, out = rc_cmd(f'{netns_cmd} ip --json address show dev {ifname}')
if rc == 0:
json_out = json.loads(out)
addresses = jmespath.search("[].addr_info[].{family: family, address: local, prefixlen: prefixlen}", json_out)
for address_info in addresses:
family = address_info['family']
address = address_info['address']
prefixlen = address_info['prefixlen']
# Remove the interface name if present in the given address
if '%' in addr:
addr = addr.split('%')[0]
interface = ip_interface(f"{address}/{prefixlen}")
if ip_interface(addr) == interface or address == addr:
return True
return False
def is_loopback_addr(addr):
""" Check if supplied IPv4/IPv6 address is a loopback address """
from ipaddress import ip_address
return ip_address(addr).is_loopback
def is_wireguard_key_pair(private_key: str, public_key:str) -> bool:
"""
Checks if public/private keys are keypair
:param private_key: Wireguard private key
:type private_key: str
:param public_key: Wireguard public key
:type public_key: str
:return: If public/private keys are keypair returns True else False
:rtype: bool
"""
from vyos.utils.process import cmd
gen_public_key = cmd('wg pubkey', input=private_key)
if gen_public_key == public_key:
return True
else:
return False
def is_subnet_connected(subnet, primary=False):
"""
Verify is the given IPv4/IPv6 subnet is connected to any interface on this
system.
primary check if the subnet is reachable via the primary IP address of this
interface, or in other words has a broadcast address configured. ISC DHCP
for instance will complain if it should listen on non broadcast interfaces.
Return True/False
"""
from ipaddress import ip_address
from ipaddress import ip_network
from netifaces import ifaddresses
from netifaces import interfaces
from netifaces import AF_INET
from netifaces import AF_INET6
from vyos.template import is_ipv6
# determine IP version (AF_INET or AF_INET6) depending on passed address
addr_type = AF_INET
if is_ipv6(subnet):
addr_type = AF_INET6
for interface in interfaces():
# check if the requested address type is configured at all
if addr_type not in ifaddresses(interface).keys():
continue
# An interface can have multiple addresses, but some software components
# only support the primary address :(
if primary:
ip = ifaddresses(interface)[addr_type][0]['addr']
if ip_address(ip) in ip_network(subnet):
return True
else:
# Check every assigned IP address if it is connected to the subnet
# in question
for ip in ifaddresses(interface)[addr_type]:
# remove interface extension (e.g. %eth0) that gets thrown on the end of _some_ addrs
addr = ip['addr'].split('%')[0]
if ip_address(addr) in ip_network(subnet):
return True
return False
def is_afi_configured(interface: str, afi):
""" Check if given address family is configured, or in other words - an IP
address is assigned to the interface. """
from netifaces import ifaddresses
from netifaces import AF_INET
from netifaces import AF_INET6
if afi not in [AF_INET, AF_INET6]:
raise ValueError('Address family must be in [AF_INET, AF_INET6]')
try:
addresses = ifaddresses(interface)
except ValueError as e:
print(e)
return False
return afi in addresses
def get_vxlan_vlan_tunnels(interface: str) -> list:
""" Return a list of strings with VLAN IDs configured in the Kernel """
from json import loads
from vyos.utils.process import cmd
if not interface.startswith('vxlan'):
raise ValueError('Only applicable for VXLAN interfaces!')
# Determine current OS Kernel configured VLANs
#
# $ bridge -j -p vlan tunnelshow dev vxlan0
# [ {
# "ifname": "vxlan0",
# "tunnels": [ {
# "vlan": 10,
# "vlanEnd": 11,
# "tunid": 10010,
# "tunidEnd": 10011
# },{
# "vlan": 20,
# "tunid": 10020
# } ]
# } ]
#
os_configured_vlan_ids = []
tmp = loads(cmd(f'bridge --json vlan tunnelshow dev {interface}'))
if tmp:
for tunnel in tmp[0].get('tunnels', {}):
vlanStart = tunnel['vlan']
if 'vlanEnd' in tunnel:
vlanEnd = tunnel['vlanEnd']
# Build a real list for user VLAN IDs
vlan_list = list(range(vlanStart, vlanEnd +1))
# Convert list of integers to list or strings
os_configured_vlan_ids.extend(map(str, vlan_list))
# Proceed with next tunnel - this one is complete
continue
# Add single tunel id - not part of a range
os_configured_vlan_ids.append(str(vlanStart))
return os_configured_vlan_ids
def get_vxlan_vni_filter(interface: str) -> list:
""" Return a list of strings with VNIs configured in the Kernel"""
from json import loads
from vyos.utils.process import cmd
if not interface.startswith('vxlan'):
raise ValueError('Only applicable for VXLAN interfaces!')
# Determine current OS Kernel configured VNI filters in VXLAN interface
#
# $ bridge -j vni show dev vxlan1
# [{"ifname":"vxlan1","vnis":[{"vni":100},{"vni":200},{"vni":300,"vniEnd":399}]}]
#
# Example output: ['10010', '10020', '10021', '10022']
os_configured_vnis = []
tmp = loads(cmd(f'bridge --json vni show dev {interface}'))
if tmp:
for tunnel in tmp[0].get('vnis', {}):
vniStart = tunnel['vni']
if 'vniEnd' in tunnel:
vniEnd = tunnel['vniEnd']
# Build a real list for user VNIs
vni_list = list(range(vniStart, vniEnd +1))
# Convert list of integers to list or strings
os_configured_vnis.extend(map(str, vni_list))
# Proceed with next tunnel - this one is complete
continue
# Add single tunel id - not part of a range
os_configured_vnis.append(str(vniStart))
return os_configured_vnis
# Calculate prefix length of an IPv6 range, where possible
# Python-ified from source: https://gitlab.isc.org/isc-projects/dhcp/-/blob/master/keama/confparse.c#L4591
def ipv6_prefix_length(low, high):
import socket
bytemasks = [0x80, 0xc0, 0xe0, 0xf0, 0xf8, 0xfc, 0xfe, 0xff]
try:
lo = bytearray(socket.inet_pton(socket.AF_INET6, low))
hi = bytearray(socket.inet_pton(socket.AF_INET6, high))
except:
return None
xor = bytearray(a ^ b for a, b in zip(lo, hi))
-
+
plen = 0
while plen < 128 and xor[plen // 8] == 0:
plen += 8
-
+
if plen == 128:
return plen
-
+
for i in range((plen // 8) + 1, 16):
if xor[i] != 0:
return None
-
+
for i in range(8):
msk = ~xor[plen // 8] & 0xff
-
+
if msk == bytemasks[i]:
return plen + i + 1
return None
diff --git a/smoketest/scripts/cli/base_interfaces_test.py b/smoketest/scripts/cli/base_interfaces_test.py
index 9be2c2f1a..4072fd5c2 100644
--- a/smoketest/scripts/cli/base_interfaces_test.py
+++ b/smoketest/scripts/cli/base_interfaces_test.py
@@ -1,1092 +1,1138 @@
# Copyright (C) 2019-2024 VyOS maintainers and contributors
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License version 2 or later as
# published by the Free Software Foundation.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
from netifaces import AF_INET
from netifaces import AF_INET6
from netifaces import ifaddresses
from netifaces import interfaces
from base_vyostest_shim import VyOSUnitTestSHIM
from vyos.configsession import ConfigSessionError
from vyos.defaults import directories
from vyos.ifconfig import Interface
from vyos.ifconfig import Section
from vyos.utils.file import read_file
from vyos.utils.dict import dict_search
from vyos.utils.process import process_named_running
from vyos.utils.network import get_interface_config
from vyos.utils.network import get_interface_vrf
+from vyos.utils.network import get_vrf_tableid
from vyos.utils.process import cmd
from vyos.utils.network import is_intf_addr_assigned
from vyos.utils.network import is_ipv6_link_local
from vyos.xml_ref import cli_defined
dhclient_base_dir = directories['isc_dhclient_dir']
dhclient_process_name = 'dhclient'
dhcp6c_base_dir = directories['dhcp6_client_dir']
dhcp6c_process_name = 'dhcp6c'
def is_mirrored_to(interface, mirror_if, qdisc):
"""
Ask TC if we are mirroring traffic to a discrete interface.
interface: source interface
mirror_if: destination where we mirror our data to
qdisc: must be ffff or 1 for ingress/egress
"""
if qdisc not in ['ffff', '1']:
raise ValueError()
ret_val = False
tmp = cmd(f'tc -s -p filter ls dev {interface} parent {qdisc}: | grep mirred')
tmp = tmp.lower()
if mirror_if in tmp:
ret_val = True
return ret_val
class BasicInterfaceTest:
class TestCase(VyOSUnitTestSHIM.TestCase):
_test_dhcp = False
_test_ip = False
_test_mtu = False
_test_vlan = False
_test_qinq = False
_test_ipv6 = False
_test_ipv6_pd = False
_test_ipv6_dhcpc6 = False
_test_mirror = False
_test_vrf = False
_base_path = []
_options = {}
_interfaces = []
_qinq_range = ['10', '20', '30']
_vlan_range = ['100', '200', '300', '2000']
_test_addr = ['192.0.2.1/26', '192.0.2.255/31', '192.0.2.64/32',
'2001:db8:1::ffff/64', '2001:db8:101::1/112']
_mirror_interfaces = []
# choose IPv6 minimum MTU value for tests - this must always work
_mtu = '1280'
@classmethod
def setUpClass(cls):
super(BasicInterfaceTest.TestCase, cls).setUpClass()
# XXX the case of test_vif_8021q_mtu_limits, below, shows that
# we should extend cli_defined to support more complex queries
cls._test_vlan = cli_defined(cls._base_path, 'vif')
cls._test_qinq = cli_defined(cls._base_path, 'vif-s')
cls._test_dhcp = cli_defined(cls._base_path, 'dhcp-options')
cls._test_ip = cli_defined(cls._base_path, 'ip')
cls._test_ipv6 = cli_defined(cls._base_path, 'ipv6')
cls._test_ipv6_dhcpc6 = cli_defined(cls._base_path, 'dhcpv6-options')
cls._test_ipv6_pd = cli_defined(cls._base_path + ['dhcpv6-options'], 'pd')
cls._test_mtu = cli_defined(cls._base_path, 'mtu')
cls._test_vrf = cli_defined(cls._base_path, 'vrf')
# Setup mirror interfaces for SPAN (Switch Port Analyzer)
for span in cls._mirror_interfaces:
section = Section.section(span)
cls.cli_set(cls, ['interfaces', section, span])
@classmethod
def tearDownClass(cls):
# Tear down mirror interfaces for SPAN (Switch Port Analyzer)
for span in cls._mirror_interfaces:
section = Section.section(span)
cls.cli_delete(cls, ['interfaces', section, span])
super(BasicInterfaceTest.TestCase, cls).tearDownClass()
def tearDown(self):
self.cli_delete(self._base_path)
self.cli_commit()
# Verify that no previously interface remained on the system
for intf in self._interfaces:
self.assertNotIn(intf, interfaces())
# No daemon started during tests should remain running
for daemon in ['dhcp6c', 'dhclient']:
# if _interface list is populated do a more fine grained search
# by also checking the cmd arguments passed to the daemon
if self._interfaces:
for tmp in self._interfaces:
self.assertFalse(process_named_running(daemon, tmp))
else:
self.assertFalse(process_named_running(daemon))
def test_dhcp_disable_interface(self):
if not self._test_dhcp:
self.skipTest('not supported')
# When interface is configured as admin down, it must be admin down
# even when dhcpc starts on the given interface
for interface in self._interfaces:
self.cli_set(self._base_path + [interface, 'disable'])
for option in self._options.get(interface, []):
self.cli_set(self._base_path + [interface] + option.split())
# Also enable DHCP (ISC DHCP always places interface in admin up
# state so we check that we do not start DHCP client.
# https://vyos.dev/T2767
self.cli_set(self._base_path + [interface, 'address', 'dhcp'])
self.cli_commit()
# Validate interface state
for interface in self._interfaces:
flags = read_file(f'/sys/class/net/{interface}/flags')
self.assertEqual(int(flags, 16) & 1, 0)
def test_dhcp_client_options(self):
if not self._test_dhcp or not self._test_vrf:
self.skipTest('not supported')
client_id = 'VyOS-router'
distance = '100'
hostname = 'vyos'
vendor_class_id = 'vyos-vendor'
user_class = 'vyos'
for interface in self._interfaces:
for option in self._options.get(interface, []):
self.cli_set(self._base_path + [interface] + option.split())
self.cli_set(self._base_path + [interface, 'address', 'dhcp'])
self.cli_set(self._base_path + [interface, 'dhcp-options', 'client-id', client_id])
self.cli_set(self._base_path + [interface, 'dhcp-options', 'default-route-distance', distance])
self.cli_set(self._base_path + [interface, 'dhcp-options', 'host-name', hostname])
self.cli_set(self._base_path + [interface, 'dhcp-options', 'vendor-class-id', vendor_class_id])
self.cli_set(self._base_path + [interface, 'dhcp-options', 'user-class', user_class])
self.cli_commit()
for interface in self._interfaces:
# Check if dhclient process runs
dhclient_pid = process_named_running(dhclient_process_name, cmdline=interface, timeout=10)
self.assertTrue(dhclient_pid)
dhclient_config = read_file(f'{dhclient_base_dir}/dhclient_{interface}.conf')
self.assertIn(f'request subnet-mask, broadcast-address, routers, domain-name-servers', dhclient_config)
self.assertIn(f'require subnet-mask;', dhclient_config)
self.assertIn(f'send host-name "{hostname}";', dhclient_config)
self.assertIn(f'send dhcp-client-identifier "{client_id}";', dhclient_config)
self.assertIn(f'send vendor-class-identifier "{vendor_class_id}";', dhclient_config)
self.assertIn(f'send user-class "{user_class}";', dhclient_config)
# and the commandline has the appropriate options
cmdline = read_file(f'/proc/{dhclient_pid}/cmdline')
self.assertIn(f'-e\x00IF_METRIC={distance}', cmdline)
def test_dhcp_vrf(self):
if not self._test_dhcp or not self._test_vrf:
self.skipTest('not supported')
vrf_name = 'purple4'
self.cli_set(['vrf', 'name', vrf_name, 'table', '65000'])
for interface in self._interfaces:
for option in self._options.get(interface, []):
self.cli_set(self._base_path + [interface] + option.split())
self.cli_set(self._base_path + [interface, 'address', 'dhcp'])
self.cli_set(self._base_path + [interface, 'vrf', vrf_name])
self.cli_commit()
# Validate interface state
for interface in self._interfaces:
tmp = get_interface_vrf(interface)
self.assertEqual(tmp, vrf_name)
# Check if dhclient process runs
dhclient_pid = process_named_running(dhclient_process_name, cmdline=interface, timeout=10)
self.assertTrue(dhclient_pid)
# .. inside the appropriate VRF instance
vrf_pids = cmd(f'ip vrf pids {vrf_name}')
self.assertIn(str(dhclient_pid), vrf_pids)
# and the commandline has the appropriate options
cmdline = read_file(f'/proc/{dhclient_pid}/cmdline')
self.assertIn('-e\x00IF_METRIC=210', cmdline) # 210 is the default value
self.cli_delete(['vrf', 'name', vrf_name])
def test_dhcpv6_vrf(self):
if not self._test_ipv6_dhcpc6 or not self._test_vrf:
self.skipTest('not supported')
vrf_name = 'purple6'
self.cli_set(['vrf', 'name', vrf_name, 'table', '65001'])
# When interface is configured as admin down, it must be admin down
# even when dhcpc starts on the given interface
for interface in self._interfaces:
for option in self._options.get(interface, []):
self.cli_set(self._base_path + [interface] + option.split())
self.cli_set(self._base_path + [interface, 'address', 'dhcpv6'])
self.cli_set(self._base_path + [interface, 'vrf', vrf_name])
self.cli_commit()
# Validate interface state
for interface in self._interfaces:
tmp = get_interface_vrf(interface)
self.assertEqual(tmp, vrf_name)
# Check if dhclient process runs
tmp = process_named_running(dhcp6c_process_name, cmdline=interface, timeout=10)
self.assertTrue(tmp)
# .. inside the appropriate VRF instance
vrf_pids = cmd(f'ip vrf pids {vrf_name}')
self.assertIn(str(tmp), vrf_pids)
self.cli_delete(['vrf', 'name', vrf_name])
+ def test_move_interface_between_vrf_instances(self):
+ if not self._test_vrf:
+ self.skipTest('not supported')
+
+ vrf1_name = 'smoketest_mgmt1'
+ vrf1_table = '5424'
+ vrf2_name = 'smoketest_mgmt2'
+ vrf2_table = '7412'
+
+ self.cli_set(['vrf', 'name', vrf1_name, 'table', vrf1_table])
+ self.cli_set(['vrf', 'name', vrf2_name, 'table', vrf2_table])
+
+ # move interface into first VRF
+ for interface in self._interfaces:
+ for option in self._options.get(interface, []):
+ self.cli_set(self._base_path + [interface] + option.split())
+ self.cli_set(self._base_path + [interface, 'vrf', vrf1_name])
+
+ self.cli_commit()
+
+ # check that interface belongs to proper VRF
+ for interface in self._interfaces:
+ tmp = get_interface_vrf(interface)
+ self.assertEqual(tmp, vrf1_name)
+
+ tmp = get_interface_config(vrf1_name)
+ self.assertEqual(int(vrf1_table), get_vrf_tableid(interface))
+
+ # move interface into second VRF
+ for interface in self._interfaces:
+ self.cli_set(self._base_path + [interface, 'vrf', vrf2_name])
+
+ self.cli_commit()
+
+ # check that interface belongs to proper VRF
+ for interface in self._interfaces:
+ tmp = get_interface_vrf(interface)
+ self.assertEqual(tmp, vrf2_name)
+
+ tmp = get_interface_config(vrf2_name)
+ self.assertEqual(int(vrf2_table), get_vrf_tableid(interface))
+
+ self.cli_delete(['vrf', 'name', vrf1_name])
+ self.cli_delete(['vrf', 'name', vrf2_name])
+
def test_span_mirror(self):
if not self._mirror_interfaces:
self.skipTest('not supported')
# Check the two-way mirror rules of ingress and egress
for mirror in self._mirror_interfaces:
for interface in self._interfaces:
self.cli_set(self._base_path + [interface, 'mirror', 'ingress', mirror])
self.cli_set(self._base_path + [interface, 'mirror', 'egress', mirror])
self.cli_commit()
# Verify config
for mirror in self._mirror_interfaces:
for interface in self._interfaces:
self.assertTrue(is_mirrored_to(interface, mirror, 'ffff'))
self.assertTrue(is_mirrored_to(interface, mirror, '1'))
def test_interface_disable(self):
# Check if description can be added to interface and
# can be read back
for intf in self._interfaces:
self.cli_set(self._base_path + [intf, 'disable'])
for option in self._options.get(intf, []):
self.cli_set(self._base_path + [intf] + option.split())
self.cli_commit()
# Validate interface description
for intf in self._interfaces:
self.assertEqual(Interface(intf).get_admin_state(), 'down')
def test_interface_description(self):
# Check if description can be added to interface and
# can be read back
for intf in self._interfaces:
test_string=f'Description-Test-{intf}'
self.cli_set(self._base_path + [intf, 'description', test_string])
for option in self._options.get(intf, []):
self.cli_set(self._base_path + [intf] + option.split())
self.cli_commit()
# Validate interface description
for intf in self._interfaces:
test_string=f'Description-Test-{intf}'
tmp = read_file(f'/sys/class/net/{intf}/ifalias')
self.assertEqual(tmp, test_string)
self.assertEqual(Interface(intf).get_alias(), test_string)
self.cli_delete(self._base_path + [intf, 'description'])
self.cli_commit()
# Validate remove interface description "empty"
for intf in self._interfaces:
tmp = read_file(f'/sys/class/net/{intf}/ifalias')
self.assertEqual(tmp, str())
self.assertEqual(Interface(intf).get_alias(), str())
# Test maximum interface description lengt (255 characters)
test_string='abcdefghijklmnopqrstuvwxyz0123456789abcdefghijklmnopqrstuvwxyz0123456789abcdefghijklmnopqrstuvwxyz0123456789abcdefghijklmnopqrstuvwxyz0123456789abcdefghijklmnopqrstuvwxyz0123456789abcdefghijklmnopqrstuvwxyz0123456789abcdefghijklmnopqrstuvwxyz0123456789___'
for intf in self._interfaces:
self.cli_set(self._base_path + [intf, 'description', test_string])
for option in self._options.get(intf, []):
self.cli_set(self._base_path + [intf] + option.split())
self.cli_commit()
# Validate interface description
for intf in self._interfaces:
tmp = read_file(f'/sys/class/net/{intf}/ifalias')
self.assertEqual(tmp, test_string)
self.assertEqual(Interface(intf).get_alias(), test_string)
def test_add_single_ip_address(self):
addr = '192.0.2.0/31'
for intf in self._interfaces:
self.cli_set(self._base_path + [intf, 'address', addr])
for option in self._options.get(intf, []):
self.cli_set(self._base_path + [intf] + option.split())
self.cli_commit()
for intf in self._interfaces:
self.assertTrue(is_intf_addr_assigned(intf, addr))
self.assertEqual(Interface(intf).get_admin_state(), 'up')
def test_add_multiple_ip_addresses(self):
# Add address
for intf in self._interfaces:
for option in self._options.get(intf, []):
self.cli_set(self._base_path + [intf] + option.split())
for addr in self._test_addr:
self.cli_set(self._base_path + [intf, 'address', addr])
self.cli_commit()
# Validate address
for intf in self._interfaces:
for af in AF_INET, AF_INET6:
for addr in ifaddresses(intf)[af]:
# checking link local addresses makes no sense
if is_ipv6_link_local(addr['addr']):
continue
self.assertTrue(is_intf_addr_assigned(intf, addr['addr']))
def test_ipv6_link_local_address(self):
# Common function for IPv6 link-local address assignemnts
if not self._test_ipv6:
self.skipTest('not supported')
for interface in self._interfaces:
base = self._base_path + [interface]
# just set the interface base without any option - some interfaces
# (VTI) do not require any option to be brought up
self.cli_set(base)
for option in self._options.get(interface, []):
self.cli_set(base + option.split())
# after commit we must have an IPv6 link-local address
self.cli_commit()
for interface in self._interfaces:
self.assertIn(AF_INET6, ifaddresses(interface))
for addr in ifaddresses(interface)[AF_INET6]:
self.assertTrue(is_ipv6_link_local(addr['addr']))
# disable IPv6 link-local address assignment
for interface in self._interfaces:
base = self._base_path + [interface]
self.cli_set(base + ['ipv6', 'address', 'no-default-link-local'])
# after commit we must have no IPv6 link-local address
self.cli_commit()
for interface in self._interfaces:
self.assertNotIn(AF_INET6, ifaddresses(interface))
def test_interface_mtu(self):
if not self._test_mtu:
self.skipTest('not supported')
for intf in self._interfaces:
base = self._base_path + [intf]
self.cli_set(base + ['mtu', self._mtu])
for option in self._options.get(intf, []):
self.cli_set(base + option.split())
# commit interface changes
self.cli_commit()
# verify changed MTU
for intf in self._interfaces:
tmp = get_interface_config(intf)
self.assertEqual(tmp['mtu'], int(self._mtu))
def test_mtu_1200_no_ipv6_interface(self):
# Testcase if MTU can be changed to 1200 on non IPv6
# enabled interfaces
if not self._test_mtu:
self.skipTest('not supported')
old_mtu = self._mtu
self._mtu = '1200'
for intf in self._interfaces:
base = self._base_path + [intf]
for option in self._options.get(intf, []):
self.cli_set(base + option.split())
self.cli_set(base + ['mtu', self._mtu])
# check validate() - can not set low MTU if 'no-default-link-local'
# is not set on CLI
with self.assertRaises(ConfigSessionError):
self.cli_commit()
for intf in self._interfaces:
base = self._base_path + [intf]
self.cli_set(base + ['ipv6', 'address', 'no-default-link-local'])
# commit interface changes
self.cli_commit()
# verify changed MTU
for intf in self._interfaces:
tmp = get_interface_config(intf)
self.assertEqual(tmp['mtu'], int(self._mtu))
self._mtu = old_mtu
def test_vif_8021q_interfaces(self):
# XXX: This testcase is not allowed to run as first testcase, reason
# is the Wireless test will first load the wifi kernel hwsim module
# which creates a wlan0 and wlan1 interface which will fail the
# tearDown() test in the end that no interface is allowed to survive!
if not self._test_vlan:
self.skipTest('not supported')
for interface in self._interfaces:
base = self._base_path + [interface]
for option in self._options.get(interface, []):
self.cli_set(base + option.split())
for vlan in self._vlan_range:
base = self._base_path + [interface, 'vif', vlan]
for address in self._test_addr:
self.cli_set(base + ['address', address])
self.cli_commit()
for intf in self._interfaces:
for vlan in self._vlan_range:
vif = f'{intf}.{vlan}'
for address in self._test_addr:
self.assertTrue(is_intf_addr_assigned(vif, address))
self.assertEqual(Interface(vif).get_admin_state(), 'up')
# T4064: Delete interface addresses, keep VLAN interface
for interface in self._interfaces:
base = self._base_path + [interface]
for vlan in self._vlan_range:
base = self._base_path + [interface, 'vif', vlan]
self.cli_delete(base + ['address'])
self.cli_commit()
# Verify no IP address is assigned
for interface in self._interfaces:
for vlan in self._vlan_range:
vif = f'{intf}.{vlan}'
for address in self._test_addr:
self.assertFalse(is_intf_addr_assigned(vif, address))
def test_vif_8021q_mtu_limits(self):
# XXX: This testcase is not allowed to run as first testcase, reason
# is the Wireless test will first load the wifi kernel hwsim module
# which creates a wlan0 and wlan1 interface which will fail the
# tearDown() test in the end that no interface is allowed to survive!
if not self._test_vlan or not self._test_mtu:
self.skipTest('not supported')
mtu_1500 = '1500'
mtu_9000 = '9000'
for interface in self._interfaces:
base = self._base_path + [interface]
self.cli_set(base + ['mtu', mtu_1500])
for option in self._options.get(interface, []):
self.cli_set(base + option.split())
if 'source-interface' in option:
iface = option.split()[-1]
iface_type = Section.section(iface)
self.cli_set(['interfaces', iface_type, iface, 'mtu', mtu_9000])
for vlan in self._vlan_range:
base = self._base_path + [interface, 'vif', vlan]
self.cli_set(base + ['mtu', mtu_9000])
# check validate() - Interface MTU "9000" too high, parent interface MTU is "1500"!
with self.assertRaises(ConfigSessionError):
self.cli_commit()
# Change MTU on base interface to be the same as on the VIF interface
for interface in self._interfaces:
base = self._base_path + [interface]
self.cli_set(base + ['mtu', mtu_9000])
self.cli_commit()
# Verify MTU on base and VIF interfaces
for interface in self._interfaces:
tmp = get_interface_config(interface)
self.assertEqual(tmp['mtu'], int(mtu_9000))
for vlan in self._vlan_range:
tmp = get_interface_config(f'{interface}.{vlan}')
self.assertEqual(tmp['mtu'], int(mtu_9000))
def test_vif_8021q_qos_change(self):
# XXX: This testcase is not allowed to run as first testcase, reason
# is the Wireless test will first load the wifi kernel hwsim module
# which creates a wlan0 and wlan1 interface which will fail the
# tearDown() test in the end that no interface is allowed to survive!
if not self._test_vlan:
self.skipTest('not supported')
for interface in self._interfaces:
base = self._base_path + [interface]
for option in self._options.get(interface, []):
self.cli_set(base + option.split())
for vlan in self._vlan_range:
base = self._base_path + [interface, 'vif', vlan]
self.cli_set(base + ['ingress-qos', '0:1'])
self.cli_set(base + ['egress-qos', '1:6'])
self.cli_commit()
for intf in self._interfaces:
for vlan in self._vlan_range:
vif = f'{intf}.{vlan}'
tmp = get_interface_config(f'{vif}')
tmp2 = dict_search('linkinfo.info_data.ingress_qos', tmp)
for item in tmp2 if tmp2 else []:
from_key = item['from']
to_key = item['to']
self.assertEqual(from_key, 0)
self.assertEqual(to_key, 1)
tmp2 = dict_search('linkinfo.info_data.egress_qos', tmp)
for item in tmp2 if tmp2 else []:
from_key = item['from']
to_key = item['to']
self.assertEqual(from_key, 1)
self.assertEqual(to_key, 6)
self.assertEqual(Interface(vif).get_admin_state(), 'up')
new_ingress_qos_from = 1
new_ingress_qos_to = 6
new_egress_qos_from = 2
new_egress_qos_to = 7
for interface in self._interfaces:
base = self._base_path + [interface]
for vlan in self._vlan_range:
base = self._base_path + [interface, 'vif', vlan]
self.cli_set(base + ['ingress-qos', f'{new_ingress_qos_from}:{new_ingress_qos_to}'])
self.cli_set(base + ['egress-qos', f'{new_egress_qos_from}:{new_egress_qos_to}'])
self.cli_commit()
for intf in self._interfaces:
for vlan in self._vlan_range:
vif = f'{intf}.{vlan}'
tmp = get_interface_config(f'{vif}')
tmp2 = dict_search('linkinfo.info_data.ingress_qos', tmp)
if tmp2:
from_key = tmp2[0]['from']
to_key = tmp2[0]['to']
self.assertEqual(from_key, new_ingress_qos_from)
self.assertEqual(to_key, new_ingress_qos_to)
tmp2 = dict_search('linkinfo.info_data.egress_qos', tmp)
if tmp2:
from_key = tmp2[0]['from']
to_key = tmp2[0]['to']
self.assertEqual(from_key, new_egress_qos_from)
self.assertEqual(to_key, new_egress_qos_to)
def test_vif_8021q_lower_up_down(self):
# Testcase for https://vyos.dev/T3349
if not self._test_vlan:
self.skipTest('not supported')
for interface in self._interfaces:
base = self._base_path + [interface]
for option in self._options.get(interface, []):
self.cli_set(base + option.split())
# disable the lower interface
self.cli_set(base + ['disable'])
for vlan in self._vlan_range:
vlan_base = self._base_path + [interface, 'vif', vlan]
# disable the vlan interface
self.cli_set(vlan_base + ['disable'])
self.cli_commit()
# re-enable all lower interfaces
for interface in self._interfaces:
base = self._base_path + [interface]
self.cli_delete(base + ['disable'])
self.cli_commit()
# verify that the lower interfaces are admin up and the vlan
# interfaces are all admin down
for interface in self._interfaces:
self.assertEqual(Interface(interface).get_admin_state(), 'up')
for vlan in self._vlan_range:
ifname = f'{interface}.{vlan}'
self.assertEqual(Interface(ifname).get_admin_state(), 'down')
def test_vif_s_8021ad_vlan_interfaces(self):
# XXX: This testcase is not allowed to run as first testcase, reason
# is the Wireless test will first load the wifi kernel hwsim module
# which creates a wlan0 and wlan1 interface which will fail the
# tearDown() test in the end that no interface is allowed to survive!
if not self._test_qinq:
self.skipTest('not supported')
for interface in self._interfaces:
base = self._base_path + [interface]
for option in self._options.get(interface, []):
self.cli_set(base + option.split())
for vif_s in self._qinq_range:
for vif_c in self._vlan_range:
base = self._base_path + [interface, 'vif-s', vif_s, 'vif-c', vif_c]
self.cli_set(base + ['mtu', self._mtu])
for address in self._test_addr:
self.cli_set(base + ['address', address])
self.cli_commit()
for interface in self._interfaces:
for vif_s in self._qinq_range:
tmp = get_interface_config(f'{interface}.{vif_s}')
self.assertEqual(dict_search('linkinfo.info_data.protocol', tmp), '802.1ad')
for vif_c in self._vlan_range:
vif = f'{interface}.{vif_s}.{vif_c}'
# For an unknown reason this regularely fails on the QEMU builds,
# thus the test for reading back IP addresses is temporary
# disabled. There is no big deal here, as this uses the same
# methods on 802.1q and here it works and is verified.
# for address in self._test_addr:
# self.assertTrue(is_intf_addr_assigned(vif, address))
tmp = get_interface_config(vif)
self.assertEqual(tmp['mtu'], int(self._mtu))
# T4064: Delete interface addresses, keep VLAN interface
for interface in self._interfaces:
base = self._base_path + [interface]
for vif_s in self._qinq_range:
for vif_c in self._vlan_range:
self.cli_delete(self._base_path + [interface, 'vif-s', vif_s, 'vif-c', vif_c, 'address'])
self.cli_commit()
# Verify no IP address is assigned
for interface in self._interfaces:
base = self._base_path + [interface]
for vif_s in self._qinq_range:
for vif_c in self._vlan_range:
vif = f'{interface}.{vif_s}.{vif_c}'
for address in self._test_addr:
self.assertFalse(is_intf_addr_assigned(vif, address))
# T3972: remove vif-c interfaces from vif-s
for interface in self._interfaces:
base = self._base_path + [interface]
for vif_s in self._qinq_range:
base = self._base_path + [interface, 'vif-s', vif_s, 'vif-c']
self.cli_delete(base)
self.cli_commit()
def test_vif_s_protocol_change(self):
# XXX: This testcase is not allowed to run as first testcase, reason
# is the Wireless test will first load the wifi kernel hwsim module
# which creates a wlan0 and wlan1 interface which will fail the
# tearDown() test in the end that no interface is allowed to survive!
if not self._test_qinq:
self.skipTest('not supported')
for interface in self._interfaces:
base = self._base_path + [interface]
for option in self._options.get(interface, []):
self.cli_set(base + option.split())
for vif_s in self._qinq_range:
for vif_c in self._vlan_range:
base = self._base_path + [interface, 'vif-s', vif_s, 'vif-c', vif_c]
for address in self._test_addr:
self.cli_set(base + ['address', address])
self.cli_commit()
for interface in self._interfaces:
for vif_s in self._qinq_range:
tmp = get_interface_config(f'{interface}.{vif_s}')
# check for the default value
self.assertEqual(tmp['linkinfo']['info_data']['protocol'], '802.1ad')
# T3532: now change ethertype
new_protocol = '802.1q'
for interface in self._interfaces:
for vif_s in self._qinq_range:
base = self._base_path + [interface, 'vif-s', vif_s]
self.cli_set(base + ['protocol', new_protocol])
self.cli_commit()
# Verify new ethertype configuration
for interface in self._interfaces:
for vif_s in self._qinq_range:
tmp = get_interface_config(f'{interface}.{vif_s}')
self.assertEqual(tmp['linkinfo']['info_data']['protocol'], new_protocol.upper())
def test_interface_ip_options(self):
if not self._test_ip:
self.skipTest('not supported')
arp_tmo = '300'
mss = '1420'
for interface in self._interfaces:
path = self._base_path + [interface]
for option in self._options.get(interface, []):
self.cli_set(path + option.split())
# Options
if cli_defined(self._base_path + ['ip'], 'adjust-mss'):
self.cli_set(path + ['ip', 'adjust-mss', mss])
if cli_defined(self._base_path + ['ip'], 'arp-cache-timeout'):
self.cli_set(path + ['ip', 'arp-cache-timeout', arp_tmo])
if cli_defined(self._base_path + ['ip'], 'disable-arp-filter'):
self.cli_set(path + ['ip', 'disable-arp-filter'])
if cli_defined(self._base_path + ['ip'], 'disable-forwarding'):
self.cli_set(path + ['ip', 'disable-forwarding'])
if cli_defined(self._base_path + ['ip'], 'enable-directed-broadcast'):
self.cli_set(path + ['ip', 'enable-directed-broadcast'])
if cli_defined(self._base_path + ['ip'], 'enable-arp-accept'):
self.cli_set(path + ['ip', 'enable-arp-accept'])
if cli_defined(self._base_path + ['ip'], 'enable-arp-announce'):
self.cli_set(path + ['ip', 'enable-arp-announce'])
if cli_defined(self._base_path + ['ip'], 'enable-arp-ignore'):
self.cli_set(path + ['ip', 'enable-arp-ignore'])
if cli_defined(self._base_path + ['ip'], 'enable-proxy-arp'):
self.cli_set(path + ['ip', 'enable-proxy-arp'])
if cli_defined(self._base_path + ['ip'], 'proxy-arp-pvlan'):
self.cli_set(path + ['ip', 'proxy-arp-pvlan'])
if cli_defined(self._base_path + ['ip'], 'source-validation'):
self.cli_set(path + ['ip', 'source-validation', 'loose'])
self.cli_commit()
for interface in self._interfaces:
if cli_defined(self._base_path + ['ip'], 'adjust-mss'):
base_options = f'oifname "{interface}"'
out = cmd('sudo nft list chain raw VYOS_TCP_MSS')
for line in out.splitlines():
if line.startswith(base_options):
self.assertIn(f'tcp option maxseg size set {mss}', line)
if cli_defined(self._base_path + ['ip'], 'arp-cache-timeout'):
tmp = read_file(f'/proc/sys/net/ipv4/neigh/{interface}/base_reachable_time_ms')
self.assertEqual(tmp, str((int(arp_tmo) * 1000))) # tmo value is in milli seconds
proc_base = f'/proc/sys/net/ipv4/conf/{interface}'
if cli_defined(self._base_path + ['ip'], 'disable-arp-filter'):
tmp = read_file(f'{proc_base}/arp_filter')
self.assertEqual('0', tmp)
if cli_defined(self._base_path + ['ip'], 'enable-arp-accept'):
tmp = read_file(f'{proc_base}/arp_accept')
self.assertEqual('1', tmp)
if cli_defined(self._base_path + ['ip'], 'enable-arp-announce'):
tmp = read_file(f'{proc_base}/arp_announce')
self.assertEqual('1', tmp)
if cli_defined(self._base_path + ['ip'], 'enable-arp-ignore'):
tmp = read_file(f'{proc_base}/arp_ignore')
self.assertEqual('1', tmp)
if cli_defined(self._base_path + ['ip'], 'disable-forwarding'):
tmp = read_file(f'{proc_base}/forwarding')
self.assertEqual('0', tmp)
if cli_defined(self._base_path + ['ip'], 'enable-directed-broadcast'):
tmp = read_file(f'{proc_base}/bc_forwarding')
self.assertEqual('1', tmp)
if cli_defined(self._base_path + ['ip'], 'enable-proxy-arp'):
tmp = read_file(f'{proc_base}/proxy_arp')
self.assertEqual('1', tmp)
if cli_defined(self._base_path + ['ip'], 'proxy-arp-pvlan'):
tmp = read_file(f'{proc_base}/proxy_arp_pvlan')
self.assertEqual('1', tmp)
if cli_defined(self._base_path + ['ip'], 'source-validation'):
base_options = f'iifname "{interface}"'
out = cmd('sudo nft list chain ip raw vyos_rpfilter')
for line in out.splitlines():
if line.startswith(base_options):
self.assertIn('fib saddr oif 0', line)
self.assertIn('drop', line)
def test_interface_ipv6_options(self):
if not self._test_ipv6:
self.skipTest('not supported')
mss = '1400'
dad_transmits = '10'
accept_dad = '0'
source_validation = 'strict'
for interface in self._interfaces:
path = self._base_path + [interface]
for option in self._options.get(interface, []):
self.cli_set(path + option.split())
# Options
if cli_defined(self._base_path + ['ipv6'], 'adjust-mss'):
self.cli_set(path + ['ipv6', 'adjust-mss', mss])
if cli_defined(self._base_path + ['ipv6'], 'accept-dad'):
self.cli_set(path + ['ipv6', 'accept-dad', accept_dad])
if cli_defined(self._base_path + ['ipv6'], 'dup-addr-detect-transmits'):
self.cli_set(path + ['ipv6', 'dup-addr-detect-transmits', dad_transmits])
if cli_defined(self._base_path + ['ipv6'], 'disable-forwarding'):
self.cli_set(path + ['ipv6', 'disable-forwarding'])
if cli_defined(self._base_path + ['ipv6'], 'source-validation'):
self.cli_set(path + ['ipv6', 'source-validation', source_validation])
self.cli_commit()
for interface in self._interfaces:
proc_base = f'/proc/sys/net/ipv6/conf/{interface}'
if cli_defined(self._base_path + ['ipv6'], 'adjust-mss'):
base_options = f'oifname "{interface}"'
out = cmd('sudo nft list chain ip6 raw VYOS_TCP_MSS')
for line in out.splitlines():
if line.startswith(base_options):
self.assertIn(f'tcp option maxseg size set {mss}', line)
if cli_defined(self._base_path + ['ipv6'], 'accept-dad'):
tmp = read_file(f'{proc_base}/accept_dad')
self.assertEqual(accept_dad, tmp)
if cli_defined(self._base_path + ['ipv6'], 'dup-addr-detect-transmits'):
tmp = read_file(f'{proc_base}/dad_transmits')
self.assertEqual(dad_transmits, tmp)
if cli_defined(self._base_path + ['ipv6'], 'disable-forwarding'):
tmp = read_file(f'{proc_base}/forwarding')
self.assertEqual('0', tmp)
if cli_defined(self._base_path + ['ipv6'], 'source-validation'):
base_options = f'iifname "{interface}"'
out = cmd('sudo nft list chain ip6 raw vyos_rpfilter')
for line in out.splitlines():
if line.startswith(base_options):
self.assertIn('fib saddr . iif oif 0', line)
self.assertIn('drop', line)
def test_dhcpv6_client_options(self):
if not self._test_ipv6_dhcpc6:
self.skipTest('not supported')
duid_base = 10
for interface in self._interfaces:
duid = '00:01:00:01:27:71:db:f0:00:50:00:00:00:{}'.format(duid_base)
path = self._base_path + [interface]
for option in self._options.get(interface, []):
self.cli_set(path + option.split())
# Enable DHCPv6 client
self.cli_set(path + ['address', 'dhcpv6'])
self.cli_set(path + ['dhcpv6-options', 'no-release'])
self.cli_set(path + ['dhcpv6-options', 'rapid-commit'])
self.cli_set(path + ['dhcpv6-options', 'parameters-only'])
self.cli_set(path + ['dhcpv6-options', 'duid', duid])
duid_base += 1
self.cli_commit()
duid_base = 10
for interface in self._interfaces:
duid = '00:01:00:01:27:71:db:f0:00:50:00:00:00:{}'.format(duid_base)
dhcpc6_config = read_file(f'{dhcp6c_base_dir}/dhcp6c.{interface}.conf')
self.assertIn(f'interface {interface} ' + '{', dhcpc6_config)
self.assertIn(f' request domain-name-servers;', dhcpc6_config)
self.assertIn(f' request domain-name;', dhcpc6_config)
self.assertIn(f' information-only;', dhcpc6_config)
self.assertIn(f' send ia-na 0;', dhcpc6_config)
self.assertIn(f' send rapid-commit;', dhcpc6_config)
self.assertIn(f' send client-id {duid};', dhcpc6_config)
self.assertIn('};', dhcpc6_config)
duid_base += 1
# Better ask the process about it's commandline in the future
pid = process_named_running(dhcp6c_process_name, cmdline=interface, timeout=10)
self.assertTrue(pid)
dhcp6c_options = read_file(f'/proc/{pid}/cmdline')
self.assertIn('-n', dhcp6c_options)
def test_dhcpv6pd_auto_sla_id(self):
if not self._test_ipv6_pd:
self.skipTest('not supported')
prefix_len = '56'
sla_len = str(64 - int(prefix_len))
# Create delegatee interfaces first to avoid any confusion by dhcpc6
# this is mainly an "issue" with virtual-ethernet interfaces
delegatees = ['dum2340', 'dum2341', 'dum2342', 'dum2343', 'dum2344']
for delegatee in delegatees:
section = Section.section(delegatee)
self.cli_set(['interfaces', section, delegatee])
self.cli_commit()
for interface in self._interfaces:
path = self._base_path + [interface]
for option in self._options.get(interface, []):
self.cli_set(path + option.split())
address = '1'
# prefix delegation stuff
pd_base = path + ['dhcpv6-options', 'pd', '0']
self.cli_set(pd_base + ['length', prefix_len])
for delegatee in delegatees:
self.cli_set(pd_base + ['interface', delegatee, 'address', address])
# increment interface address
address = str(int(address) + 1)
self.cli_commit()
for interface in self._interfaces:
dhcpc6_config = read_file(f'{dhcp6c_base_dir}/dhcp6c.{interface}.conf')
# verify DHCPv6 prefix delegation
self.assertIn(f'prefix ::/{prefix_len} infinity;', dhcpc6_config)
address = '1'
sla_id = '0'
for delegatee in delegatees:
self.assertIn(f'prefix-interface {delegatee}' + r' {', dhcpc6_config)
self.assertIn(f'ifid {address};', dhcpc6_config)
self.assertIn(f'sla-id {sla_id};', dhcpc6_config)
self.assertIn(f'sla-len {sla_len};', dhcpc6_config)
# increment sla-id
sla_id = str(int(sla_id) + 1)
# increment interface address
address = str(int(address) + 1)
# Check for running process
self.assertTrue(process_named_running(dhcp6c_process_name, cmdline=interface, timeout=10))
for delegatee in delegatees:
# we can already cleanup the test delegatee interface here
# as until commit() is called, nothing happens
section = Section.section(delegatee)
self.cli_delete(['interfaces', section, delegatee])
def test_dhcpv6pd_manual_sla_id(self):
if not self._test_ipv6_pd:
self.skipTest('not supported')
prefix_len = '56'
sla_len = str(64 - int(prefix_len))
# Create delegatee interfaces first to avoid any confusion by dhcpc6
# this is mainly an "issue" with virtual-ethernet interfaces
delegatees = ['dum3340', 'dum3341', 'dum3342', 'dum3343', 'dum3344']
for delegatee in delegatees:
section = Section.section(delegatee)
self.cli_set(['interfaces', section, delegatee])
self.cli_commit()
for interface in self._interfaces:
path = self._base_path + [interface]
for option in self._options.get(interface, []):
self.cli_set(path + option.split())
# prefix delegation stuff
address = '1'
sla_id = '1'
pd_base = path + ['dhcpv6-options', 'pd', '0']
self.cli_set(pd_base + ['length', prefix_len])
for delegatee in delegatees:
self.cli_set(pd_base + ['interface', delegatee, 'address', address])
self.cli_set(pd_base + ['interface', delegatee, 'sla-id', sla_id])
# increment interface address
address = str(int(address) + 1)
sla_id = str(int(sla_id) + 1)
self.cli_commit()
# Verify dhcpc6 client configuration
for interface in self._interfaces:
address = '1'
sla_id = '1'
dhcpc6_config = read_file(f'{dhcp6c_base_dir}/dhcp6c.{interface}.conf')
# verify DHCPv6 prefix delegation
self.assertIn(f'prefix ::/{prefix_len} infinity;', dhcpc6_config)
for delegatee in delegatees:
self.assertIn(f'prefix-interface {delegatee}' + r' {', dhcpc6_config)
self.assertIn(f'ifid {address};', dhcpc6_config)
self.assertIn(f'sla-id {sla_id};', dhcpc6_config)
self.assertIn(f'sla-len {sla_len};', dhcpc6_config)
# increment sla-id
sla_id = str(int(sla_id) + 1)
# increment interface address
address = str(int(address) + 1)
# Check for running process
self.assertTrue(process_named_running(dhcp6c_process_name, cmdline=interface, timeout=10))
for delegatee in delegatees:
# we can already cleanup the test delegatee interface here
# as until commit() is called, nothing happens
section = Section.section(delegatee)
self.cli_delete(['interfaces', section, delegatee])
diff --git a/smoketest/scripts/cli/test_protocols_static.py b/smoketest/scripts/cli/test_protocols_static.py
index c5cf2aab6..f676e2a52 100755
--- a/smoketest/scripts/cli/test_protocols_static.py
+++ b/smoketest/scripts/cli/test_protocols_static.py
@@ -1,481 +1,482 @@
#!/usr/bin/env python3
#
# Copyright (C) 2021-2024 VyOS maintainers and contributors
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License version 2 or later as
# published by the Free Software Foundation.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
import unittest
from base_vyostest_shim import VyOSUnitTestSHIM
from vyos.configsession import ConfigSessionError
from vyos.template import is_ipv6
from vyos.utils.network import get_interface_config
+from vyos.utils.network import get_vrf_tableid
base_path = ['protocols', 'static']
vrf_path = ['protocols', 'vrf']
routes = {
'10.0.0.0/8' : {
'next_hop' : {
'192.0.2.100' : { 'distance' : '100' },
'192.0.2.110' : { 'distance' : '110', 'interface' : 'eth0' },
'192.0.2.120' : { 'distance' : '120', 'disable' : '' },
'192.0.2.130' : { 'bfd' : '' },
'192.0.2.140' : { 'bfd_source' : '192.0.2.10' },
},
'interface' : {
'eth0' : { 'distance' : '130' },
'eth1' : { 'distance' : '140' },
},
'blackhole' : { 'distance' : '250', 'tag' : '500' },
},
'172.16.0.0/12' : {
'interface' : {
'eth0' : { 'distance' : '50', 'vrf' : 'black' },
'eth1' : { 'distance' : '60', 'vrf' : 'black' },
},
'blackhole' : { 'distance' : '90' },
},
'192.0.2.0/24' : {
'interface' : {
'eth0' : { 'distance' : '50', 'vrf' : 'black' },
'eth1' : { 'disable' : '' },
},
'blackhole' : { 'distance' : '90' },
},
'100.64.0.0/16' : {
'blackhole' : {},
},
'100.65.0.0/16' : {
'reject' : { 'distance' : '10', 'tag' : '200' },
},
'100.66.0.0/16' : {
'blackhole' : {},
'reject' : { 'distance' : '10', 'tag' : '200' },
},
'2001:db8:100::/40' : {
'next_hop' : {
'2001:db8::1' : { 'distance' : '10' },
'2001:db8::2' : { 'distance' : '20', 'interface' : 'eth0' },
'2001:db8::3' : { 'distance' : '30', 'disable' : '' },
'2001:db8::4' : { 'bfd' : '' },
'2001:db8::5' : { 'bfd_source' : '2001:db8::ffff' },
},
'interface' : {
'eth0' : { 'distance' : '40', 'vrf' : 'black' },
'eth1' : { 'distance' : '50', 'disable' : '' },
},
'blackhole' : { 'distance' : '250', 'tag' : '500' },
},
'2001:db8:200::/40' : {
'interface' : {
'eth0' : { 'distance' : '40' },
'eth1' : { 'distance' : '50', 'disable' : '' },
},
'blackhole' : { 'distance' : '250', 'tag' : '500' },
},
'2001:db8:300::/40' : {
'reject' : { 'distance' : '250', 'tag' : '500' },
},
'2001:db8:400::/40' : {
'next_hop' : {
'2001:db8::400' : { 'segments' : '2001:db8:aaaa::400/2002::400/2003::400/2004::400' },
},
},
'2001:db8:500::/40' : {
'next_hop' : {
'2001:db8::500' : { 'segments' : '2001:db8:aaaa::500/2002::500/2003::500/2004::500' },
},
},
'2001:db8:600::/40' : {
'interface' : {
'eth0' : { 'segments' : '2001:db8:aaaa::600/2002::600' },
},
},
'2001:db8:700::/40' : {
'interface' : {
'eth1' : { 'segments' : '2001:db8:aaaa::700' },
},
},
'2001:db8::/32' : {
'blackhole' : { 'distance' : '200', 'tag' : '600' }
},
}
tables = ['80', '81', '82']
class TestProtocolsStatic(VyOSUnitTestSHIM.TestCase):
@classmethod
def setUpClass(cls):
super(TestProtocolsStatic, cls).setUpClass()
cls.cli_delete(cls, ['vrf'])
cls.cli_set(cls, ['vrf', 'name', 'black', 'table', '43210'])
@classmethod
def tearDownClass(cls):
cls.cli_delete(cls, ['vrf'])
super(TestProtocolsStatic, cls).tearDownClass()
def tearDown(self):
self.cli_delete(base_path)
self.cli_commit()
v4route = self.getFRRconfig('ip route', end='')
self.assertFalse(v4route)
v6route = self.getFRRconfig('ipv6 route', end='')
self.assertFalse(v6route)
def test_01_static(self):
bfd_profile = 'vyos-test'
for route, route_config in routes.items():
route_type = 'route'
if is_ipv6(route):
route_type = 'route6'
base = base_path + [route_type, route]
if 'next_hop' in route_config:
for next_hop, next_hop_config in route_config['next_hop'].items():
self.cli_set(base + ['next-hop', next_hop])
if 'disable' in next_hop_config:
self.cli_set(base + ['next-hop', next_hop, 'disable'])
if 'distance' in next_hop_config:
self.cli_set(base + ['next-hop', next_hop, 'distance', next_hop_config['distance']])
if 'interface' in next_hop_config:
self.cli_set(base + ['next-hop', next_hop, 'interface', next_hop_config['interface']])
if 'vrf' in next_hop_config:
self.cli_set(base + ['next-hop', next_hop, 'vrf', next_hop_config['vrf']])
if 'bfd' in next_hop_config:
self.cli_set(base + ['next-hop', next_hop, 'bfd', 'profile', bfd_profile ])
if 'bfd_source' in next_hop_config:
self.cli_set(base + ['next-hop', next_hop, 'bfd', 'multi-hop', 'source', next_hop_config['bfd_source'], 'profile', bfd_profile])
if 'segments' in next_hop_config:
self.cli_set(base + ['next-hop', next_hop, 'segments', next_hop_config['segments']])
if 'interface' in route_config:
for interface, interface_config in route_config['interface'].items():
self.cli_set(base + ['interface', interface])
if 'disable' in interface_config:
self.cli_set(base + ['interface', interface, 'disable'])
if 'distance' in interface_config:
self.cli_set(base + ['interface', interface, 'distance', interface_config['distance']])
if 'vrf' in interface_config:
self.cli_set(base + ['interface', interface, 'vrf', interface_config['vrf']])
if 'segments' in interface_config:
self.cli_set(base + ['interface', interface, 'segments', interface_config['segments']])
if 'blackhole' in route_config:
self.cli_set(base + ['blackhole'])
if 'distance' in route_config['blackhole']:
self.cli_set(base + ['blackhole', 'distance', route_config['blackhole']['distance']])
if 'tag' in route_config['blackhole']:
self.cli_set(base + ['blackhole', 'tag', route_config['blackhole']['tag']])
if 'reject' in route_config:
self.cli_set(base + ['reject'])
if 'distance' in route_config['reject']:
self.cli_set(base + ['reject', 'distance', route_config['reject']['distance']])
if 'tag' in route_config['reject']:
self.cli_set(base + ['reject', 'tag', route_config['reject']['tag']])
if {'blackhole', 'reject'} <= set(route_config):
# Can not use blackhole and reject at the same time
with self.assertRaises(ConfigSessionError):
self.cli_commit()
self.cli_delete(base + ['blackhole'])
self.cli_delete(base + ['reject'])
# commit changes
self.cli_commit()
# Verify FRR bgpd configuration
frrconfig = self.getFRRconfig('ip route', end='')
# Verify routes
for route, route_config in routes.items():
ip_ipv6 = 'ip'
if is_ipv6(route):
ip_ipv6 = 'ipv6'
if 'next_hop' in route_config:
for next_hop, next_hop_config in route_config['next_hop'].items():
tmp = f'{ip_ipv6} route {route} {next_hop}'
if 'interface' in next_hop_config:
tmp += ' ' + next_hop_config['interface']
if 'distance' in next_hop_config:
tmp += ' ' + next_hop_config['distance']
if 'vrf' in next_hop_config:
tmp += ' nexthop-vrf ' + next_hop_config['vrf']
if 'bfd' in next_hop_config:
tmp += ' bfd profile ' + bfd_profile
if 'bfd_source' in next_hop_config:
tmp += ' bfd multi-hop source ' + next_hop_config['bfd_source'] + ' profile ' + bfd_profile
if 'segments' in next_hop_config:
tmp += ' segments ' + next_hop_config['segments']
if 'disable' in next_hop_config:
self.assertNotIn(tmp, frrconfig)
else:
self.assertIn(tmp, frrconfig)
if 'interface' in route_config:
for interface, interface_config in route_config['interface'].items():
tmp = f'{ip_ipv6} route {route} {interface}'
if 'interface' in interface_config:
tmp += ' ' + interface_config['interface']
if 'distance' in interface_config:
tmp += ' ' + interface_config['distance']
if 'vrf' in interface_config:
tmp += ' nexthop-vrf ' + interface_config['vrf']
if 'segments' in interface_config:
tmp += ' segments ' + interface_config['segments']
if 'disable' in interface_config:
self.assertNotIn(tmp, frrconfig)
else:
self.assertIn(tmp, frrconfig)
if {'blackhole', 'reject'} <= set(route_config):
# Can not use blackhole and reject at the same time
# Config error validated above - skip this route
continue
if 'blackhole' in route_config:
tmp = f'{ip_ipv6} route {route} blackhole'
if 'tag' in route_config['blackhole']:
tmp += ' tag ' + route_config['blackhole']['tag']
if 'distance' in route_config['blackhole']:
tmp += ' ' + route_config['blackhole']['distance']
self.assertIn(tmp, frrconfig)
if 'reject' in route_config:
tmp = f'{ip_ipv6} route {route} reject'
if 'tag' in route_config['reject']:
tmp += ' tag ' + route_config['reject']['tag']
if 'distance' in route_config['reject']:
tmp += ' ' + route_config['reject']['distance']
self.assertIn(tmp, frrconfig)
def test_02_static_table(self):
for table in tables:
for route, route_config in routes.items():
route_type = 'route'
if is_ipv6(route):
route_type = 'route6'
base = base_path + ['table', table, route_type, route]
if 'next_hop' in route_config:
for next_hop, next_hop_config in route_config['next_hop'].items():
self.cli_set(base + ['next-hop', next_hop])
if 'disable' in next_hop_config:
self.cli_set(base + ['next-hop', next_hop, 'disable'])
if 'distance' in next_hop_config:
self.cli_set(base + ['next-hop', next_hop, 'distance', next_hop_config['distance']])
if 'interface' in next_hop_config:
self.cli_set(base + ['next-hop', next_hop, 'interface', next_hop_config['interface']])
if 'vrf' in next_hop_config:
self.cli_set(base + ['next-hop', next_hop, 'vrf', next_hop_config['vrf']])
if 'interface' in route_config:
for interface, interface_config in route_config['interface'].items():
self.cli_set(base + ['interface', interface])
if 'disable' in interface_config:
self.cli_set(base + ['interface', interface, 'disable'])
if 'distance' in interface_config:
self.cli_set(base + ['interface', interface, 'distance', interface_config['distance']])
if 'vrf' in interface_config:
self.cli_set(base + ['interface', interface, 'vrf', interface_config['vrf']])
if 'blackhole' in route_config:
self.cli_set(base + ['blackhole'])
if 'distance' in route_config['blackhole']:
self.cli_set(base + ['blackhole', 'distance', route_config['blackhole']['distance']])
if 'tag' in route_config['blackhole']:
self.cli_set(base + ['blackhole', 'tag', route_config['blackhole']['tag']])
# commit changes
self.cli_commit()
# Verify FRR bgpd configuration
frrconfig = self.getFRRconfig('ip route', end='')
for table in tables:
# Verify routes
for route, route_config in routes.items():
ip_ipv6 = 'ip'
if is_ipv6(route):
ip_ipv6 = 'ipv6'
if 'next_hop' in route_config:
for next_hop, next_hop_config in route_config['next_hop'].items():
tmp = f'{ip_ipv6} route {route} {next_hop}'
if 'interface' in next_hop_config:
tmp += ' ' + next_hop_config['interface']
if 'distance' in next_hop_config:
tmp += ' ' + next_hop_config['distance']
if 'vrf' in next_hop_config:
tmp += ' nexthop-vrf ' + next_hop_config['vrf']
tmp += ' table ' + table
if 'disable' in next_hop_config:
self.assertNotIn(tmp, frrconfig)
else:
self.assertIn(tmp, frrconfig)
if 'interface' in route_config:
for interface, interface_config in route_config['interface'].items():
tmp = f'{ip_ipv6} route {route} {interface}'
if 'interface' in interface_config:
tmp += ' ' + interface_config['interface']
if 'distance' in interface_config:
tmp += ' ' + interface_config['distance']
if 'vrf' in interface_config:
tmp += ' nexthop-vrf ' + interface_config['vrf']
tmp += ' table ' + table
if 'disable' in interface_config:
self.assertNotIn(tmp, frrconfig)
else:
self.assertIn(tmp, frrconfig)
if 'blackhole' in route_config:
tmp = f'{ip_ipv6} route {route} blackhole'
if 'tag' in route_config['blackhole']:
tmp += ' tag ' + route_config['blackhole']['tag']
if 'distance' in route_config['blackhole']:
tmp += ' ' + route_config['blackhole']['distance']
tmp += ' table ' + table
self.assertIn(tmp, frrconfig)
def test_03_static_vrf(self):
# Create VRF instances and apply the static routes from above to FRR.
# Re-read the configured routes and match them if they are programmed
# properly. This also includes VRF leaking
vrfs = {
'red' : { 'table' : '1000' },
'green' : { 'table' : '2000' },
'blue' : { 'table' : '3000' },
}
for vrf, vrf_config in vrfs.items():
vrf_base_path = ['vrf', 'name', vrf]
self.cli_set(vrf_base_path + ['table', vrf_config['table']])
for route, route_config in routes.items():
route_type = 'route'
if is_ipv6(route):
route_type = 'route6'
route_base_path = vrf_base_path + ['protocols', 'static', route_type, route]
if 'next_hop' in route_config:
for next_hop, next_hop_config in route_config['next_hop'].items():
self.cli_set(route_base_path + ['next-hop', next_hop])
if 'disable' in next_hop_config:
self.cli_set(route_base_path + ['next-hop', next_hop, 'disable'])
if 'distance' in next_hop_config:
self.cli_set(route_base_path + ['next-hop', next_hop, 'distance', next_hop_config['distance']])
if 'interface' in next_hop_config:
self.cli_set(route_base_path + ['next-hop', next_hop, 'interface', next_hop_config['interface']])
if 'vrf' in next_hop_config:
self.cli_set(route_base_path + ['next-hop', next_hop, 'vrf', next_hop_config['vrf']])
if 'segments' in next_hop_config:
self.cli_set(route_base_path + ['next-hop', next_hop, 'segments', next_hop_config['segments']])
if 'interface' in route_config:
for interface, interface_config in route_config['interface'].items():
self.cli_set(route_base_path + ['interface', interface])
if 'disable' in interface_config:
self.cli_set(route_base_path + ['interface', interface, 'disable'])
if 'distance' in interface_config:
self.cli_set(route_base_path + ['interface', interface, 'distance', interface_config['distance']])
if 'vrf' in interface_config:
self.cli_set(route_base_path + ['interface', interface, 'vrf', interface_config['vrf']])
if 'segments' in interface_config:
self.cli_set(route_base_path + ['interface', interface, 'segments', interface_config['segments']])
if 'blackhole' in route_config:
self.cli_set(route_base_path + ['blackhole'])
if 'distance' in route_config['blackhole']:
self.cli_set(route_base_path + ['blackhole', 'distance', route_config['blackhole']['distance']])
if 'tag' in route_config['blackhole']:
self.cli_set(route_base_path + ['blackhole', 'tag', route_config['blackhole']['tag']])
# commit changes
self.cli_commit()
for vrf, vrf_config in vrfs.items():
tmp = get_interface_config(vrf)
# Compare VRF table ID
- self.assertEqual(tmp['linkinfo']['info_data']['table'], int(vrf_config['table']))
+ self.assertEqual(get_vrf_tableid(vrf), int(vrf_config['table']))
self.assertEqual(tmp['linkinfo']['info_kind'], 'vrf')
# Verify FRR bgpd configuration
frrconfig = self.getFRRconfig(f'vrf {vrf}')
self.assertIn(f'vrf {vrf}', frrconfig)
# Verify routes
for route, route_config in routes.items():
ip_ipv6 = 'ip'
if is_ipv6(route):
ip_ipv6 = 'ipv6'
if 'next_hop' in route_config:
for next_hop, next_hop_config in route_config['next_hop'].items():
tmp = f'{ip_ipv6} route {route} {next_hop}'
if 'interface' in next_hop_config:
tmp += ' ' + next_hop_config['interface']
if 'distance' in next_hop_config:
tmp += ' ' + next_hop_config['distance']
if 'vrf' in next_hop_config:
tmp += ' nexthop-vrf ' + next_hop_config['vrf']
if 'segments' in next_hop_config:
tmp += ' segments ' + next_hop_config['segments']
if 'disable' in next_hop_config:
self.assertNotIn(tmp, frrconfig)
else:
self.assertIn(tmp, frrconfig)
if 'interface' in route_config:
for interface, interface_config in route_config['interface'].items():
tmp = f'{ip_ipv6} route {route} {interface}'
if 'interface' in interface_config:
tmp += ' ' + interface_config['interface']
if 'distance' in interface_config:
tmp += ' ' + interface_config['distance']
if 'vrf' in interface_config:
tmp += ' nexthop-vrf ' + interface_config['vrf']
if 'segments' in interface_config:
tmp += ' segments ' + interface_config['segments']
if 'disable' in interface_config:
self.assertNotIn(tmp, frrconfig)
else:
self.assertIn(tmp, frrconfig)
if 'blackhole' in route_config:
tmp = f'{ip_ipv6} route {route} blackhole'
if 'tag' in route_config['blackhole']:
tmp += ' tag ' + route_config['blackhole']['tag']
if 'distance' in route_config['blackhole']:
tmp += ' ' + route_config['blackhole']['distance']
self.assertIn(tmp, frrconfig)
if __name__ == '__main__':
- unittest.main(verbosity=2)
+ unittest.main(verbosity=2, failfast=True)
diff --git a/smoketest/scripts/cli/test_vrf.py b/smoketest/scripts/cli/test_vrf.py
index 243397dc2..176882ca5 100755
--- a/smoketest/scripts/cli/test_vrf.py
+++ b/smoketest/scripts/cli/test_vrf.py
@@ -1,584 +1,583 @@
#!/usr/bin/env python3
#
# Copyright (C) 2020-2024 VyOS maintainers and contributors
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License version 2 or later as
# published by the Free Software Foundation.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
import re
import os
import unittest
from base_vyostest_shim import VyOSUnitTestSHIM
from vyos.configsession import ConfigSessionError
from vyos.ifconfig import Interface
from vyos.ifconfig import Section
from vyos.utils.file import read_file
from vyos.utils.network import get_interface_config
+from vyos.utils.network import get_vrf_tableid
from vyos.utils.network import is_intf_addr_assigned
from vyos.utils.network import interface_exists
from vyos.utils.system import sysctl_read
base_path = ['vrf']
vrfs = ['red', 'green', 'blue', 'foo-bar', 'baz_foo']
v4_protocols = ['any', 'babel', 'bgp', 'connected', 'eigrp', 'isis', 'kernel', 'ospf', 'rip', 'static', 'table']
v6_protocols = ['any', 'babel', 'bgp', 'connected', 'isis', 'kernel', 'ospfv3', 'ripng', 'static', 'table']
class VRFTest(VyOSUnitTestSHIM.TestCase):
_interfaces = []
@classmethod
def setUpClass(cls):
# we need to filter out VLAN interfaces identified by a dot (.)
# in their name - just in case!
if 'TEST_ETH' in os.environ:
tmp = os.environ['TEST_ETH'].split()
cls._interfaces = tmp
else:
for tmp in Section.interfaces('ethernet', vlan=False):
cls._interfaces.append(tmp)
# call base-classes classmethod
super(VRFTest, cls).setUpClass()
def setUp(self):
# VRF strict_most ist always enabled
tmp = read_file('/proc/sys/net/vrf/strict_mode')
self.assertEqual(tmp, '1')
def tearDown(self):
# delete all VRFs
self.cli_delete(base_path)
self.cli_commit()
for vrf in vrfs:
self.assertFalse(interface_exists(vrf))
def test_vrf_vni_and_table_id(self):
base_table = '1000'
table = base_table
for vrf in vrfs:
base = base_path + ['name', vrf]
description = f'VyOS-VRF-{vrf}'
self.cli_set(base + ['description', description])
# check validate() - a table ID is mandatory
with self.assertRaises(ConfigSessionError):
self.cli_commit()
self.cli_set(base + ['table', table])
self.cli_set(base + ['vni', table])
if vrf == 'green':
self.cli_set(base + ['disable'])
table = str(int(table) + 1)
# commit changes
self.cli_commit()
# Verify VRF configuration
table = base_table
iproute2_config = read_file('/etc/iproute2/rt_tables.d/vyos-vrf.conf')
for vrf in vrfs:
description = f'VyOS-VRF-{vrf}'
self.assertTrue(interface_exists(vrf))
vrf_if = Interface(vrf)
# validate proper interface description
self.assertEqual(vrf_if.get_alias(), description)
# validate admin up/down state of VRF
state = 'up'
if vrf == 'green':
state = 'down'
self.assertEqual(vrf_if.get_admin_state(), state)
# Test the iproute2 lookup file, syntax is as follows:
#
# # id vrf name comment
# 1000 red # VyOS-VRF-red
# 1001 green # VyOS-VRF-green
# ...
regex = f'{table}\s+{vrf}\s+#\s+{description}'
self.assertTrue(re.findall(regex, iproute2_config))
frrconfig = self.getFRRconfig(f'vrf {vrf}')
self.assertIn(f' vni {table}', frrconfig)
- tmp = get_interface_config(vrf)
- self.assertEqual(int(table), tmp['linkinfo']['info_data']['table'])
+ self.assertEqual(int(table), get_vrf_tableid(vrf))
# Increment table ID for the next run
table = str(int(table) + 1)
def test_vrf_loopbacks_ips(self):
table = '2000'
for vrf in vrfs:
base = base_path + ['name', vrf]
self.cli_set(base + ['table', str(table)])
table = str(int(table) + 1)
# commit changes
self.cli_commit()
# Verify VRF configuration
loopbacks = ['127.0.0.1', '::1']
for vrf in vrfs:
# Ensure VRF was created
self.assertTrue(interface_exists(vrf))
# Verify IP forwarding is 1 (enabled)
self.assertEqual(sysctl_read(f'net.ipv4.conf.{vrf}.forwarding'), '1')
self.assertEqual(sysctl_read(f'net.ipv6.conf.{vrf}.forwarding'), '1')
# Test for proper loopback IP assignment
for addr in loopbacks:
self.assertTrue(is_intf_addr_assigned(vrf, addr))
def test_vrf_bind_all(self):
table = '2000'
for vrf in vrfs:
base = base_path + ['name', vrf]
self.cli_set(base + ['table', str(table)])
table = str(int(table) + 1)
self.cli_set(base_path + ['bind-to-all'])
# commit changes
self.cli_commit()
# Verify VRF configuration
self.assertEqual(sysctl_read('net.ipv4.tcp_l3mdev_accept'), '1')
self.assertEqual(sysctl_read('net.ipv4.udp_l3mdev_accept'), '1')
# If there is any VRF defined, strict_mode should be on
self.assertEqual(sysctl_read('net.vrf.strict_mode'), '1')
def test_vrf_table_id_is_unalterable(self):
# Linux Kernel prohibits the change of a VRF table on the fly.
# VRF must be deleted and recreated!
table = '1000'
vrf = vrfs[0]
base = base_path + ['name', vrf]
self.cli_set(base + ['table', table])
# commit changes
self.cli_commit()
# Check if VRF has been created
self.assertTrue(interface_exists(vrf))
table = str(int(table) + 1)
self.cli_set(base + ['table', table])
# check validate() - table ID can not be altered!
with self.assertRaises(ConfigSessionError):
self.cli_commit()
def test_vrf_assign_interface(self):
vrf = vrfs[0]
table = '5000'
self.cli_set(['vrf', 'name', vrf, 'table', table])
for interface in self._interfaces:
section = Section.section(interface)
self.cli_set(['interfaces', section, interface, 'vrf', vrf])
# commit changes
self.cli_commit()
# Verify VRF assignmant
for interface in self._interfaces:
tmp = get_interface_config(interface)
self.assertEqual(vrf, tmp['master'])
# cleanup
section = Section.section(interface)
self.cli_delete(['interfaces', section, interface, 'vrf'])
def test_vrf_static_route(self):
base_table = '100'
table = base_table
for vrf in vrfs:
next_hop = f'192.0.{table}.1'
prefix = f'10.0.{table}.0/24'
base = base_path + ['name', vrf]
self.cli_set(base + ['vni', table])
# check validate() - a table ID is mandatory
with self.assertRaises(ConfigSessionError):
self.cli_commit()
self.cli_set(base + ['table', table])
self.cli_set(base + ['protocols', 'static', 'route', prefix, 'next-hop', next_hop])
table = str(int(table) + 1)
# commit changes
self.cli_commit()
# Verify VRF configuration
table = base_table
for vrf in vrfs:
next_hop = f'192.0.{table}.1'
prefix = f'10.0.{table}.0/24'
self.assertTrue(interface_exists(vrf))
frrconfig = self.getFRRconfig(f'vrf {vrf}')
self.assertIn(f' vni {table}', frrconfig)
self.assertIn(f' ip route {prefix} {next_hop}', frrconfig)
# Increment table ID for the next run
table = str(int(table) + 1)
def test_vrf_link_local_ip_addresses(self):
# Testcase for issue T4331
table = '100'
vrf = 'orange'
interface = 'dum9998'
addresses = ['192.0.2.1/26', '2001:db8:9998::1/64', 'fe80::1/64']
for address in addresses:
self.cli_set(['interfaces', 'dummy', interface, 'address', address])
# Create dummy interfaces
self.cli_commit()
# ... and verify IP addresses got assigned
for address in addresses:
self.assertTrue(is_intf_addr_assigned(interface, address))
# Move interface to VRF
self.cli_set(base_path + ['name', vrf, 'table', table])
self.cli_set(['interfaces', 'dummy', interface, 'vrf', vrf])
# Apply VRF config
self.cli_commit()
# Ensure VRF got created
self.assertTrue(interface_exists(vrf))
# ... and IP addresses are still assigned
for address in addresses:
self.assertTrue(is_intf_addr_assigned(interface, address))
# Verify VRF table ID
- tmp = get_interface_config(vrf)
- self.assertEqual(int(table), tmp['linkinfo']['info_data']['table'])
+ self.assertEqual(int(table), get_vrf_tableid(vrf))
# Verify interface is assigned to VRF
tmp = get_interface_config(interface)
self.assertEqual(vrf, tmp['master'])
# Delete Interface
self.cli_delete(['interfaces', 'dummy', interface])
self.cli_commit()
def test_vrf_disable_forwarding(self):
table = '2000'
for vrf in vrfs:
base = base_path + ['name', vrf]
self.cli_set(base + ['table', table])
self.cli_set(base + ['ip', 'disable-forwarding'])
self.cli_set(base + ['ipv6', 'disable-forwarding'])
table = str(int(table) + 1)
# commit changes
self.cli_commit()
# Verify VRF configuration
loopbacks = ['127.0.0.1', '::1']
for vrf in vrfs:
# Ensure VRF was created
self.assertTrue(interface_exists(vrf))
# Verify IP forwarding is 0 (disabled)
self.assertEqual(sysctl_read(f'net.ipv4.conf.{vrf}.forwarding'), '0')
self.assertEqual(sysctl_read(f'net.ipv6.conf.{vrf}.forwarding'), '0')
def test_vrf_ip_protocol_route_map(self):
table = '6000'
for vrf in vrfs:
base = base_path + ['name', vrf]
self.cli_set(base + ['table', table])
for protocol in v4_protocols:
self.cli_set(['policy', 'route-map', f'route-map-{vrf}-{protocol}', 'rule', '10', 'action', 'permit'])
self.cli_set(base + ['ip', 'protocol', protocol, 'route-map', f'route-map-{vrf}-{protocol}'])
table = str(int(table) + 1)
self.cli_commit()
# Verify route-map properly applied to FRR
for vrf in vrfs:
frrconfig = self.getFRRconfig(f'vrf {vrf}', daemon='zebra')
self.assertIn(f'vrf {vrf}', frrconfig)
for protocol in v4_protocols:
self.assertIn(f' ip protocol {protocol} route-map route-map-{vrf}-{protocol}', frrconfig)
# Delete route-maps
for vrf in vrfs:
base = base_path + ['name', vrf]
self.cli_delete(['policy', 'route-map', f'route-map-{vrf}-{protocol}'])
self.cli_delete(base + ['ip', 'protocol'])
self.cli_commit()
# Verify route-map properly is removed from FRR
for vrf in vrfs:
frrconfig = self.getFRRconfig(f'vrf {vrf}', daemon='zebra')
self.assertNotIn(f'vrf {vrf}', frrconfig)
def test_vrf_ip_ipv6_protocol_non_existing_route_map(self):
table = '6100'
non_existing = 'non-existing'
for vrf in vrfs:
base = base_path + ['name', vrf]
self.cli_set(base + ['table', table])
for protocol in v4_protocols:
self.cli_set(base + ['ip', 'protocol', protocol, 'route-map', f'v4-{non_existing}'])
for protocol in v6_protocols:
self.cli_set(base + ['ipv6', 'protocol', protocol, 'route-map', f'v6-{non_existing}'])
table = str(int(table) + 1)
# Both v4 and v6 route-maps do not exist yet
with self.assertRaises(ConfigSessionError):
self.cli_commit()
self.cli_set(['policy', 'route-map', f'v4-{non_existing}', 'rule', '10', 'action', 'deny'])
# v6 route-map does not exist yet
with self.assertRaises(ConfigSessionError):
self.cli_commit()
self.cli_set(['policy', 'route-map', f'v6-{non_existing}', 'rule', '10', 'action', 'deny'])
# Commit again
self.cli_commit()
def test_vrf_ipv6_protocol_route_map(self):
table = '6200'
for vrf in vrfs:
base = base_path + ['name', vrf]
self.cli_set(base + ['table', table])
for protocol in v6_protocols:
route_map = f'route-map-{vrf}-{protocol.replace("ospfv3", "ospf6")}'
self.cli_set(['policy', 'route-map', route_map, 'rule', '10', 'action', 'permit'])
self.cli_set(base + ['ipv6', 'protocol', protocol, 'route-map', route_map])
table = str(int(table) + 1)
self.cli_commit()
# Verify route-map properly applied to FRR
for vrf in vrfs:
frrconfig = self.getFRRconfig(f'vrf {vrf}', daemon='zebra')
self.assertIn(f'vrf {vrf}', frrconfig)
for protocol in v6_protocols:
# VyOS and FRR use a different name for OSPFv3 (IPv6)
if protocol == 'ospfv3':
protocol = 'ospf6'
route_map = f'route-map-{vrf}-{protocol}'
self.assertIn(f' ipv6 protocol {protocol} route-map {route_map}', frrconfig)
# Delete route-maps
for vrf in vrfs:
base = base_path + ['name', vrf]
self.cli_delete(['policy', 'route-map', f'route-map-{vrf}-{protocol}'])
self.cli_delete(base + ['ipv6', 'protocol'])
self.cli_commit()
# Verify route-map properly is removed from FRR
for vrf in vrfs:
frrconfig = self.getFRRconfig(f'vrf {vrf}', daemon='zebra')
self.assertNotIn(f'vrf {vrf}', frrconfig)
def test_vrf_vni_duplicates(self):
base_table = '6300'
table = base_table
for vrf in vrfs:
base = base_path + ['name', vrf]
self.cli_set(base + ['table', str(table)])
self.cli_set(base + ['vni', '100'])
table = str(int(table) + 1)
# L3VNIs can only be used once
with self.assertRaises(ConfigSessionError):
self.cli_commit()
table = base_table
for vrf in vrfs:
base = base_path + ['name', vrf]
self.cli_set(base + ['vni', str(table)])
table = str(int(table) + 1)
# commit changes
self.cli_commit()
# Verify VRF configuration
table = base_table
for vrf in vrfs:
self.assertTrue(interface_exists(vrf))
frrconfig = self.getFRRconfig(f'vrf {vrf}')
self.assertIn(f' vni {table}', frrconfig)
# Increment table ID for the next run
table = str(int(table) + 1)
def test_vrf_vni_add_change_remove(self):
base_table = '6300'
table = base_table
for vrf in vrfs:
base = base_path + ['name', vrf]
self.cli_set(base + ['table', str(table)])
self.cli_set(base + ['vni', str(table)])
table = str(int(table) + 1)
# commit changes
self.cli_commit()
# Verify VRF configuration
table = base_table
for vrf in vrfs:
self.assertTrue(interface_exists(vrf))
frrconfig = self.getFRRconfig(f'vrf {vrf}')
self.assertIn(f' vni {table}', frrconfig)
# Increment table ID for the next run
table = str(int(table) + 1)
# Now change all L3VNIs (increment 2)
# We must also change the base_table number as we probably could get
# duplicate VNI's during the test as VNIs are applied 1:1 to FRR
base_table = '5000'
table = base_table
for vrf in vrfs:
base = base_path + ['name', vrf]
self.cli_set(base + ['vni', str(table)])
table = str(int(table) + 2)
# commit changes
self.cli_commit()
# Verify VRF configuration
table = base_table
for vrf in vrfs:
self.assertTrue(interface_exists(vrf))
frrconfig = self.getFRRconfig(f'vrf {vrf}')
self.assertIn(f' vni {table}', frrconfig)
# Increment table ID for the next run
table = str(int(table) + 2)
# add a new VRF with VNI - this must not delete any existing VRF/VNI
purple = 'purple'
table = str(int(table) + 10)
self.cli_set(base_path + ['name', purple, 'table', table])
self.cli_set(base_path + ['name', purple, 'vni', table])
# commit changes
self.cli_commit()
# Verify VRF configuration
table = base_table
for vrf in vrfs:
self.assertTrue(interface_exists(vrf))
frrconfig = self.getFRRconfig(f'vrf {vrf}')
self.assertIn(f' vni {table}', frrconfig)
# Increment table ID for the next run
table = str(int(table) + 2)
# Verify purple VRF/VNI
self.assertTrue(interface_exists(purple))
table = str(int(table) + 10)
frrconfig = self.getFRRconfig(f'vrf {purple}')
self.assertIn(f' vni {table}', frrconfig)
# Now delete all the VNIs
for vrf in vrfs:
base = base_path + ['name', vrf]
self.cli_delete(base + ['vni'])
# commit changes
self.cli_commit()
# Verify no VNI is defined
for vrf in vrfs:
self.assertTrue(interface_exists(vrf))
frrconfig = self.getFRRconfig(f'vrf {vrf}')
self.assertNotIn('vni', frrconfig)
# Verify purple VNI remains
self.assertTrue(interface_exists(purple))
frrconfig = self.getFRRconfig(f'vrf {purple}')
self.assertIn(f' vni {table}', frrconfig)
def test_vrf_ip_ipv6_nht(self):
table = '6910'
for vrf in vrfs:
base = base_path + ['name', vrf]
self.cli_set(base + ['table', table])
self.cli_set(base + ['ip', 'nht', 'no-resolve-via-default'])
self.cli_set(base + ['ipv6', 'nht', 'no-resolve-via-default'])
table = str(int(table) + 1)
self.cli_commit()
# Verify route-map properly applied to FRR
for vrf in vrfs:
frrconfig = self.getFRRconfig(f'vrf {vrf}', daemon='zebra')
self.assertIn(f'vrf {vrf}', frrconfig)
self.assertIn(f' no ip nht resolve-via-default', frrconfig)
self.assertIn(f' no ipv6 nht resolve-via-default', frrconfig)
# Delete route-maps
for vrf in vrfs:
base = base_path + ['name', vrf]
self.cli_delete(base + ['ip'])
self.cli_delete(base + ['ipv6'])
self.cli_commit()
# Verify route-map properly is removed from FRR
for vrf in vrfs:
frrconfig = self.getFRRconfig(f'vrf {vrf}', daemon='zebra')
self.assertNotIn(f' no ip nht resolve-via-default', frrconfig)
self.assertNotIn(f' no ipv6 nht resolve-via-default', frrconfig)
def test_vrf_conntrack(self):
table = '1000'
nftables_rules = {
'vrf_zones_ct_in': ['ct original zone set iifname map @ct_iface_map'],
'vrf_zones_ct_out': ['ct original zone set oifname map @ct_iface_map']
}
self.cli_set(base_path + ['name', 'blue', 'table', table])
self.cli_commit()
# Conntrack rules should not be present
for chain, rule in nftables_rules.items():
self.verify_nftables_chain(rule, 'inet vrf_zones', chain, inverse=True)
self.cli_set(['nat'])
self.cli_commit()
# Conntrack rules should now be present
for chain, rule in nftables_rules.items():
self.verify_nftables_chain(rule, 'inet vrf_zones', chain, inverse=False)
self.cli_delete(['nat'])
if __name__ == '__main__':
unittest.main(verbosity=2)
diff --git a/src/conf_mode/vrf.py b/src/conf_mode/vrf.py
index 8d8c234c0..12edb7d02 100755
--- a/src/conf_mode/vrf.py
+++ b/src/conf_mode/vrf.py
@@ -1,349 +1,350 @@
#!/usr/bin/env python3
#
# Copyright (C) 2020-2024 VyOS maintainers and contributors
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License version 2 or later as
# published by the Free Software Foundation.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
from sys import exit
from json import loads
from vyos.config import Config
from vyos.configdict import dict_merge
from vyos.configdict import node_changed
from vyos.configverify import verify_route_map
from vyos.firewall import conntrack_required
from vyos.ifconfig import Interface
from vyos.template import render
from vyos.template import render_to_string
from vyos.utils.dict import dict_search
from vyos.utils.network import get_interface_config
+from vyos.utils.network import get_vrf_tableid
from vyos.utils.network import get_vrf_members
from vyos.utils.network import interface_exists
from vyos.utils.process import call
from vyos.utils.process import cmd
from vyos.utils.process import popen
from vyos.utils.system import sysctl_write
from vyos import ConfigError
from vyos import frr
from vyos import airbag
airbag.enable()
config_file = '/etc/iproute2/rt_tables.d/vyos-vrf.conf'
k_mod = ['vrf']
nftables_table = 'inet vrf_zones'
nftables_rules = {
'vrf_zones_ct_in': 'counter ct original zone set iifname map @ct_iface_map',
'vrf_zones_ct_out': 'counter ct original zone set oifname map @ct_iface_map'
}
def has_rule(af : str, priority : int, table : str=None):
"""
Check if a given ip rule exists
$ ip --json -4 rule show
[{'l3mdev': None, 'priority': 1000, 'src': 'all'},
{'action': 'unreachable', 'l3mdev': None, 'priority': 2000, 'src': 'all'},
{'priority': 32765, 'src': 'all', 'table': 'local'},
{'priority': 32766, 'src': 'all', 'table': 'main'},
{'priority': 32767, 'src': 'all', 'table': 'default'}]
"""
if af not in ['-4', '-6']:
raise ValueError()
command = f'ip --detail --json {af} rule show'
for tmp in loads(cmd(command)):
if 'priority' in tmp and 'table' in tmp:
if tmp['priority'] == priority and tmp['table'] == table:
return True
elif 'priority' in tmp and table in tmp:
# l3mdev table has a different layout
if tmp['priority'] == priority:
return True
return False
def vrf_interfaces(c, match):
matched = []
old_level = c.get_level()
c.set_level(['interfaces'])
section = c.get_config_dict([], get_first_key=True)
for type in section:
interfaces = section[type]
for name in interfaces:
interface = interfaces[name]
if 'vrf' in interface:
v = interface.get('vrf', '')
if v == match:
matched.append(name)
c.set_level(old_level)
return matched
def vrf_routing(c, match):
matched = []
old_level = c.get_level()
c.set_level(['protocols', 'vrf'])
if match in c.list_nodes([]):
matched.append(match)
c.set_level(old_level)
return matched
def get_config(config=None):
if config:
conf = config
else:
conf = Config()
base = ['vrf']
vrf = conf.get_config_dict(base, key_mangling=('-', '_'),
no_tag_node_value_mangle=True, get_first_key=True)
# determine which VRF has been removed
for name in node_changed(conf, base + ['name']):
if 'vrf_remove' not in vrf:
vrf.update({'vrf_remove' : {}})
vrf['vrf_remove'][name] = {}
# get VRF bound interfaces
interfaces = vrf_interfaces(conf, name)
if interfaces: vrf['vrf_remove'][name]['interface'] = interfaces
# get VRF bound routing instances
routes = vrf_routing(conf, name)
if routes: vrf['vrf_remove'][name]['route'] = routes
if 'name' in vrf:
vrf['conntrack'] = conntrack_required(conf)
# We also need the route-map information from the config
#
# XXX: one MUST always call this without the key_mangling() option! See
# vyos.configverify.verify_common_route_maps() for more information.
tmp = {'policy' : {'route-map' : conf.get_config_dict(['policy', 'route-map'],
get_first_key=True)}}
# Merge policy dict into "regular" config dict
vrf = dict_merge(tmp, vrf)
return vrf
def verify(vrf):
# ensure VRF is not assigned to any interface
if 'vrf_remove' in vrf:
for name, config in vrf['vrf_remove'].items():
if 'interface' in config:
raise ConfigError(f'Can not remove VRF "{name}", it still has '\
f'member interfaces!')
if 'route' in config:
raise ConfigError(f'Can not remove VRF "{name}", it still has '\
f'static routes installed!')
if 'name' in vrf:
reserved_names = ["add", "all", "broadcast", "default", "delete", "dev",
"get", "inet", "mtu", "link", "type", "vrf"]
table_ids = []
for name, vrf_config in vrf['name'].items():
# Reserved VRF names
if name in reserved_names:
raise ConfigError(f'VRF name "{name}" is reserved and connot be used!')
# table id is mandatory
if 'table' not in vrf_config:
raise ConfigError(f'VRF "{name}" table id is mandatory!')
# routing table id can't be changed - OS restriction
if interface_exists(name):
- tmp = str(dict_search('linkinfo.info_data.table', get_interface_config(name)))
- if tmp and tmp != vrf_config['table']:
+ tmp = get_vrf_tableid(name)
+ if tmp and tmp != int(vrf_config['table']):
raise ConfigError(f'VRF "{name}" table id modification not possible!')
# VRF routing table ID must be unique on the system
if 'table' in vrf_config and vrf_config['table'] in table_ids:
raise ConfigError(f'VRF "{name}" table id is not unique!')
table_ids.append(vrf_config['table'])
tmp = dict_search('ip.protocol', vrf_config)
if tmp != None:
for protocol, protocol_options in tmp.items():
if 'route_map' in protocol_options:
verify_route_map(protocol_options['route_map'], vrf)
tmp = dict_search('ipv6.protocol', vrf_config)
if tmp != None:
for protocol, protocol_options in tmp.items():
if 'route_map' in protocol_options:
verify_route_map(protocol_options['route_map'], vrf)
return None
def generate(vrf):
# Render iproute2 VR helper names
render(config_file, 'iproute2/vrf.conf.j2', vrf)
# Render VRF Kernel/Zebra route-map filters
vrf['frr_zebra_config'] = render_to_string('frr/zebra.vrf.route-map.frr.j2', vrf)
return None
def apply(vrf):
# Documentation
#
# - https://github.com/torvalds/linux/blob/master/Documentation/networking/vrf.txt
# - https://github.com/Mellanox/mlxsw/wiki/Virtual-Routing-and-Forwarding-(VRF)
# - https://github.com/Mellanox/mlxsw/wiki/L3-Tunneling
# - https://netdevconf.info/1.1/proceedings/slides/ahern-vrf-tutorial.pdf
# - https://netdevconf.info/1.2/slides/oct6/02_ahern_what_is_l3mdev_slides.pdf
# set the default VRF global behaviour
bind_all = '0'
if 'bind_to_all' in vrf:
bind_all = '1'
sysctl_write('net.ipv4.tcp_l3mdev_accept', bind_all)
sysctl_write('net.ipv4.udp_l3mdev_accept', bind_all)
for tmp in (dict_search('vrf_remove', vrf) or []):
if interface_exists(tmp):
# T5492: deleting a VRF instance may leafe processes running
# (e.g. dhclient) as there is a depedency ordering issue in the CLI.
# We need to ensure that we stop the dhclient processes first so
# a proper DHCLP RELEASE message is sent
for interface in get_vrf_members(tmp):
vrf_iface = Interface(interface)
vrf_iface.set_dhcp(False)
vrf_iface.set_dhcpv6(False)
# Remove nftables conntrack zone map item
nft_del_element = f'delete element inet vrf_zones ct_iface_map {{ "{tmp}" }}'
# Check if deleting is possible first to avoid raising errors
_, err = popen(f'nft --check {nft_del_element}')
if not err:
# Remove map element
cmd(f'nft {nft_del_element}')
# Delete the VRF Kernel interface
call(f'ip link delete dev {tmp}')
if 'name' in vrf:
# Linux routing uses rules to find tables - routing targets are then
# looked up in those tables. If the lookup got a matching route, the
# process ends.
#
# TL;DR; first table with a matching entry wins!
#
# You can see your routing table lookup rules using "ip rule", sadly the
# local lookup is hit before any VRF lookup. Pinging an addresses from the
# VRF will usually find a hit in the local table, and never reach the VRF
# routing table - this is usually not what you want. Thus we will
# re-arrange the tables and move the local lookup further down once VRFs
# are enabled.
#
# Thanks to https://stbuehler.de/blog/article/2020/02/29/using_vrf__virtual_routing_and_forwarding__on_linux.html
for afi in ['-4', '-6']:
# move lookup local to pref 32765 (from 0)
if not has_rule(afi, 32765, 'local'):
call(f'ip {afi} rule add pref 32765 table local')
if has_rule(afi, 0, 'local'):
call(f'ip {afi} rule del pref 0')
# make sure that in VRFs after failed lookup in the VRF specific table
# nothing else is reached
if not has_rule(afi, 1000, 'l3mdev'):
# this should be added by the kernel when a VRF is created
# add it here for completeness
call(f'ip {afi} rule add pref 1000 l3mdev protocol kernel')
# add another rule with an unreachable target which only triggers in VRF context
# if a route could not be reached
if not has_rule(afi, 2000, 'l3mdev'):
call(f'ip {afi} rule add pref 2000 l3mdev unreachable')
for name, config in vrf['name'].items():
table = config['table']
if not interface_exists(name):
# For each VRF apart from your default context create a VRF
# interface with a separate routing table
call(f'ip link add {name} type vrf table {table}')
# set VRF description for e.g. SNMP monitoring
vrf_if = Interface(name)
# We also should add proper loopback IP addresses to the newly added
# VRF for services bound to the loopback address (SNMP, NTP)
vrf_if.add_addr('127.0.0.1/8')
vrf_if.add_addr('::1/128')
# add VRF description if available
vrf_if.set_alias(config.get('description', ''))
# Enable/Disable IPv4 forwarding
tmp = dict_search('ip.disable_forwarding', config)
value = '0' if (tmp != None) else '1'
vrf_if.set_ipv4_forwarding(value)
# Enable/Disable IPv6 forwarding
tmp = dict_search('ipv6.disable_forwarding', config)
value = '0' if (tmp != None) else '1'
vrf_if.set_ipv6_forwarding(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'
vrf_if.set_admin_state(state)
# Add nftables conntrack zone map item
nft_add_element = f'add element inet vrf_zones ct_iface_map {{ "{name}" : {table} }}'
cmd(f'nft {nft_add_element}')
if vrf['conntrack']:
for chain, rule in nftables_rules.items():
cmd(f'nft add rule inet vrf_zones {chain} {rule}')
if 'name' not in vrf or not vrf['conntrack']:
for chain, rule in nftables_rules.items():
cmd(f'nft flush chain inet vrf_zones {chain}')
# Return default ip rule values
if 'name' not in vrf:
for afi in ['-4', '-6']:
# move lookup local to pref 0 (from 32765)
if not has_rule(afi, 0, 'local'):
call(f'ip {afi} rule add pref 0 from all lookup local')
if has_rule(afi, 32765, 'local'):
call(f'ip {afi} rule del pref 32765 table local')
if has_rule(afi, 1000, 'l3mdev'):
call(f'ip {afi} rule del pref 1000 l3mdev protocol kernel')
if has_rule(afi, 2000, 'l3mdev'):
call(f'ip {afi} rule del pref 2000 l3mdev unreachable')
# Apply FRR filters
zebra_daemon = 'zebra'
# Save original configuration prior to starting any commit actions
frr_cfg = frr.FRRConfig()
# The route-map used for the FIB (zebra) is part of the zebra daemon
frr_cfg.load_configuration(zebra_daemon)
frr_cfg.modify_section(f'^vrf .+', stop_pattern='^exit-vrf', remove_stop_mark=True)
if 'frr_zebra_config' in vrf:
frr_cfg.add_before(frr.default_add_before, vrf['frr_zebra_config'])
frr_cfg.commit_configuration(zebra_daemon)
return None
if __name__ == '__main__':
try:
c = get_config()
verify(c)
generate(c)
apply(c)
except ConfigError as e:
print(e)
exit(1)
File Metadata
Details
Attached
Mime Type
text/x-diff
Expires
Thu, Nov 26, 7:49 PM (20 h, 41 m)
Storage Engine
blob
Storage Format
Raw Data
Storage Handle
4970528
Default Alt Text
(204 KB)
Attached To
Mode
rVYOSONEX vyos-1x
Attached
Detach File
Event Timeline
Log In to Comment