From bac758ad16b7cfa855eb977af8f50f4b9b0639d7 Mon Sep 17 00:00:00 2001 From: Ruben Herold Date: Mon, 2 Nov 2026 10:38:50 +0100 Subject: utils: T9322: reject addresses that are not a single address and honour zone indexes The helper that tells whether an address is assigned to an interface accepted ranges and addresses with a zone index. A range ended in a traceback. A zone index was ignored, so an address on the loopback interface was reported as assigned to the interface named in the zone. The helper now rejects everything that is not a single address, a zone index included. The functions that look for an address on all interfaces use the zone to pick the one interface to check, so a zone that names an interface which does not hold the address is no longer accepted. The command that lists the addresses is passed as a list, so the interface name and the namespace do not reach a shell. Unit tests and a smoketest cover the cases. --- python/vyos/utils/network.py | 74 +++++++++++++++++++++++++++++++------------- 1 file changed, 53 insertions(+), 21 deletions(-) (limited to 'python') diff --git a/python/vyos/utils/network.py b/python/vyos/utils/network.py index c7304d15b..84e0c3b0c 100644 --- a/python/vyos/utils/network.py +++ b/python/vyos/utils/network.py @@ -521,7 +521,9 @@ def is_addr_assigned( from vyos.template import is_ipv4 from vyos.template import is_ipv6 - if allow_nonlocal: + # An address with a zone index ("fe80::1%eth0") is always looked up on the + # interface it names, nonlocal bind does not apply to it. + if allow_nonlocal and '%' not in ip_address: if is_ipv4(ip_address) and \ sysctl_read(['net', 'ipv4', 'ip_nonlocal_bind']) == '1': return True @@ -529,7 +531,14 @@ def is_addr_assigned( sysctl_read(['net', 'ipv6', 'ip_nonlocal_bind']) == '1': return True - for interface in interfaces(): + # A zone index ("fe80::1%eth0") names the one interface the address has to + # be assigned to. It still has to pass the VRF filter below. + candidates = interfaces() + if '%' in ip_address: + ip_address, zone = ip_address.split('%', 1) + candidates = [zone] if zone in candidates else [] + + for interface in candidates: # Only an interface of the requested VRF may satisfy the lookup - an # enslaved interface and a VRF device alike belong to their own L3 # domain, not to the default one. Naming the VRF device is the way to @@ -549,33 +558,50 @@ def is_addr_assigned( 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 + It can check both a single IP address (e.g. 192.0.2.1) or an assigned CIDR address 192.0.2.1/24. + + A zone index ("%interface" suffix) is rejected - the interface to check + against is this function's own argument. """ import jmespath from vyos.utils.process import rc_cmd - from vyos.template import is_ipv4 - from vyos.template import is_ipv6 + from vyos.template import is_ip from ipaddress import ip_interface - if not is_ipv4(addr) and not is_ipv6(addr): + # A zone index is a caller-side mistake, not bad operator input: the + # interface to check against is already an argument of this function. Keep + # it separate from the address check so the two are told apart. Note that + # is_ip() does not cover this - the ipaddress module accepts a zone index + # since Python 3.9, while "ip --json address show" never reports one, so + # such a value could only ever match by ignoring the zone, which reported + # an address as assigned to the wrong interface. + if '%' in addr: + raise ValueError(f'{addr} carries a zone index, pass the interface as "ifname"') + if not is_ip(addr): + raise ValueError(f'{addr} is not a valid IPv4 or IPv6 address') + + # Pass the command as a list and let rc_cmd() enter the namespace, so + # neither ifname nor netns reach a shell + rc, out = rc_cmd(['ip', '--json', 'address', 'show', 'dev', ifname], netns=netns) + if rc != 0: return False - 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 = loads(out) - addresses = jmespath.search("[].addr_info[].{family: family, address: local, prefixlen: prefixlen}", json_out) - for address_info in addresses: - 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 + wanted = ip_interface(addr) + addresses = jmespath.search( + '[].addr_info[].{address: local, prefixlen: prefixlen}', loads(out) + ) + # An address without a prefix length matches on the address alone, however + # it is written (2001:0DB8::1 is 2001:db8::1) and whatever prefix length it + # is assigned with. A CIDR address has to match the prefix length as well. + with_prefix = '/' in addr + for address_info in addresses or []: + address = address_info['address'] + prefixlen = address_info['prefixlen'] + assigned = ip_interface(f'{address}/{prefixlen}') + if (wanted == assigned) if with_prefix else (wanted.ip == assigned.ip): + return True return False @@ -893,8 +919,14 @@ def get_interfaces_by_ip(ip_address: str, vrf=None, include_vrf: bool = False) - import netifaces from vyos.utils.dict import dict_search + # A zone index names the one interface to look at, see is_addr_assigned() + candidates = netifaces.interfaces() + if '%' in ip_address: + ip_address, zone = ip_address.split('%', 1) + candidates = [zone] if zone in candidates else [] + ifaces = [] - for interface in netifaces.interfaces(): + for interface in candidates: # Only an interface of the requested VRF may satisfy the lookup - an # enslaved interface and a VRF device alike belong to their own L3 # domain, not to the default one. Naming the VRF device is the way to -- cgit v1.2.3 From 589f2e5552e8508dcc21fcc488ffc25a17e8f91f Mon Sep 17 00:00:00 2001 From: Christian Breunig Date: Sun, 8 Nov 2026 08:50:45 +0100 Subject: utils: T9322: simplify address assignment lookup and document ValueError The lookup for an address on all interfaces carried a copy of the zone index and VRF filtering that already exists in the lookup returning the matching interfaces. It now delegates to it, so the two cannot drift. The per-interface address match is written as a single condition, the comments are trimmed, and the docstrings state that anything but a single address raises ValueError instead of being reported as not assigned. The sflow zone index smoketest removes the dummy interface it creates, and the unit tests drop a stale task reference and a duplicate import. --- python/vyos/utils/network.py | 74 ++++++++---------------------- smoketest/scripts/cli/test_system_sflow.py | 2 + src/tests/test_utils_network.py | 4 +- 3 files changed, 21 insertions(+), 59 deletions(-) (limited to 'python') diff --git a/python/vyos/utils/network.py b/python/vyos/utils/network.py index 84e0c3b0c..f69a463f3 100644 --- a/python/vyos/utils/network.py +++ b/python/vyos/utils/network.py @@ -513,16 +513,16 @@ def is_ipv6_link_local(addr): def is_addr_assigned( ip_address: str, vrf=None, include_vrf=False, allow_nonlocal: bool = False ) -> bool: - """ Verify if the given IPv4/IPv6 address is assigned to any interface """ - from netifaces import interfaces # pylint: disable = no-name-in-module - from vyos.utils.network import get_interface_config - from vyos.utils.dict import dict_search + """ + Verify if the given IPv4/IPv6 address is assigned to any interface. + + Raises ValueError if ip_address is not a single address. + """ from vyos.utils.system import sysctl_read from vyos.template import is_ipv4 from vyos.template import is_ipv6 - # An address with a zone index ("fe80::1%eth0") is always looked up on the - # interface it names, nonlocal bind does not apply to it. + # A zone index pins the address to one interface, nonlocal bind does not apply if allow_nonlocal and '%' not in ip_address: if is_ipv4(ip_address) and \ sysctl_read(['net', 'ipv4', 'ip_nonlocal_bind']) == '1': @@ -531,38 +531,15 @@ def is_addr_assigned( sysctl_read(['net', 'ipv6', 'ip_nonlocal_bind']) == '1': return True - # A zone index ("fe80::1%eth0") names the one interface the address has to - # be assigned to. It still has to pass the VRF filter below. - candidates = interfaces() - if '%' in ip_address: - ip_address, zone = ip_address.split('%', 1) - candidates = [zone] if zone in candidates else [] - - for interface in candidates: - # Only an interface of the requested VRF may satisfy the lookup - an - # enslaved interface and a VRF device alike belong to their own L3 - # domain, not to the default one. Naming the VRF device is the way to - # ask for the addresses it carries itself. - if not include_vrf and interface != vrf: - tmp = get_interface_config(interface) - if dict_search('master', tmp) != vrf: - continue - if dict_search('linkinfo.info_kind', tmp) == 'vrf': - continue - - if is_intf_addr_assigned(interface, ip_address): - return True - - return False + return bool(get_interfaces_by_ip(ip_address, vrf=vrf, include_vrf=include_vrf)) 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 an assigned CIDR - address 192.0.2.1/24. + Verify if the given IPv4/IPv6 address is assigned to a specific interface. + A plain address (192.0.2.1) matches whatever prefix length it is assigned + with, a CIDR address (192.0.2.1/24) has to match the prefix length as well. - A zone index ("%interface" suffix) is rejected - the interface to check - against is this function's own argument. + Raises ValueError if addr is not a single address or carries a zone index. """ import jmespath @@ -570,37 +547,20 @@ def is_intf_addr_assigned(ifname: str, addr: str, netns: str=None) -> bool: from vyos.template import is_ip from ipaddress import ip_interface - # A zone index is a caller-side mistake, not bad operator input: the - # interface to check against is already an argument of this function. Keep - # it separate from the address check so the two are told apart. Note that - # is_ip() does not cover this - the ipaddress module accepts a zone index - # since Python 3.9, while "ip --json address show" never reports one, so - # such a value could only ever match by ignoring the zone, which reported - # an address as assigned to the wrong interface. + # ipaddress accepts "fe80::1%eth0" - the interface to check is ifname if '%' in addr: raise ValueError(f'{addr} carries a zone index, pass the interface as "ifname"') if not is_ip(addr): raise ValueError(f'{addr} is not a valid IPv4 or IPv6 address') - # Pass the command as a list and let rc_cmd() enter the namespace, so - # neither ifname nor netns reach a shell rc, out = rc_cmd(['ip', '--json', 'address', 'show', 'dev', ifname], netns=netns) if rc != 0: return False wanted = ip_interface(addr) - addresses = jmespath.search( - '[].addr_info[].{address: local, prefixlen: prefixlen}', loads(out) - ) - # An address without a prefix length matches on the address alone, however - # it is written (2001:0DB8::1 is 2001:db8::1) and whatever prefix length it - # is assigned with. A CIDR address has to match the prefix length as well. - with_prefix = '/' in addr - for address_info in addresses or []: - address = address_info['address'] - prefixlen = address_info['prefixlen'] - assigned = ip_interface(f'{address}/{prefixlen}') - if (wanted == assigned) if with_prefix else (wanted.ip == assigned.ip): + for info in jmespath.search('[].addr_info[]', loads(out)) or []: + assigned = ip_interface(f"{info['local']}/{info['prefixlen']}") + if wanted.ip == assigned.ip and ('/' not in addr or wanted == assigned): return True return False @@ -915,11 +875,13 @@ def get_interfaces_by_ip(ip_address: str, vrf=None, include_vrf: bool = False) - Returns: list: List of interface names (str) that have the given IP address assigned. Returns an empty list if no interface has the IP assigned. + Raises: + ValueError: ip_address is not a single address. """ import netifaces from vyos.utils.dict import dict_search - # A zone index names the one interface to look at, see is_addr_assigned() + # A zone index ("fe80::1%eth0") names the one interface to look at candidates = netifaces.interfaces() if '%' in ip_address: ip_address, zone = ip_address.split('%', 1) diff --git a/smoketest/scripts/cli/test_system_sflow.py b/smoketest/scripts/cli/test_system_sflow.py index d708973fc..d99447e68 100755 --- a/smoketest/scripts/cli/test_system_sflow.py +++ b/smoketest/scripts/cli/test_system_sflow.py @@ -148,6 +148,8 @@ class TestSystemFlowAccounting(VyOSUnitTestSHIM.TestCase): self.cli_set(base_path + ['agent-address', f'{address}%{interface}']) self.cli_commit() + self.cli_delete(['interfaces', 'dummy', interface]) + def test_vrf(self): interface = 'eth0' server = '192.0.2.1' diff --git a/src/tests/test_utils_network.py b/src/tests/test_utils_network.py index 630d5dff2..48b71baf2 100644 --- a/src/tests/test_utils_network.py +++ b/src/tests/test_utils_network.py @@ -56,8 +56,6 @@ class TestVyOSUtilsNetwork(TestCase): def test_is_addr_assigned_zone_index_honours_vrf(self): # the interface named by the zone index has to be part of the VRF # asked for, just like any other candidate - from unittest.mock import patch - tmp = {'master': 'red', 'linkinfo': {'info_kind': 'dummy'}} with patch('netifaces.interfaces', return_value=['lo', 'dum0']), patch( 'vyos.utils.network.get_interface_config', return_value=tmp @@ -122,7 +120,7 @@ class TestVyOSUtilsNetwork(TestCase): ) def test_is_intf_addr_assigned_rejects_invalid(self): - # T9207: a range used to raise ValueError out of the ipaddress module + # anything but a single address is rejected for addr in ['192.0.2.1-192.0.2.2', 'VyOS', '']: with self.assertRaises(ValueError) as e: vyos.utils.network.is_intf_addr_assigned('lo', addr) -- cgit v1.2.3