Add acl.get_network_list() + tests; Update docs to reference the ability to use prefixlist as a source/destination

This commit is contained in:
Pim van Pelt
2023-01-16 12:03:34 +00:00
parent a274fdc2af
commit 4e2354c3d8
3 changed files with 91 additions and 2 deletions

View File

@ -15,6 +15,7 @@
import logging
import socket
import ipaddress
from . import prefixlist
def get_acls(yaml):
@ -151,6 +152,32 @@ def get_port_low_high(portstring):
return None, None
def is_ip(ip_string):
"""Return True if the given ip_string is either an IPv4/IPv6 address or prefix."""
if not isinstance(ip_string, str):
return False
try:
ipn = ipaddress.ip_network(ip_string, strict=False)
return True
except:
pass
return False
def get_network_list(yaml, network_string):
"""Return the full list of source or destination address(es). This function resolves the
'source' or 'destination' field, which can either be an IP address, a Prefix, or the name
of a Prefix List. It returns a list of ip_network() objects, including prefix. IP addresses
will receive prefixlen /32 or /128."""
if is_ip(network_string):
ipn = ipaddress.ip_network(network_string, strict=False)
return [ipn]
return prefixlist.get_network_list(yaml, network_string)
def get_protocol(protostring):
"""For a given protocol string, which can be either an integer or a symbolic port
name in /etc/protocols, return the protocol number as integer, or None if it cannot

View File

@ -113,3 +113,30 @@ class TestACLMethods(unittest.TestCase):
lo, hi = acl.get_icmp_low_high("10-20")
self.assertEqual(10, lo)
self.assertEqual(20, hi)
def test_is_ip(self):
self.assertTrue(acl.is_ip("192.0.2.1"))
self.assertTrue(acl.is_ip("192.0.2.1/24"))
self.assertTrue(acl.is_ip("192.0.2.0/24"))
self.assertTrue(acl.is_ip("2001:db8::1"))
self.assertTrue(acl.is_ip("2001:db8::1/64"))
self.assertTrue(acl.is_ip("2001:db8::/64"))
self.assertFalse(acl.is_ip(True))
self.assertFalse(acl.is_ip("String"))
self.assertFalse(acl.is_ip([]))
self.assertFalse(acl.is_ip({}))
def test_get_network_list(self):
for s in ["192.0.2.1", "192.0.2.1/24", "2001:db8::1", "2001:db8::1/64"]:
l = acl.get_network_list(self.cfg, s)
self.assertIsInstance(l, list)
self.assertEquals(1, len(l))
n = l[0]
l = acl.get_network_list(self.cfg, "trusted")
self.assertIsInstance(l, list)
self.assertEquals(4, len(l))
l = acl.get_network_list(self.cfg, "pl-notexist")
self.assertIsInstance(l, list)
self.assertEquals(0, len(l))