Skip to content
Open
31 changes: 30 additions & 1 deletion dockers/docker-dhcp-server/cli-plugin-tests/conftest.py
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@
import sys

import mock_tables
from swsscommon import swsscommon

TEST_DATA_PATH = os.path.dirname(os.path.abspath(__file__))

Expand Down Expand Up @@ -102,4 +103,32 @@ def get_redis_client(table):
redis_client_config_db.hdel = mock.Mock(side_effect=config_db_hdel)
redis_client_state_db.hdel = mock.Mock(side_effect=state_db_hdel)

yield db
class RedisCommand:
def format(self, command):
self.command = list(command)

class RedisTransactioner:
def __init__(self, client):
assert client is redis_client_config_db
self.commands = None

def multi(self):
self.commands = []

def enqueue(self, command, expected_type):
self.commands.append(command.command)

def _exec(self):
for name, key, *args in self.commands:
if name == "DEL":
mock_config_db.pop(key, None)
else:
assert name == "HSET"
mock_config_db.setdefault(key, {}).update(zip(args[::2], args[1::2]))
db.transactions.append(self.commands)
return True

db.transactions = []
with mock.patch.object(swsscommon, "RedisCommand", RedisCommand), \
mock.patch.object(swsscommon, "RedisTransactioner", RedisTransactioner):
yield db

Large diffs are not rendered by default.

179 changes: 147 additions & 32 deletions dockers/docker-dhcp-server/cli/config/plugins/dhcp_server.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,8 +5,11 @@
import string
import unicodedata

from swsscommon import swsscommon


SUPPORTED_TYPE = ["binary", "boolean", "ipv4-address", "string", "uint8", "uint16", "uint32"]
SUPPORTED_MODE = ["PORT", "MATCH"]
SUPPORTED_MATCH_TYPE = ["circuit_id", "option60"]


Expand Down Expand Up @@ -97,21 +100,62 @@ def get_vlan_subnets(dbconn, dhcp_interface):
return subnets


def validate_ip_pool(ips, subnets, dhcp_interface):
REDIS_REPLY_INTEGER = 3


Comment on lines +103 to +105
def replace_config_db_entry(dbconn, key, entry):
"""Replace a Config DB hash in one MULTI/EXEC so subscribers never read it missing or half-written."""
transaction = swsscommon.RedisTransactioner(dbconn.get_redis_client("CONFIG_DB"))
transaction.multi()
fields = [item for field in sorted(entry) for item in (field, entry[field])]
for command in (["DEL", key], ["HSET", key] + fields):
redis_command = swsscommon.RedisCommand()
redis_command.format(command)
transaction.enqueue(redis_command, REDIS_REPLY_INTEGER)
# SWIG exposes RedisTransactioner::exec() as _exec()
if not transaction._exec():
click.get_current_context().fail("Failed to update {}".format(key))


class AmbiguousPoolError(click.UsageError):
"""A pool fits more than one VLAN prefix, which dhcp_cfggen rejects for the whole configuration."""


def add_pool_interval(intervals, subnets, start, end, dhcp_interface):
"""Record an address interval under the single VLAN prefix that contains it."""
start = ipaddress.ip_address(start)
end = ipaddress.ip_address(end)
matching = sorted({subnet for subnet in subnets if start in subnet and end in subnet}, key=str)
if len(matching) > 1:
raise AmbiguousPoolError(
"Pool {}-{} matches multiple IPv4 subnets of {}".format(start, end, dhcp_interface),
ctx=click.get_current_context())
if matching:
intervals.setdefault(matching[0], []).append((int(start), int(end)))
return bool(matching)


def validate_ip_pool(ips, subnets, dhcp_interface, allow_off_subnet=False):
intervals = {}
for ip in ips:
if not validate_str_type("ipv4-address", ip):
click.get_current_context().fail("Illegal IP address {}".format(ip))
if not any(ipaddress.ip_address(ip) in subnet for subnet in subnets):
if not add_pool_interval(intervals, subnets, ip, ip, dhcp_interface) and not allow_off_subnet:
click.get_current_context().fail("IP {} is not in any subnet of vlan {}".format(ip, dhcp_interface))
return intervals


def validate_range_pool(dbconn, ranges, subnets, dhcp_interface, range_overrides=None):
def validate_range_pool(dbconn, ranges, subnets, dhcp_interface, range_overrides=None,
allow_missing_ranges=False, allow_off_subnet=False):
intervals = {}
for range_name in ranges:
key = "DHCP_SERVER_IPV4_RANGE|" + range_name
if range_overrides and range_name in range_overrides:
range_value = range_overrides[range_name]
else:
if not dbconn.exists("CONFIG_DB", key):
if allow_missing_ranges:
continue
click.get_current_context().fail("Range {} does not exist".format(range_name))
range_value = dbconn.get("CONFIG_DB", key, "range@")
range_ips = range_value.split(",") if range_value else []
Expand All @@ -123,10 +167,11 @@ def validate_range_pool(dbconn, ranges, subnets, dhcp_interface, range_overrides
click.get_current_context().fail("Range {} has an invalid IPv4 address".format(range_name))
if count_ipv4(ip_start, ip_end) < 1:
click.get_current_context().fail("Range {} has an invalid address order".format(range_name))
if not any(ipaddress.ip_address(ip_start) in subnet and ipaddress.ip_address(ip_end) in subnet
for subnet in subnets):
if not add_pool_interval(intervals, subnets, ip_start, ip_end, dhcp_interface) and (
not allow_off_subnet or (range_overrides and range_name in range_overrides)):
click.get_current_context().fail(
"Range {} is not in any subnet of vlan {}".format(range_name, dhcp_interface))
return intervals


def get_match_entry(dbconn, match_name, match_overrides=None):
Expand All @@ -139,8 +184,8 @@ def get_match_entry(dbconn, match_name, match_overrides=None):
entry = dbconn.get_all("CONFIG_DB", key)
if entry.get("type") not in SUPPORTED_MATCH_TYPE:
click.get_current_context().fail("Match {} has unsupported type {}".format(match_name, entry.get("type", "")))
if not entry.get("value") or len(entry["value"]) > 255:
click.get_current_context().fail("Match {} has an invalid value".format(match_name))
if not entry.get("value") or len(entry["value"].encode("utf-8")) > 255:
click.get_current_context().fail("Match {} has an invalid value or exceeds 255 UTF-8 bytes".format(match_name))
Comment on lines +191 to +192
return entry


Expand Down Expand Up @@ -172,7 +217,8 @@ def resolve_port_alias(dbconn, alias, port_alias_map=None):


def validate_binding_entry(dbconn, dhcp_interface, binding_name, entry, match_overrides=None,
range_overrides=None, port_alias_map=None):
range_overrides=None, port_alias_map=None, allow_missing_ranges=False,
allow_off_subnet=False):
validate_key_name(binding_name, "Binding name", "|")
if not dbconn.exists("CONFIG_DB", "DHCP_SERVER_IPV4|" + dhcp_interface):
click.get_current_context().fail("Interface {} is not a valid dhcp interface".format(dhcp_interface))
Expand Down Expand Up @@ -205,17 +251,50 @@ def validate_binding_entry(dbconn, dhcp_interface, binding_name, entry, match_ov

subnets = get_vlan_subnets(dbconn, dhcp_interface)
if has_ips:
validate_ip_pool(split_csv(entry["ips@"], "IP list"), subnets, dhcp_interface)
intervals = validate_ip_pool(split_csv(entry["ips@"], "IP list"), subnets, dhcp_interface,
allow_off_subnet=allow_off_subnet)
else:
validate_range_pool(dbconn, split_csv(entry["ranges@"], "Range list"), subnets, dhcp_interface,
range_overrides)
return conditions
intervals = validate_range_pool(dbconn, split_csv(entry["ranges@"], "Range list"), subnets,
dhcp_interface, range_overrides, allow_missing_ranges, allow_off_subnet)
return conditions, {subnet: merge_pool_intervals(pool) for subnet, pool in intervals.items()}


def merge_pool_intervals(intervals):
"""Merge overlapping or adjacent intervals the same way dhcp_cfggen builds Kea pools."""
merged = []
for start, end in sorted(intervals):
if merged and start <= merged[-1][1] + 1:
merged[-1] = (merged[-1][0], max(merged[-1][1], end))
else:
merged.append((start, end))
return merged


def pools_partially_overlap(first, second):
"""Identical pools share one Kea pool; any other shared address cannot be compiled."""
for subnet in set(first) & set(second):
if first[subnet] != second[subnet] and any(
first_start <= second_end and second_start <= first_end
for first_start, first_end in first[subnet]
for second_start, second_end in second[subnet]):
return True
return False


def predicates_overlap(first, second):
return all(match_type not in second or second[match_type] == value for match_type, value in first.items())


def validate_single_prefix(dhcp_interface, prefixes):
prefixes = sorted(set(prefixes), key=str)
if len(prefixes) > 1:
click.get_current_context().fail(
"DHCP pools on {} cannot span multiple IPv4 prefixes: {}".format(
dhcp_interface, ", ".join(str(prefix) for prefix in prefixes)
)
)


def validate_vlan_bindings(dbconn, dhcp_interface, candidate=None, match_overrides=None,
range_overrides=None, port_alias_map=None):
bindings = {}
Expand All @@ -226,13 +305,39 @@ def validate_vlan_bindings(dbconn, dhcp_interface, candidate=None, match_overrid
bindings[candidate[0]] = candidate[1]
if port_alias_map is None:
port_alias_map = {}

predicates = {}
pools = {}
for binding_name in sorted(bindings):
predicates[binding_name] = validate_binding_entry(
dbconn, dhcp_interface, binding_name, bindings[binding_name], match_overrides,
range_overrides, port_alias_map
)

is_candidate = candidate and binding_name == candidate[0]
try:
conditions, intervals = validate_binding_entry(
dbconn, dhcp_interface, binding_name, bindings[binding_name], match_overrides,
range_overrides, port_alias_map,
allow_missing_ranges=not is_candidate, allow_off_subnet=not is_candidate
)
# Existing bindings still serve their usable pools, as dhcp_cfggen does.
if intervals:
predicates[binding_name], pools[binding_name] = conditions, intervals
except AmbiguousPoolError:
# dhcp_cfggen fails the whole generation here, not just this binding.
raise
except click.UsageError:
if is_candidate:
raise
# dhcp_cfggen skips a binding that is already invalid (for example after
# its port left the VLAN), so it must not block unrelated changes. Only
# reject when this change is what breaks the binding.
if match_overrides or range_overrides:
try:
validate_binding_entry(dbconn, dhcp_interface, binding_name, bindings[binding_name],
port_alias_map=port_alias_map, allow_missing_ranges=True,
allow_off_subnet=True)
except click.UsageError:
continue
Comment thread
nishant111 marked this conversation as resolved.
Resolved
raise

validate_single_prefix(dhcp_interface, (subnet for pool in pools.values() for subnet in pool))
binding_names = sorted(predicates)
for index, first_name in enumerate(binding_names):
for second_name in binding_names[index + 1:]:
Expand All @@ -244,20 +349,23 @@ def validate_vlan_bindings(dbconn, dhcp_interface, candidate=None, match_overrid
first_name, second_name, dhcp_interface
)
)
if pools_partially_overlap(pools[first_name], pools[second_name]):
click.get_current_context().fail(
"Bindings {} and {} have partially overlapping pools on {}".format(
first_name, second_name, dhcp_interface
)
)


def validate_range_update(dbconn, range_name, updated_value):
"""Re-validate every binding that references a range before its endpoints move.

A binding's pool is checked against the VLAN subnet when the binding itself is
written, but the range it names can be edited afterwards. dhcp_cfggen aborts
generation of the entire Kea config - not just the offending binding - when a
pool falls outside the VLAN, so an unchecked range update can take DHCP down
for every interface on the box, not only this one.

DHCP_SERVER_IPV4_PORT entries can also reference a range and are deliberately
not covered here: they are validated nowhere today, so guarding them would
change behaviour that predates this series and belongs in its own change.
written, but the range it names can be edited afterwards. dhcp_cfggen drops a
pool that falls outside the VLAN, so an unchecked range update would silently
stop serving the binding.

PORT entries retain their existing validation behavior.
"""
affected_vlans = set()
for key in dbconn.keys("CONFIG_DB", "DHCP_SERVER_IPV4_BINDING|*"):
Expand Down Expand Up @@ -306,7 +414,7 @@ def dhcp_server(db):

@dhcp_server.group(cls=clicommon.AliasedGroup, name="ipv4")
def dhcp_server_ipv4():
"""Show ipv4 related dhcp_server info"""
"""Configure IPv4 DHCP; MATCH pools on each interface must use one IPv4 prefix."""
pass


Expand All @@ -320,8 +428,8 @@ def dhcp_server_ipv4():
@clicommon.pass_db
def dhcp_server_ipv4_add(db, mode, lease_time, dup_gw_nm, gateway, netmask, dhcp_interface):
ctx = click.get_current_context()
if mode != "PORT":
ctx.fail("Only mode PORT is supported")
if mode not in SUPPORTED_MODE:
ctx.fail("Only modes {} are supported".format(", ".join(SUPPORTED_MODE)))
if not validate_str_type("uint32", lease_time):
ctx.fail("lease_time is required and must be nonnegative integer")
dbconn = db.db
Expand Down Expand Up @@ -385,8 +493,10 @@ def dhcp_server_ipv4_update(db, mode, lease_time, dup_gw_nm, gateway, netmask, d
ctx.fail("Dhcp interface {} does not exist in config db".format(dhcp_interface))
updates = {}
if mode:
if mode != "PORT":
ctx.fail("Only mode PORT is supported")
if mode not in SUPPORTED_MODE:
ctx.fail("Only modes {} are supported".format(", ".join(SUPPORTED_MODE)))
if mode == "MATCH" and dbconn.get("CONFIG_DB", interface_key, "state") == "enabled":
validate_vlan_bindings(dbconn, dhcp_interface)
updates["mode"] = mode
if lease_time:
if not validate_str_type("uint32", lease_time):
Expand Down Expand Up @@ -422,6 +532,8 @@ def dhcp_server_ipv4_enable(db, dhcp_interface):
dbconn = db.db
key = "DHCP_SERVER_IPV4|" + dhcp_interface
if dbconn.exists("CONFIG_DB", key):
if dbconn.get("CONFIG_DB", key, "mode") == "MATCH":
validate_vlan_bindings(dbconn, dhcp_interface)
dbconn.set("CONFIG_DB", key, "state", "enabled")
else:
ctx.fail("Failed to enable, dhcp interface {} does not exist".format(dhcp_interface))
Expand Down Expand Up @@ -469,6 +581,8 @@ def dhcp_server_ipv4_range_add(db, range_name, ip_start, ip_end):
if dbconn.exists("CONFIG_DB", key):
ctx.fail("Range {} already exist".format(range_name))
else:
# Bindings can still reference a force-deleted range, so recreating it is validated like an update.
validate_range_update(dbconn, range_name, ip_start + "," + ip_end)
dbconn.hmset("CONFIG_DB", key, {"range@": ip_start + "," + ip_end})


Expand Down Expand Up @@ -672,8 +786,9 @@ def dhcp_server_ipv4_binding_update(db, dhcp_interface, binding_name, match_list
entry["ranges@"] = existing.get("ranges@", "")

validate_vlan_bindings(dbconn, dhcp_interface, candidate=(binding_name, entry))
dbconn.delete("CONFIG_DB", key)
dbconn.hmset("CONFIG_DB", key, entry)
# A separate delete would let dhcpservd briefly generate without this binding,
# dropping its exclusion from less specific classes.
replace_config_db_entry(dbconn, key, entry)


@dhcp_server_ipv4_binding.command(name="del")
Expand Down
Loading
Loading