From 536e49050f783c9ee1c6b46afb8af3ed1cf6f261 Mon Sep 17 00:00:00 2001 From: Matteo Di Lorenzi Date: Thu, 12 Nov 2026 15:29:02 +0100 Subject: [PATCH 1/3] feat(dpi): add support for source objects in DPI rules and address group management --- .agents/skills/netifyd/SKILL.md | 14 + packages/ns-api/Makefile | 1 + packages/ns-api/README.md | 56 ++- packages/ns-api/files/ns.dpi | 12 +- packages/ns-api/files/ns.ovpnrw | 8 +- .../ns-api/files/post-commit/reload-dpi.py | 22 + packages/ns-dpi/README.md | 42 +- packages/ns-dpi/files/dpi-config | 13 + .../src/nethsec/dpi/__init__.py | 189 ++++++++- .../src/nethsec/objects/__init__.py | 7 +- packages/python3-nethsec/tests/test_dpi.py | 378 +++++++++++++++++- 11 files changed, 723 insertions(+), 19 deletions(-) create mode 100755 packages/ns-api/files/post-commit/reload-dpi.py diff --git a/.agents/skills/netifyd/SKILL.md b/.agents/skills/netifyd/SKILL.md index 48f2fe6c7..63ad1751a 100644 --- a/.agents/skills/netifyd/SKILL.md +++ b/.agents/skills/netifyd/SKILL.md @@ -204,6 +204,20 @@ Two operational facts: MAC members only match via `mac ==`, so don't put them in a group a `local_ip` rule references. +`dpi-config` owns the `30-` prefix: one `30-_.conf` group per object referenced by a DPI +rule source, with a `# ` and a `# , generated by dpi-config: do not edit` header +(`nethsec.dpi.write_address_groups`), and every other `30-*.conf` file is removed. The agent keeps the +groups it loaded in memory, a reload doesn't drop the ones whose file was removed, and on stop it saves all +of them back, without comments: that's why ownership goes by prefix. A group removed from every rule +therefore comes back as a file on the next agent restart (unreferenced, so harmless) until the agent +drops it from memory, e.g. with the `flush-address-group` socket command, which also deletes its file. +A `kill -9` saves nothing. Verified on a device with agent 5.2.9: a reload re-reads the groups +without restarting the agent; a range line is silently ignored, so ranges are written as CIDR blocks; +a `/0` matches nothing (in a group and inline), so it is written as two `/1`; an IPv4-mapped IPv6 address +never matches an IPv4 flow; an empty group or a missing tag matches nothing without errors. IPv6 +literals written inline in a criteria, especially the ones starting with `::`, were seen to trigger an +intermittent `criteria parse error` that takes the agent down: a group reference never does. + --- ## Verify on a live device diff --git a/packages/ns-api/Makefile b/packages/ns-api/Makefile index 930202e46..3d0d2af57 100644 --- a/packages/ns-api/Makefile +++ b/packages/ns-api/Makefile @@ -198,6 +198,7 @@ define Package/ns-api/install $(INSTALL_BIN) ./files/post-commit/update-timezone.py $(1)/usr/libexec/ns-api/post-commit $(INSTALL_BIN) ./files/post-commit/restart-wireguard.py $(1)/usr/libexec/ns-api/post-commit $(INSTALL_BIN) ./files/post-commit/clear-user-tokens.py $(1)/usr/libexec/ns-api/post-commit + $(INSTALL_BIN) ./files/post-commit/reload-dpi.py $(1)/usr/libexec/ns-api/post-commit $(INSTALL_BIN) ./files/pre-commit/clean-network.py $(1)/usr/libexec/ns-api/pre-commit $(INSTALL_BIN) ./files/remove-pppoe-keepalive $(1)/usr/share/ns-api $(INSTALL_DIR) $(1)/etc/uci-defaults diff --git a/packages/ns-api/README.md b/packages/ns-api/README.md index b356623ba..bb07704bf 100644 --- a/packages/ns-api/README.md +++ b/packages/ns-api/README.md @@ -3801,6 +3801,10 @@ Rules with `ns_visible '0'` are left out. previous schema, carry their raw `criteria` and can be renamed, enabled, disabled, reordered and deleted, but not edited - `match_all`: the rule matches every flow instead of naming application groups +- `source_objects`: objects the source references, with their `name`, `type` and `subtype` (the same + values `ns.objects list-hosts` reports). An object gone from the configuration is reported with its id + as name and `null` type. `empty` is true when the object has no address, e.g. a VPN user whose + reserved IP was removed: the rule matches no host for that object - `index`: position of the rule in the list Example response: @@ -3813,7 +3817,16 @@ Example response: "name": "Block streaming", "enabled": true, "action": "block", - "source": ["192.168.1.0/24"], + "source": [], + "source_objects": [ + { + "id": "objects/ns_16faa17f", + "name": "office", + "type": "host_set", + "subtype": "host_set", + "empty": false + } + ], "appgroups": [ { "id": "ns_1a2b3c4d5", @@ -3830,6 +3843,7 @@ Example response: "enabled": true, "action": "allow", "source": [], + "source_objects": [], "appgroups": [], "match_all": true, "managed": true, @@ -3841,6 +3855,7 @@ Example response: "enabled": true, "action": "block", "source": [], + "source_objects": [], "appgroups": [], "match_all": false, "managed": false, @@ -3860,7 +3875,8 @@ api-cli ns.dpi add-rule --data '{ "name": "Block streaming", "enabled": true, "action": "block", - "source": ["192.168.1.0/24"], + "source": [], + "source_objects": ["objects/ns_16faa17f"], "appgroups": ["ns_1a2b3c4d5"], "match_all": false, "position": "bottom" @@ -3872,7 +3888,12 @@ api-cli ns.dpi add-rule --data '{ - `action`: mandatory, `block` or `allow`. `allow` stops the evaluation, so the rules below it don't apply to the matching flows - `source`: addresses, networks or ranges, IPv4 or IPv6, e.g. - `["192.168.1.1", "192.168.1.0/24", "10.0.0.10-10.0.0.20"]`. Empty or omitted matches every host + `["192.168.1.1", "192.168.1.0/24", "10.0.0.10-10.0.0.20"]`. Empty or omitted, together with + `source_objects`, matches every host +- `source_objects`: ids of objects whose addresses the rule is narrowed to, see `list-source-objects`: + host sets, DHCP static leases, DNS records and VPN users with a reserved IP. Domain sets are refused. + Alternative to `source`: a rule can't have both (`source_objects_with_source`). A change to a + referenced object applies to the rule on commit, without editing it - `appgroups`: ids of the application groups to match, see `list-appgroups`. Mandatory unless `match_all` is `true` - `match_all`: match every flow, optionally narrowed by `source`. `appgroups` must be empty. Defaults to @@ -3899,6 +3920,7 @@ api-cli ns.dpi edit-rule --data '{ "enabled": false, "action": "block", "source": [], + "source_objects": [], "appgroups": ["ns_1a2b3c4d5"], "match_all": false }' @@ -3912,6 +3934,34 @@ Example response: } ``` +### list-source-objects + +List the objects a rule source can reference: the same objects as `ns.objects list-hosts`, domain sets +excluded. + +```bash +api-cli ns.dpi list-source-objects +``` + +Example response: + +```json +{ + "values": [ + { + "name": "office", + "family": "ipv4", + "id": "objects/ns_16faa17f", + "singleton": false, + "subtype": "host_set", + "used": true, + "matches": ["dpi/ns_3869dc35"], + "type": "host_set" + } + ] +} +``` + ### delete-rule Delete a rule. The remaining rules are renumbered: diff --git a/packages/ns-api/files/ns.dpi b/packages/ns-api/files/ns.dpi index aa6a6d002..cf4f5063f 100755 --- a/packages/ns-api/files/ns.dpi +++ b/packages/ns-api/files/ns.dpi @@ -9,18 +9,20 @@ import json import sys from euci import EUci -from nethsec import dpi, utils +from nethsec import dpi, objects, utils cmd = sys.argv[1] if cmd == 'list': print(json.dumps({ 'list-rules': {}, + 'list-source-objects': {}, 'add-rule': { 'name': 'str', 'enabled': False, 'action': 'str', 'source': [], + 'source_objects': [], 'appgroups': [], 'match_all': False, 'position': 'str' @@ -31,6 +33,7 @@ if cmd == 'list': 'enabled': False, 'action': 'str', 'source': [], + 'source_objects': [], 'appgroups': [], 'match_all': False }, @@ -102,17 +105,20 @@ elif cmd == 'call': print(json.dumps(utils.generic_error('catalog_not_available'))) elif action == 'list-rules': print(json.dumps({'values': dpi.list_rules(e_uci)})) + elif action == 'list-source-objects': + print(json.dumps({'values': objects.list_objects(e_uci, include_domain_sets=False)})) elif action == 'add-rule': data = json.load(sys.stdin) config_name = dpi.add_rule(e_uci, data['name'], data['enabled'], data['action'], data.get('source', []), data.get('appgroups', []), - data.get('position', 'bottom'), data.get('match_all', False)) + data.get('position', 'bottom'), data.get('match_all', False), + data.get('source_objects', [])) print(json.dumps({'id': config_name})) elif action == 'edit-rule': data = json.load(sys.stdin) config_name = dpi.edit_rule(e_uci, data['id'], data['name'], data['enabled'], data['action'], data.get('source', []), data.get('appgroups', []), - data.get('match_all', False)) + data.get('match_all', False), data.get('source_objects', [])) print(json.dumps({'id': config_name})) elif action == 'delete-rule': data = json.load(sys.stdin) diff --git a/packages/ns-api/files/ns.ovpnrw b/packages/ns-api/files/ns.ovpnrw index 8439a62dd..ab4bd2074 100755 --- a/packages/ns-api/files/ns.ovpnrw +++ b/packages/ns-api/files/ns.ovpnrw @@ -841,7 +841,8 @@ def edit_user(args): if user_id == None: return utils.validation_error("username", "user_not_found", args["username"]) - if args["ipaddr"] and u.get("users", user_id, 'openvpn_ipaddr', default="") != args["ipaddr"]: + old_ipaddr = u.get("users", user_id, 'openvpn_ipaddr', default="") + if args["ipaddr"] and old_ipaddr != args["ipaddr"]: valid, error = is_valid_ip(ovpninstance, args["ipaddr"]) if not valid: return utils.validation_error("ipaddr", error, args["ipaddr"]) @@ -856,6 +857,11 @@ def edit_user(args): pass u.set("users", user_id, "openvpn_enabled", args["enabled"]) u.commit("users") + # reload dpi if the ipaddr changed and the user is used by dpi + if u.get("users", user_id, 'openvpn_ipaddr', default="") != old_ipaddr: + _, matches = objects.is_used_object(u, f"users/{user_id}") + if any(match.startswith("dpi/") for match in matches): + subprocess.run(["/etc/init.d/dpi", "reload"], check=False, capture_output=True) return {"result": "success"} def delete_user(ovpninstance, username): diff --git a/packages/ns-api/files/post-commit/reload-dpi.py b/packages/ns-api/files/post-commit/reload-dpi.py new file mode 100755 index 000000000..407cdd6cc --- /dev/null +++ b/packages/ns-api/files/post-commit/reload-dpi.py @@ -0,0 +1,22 @@ +#!/usr/bin/python + +# +# Copyright (C) 2026 Nethesis S.r.l. +# SPDX-License-Identifier: GPL-2.0-only +# + +# This script reloads the DPI when an object referenced by a DPI rule source may have changed: +# the address group of every referenced object is regenerated from the committed configuration. +# reload_config can't do it, as it reloads dpi only when /etc/config/dpi itself changes. + +import subprocess + +from euci import EUci +from nethsec import utils + +# A change to dpi itself is left to reload_config, which reloads the service anyway. +if "dpi" not in changes and ("objects" in changes or "users" in changes or "dhcp" in changes): # noqa: F821 + for rule in (utils.get_all_by_type(EUci(), "dpi", "rule") or {}).values(): + if rule.get("source_object"): + subprocess.run(["/etc/init.d/dpi", "reload"], check=False) + break diff --git a/packages/ns-dpi/README.md b/packages/ns-dpi/README.md index e5bbbe5ae..091f29d19 100644 --- a/packages/ns-dpi/README.md +++ b/packages/ns-dpi/README.md @@ -40,7 +40,10 @@ Rule (`rule` section): - `action`: `block` or `allow` - `priority`: evaluation order, starting at `1`; the first rule matching a flow wins - `appgroup`: list of application groups to match -- `source`: list of addresses, networks or ranges to narrow the rule to; empty means every host +- `source`: list of addresses, networks or ranges to narrow the rule to; empty, together with + `source_object`, means every host +- `source_object`: list of objects, in the form `/`, whose addresses narrow the rule, as + an alternative to `source`: host sets, DHCP static leases, DNS records and VPN users with a reserved IP - `ns_match_all`: `1` matches every flow instead of naming application groups - `ns_managed`: `1` for the rules created by the API - `criteria`: raw netifyd expression, used by the rules not created by the API; the API can't edit them @@ -71,9 +74,39 @@ config rule 'ns_9d40be71' option action 'block' option priority '2' list appgroup 'ns_1a2b3c4d' - list source '192.168.1.0/24' + list source_object 'objects/ns_16faa17f' ``` +### Objects as source + +`dpi-config` writes the addresses of every object referenced by a rule to a netifyd address group, +`/etc/netifyd/address-groups.d/30-_.conf`, and the criteria matches it as +`local_ip == @_`. Each file starts with a comment holding the object name, when the object +has one, followed by a comment holding the object id and `generated by dpi-config: do not edit`. The files +are regenerated on every DPI reload. The `30-` prefix belongs to `dpi-config`: every `30-*.conf` file no +rule references is removed, files with other prefixes are never touched. + +netifyd keeps the groups it loaded in memory, a reload doesn't drop the ones whose file was removed, and +when it stops it saves all of them back to the directory, without comments. So a group removed from every +rule comes back as a file when netifyd restarts: no rule references it, so it matches nothing, and the +next DPI reload removes the file again. Known limitation: the group stays in the agent memory until it is +flushed. + +The addresses are written the way an address group can match them: + +- ranges become CIDR blocks, as address groups ignore them. A range whose first address is greater than + its last is skipped and logged +- references to other objects are resolved +- IPv4-mapped IPv6 addresses (`::ffff:a.b.c.d`) become IPv4 addresses, as they never match IPv4 flows +- `0.0.0.0/0` and `::/0` become their two `/1` halves, as a zero length prefix matches nothing +- the zone of link-local addresses is dropped + +An object with no address, e.g. a VPN user with no reserved IP, gets an empty group: the rule matches no +host instead of every host. + +When an object changes, the `reload-dpi.py` post-commit hook of `ns.commit` reloads the DPI if any rule +references an object, so the group follows the object. + ## Migration from the previous schema On upgrade, and every time the DPI service starts, `/usr/libexec/ns-dpi/dpi-migrate` converts the @@ -98,6 +131,11 @@ cat /etc/netifyd/netify-proc-flow-actions.json nft list chain inet fw4 dpi_actions ``` +Check the address groups of the objects used as source: +``` +head /etc/netifyd/address-groups.d/30-* +``` + List the blocked connections: ``` conntrack -L -o label -l netify-blocked diff --git a/packages/ns-dpi/files/dpi-config b/packages/ns-dpi/files/dpi-config index fa3748b29..0cbe6c18f 100755 --- a/packages/ns-dpi/files/dpi-config +++ b/packages/ns-dpi/files/dpi-config @@ -62,6 +62,16 @@ config = { u = EUci() +# address groups of the objects referenced by the rule sources: written before the criteria that +# reference them, and reloaded by the agent together with this file. If they can't be written, the +# rules using objects are skipped below: their criteria would reference groups that don't exist +try: + dpi.write_address_groups(u) + address_groups_ok = True +except OSError as error: + syslog.syslog(syslog.LOG_ERR, f"dpi-config: cannot write the address groups: {error}") + address_groups_ok = False + # a rule from the schema used before application groups existed carries at least one of these fields; # dpi.migrate_schema converts it, so one still here was not migrated yet legacy_fields = ('device', 'application', 'protocol', 'category') @@ -93,6 +103,9 @@ for section in u.get_all('dpi'): if criteria and not criteria.endswith(';'): criteria = f'{criteria};' else: + if rule.get('source_object') and not address_groups_ok: + syslog.syslog(syslog.LOG_WARNING, f"dpi-config: skipping {section}, its source objects are not available") + continue # application groups, optionally narrowed to a source, or a match-all rule criteria = dpi.build_rule_criteria(u, rule) if not criteria: diff --git a/packages/python3-nethsec/src/nethsec/dpi/__init__.py b/packages/python3-nethsec/src/nethsec/dpi/__init__.py index 7c640ca98..a62d3577c 100644 --- a/packages/python3-nethsec/src/nethsec/dpi/__init__.py +++ b/packages/python3-nethsec/src/nethsec/dpi/__init__.py @@ -11,6 +11,7 @@ import ipaddress import json +import os import subprocess import syslog @@ -656,10 +657,148 @@ def expand_source(values: list[str]) -> list[str]: return expanded +# Source objects: firewall objects resolving to IP addresses, referenced by a rule instead of typing the +# addresses in. Each one is written to a netifyd address group, `ADDRESS_GROUPS_DIR/30-.conf`, and +# the criteria matches it as `local_ip == @`: the criteria stays one term wide whatever the object +# holds, and a change to the object only rewrites its file. + +ADDRESS_GROUPS_DIR = '/etc/netifyd/address-groups.d' + +# prefixes below 20 belong to the agent itself, this one belongs to dpi-config: every file carrying it and +# not referenced by a rule is removed. The agent saves the groups it holds when it stops, without comments +# and including the ones whose file was removed while it was running, so the prefix is what tells a stale +# file apart. Such a file comes back on every agent restart until the agent drops the group from memory +ADDRESS_GROUP_FILE_PREFIX = '30-' + +# ending of the header comment of every file written here, for whoever reads it +ADDRESS_GROUP_FILE_MARKER = 'generated by dpi-config: do not edit' + +# (database, section type) of the objects a source can reference: everything resolving to addresses. +# Domain sets are left out: they describe destinations, while a source is matched against the local host +SOURCE_OBJECT_TYPES = (('objects', 'host'), ('dhcp', 'host'), ('dhcp', 'domain'), ('users', 'user')) + + +def __validate_source_objects(e_uci: EUci, values: list[str], source: list[str]) -> list[str]: + """ + Validate the objects a rule source references: they must exist and resolve to addresses. Objects and + addresses are alternatives: a rule can't have both. + """ + if values and source: + raise ValidationError('source_objects', 'source_objects_with_source', values) + source_objects = [] + for value in values or []: + if not isinstance(value, str) or not objects.is_object_id(value): + raise ValidationError('source_objects', 'invalid_source_object', value) + database, _, section = value.partition('/') + if not section or (database, e_uci.get(database, section, default=None)) not in SOURCE_OBJECT_TYPES: + raise ValidationError('source_objects', 'invalid_source_object', value) + # a user is an object only with a VPN account holding a reserved address + if database == 'users' and not e_uci.get('users', section, 'openvpn_ipaddr', default=None): + raise ValidationError('source_objects', 'invalid_source_object', value) + if value not in source_objects: + source_objects.append(value) + return source_objects + + +def __strip_zone(value: str) -> str: + """Drop the zone of a link-local address, e.g. `fe80::1%eth0/64` becomes `fe80::1/64`.""" + if '%' not in value: + return value + address, _, rest = value.partition('%') + _, slash, prefix = rest.partition('/') + return f'{address}{slash}{prefix}' + + +def __address_group_entries(e_uci: EUci, object_id: str) -> list[str]: + """ + The entries of the address group of an object, see `write_address_groups`: empty when the object has + no address the agent can match, or is gone. + """ + entries = [] + for value in objects.get_object_ips(e_uci, object_id): + try: + if '-' in value: + first, last = (ipaddress.ip_address(__strip_zone(part.strip())) for part in value.split('-', 1)) + networks = list(ipaddress.summarize_address_range(first, last)) + else: + networks = [ipaddress.ip_network(__strip_zone(value.strip()), strict=False)] + except (ValueError, TypeError) as error: + syslog.syslog(syslog.LOG_WARNING, f"dpi: skipping {value!r} of {object_id}: {error}") + continue + for network in networks: + if network.version == 6 and network.prefixlen >= 96 and network.network_address.ipv4_mapped: + network = ipaddress.ip_network(f'{network.network_address.ipv4_mapped}/{network.prefixlen - 96}') + for entry in network.subnets(new_prefix=1) if network.prefixlen == 0 else [network]: + if str(entry) not in entries: + entries.append(str(entry)) + return entries + + +def write_address_groups(e_uci: EUci) -> list[str]: + """ + Write the address group of every object referenced by a rule source, and remove every other file with + the `ADDRESS_GROUP_FILE_PREFIX` prefix. A file is rewritten only when its content changes. + + Every referenced object gets its file, even an empty one: the criteria references it anyway, and an + empty group simply matches nothing, which is what a source with no address means. + + The addresses are written the way an address group can match them: ranges become CIDR blocks, as an + address group silently ignores them; an IPv4-mapped IPv6 network becomes the IPv4 network it maps, as + it never matches an IPv4 flow; a zero length prefix, which matches nothing, is split into its two + halves. A value that cannot be turned into an address, like a range whose first address is greater + than its last, is skipped with a log line: the object API accepts it, the agent would ignore it. + + Args: + - e_uci: euci instance + + Returns: + the tags written + """ + os.makedirs(ADDRESS_GROUPS_DIR, exist_ok=True) + wanted = {} + for rule in (utils.get_all_by_type(e_uci, 'dpi', 'rule') or {}).values(): + for object_id in rule.get('source_object', []): + tag = object_id.replace('/', '_') + if tag in wanted: + continue + # header: the object name, when it has one, on one line, then the id and the marker + database, _, section = object_id.partition('/') + name = e_uci.get(database, section, 'name', default='') or \ + e_uci.get(database, section, 'label', default='') + name = ' '.join(str(name).split()) + lines = [f'# {name}'] if name else [] + lines.append(f'# {object_id}, {ADDRESS_GROUP_FILE_MARKER}') + lines.extend(__address_group_entries(e_uci, object_id)) + wanted[tag] = ''.join(f'{line}\n' for line in lines) + + for filename in os.listdir(ADDRESS_GROUPS_DIR): + if not filename.startswith(ADDRESS_GROUP_FILE_PREFIX) or not filename.endswith('.conf'): + continue + if filename[len(ADDRESS_GROUP_FILE_PREFIX):-len('.conf')] not in wanted: + os.remove(os.path.join(ADDRESS_GROUPS_DIR, filename)) + + for tag, content in wanted.items(): + path = os.path.join(ADDRESS_GROUPS_DIR, f'{ADDRESS_GROUP_FILE_PREFIX}{tag}.conf') + try: + with open(path, 'r') as fp: + if fp.read() == content: + continue + except FileNotFoundError: + pass + with open(f'{path}.tmp', 'w') as fp: + fp.write(content) + os.replace(f'{path}.tmp', path) + + return list(wanted) + + def build_rule_criteria(e_uci: EUci, rule: dict) -> str: """ Build the criteria of a managed rule: the source, when set, ANDed with the union of its groups. + The source is made of its addresses or of the address groups of its objects, see + `write_address_groups`; a rule holding both, e.g. edited by hand, matches either. + Args: - e_uci: euci instance - rule: the rule section, as returned by `uci.get_all` @@ -669,6 +808,7 @@ def build_rule_criteria(e_uci: EUci, rule: dict) -> str: """ match = expand_appgroups(e_uci, list(rule.get('appgroup', []))) sources = [f'local_ip == {source}' for source in expand_source(list(rule.get('source', [])))] + sources += [f"local_ip == @{object_id.replace('/', '_')}" for object_id in rule.get('source_object', [])] if not match: if not sources: @@ -691,8 +831,9 @@ def list_rules(e_uci: EUci) -> list[dict]: Returns: list of dicts, each dict contains the property "id", "name", "enabled", "action", "source", - "appgroups", "match_all", "managed" and "index", plus "criteria" for the rules the API did not - create + "source_objects", "appgroups", "match_all", "managed" and "index", plus "criteria" for the rules + the API did not create. Each source object carries "id", "name", "type", "subtype" and "empty", true + when its address group holds no address """ groups = {section: group.get('ns_name', '') for section, group in (utils.get_all_by_type(e_uci, 'dpi', 'appgroup') or {}).items()} @@ -706,6 +847,7 @@ def list_rules(e_uci: EUci) -> list[dict]: 'enabled': rule.get('enabled', '1') == '1', 'action': rule.get('action', ''), 'source': list(rule.get('source', [])), + 'source_objects': [], 'appgroups': [{'id': group, 'name': groups.get(group, group)} for group in rule.get('appgroup', [])], 'match_all': rule.get('ns_match_all', '0') == '1', @@ -713,6 +855,27 @@ def list_rules(e_uci: EUci) -> list[dict]: 'managed': rule.get('ns_managed', '0') == '1', 'index': len(rules) } + for object_id in rule.get('source_object', []): + # an object gone from the configuration is still listed, named after its id, so the rule can be fixed + info = objects.get_info(e_uci, object_id) if objects.object_exists(e_uci, object_id) else None + # its address group matches nothing, e.g. a VPN user without a reserved IP anymore + empty = not __address_group_entries(e_uci, object_id) + if info is None: + data_rule['source_objects'].append( + {'id': object_id, 'name': object_id, 'type': None, 'subtype': None, 'empty': empty}) + continue + if info['database'] == 'objects': + # same subtype `objects.list_host_sets` reports, so the client can reuse its icons and labels + object_type = subtype = 'host_set' + if objects.is_singleton_host_set(e_uci, object_id): + address = objects.get_object_ip(e_uci, object_id) or '' + subtype = 'cidr' if '/' in address else 'range' if '-' in address else 'host' + elif info['database'] == 'dhcp': + object_type = subtype = 'dhcp_static_lease' if info['type'] == 'host' else 'dns_record' + else: + object_type = subtype = 'vpn_user' + data_rule['source_objects'].append( + {'id': object_id, 'name': info['name'], 'type': object_type, 'subtype': subtype, 'empty': empty}) if 'criteria' in rule: data_rule['criteria'] = rule.get('criteria') rules.append(data_rule) @@ -721,7 +884,8 @@ def list_rules(e_uci: EUci) -> list[dict]: def __save_rule_data(e_uci: EUci, config_name: str, name: str, enabled: bool, action: str, - source: list[str], appgroups: list[str], match_all: bool = False): + source: list[str], appgroups: list[str], match_all: bool = False, + source_objects: list[str] = None): e_uci.set('dpi', config_name, 'ns_name', name) e_uci.set('dpi', config_name, 'ns_managed', '1') e_uci.set('dpi', config_name, 'enabled', enabled) @@ -740,10 +904,15 @@ def __save_rule_data(e_uci: EUci, config_name: str, name: str, enabled: bool, ac else: # no source means every host: the option must go, not stay empty e_uci.delete('dpi', config_name, 'source') + if source_objects: + e_uci.set('dpi', config_name, 'source_object', source_objects) + else: + e_uci.delete('dpi', config_name, 'source_object') def add_rule(e_uci: EUci, name: str, enabled: bool, action: str, source: list[str], - appgroups: list[str], position: str = 'bottom', match_all: bool = False) -> str: + appgroups: list[str], position: str = 'bottom', match_all: bool = False, + source_objects: list[str] = None) -> str: """ Store a new rule. @@ -758,6 +927,8 @@ def add_rule(e_uci: EUci, name: str, enabled: bool, action: str, source: list[st - position: 'top' to evaluate the rule before every other one, 'bottom' after them - match_all: the rule matches every flow, narrowed to `source` when one is given. Mutually exclusive with `appgroups` + - source_objects: ids of the objects, in the form of `/`, whose addresses the rule is + narrowed to, as an alternative to `source`; see `SOURCE_OBJECT_TYPES` for the accepted ones Returns: config name of the rule created @@ -771,11 +942,12 @@ def add_rule(e_uci: EUci, name: str, enabled: bool, action: str, source: list[st if position not in DPI_RULE_POSITIONS: raise ValidationError('position', 'invalid_position', position) source = __validate_source(source) + source_objects = __validate_source_objects(e_uci, source_objects, source) appgroups = __validate_appgroups(e_uci, appgroups, match_all) config_name = utils.get_random_id() e_uci.set('dpi', config_name, 'rule') - __save_rule_data(e_uci, config_name, name, enabled, action, source, appgroups, match_all) + __save_rule_data(e_uci, config_name, name, enabled, action, source, appgroups, match_all, source_objects) order = [section for section, _ in __sorted_rules(e_uci) if section != config_name] order.insert(0, config_name) if position == 'top' else order.append(config_name) @@ -786,7 +958,7 @@ def add_rule(e_uci: EUci, name: str, enabled: bool, action: str, source: list[st def edit_rule(e_uci: EUci, config_name: str, name: str, enabled: bool, action: str, source: list[str], - appgroups: list[str], match_all: bool = False) -> str: + appgroups: list[str], match_all: bool = False, source_objects: list[str] = None) -> str: """ Edit a rule. Only rules created through the API can be edited: a rule carrying a hand-written criteria has no source and no group to fill the form with, and rewriting it would change what it @@ -803,6 +975,8 @@ def edit_rule(e_uci: EUci, config_name: str, name: str, enabled: bool, action: s `match_all` is set - match_all: the rule matches every flow, narrowed to `source` when one is given. Mutually exclusive with `appgroups` + - source_objects: ids of the objects, in the form of `/`, whose addresses the rule is + narrowed to, as an alternative to `source`; see `SOURCE_OBJECT_TYPES` for the accepted ones Returns: config name of the rule edited @@ -819,9 +993,10 @@ def edit_rule(e_uci: EUci, config_name: str, name: str, enabled: bool, action: s if action not in DPI_RULE_ACTIONS: raise ValidationError('action', 'invalid_action', action) source = __validate_source(source) + source_objects = __validate_source_objects(e_uci, source_objects, source) appgroups = __validate_appgroups(e_uci, appgroups, match_all) - __save_rule_data(e_uci, config_name, name, enabled, action, source, appgroups, match_all) + __save_rule_data(e_uci, config_name, name, enabled, action, source, appgroups, match_all, source_objects) e_uci.save('dpi') return config_name diff --git a/packages/python3-nethsec/src/nethsec/objects/__init__.py b/packages/python3-nethsec/src/nethsec/objects/__init__.py index c505ac70d..4253abf82 100644 --- a/packages/python3-nethsec/src/nethsec/objects/__init__.py +++ b/packages/python3-nethsec/src/nethsec/objects/__init__.py @@ -92,7 +92,7 @@ def is_used_object(uci, database_id): if uci.get('mwan3', section, 'ns_src', default=None) == database_id or uci.get('mwan3', section, 'ns_dst', default=None) == database_id: matches.append(f'mwan3/{section}') for section in uci.get_all("dpi"): - if uci.get('dpi', section, 'source', default=None) == database_id: + if database_id in uci.get('dpi', section, 'source_object', list=True, default=[]): matches.append(f'dpi/{section}') for section in uci.get_all("objects"): try: @@ -878,7 +878,10 @@ def get_info(uci, database_id): if not name: name = uci.get(database, id, 'label', default=None) if not name: - name = id + # DPI rules keep their name here + name = uci.get(database, id, 'ns_name', default=None) + if not name: + name = id return {'database': database, 'id': id, 'name': name, 'type': type, 'family': family} except: return None diff --git a/packages/python3-nethsec/tests/test_dpi.py b/packages/python3-nethsec/tests/test_dpi.py index 739585915..b7ac083b3 100644 --- a/packages/python3-nethsec/tests/test_dpi.py +++ b/packages/python3-nethsec/tests/test_dpi.py @@ -5,7 +5,7 @@ from euci import EUci from pytest_mock import MockFixture -from nethsec import dpi, utils +from nethsec import dpi, objects, utils from nethsec.utils import ValidationError applications = { @@ -875,6 +875,7 @@ def test_list_rules(e_uci_rules): 'enabled': True, 'action': 'block', 'source': ['192.168.1.0/24'], + 'source_objects': [], 'appgroups': [{'id': group, 'name': 'Group one'}], 'match_all': False, 'managed': True, @@ -1256,3 +1257,378 @@ def test_migrate_schema_is_idempotent(e_uci_legacy, mock_reload): assert dpi_config_file(e_uci_legacy) == config_after_first_run assert not has_pending_changes(e_uci_legacy) assert not reloaded(mock_reload) + + +# Source objects + +objects_config = """ +config host 'ns_host' + option name 'host1' + option family 'ipv4' + list ipaddr '192.168.1.10' + +config host 'ns_cidr' + option name 'cidr1' + option family 'ipv4' + list ipaddr '192.168.1.0/24' + +config host 'ns_range' + option name 'range1' + option family 'ipv4' + list ipaddr '192.168.1.10-192.168.1.13' + +config host 'ns_reversed' + option name 'reversed1' + option family 'ipv4' + list ipaddr '192.168.1.20-192.168.1.10' + list ipaddr '192.168.1.30' + +config host 'ns_nested' + option name 'nested1' + option family 'ipv4' + list ipaddr 'objects/ns_host' + list ipaddr 'dhcp/ns_lease' + list ipaddr '10.0.0.1' + list ipaddr '192.168.1.10' + +config host 'ns_mapped' + option name 'mapped1' + option family 'ipv6' + list ipaddr '::ffff:192.168.1.10' + list ipaddr '::ffff:192.168.2.0/120' + +config host 'ns_all' + option name 'all1' + option family 'ipv4' + list ipaddr '0.0.0.0/0' + +config host 'ns_all6' + option name 'all6' + option family 'ipv6' + list ipaddr '::-ffff:ffff:ffff:ffff:ffff:ffff:ffff:ffff' + +config host 'ns_zone' + option name 'zone1' + option family 'ipv6' + list ipaddr 'fe80::1%eth0' + list ipaddr 'fe80::10%eth0-fe80::11%eth0' + +config host 'ns_v6range' + option name 'v6range1' + option family 'ipv6' + list ipaddr 'fd00::1-fd00::4' + list ipaddr 'FD00::50' + +config host 'ns_with_domain' + option name 'withdomain1' + option family 'ipv4' + list ipaddr 'objects/ns_domain' + +config domain 'ns_domain' + option name 'domain1' + option family 'ipv4' + option timeout '600' + list domain 'example.com' +""" + +dhcp_config = """ +config host 'ns_lease' + option name 'lease1' + option ip '192.168.1.50' + option mac '02:00:00:00:00:50' + +config domain 'ns_record' + option name 'record.lan' + option ip '192.168.1.60' +""" + +users_config = """ +config user 'ns_vpn' + option name 'vpnuser' + option openvpn_ipaddr '10.9.0.2' + +config user 'ns_novpn' + option name 'novpnuser' +""" + + +@pytest.fixture +def e_uci_sources(e_uci_rules, tmp_path, monkeypatch): + """Rules on top of a configuration holding every kind of object, address groups in a temp dir.""" + conf_dir = pathlib.Path(e_uci_rules.confdir()) + conf_dir.joinpath('objects').write_text(objects_config) + conf_dir.joinpath('dhcp').write_text(dhcp_config) + conf_dir.joinpath('users').write_text(users_config) + conf_dir.joinpath('mwan3').write_text('') + groups_dir = tmp_path.joinpath('address-groups.d') + monkeypatch.setattr(dpi, 'ADDRESS_GROUPS_DIR', groups_dir.as_posix()) + return e_uci_rules + + +def groups_dir(): + return pathlib.Path(dpi.ADDRESS_GROUPS_DIR) + + +def test_add_rule_with_source_objects(e_uci_sources): + group = group_of(e_uci_sources) + rule_id = dpi.add_rule(e_uci_sources, 'Block hosts', True, 'block', [], [group], + source_objects=['objects/ns_host', 'dhcp/ns_lease', 'objects/ns_host']) + assert e_uci_sources.get('dpi', rule_id, 'source_object', list=True) == ('objects/ns_host', 'dhcp/ns_lease') + assert e_uci_sources.get('dpi', rule_id, 'source', default=None) is None + + +@pytest.mark.parametrize('object_id', ['objects/ns_host', 'objects/ns_cidr', 'objects/ns_range', 'objects/ns_nested', + 'dhcp/ns_lease', 'dhcp/ns_record', 'users/ns_vpn']) +def test_add_rule_accepts_every_source_object_kind(e_uci_sources, object_id): + group = group_of(e_uci_sources) + rule_id = dpi.add_rule(e_uci_sources, 'Rule', True, 'block', [], [group], source_objects=[object_id]) + assert e_uci_sources.get('dpi', rule_id, 'source_object', list=True) == (object_id,) + + +@pytest.mark.parametrize('object_id', ['objects/ns_domain', 'objects/ns_missing', 'dhcp/ns_missing', 'firewall/ns_lan', + 'users/ns_novpn', '192.168.1.1', '', None, 'objects/']) +def test_add_rule_refuses_an_invalid_source_object(e_uci_sources, object_id): + group = group_of(e_uci_sources) + with pytest.raises(ValidationError) as err: + dpi.add_rule(e_uci_sources, 'Rule', True, 'block', [], [group], source_objects=[object_id]) + assert err.value.args[0] == 'source_objects' + assert err.value.args[1] == 'invalid_source_object' + + +def test_add_rule_refuses_addresses_and_source_objects_together(e_uci_sources): + group = group_of(e_uci_sources) + with pytest.raises(ValidationError) as err: + dpi.add_rule(e_uci_sources, 'Rule', True, 'block', ['192.168.1.1'], [group], + source_objects=['objects/ns_host']) + assert err.value.args[0] == 'source_objects' + assert err.value.args[1] == 'source_objects_with_source' + + +def test_edit_rule_refuses_addresses_and_source_objects_together(e_uci_sources): + group = group_of(e_uci_sources) + rule_id = dpi.add_rule(e_uci_sources, 'Rule', True, 'block', ['192.168.1.1'], [group]) + with pytest.raises(ValidationError) as err: + dpi.edit_rule(e_uci_sources, rule_id, 'Rule', True, 'block', ['192.168.1.1'], [group], + source_objects=['objects/ns_host']) + assert err.value.args[1] == 'source_objects_with_source' + + +def test_edit_rule_sets_and_clears_source_objects(e_uci_sources): + group = group_of(e_uci_sources) + rule_id = dpi.add_rule(e_uci_sources, 'Rule', True, 'block', ['192.168.1.1'], [group]) + dpi.edit_rule(e_uci_sources, rule_id, 'Rule', True, 'block', [], [group], source_objects=['users/ns_vpn']) + assert e_uci_sources.get('dpi', rule_id, 'source_object', list=True) == ('users/ns_vpn',) + assert e_uci_sources.get('dpi', rule_id, 'source', default=None) is None + dpi.edit_rule(e_uci_sources, rule_id, 'Rule', True, 'block', [], [group]) + assert e_uci_sources.get('dpi', rule_id, 'source_object', default=None) is None + + +def test_list_rules_reports_source_objects(e_uci_sources): + group = group_of(e_uci_sources) + dpi.add_rule(e_uci_sources, 'Rule', True, 'block', [], [group], + source_objects=['objects/ns_host', 'objects/ns_cidr', 'objects/ns_range', 'objects/ns_nested', + 'dhcp/ns_lease', 'dhcp/ns_record', 'users/ns_vpn']) + rule = dpi.list_rules(e_uci_sources)[0] + assert rule['source'] == [] + assert rule['source_objects'] == [ + {'id': 'objects/ns_host', 'name': 'host1', 'type': 'host_set', 'subtype': 'host', 'empty': False}, + {'id': 'objects/ns_cidr', 'name': 'cidr1', 'type': 'host_set', 'subtype': 'host_set', 'empty': False}, + {'id': 'objects/ns_range', 'name': 'range1', 'type': 'host_set', 'subtype': 'host_set', 'empty': False}, + {'id': 'objects/ns_nested', 'name': 'nested1', 'type': 'host_set', 'subtype': 'host_set', 'empty': False}, + {'id': 'dhcp/ns_lease', 'name': 'lease1', 'type': 'dhcp_static_lease', 'subtype': 'dhcp_static_lease', 'empty': False}, + {'id': 'dhcp/ns_record', 'name': 'record.lan', 'type': 'dns_record', 'subtype': 'dns_record', 'empty': False}, + {'id': 'users/ns_vpn', 'name': 'vpnuser', 'type': 'vpn_user', 'subtype': 'vpn_user', 'empty': False}, + ] + + +def test_list_rules_reports_a_source_object_gone_from_the_configuration(e_uci_sources): + group = group_of(e_uci_sources) + rule_id = dpi.add_rule(e_uci_sources, 'Rule', True, 'block', [], [group], source_objects=['objects/ns_host']) + e_uci_sources.set('dpi', rule_id, 'source_object', ['objects/ns_gone']) + assert dpi.list_rules(e_uci_sources)[0]['source_objects'] == [ + {'id': 'objects/ns_gone', 'name': 'objects/ns_gone', 'type': None, 'subtype': None, 'empty': True}] + + +def test_list_rules_reports_source_objects_with_an_empty_group(e_uci_sources): + group = group_of(e_uci_sources) + dpi.add_rule(e_uci_sources, 'Rule', True, 'block', [], [group], + source_objects=['objects/ns_host', 'objects/ns_with_domain', 'users/ns_vpn']) + # a host set holding only a domain set has no address + assert [(item['id'], item['empty']) for item in dpi.list_rules(e_uci_sources)[0]['source_objects']] == [ + ('objects/ns_host', False), ('objects/ns_with_domain', True), ('users/ns_vpn', False)] + # the VPN user loses its reserved IP: the rule stays, its group is empty + e_uci_sources.delete('users', 'ns_vpn', 'openvpn_ipaddr') + assert dpi.list_rules(e_uci_sources)[0]['source_objects'][2] == { + 'id': 'users/ns_vpn', 'name': 'vpnuser', 'type': 'vpn_user', 'subtype': 'vpn_user', 'empty': True} + + +def test_list_rules_without_source_objects(e_uci_sources): + group = group_of(e_uci_sources) + dpi.add_rule(e_uci_sources, 'Rule', True, 'block', [], [group]) + assert dpi.list_rules(e_uci_sources)[0]['source_objects'] == [] + + +@pytest.mark.parametrize('object_id, entries', [ + ('objects/ns_host', ['192.168.1.10/32']), + ('objects/ns_cidr', ['192.168.1.0/24']), + # an address group ignores ranges: they become CIDR blocks + ('objects/ns_range', ['192.168.1.10/31', '192.168.1.12/31']), + ('objects/ns_v6range', ['fd00::1/128', 'fd00::2/127', 'fd00::4/128', 'fd00::50/128']), + # the object API accepts a reversed range: it is skipped, the rest of the object is kept + ('objects/ns_reversed', ['192.168.1.30/32']), + # references are resolved, duplicates dropped + ('objects/ns_nested', ['192.168.1.10/32', '192.168.1.50/32', '10.0.0.1/32']), + # an IPv4-mapped address never matches the IPv4 flow it maps + ('objects/ns_mapped', ['192.168.1.10/32', '192.168.2.0/24']), + # a zero length prefix matches nothing in a group: its two halves match everything + ('objects/ns_all', ['0.0.0.0/1', '128.0.0.0/1']), + ('objects/ns_all6', ['::/1', '8000::/1']), + ('objects/ns_zone', ['fe80::1/128', 'fe80::10/127']), + ('dhcp/ns_lease', ['192.168.1.50/32']), + ('dhcp/ns_record', ['192.168.1.60/32']), + ('users/ns_vpn', ['10.9.0.2/32']), + # objects with no address: an empty group, matching nothing + ('users/ns_novpn', []), + ('objects/ns_with_domain', []), + ('objects/ns_domain', []), + ('objects/ns_missing', []), +]) +def test_write_address_groups_entries(e_uci_sources, object_id, entries): + # set directly: add_rule refuses some of these objects + e_uci_sources.set('dpi', 'ns_entries', 'rule') + e_uci_sources.set('dpi', 'ns_entries', 'source_object', [object_id]) + dpi.write_address_groups(e_uci_sources) + content = groups_dir().joinpath(f"30-{object_id.replace('/', '_')}.conf").read_text() + assert [line for line in content.splitlines() if not line.startswith('#')] == entries + + +def test_build_rule_criteria_with_source_objects(e_uci_sources): + group = group_of(e_uci_sources) + rule_id = dpi.add_rule(e_uci_sources, 'Rule', True, 'block', [], [group], + source_objects=['objects/ns_host', 'users/ns_vpn']) + assert dpi.build_rule_criteria(e_uci_sources, e_uci_sources.get_all('dpi', rule_id)) == ( + "(local_ip == @objects_ns_host || local_ip == @users_ns_vpn) && (app == 'netify.netflix');" + ) + + +def test_build_rule_criteria_of_a_rule_edited_by_hand_with_addresses_and_source_objects(e_uci_sources): + # the API refuses both together, a rule edited by hand matches either + group = group_of(e_uci_sources) + rule = {'appgroup': [group], 'source': ['192.168.5.5'], 'source_object': ['objects/ns_range']} + assert dpi.build_rule_criteria(e_uci_sources, rule) == ( + "(local_ip == 192.168.5.5 || local_ip == @objects_ns_range) && (app == 'netify.netflix');" + ) + + +def test_build_rule_criteria_of_a_match_all_rule_narrowed_to_source_objects(e_uci_sources): + rule_id = dpi.add_rule(e_uci_sources, 'Rule', True, 'allow', [], [], match_all=True, + source_objects=['dhcp/ns_lease']) + assert dpi.build_rule_criteria(e_uci_sources, e_uci_sources.get_all('dpi', rule_id)) == ( + '(local_ip == @dhcp_ns_lease);' + ) + + +def test_build_rule_criteria_keeps_a_source_object_without_addresses(e_uci_sources): + # dropping the term would turn the rule into one matching every host + group = group_of(e_uci_sources) + rule_id = dpi.add_rule(e_uci_sources, 'Rule', True, 'block', [], [group], source_objects=['objects/ns_with_domain']) + assert dpi.build_rule_criteria(e_uci_sources, e_uci_sources.get_all('dpi', rule_id)) == ( + "(local_ip == @objects_ns_with_domain) && (app == 'netify.netflix');" + ) + + +def test_write_address_groups(e_uci_sources): + group = group_of(e_uci_sources) + dpi.add_rule(e_uci_sources, 'One', True, 'block', [], [group], source_objects=['objects/ns_range', 'objects/ns_with_domain']) + dpi.add_rule(e_uci_sources, 'Two', False, 'block', [], [group], source_objects=['objects/ns_range', 'dhcp/ns_lease']) + tags = dpi.write_address_groups(e_uci_sources) + assert sorted(tags) == ['dhcp_ns_lease', 'objects_ns_range', 'objects_ns_with_domain'] + assert sorted(path.name for path in groups_dir().iterdir()) == [ + '30-dhcp_ns_lease.conf', '30-objects_ns_range.conf', '30-objects_ns_with_domain.conf'] + assert groups_dir().joinpath('30-objects_ns_range.conf').read_text() == ( + '# range1\n# objects/ns_range, generated by dpi-config: do not edit\n192.168.1.10/31\n192.168.1.12/31\n') + # an object without addresses still gets its file: the criteria references it + assert groups_dir().joinpath('30-objects_ns_with_domain.conf').read_text() == ( + '# withdomain1\n# objects/ns_with_domain, generated by dpi-config: do not edit\n') + assert groups_dir().joinpath('30-dhcp_ns_lease.conf').read_text().startswith( + '# lease1\n# dhcp/ns_lease, generated by dpi-config: do not edit\n') + + +def test_write_address_groups_removes_only_its_own_stale_files(e_uci_sources): + group = group_of(e_uci_sources) + groups_dir().mkdir() + generated = '# objects/ns_old, generated by dpi-config: do not edit\n10.0.0.1/32\n' + # other prefixes or extensions: kept + for name in ('10-agent.conf', '20-other.conf', '30-objects_ns_old.txt'): + groups_dir().joinpath(name).write_text(generated) + # stale with the prefix: removed, with or without the header, as the agent saves its groups without it + groups_dir().joinpath('30-objects_ns_old.conf').write_text('# old1\n' + generated) + groups_dir().joinpath('30-objects_ns_saved.conf').write_text('10.0.0.1\n') + groups_dir().joinpath('30-dpi_objects_ns_old.conf').write_text('') + # referenced, as saved by the agent: rewritten with the header + groups_dir().joinpath('30-objects_ns_host.conf').write_text('192.168.1.10\n') + dpi.add_rule(e_uci_sources, 'One', True, 'block', [], [group], source_objects=['objects/ns_host']) + dpi.write_address_groups(e_uci_sources) + assert sorted(path.name for path in groups_dir().iterdir()) == [ + '10-agent.conf', '20-other.conf', '30-objects_ns_host.conf', '30-objects_ns_old.txt'] + assert groups_dir().joinpath('30-objects_ns_host.conf').read_text().splitlines()[1] == ( + '# objects/ns_host, generated by dpi-config: do not edit') + + +def test_write_address_groups_follows_the_object(e_uci_sources): + group = group_of(e_uci_sources) + rule_id = dpi.add_rule(e_uci_sources, 'One', True, 'block', [], [group], source_objects=['objects/ns_host']) + dpi.write_address_groups(e_uci_sources) + path = groups_dir().joinpath('30-objects_ns_host.conf') + inode = path.stat().st_ino + # unchanged: the file is left alone + dpi.write_address_groups(e_uci_sources) + assert path.stat().st_ino == inode + # the object changes: the file follows + e_uci_sources.set('objects', 'ns_host', 'ipaddr', ['192.168.1.11']) + dpi.write_address_groups(e_uci_sources) + assert path.read_text().splitlines()[2:] == ['192.168.1.11/32'] + # the object is renamed: the file follows + e_uci_sources.set('objects', 'ns_host', 'name', 'renamed') + dpi.write_address_groups(e_uci_sources) + assert path.read_text().splitlines()[0] == '# renamed' + # no rule references it anymore: the file goes + dpi.edit_rule(e_uci_sources, rule_id, 'One', True, 'block', [], [group]) + assert dpi.write_address_groups(e_uci_sources) == [] + assert not path.exists() + + +def test_source_object_is_used(e_uci_sources): + group = group_of(e_uci_sources) + assert objects.is_used_object(e_uci_sources, 'objects/ns_cidr') == (False, []) + rule_id = dpi.add_rule(e_uci_sources, 'One', True, 'block', [], [group], source_objects=['objects/ns_cidr']) + assert objects.is_used_object(e_uci_sources, 'objects/ns_cidr') == (True, [f'dpi/{rule_id}']) + with pytest.raises(ValidationError) as err: + objects.delete_host_set(e_uci_sources, 'ns_cidr') + assert err.value.args[1] == 'host_set_is_used' + assert objects.is_used_object(e_uci_sources, 'dhcp/ns_record') == (False, []) + # the usage is shown with the rule name + assert objects.get_info(e_uci_sources, f'dpi/{rule_id}')['name'] == 'One' + + +def test_write_address_groups_header_without_name(e_uci_sources): + group = group_of(e_uci_sources) + dpi.add_rule(e_uci_sources, 'One', True, 'block', [], [group], source_objects=['objects/ns_host']) + # the object loses its name, or is gone altogether: the header holds only the id + e_uci_sources.delete('objects', 'ns_host', 'name') + dpi.write_address_groups(e_uci_sources) + assert groups_dir().joinpath('30-objects_ns_host.conf').read_text().splitlines()[0] == ( + '# objects/ns_host, generated by dpi-config: do not edit') + e_uci_sources.delete('objects', 'ns_host') + dpi.write_address_groups(e_uci_sources) + assert groups_dir().joinpath('30-objects_ns_host.conf').read_text() == ( + '# objects/ns_host, generated by dpi-config: do not edit\n') + + +def test_write_address_groups_header_name_on_one_line(e_uci_sources): + group = group_of(e_uci_sources) + dpi.add_rule(e_uci_sources, 'One', True, 'block', [], [group], source_objects=['objects/ns_host']) + e_uci_sources.set('objects', 'ns_host', 'name', 'two\nlines') + dpi.write_address_groups(e_uci_sources) + assert groups_dir().joinpath('30-objects_ns_host.conf').read_text().splitlines()[:2] == [ + '# two lines', '# objects/ns_host, generated by dpi-config: do not edit'] From c427a4da64e3d939950ce12baf03007dad38d231 Mon Sep 17 00:00:00 2001 From: Matteo Di Lorenzi Date: Mon, 16 Nov 2026 11:57:50 +0100 Subject: [PATCH 2/3] feat(dpi): refactor logic to make one address-group file for each object --- .agents/skills/netifyd/SKILL.md | 22 +- packages/ns-api/Makefile | 2 +- packages/ns-api/README.md | 13 +- packages/ns-api/files/ns.ovpnrw | 20 +- .../ns-api/files/post-commit/reload-dpi.py | 22 -- .../post-commit/update-address-groups.py | 16 + packages/ns-dpi/Makefile | 6 +- packages/ns-dpi/README.md | 52 ++- packages/ns-dpi/files/address-groups.init | 16 + packages/ns-dpi/files/address-groups.keep | 1 + packages/ns-dpi/files/dpi-config | 13 - packages/ns-dpi/files/write-address-groups | 13 + .../src/nethsec/dpi/__init__.py | 135 +------ .../src/nethsec/objects/__init__.py | 165 +++++++++ packages/python3-nethsec/tests/test_dpi.py | 157 +-------- .../python3-nethsec/tests/test_objects.py | 331 +++++++++++++++++- 16 files changed, 640 insertions(+), 344 deletions(-) delete mode 100755 packages/ns-api/files/post-commit/reload-dpi.py create mode 100755 packages/ns-api/files/post-commit/update-address-groups.py create mode 100755 packages/ns-dpi/files/address-groups.init create mode 100644 packages/ns-dpi/files/address-groups.keep create mode 100755 packages/ns-dpi/files/write-address-groups diff --git a/.agents/skills/netifyd/SKILL.md b/.agents/skills/netifyd/SKILL.md index 63ad1751a..645fbc016 100644 --- a/.agents/skills/netifyd/SKILL.md +++ b/.agents/skills/netifyd/SKILL.md @@ -104,6 +104,7 @@ until the next reload and then vanishes. Change the generator or its UCI input i | `table inet netifyd` (nftables) | `/usr/sbin/ns-netifyd-configure` (on start and reload) | `/etc/config/netifyd` → `ns_config` | | `netify-application-catalog.json` and the other catalog/category files | `dpi-data-update` (nightly cron) | Netify's data service | | `/usr/share/nftables.d/table-pre/` DPI chains | `/usr/sbin/dpi-nft` | `/etc/config/dpi` | +| `address-groups.d/30-*.conf` | `nethsec.objects.write_address_groups` (on commit, by `ns.ovpnrw`, at boot) | `/etc/config/objects`, `dhcp`, `users` | `/usr/sbin/dpi` is the whole DPI apply path: `dpi-config` → `dpi-nft` → `/etc/init.d/netifyd reload`. Run it after changing `/etc/config/dpi`; don't reproduce its steps by hand. @@ -204,14 +205,19 @@ Two operational facts: MAC members only match via `mac ==`, so don't put them in a group a `local_ip` rule references. -`dpi-config` owns the `30-` prefix: one `30-_.conf` group per object referenced by a DPI -rule source, with a `# ` and a `# , generated by dpi-config: do not edit` header -(`nethsec.dpi.write_address_groups`), and every other `30-*.conf` file is removed. The agent keeps the -groups it loaded in memory, a reload doesn't drop the ones whose file was removed, and on stop it saves all -of them back, without comments: that's why ownership goes by prefix. A group removed from every rule -therefore comes back as a file on the next agent restart (unreferenced, so harmless) until the agent -drops it from memory, e.g. with the `flush-address-group` socket command, which also deletes its file. -A `kill -9` saves nothing. Verified on a device with agent 5.2.9: a reload re-reads the groups +The `30-` prefix belongs to `nethsec.objects.write_address_groups`: one `30-_.conf` group +per firewall object resolving to addresses, used by a DPI rule or not, with a `# ` and a +`# , generated from the firewall objects: do not edit` header, and every other `30-*.conf` file is +removed. It runs from the `update-address-groups.py` post-commit hook (`objects`, `dhcp`, `users`), from +`ns.ovpnrw` (reserved IP of a VPN user) and at boot (`/etc/init.d/address-groups`, `START=95`, before +netifyd); `dpi-config` only references the groups. The `30-*.conf` files are in +`/lib/upgrade/keep.d/ns-dpi`, so backups and the HA sync carry them. The agent keeps the groups it loaded +in memory, a reload doesn't drop the ones whose file was removed (it drops their single addresses, not +their networks), and on stop it saves all of them back, without comments: that's why ownership goes by +prefix. The group of a deleted object therefore comes back as a file on the next agent restart +(unreferenced, so harmless) until the next write removes it; the boot write runs between the stop that +saved it and the start that would load it, so after a reboot it is gone from memory too. The +`flush-address-group` socket command drops a group from memory and deletes its file. A `kill -9` saves nothing. Verified on a device with agent 5.2.9: a reload re-reads the groups without restarting the agent; a range line is silently ignored, so ranges are written as CIDR blocks; a `/0` matches nothing (in a group and inline), so it is written as two `/1`; an IPv4-mapped IPv6 address never matches an IPv4 flow; an empty group or a missing tag matches nothing without errors. IPv6 diff --git a/packages/ns-api/Makefile b/packages/ns-api/Makefile index 3d0d2af57..e87596cae 100644 --- a/packages/ns-api/Makefile +++ b/packages/ns-api/Makefile @@ -198,7 +198,7 @@ define Package/ns-api/install $(INSTALL_BIN) ./files/post-commit/update-timezone.py $(1)/usr/libexec/ns-api/post-commit $(INSTALL_BIN) ./files/post-commit/restart-wireguard.py $(1)/usr/libexec/ns-api/post-commit $(INSTALL_BIN) ./files/post-commit/clear-user-tokens.py $(1)/usr/libexec/ns-api/post-commit - $(INSTALL_BIN) ./files/post-commit/reload-dpi.py $(1)/usr/libexec/ns-api/post-commit + $(INSTALL_BIN) ./files/post-commit/update-address-groups.py $(1)/usr/libexec/ns-api/post-commit $(INSTALL_BIN) ./files/pre-commit/clean-network.py $(1)/usr/libexec/ns-api/pre-commit $(INSTALL_BIN) ./files/remove-pppoe-keepalive $(1)/usr/share/ns-api $(INSTALL_DIR) $(1)/etc/uci-defaults diff --git a/packages/ns-api/README.md b/packages/ns-api/README.md index bb07704bf..677dcd299 100644 --- a/packages/ns-api/README.md +++ b/packages/ns-api/README.md @@ -1844,6 +1844,8 @@ The APIs can raise the following validation errors: - reserved_ip_must_be_in_server_network - reserverd_ip_already_used - reserved_ip_must_be_in_server_network +- reserved_ip_is_used: the reserved IP can't be removed while the user is used as an object, e.g. by a + DPI rule, a firewall rule or a host set; the error value lists where it is used ### disconnect-user @@ -3803,8 +3805,7 @@ Rules with `ns_visible '0'` are left out. - `match_all`: the rule matches every flow instead of naming application groups - `source_objects`: objects the source references, with their `name`, `type` and `subtype` (the same values `ns.objects list-hosts` reports). An object gone from the configuration is reported with its id - as name and `null` type. `empty` is true when the object has no address, e.g. a VPN user whose - reserved IP was removed: the rule matches no host for that object + as name and `null` type - `index`: position of the rule in the list Example response: @@ -3823,8 +3824,7 @@ Example response: "id": "objects/ns_16faa17f", "name": "office", "type": "host_set", - "subtype": "host_set", - "empty": false + "subtype": "host_set" } ], "appgroups": [ @@ -8045,6 +8045,11 @@ Example response: Manage domain sets and host sets. +Every object resolving to addresses (host sets, DHCP static leases, DNS records, VPN users with a reserved +IP) has a netifyd address group, `/etc/netifyd/address-groups.d/30-_.conf`, used by the DPI +rules. The `update-address-groups.py` post-commit hook writes them when `objects`, `dhcp` or `users` are +committed, see the `ns-dpi` package. + ### list-domain-sets List all domain sets: diff --git a/packages/ns-api/files/ns.ovpnrw b/packages/ns-api/files/ns.ovpnrw index ab4bd2074..dbc1a32bd 100755 --- a/packages/ns-api/files/ns.ovpnrw +++ b/packages/ns-api/files/ns.ovpnrw @@ -807,6 +807,8 @@ def add_user(args): else: users.edit_local_user(u, args['username'], extra_fields=ovpn_config) u.commit("users") + # add related address groups used by DPI rules + objects.update_address_groups(u) return {"result": "success"} def import_users(ovpninstance): @@ -841,8 +843,13 @@ def edit_user(args): if user_id == None: return utils.validation_error("username", "user_not_found", args["username"]) - old_ipaddr = u.get("users", user_id, 'openvpn_ipaddr', default="") - if args["ipaddr"] and old_ipaddr != args["ipaddr"]: + # an object needs its reserved IP: removing it would leave the rules using the user without an address + if not args["ipaddr"] and u.get("users", user_id, 'openvpn_ipaddr', default=""): + used, matches = objects.is_used_object(u, f'users/{user_id}') + if used: + return utils.validation_error("ipaddr", "reserved_ip_is_used", matches) + + if args["ipaddr"] and u.get("users", user_id, 'openvpn_ipaddr', default="") != args["ipaddr"]: valid, error = is_valid_ip(ovpninstance, args["ipaddr"]) if not valid: return utils.validation_error("ipaddr", error, args["ipaddr"]) @@ -857,11 +864,8 @@ def edit_user(args): pass u.set("users", user_id, "openvpn_enabled", args["enabled"]) u.commit("users") - # reload dpi if the ipaddr changed and the user is used by dpi - if u.get("users", user_id, 'openvpn_ipaddr', default="") != old_ipaddr: - _, matches = objects.is_used_object(u, f"users/{user_id}") - if any(match.startswith("dpi/") for match in matches): - subprocess.run(["/etc/init.d/dpi", "reload"], check=False, capture_output=True) + # update related address groups used by DPI rules + objects.update_address_groups(u) return {"result": "success"} def delete_user(ovpninstance, username): @@ -895,6 +899,8 @@ def delete_user(ovpninstance, username): u.commit("users") except: pass + # delete related address groups used by DPI rules + objects.update_address_groups(u) try: revoke_user_certificate(ovpninstance, username) except: diff --git a/packages/ns-api/files/post-commit/reload-dpi.py b/packages/ns-api/files/post-commit/reload-dpi.py deleted file mode 100755 index 407cdd6cc..000000000 --- a/packages/ns-api/files/post-commit/reload-dpi.py +++ /dev/null @@ -1,22 +0,0 @@ -#!/usr/bin/python - -# -# Copyright (C) 2026 Nethesis S.r.l. -# SPDX-License-Identifier: GPL-2.0-only -# - -# This script reloads the DPI when an object referenced by a DPI rule source may have changed: -# the address group of every referenced object is regenerated from the committed configuration. -# reload_config can't do it, as it reloads dpi only when /etc/config/dpi itself changes. - -import subprocess - -from euci import EUci -from nethsec import utils - -# A change to dpi itself is left to reload_config, which reloads the service anyway. -if "dpi" not in changes and ("objects" in changes or "users" in changes or "dhcp" in changes): # noqa: F821 - for rule in (utils.get_all_by_type(EUci(), "dpi", "rule") or {}).values(): - if rule.get("source_object"): - subprocess.run(["/etc/init.d/dpi", "reload"], check=False) - break diff --git a/packages/ns-api/files/post-commit/update-address-groups.py b/packages/ns-api/files/post-commit/update-address-groups.py new file mode 100755 index 000000000..2f8bcae22 --- /dev/null +++ b/packages/ns-api/files/post-commit/update-address-groups.py @@ -0,0 +1,16 @@ +#!/usr/bin/python + +# +# Copyright (C) 2026 Nethesis S.r.l. +# SPDX-License-Identifier: GPL-2.0-only +# + +# This script writes the netifyd address groups of the firewall objects once their changes are committed: +# one file per object resolving to addresses, the ones of objects that are gone removed, and netifyd +# reloaded when a file changed. DPI rules match an object through its group. + +from euci import EUci +from nethsec import objects + +if "objects" in changes or "dhcp" in changes or "users" in changes: # noqa: F821 + objects.update_address_groups(EUci()) diff --git a/packages/ns-dpi/Makefile b/packages/ns-dpi/Makefile index 0931ef1bd..78d028572 100644 --- a/packages/ns-dpi/Makefile +++ b/packages/ns-dpi/Makefile @@ -53,7 +53,7 @@ fi exit 0 endef -define Package/ns-plug/conffiles +define Package/ns-dpi/conffiles /etc/config/dpi endef @@ -68,12 +68,14 @@ define Package/ns-dpi/install $(INSTALL_DIR) $(1)/etc/uci-defaults $(INSTALL_DIR) $(1)/usr/share/ns-plug/hooks/unregister $(INSTALL_DIR) $(1)/etc/xtables + $(INSTALL_DIR) $(1)/lib/upgrade/keep.d $(INSTALL_CONF) ./files/connlabel.conf $(1)/etc/connlabel.conf $(LN) /etc/connlabel.conf $(1)/etc/xtables/connlabel.conf $(INSTALL_BIN) ./files/dpi.init $(1)/etc/init.d/dpi $(INSTALL_BIN) ./files/dpi-license-update.init $(1)/etc/init.d/dpi-license-update $(INSTALL_BIN) ./files/dpi-data-update.init $(1)/etc/init.d/dpi-data-update $(INSTALL_BIN) ./files/dpi-update.init $(1)/etc/init.d/dpi-update + $(INSTALL_BIN) ./files/address-groups.init $(1)/etc/init.d/address-groups $(INSTALL_BIN) ./files/dpi $(1)/usr/sbin/ $(INSTALL_BIN) ./files/dpi-nft $(1)/usr/sbin/ $(INSTALL_BIN) ./files/dpi-config $(1)/usr/sbin/ @@ -81,6 +83,8 @@ define Package/ns-dpi/install $(INSTALL_BIN) ./files/dpi-data-update.py $(1)/usr/sbin/dpi-data-update $(INSTALL_BIN) ./files/dpi-update.py $(1)/usr/sbin/dpi-update $(INSTALL_BIN) ./files/dpi-migrate.py $(1)/usr/libexec/ns-dpi/dpi-migrate + $(INSTALL_BIN) ./files/write-address-groups $(1)/usr/libexec/ns-dpi/write-address-groups + $(INSTALL_CONF) ./files/address-groups.keep $(1)/lib/upgrade/keep.d/ns-dpi $(INSTALL_CONF) ./files/20_dpi $(1)/etc/uci-defaults $(INSTALL_BIN) ./files/21_dpi_migrate $(1)/etc/uci-defaults/21_dpi_migrate $(INSTALL_BIN) ./files/23_dpi_drop_options $(1)/etc/uci-defaults/23_dpi_drop_options diff --git a/packages/ns-dpi/README.md b/packages/ns-dpi/README.md index 091f29d19..6a6705bab 100644 --- a/packages/ns-dpi/README.md +++ b/packages/ns-dpi/README.md @@ -79,34 +79,45 @@ config rule 'ns_9d40be71' ### Objects as source -`dpi-config` writes the addresses of every object referenced by a rule to a netifyd address group, -`/etc/netifyd/address-groups.d/30-_.conf`, and the criteria matches it as -`local_ip == @_`. Each file starts with a comment holding the object name, when the object -has one, followed by a comment holding the object id and `generated by dpi-config: do not edit`. The files -are regenerated on every DPI reload. The `30-` prefix belongs to `dpi-config`: every `30-*.conf` file no -rule references is removed, files with other prefixes are never touched. +Every firewall object resolving to addresses has a netifyd address group, +`/etc/netifyd/address-groups.d/30-_.conf`, whether a rule uses it or not: host sets, DHCP +static leases, DNS records and VPN users with a reserved IP. A rule references the object as +`local_ip == @_`, so `dpi-config` only builds the criteria and never writes a group. + +The files follow the objects, not the rules. They are written by `nethsec.objects.write_address_groups`: + +- on commit, by the `update-address-groups.py` post-commit hook of `ns.commit`, when `objects`, `dhcp` or + `users` change; netifyd is reloaded if a file changed +- by `ns.ovpnrw` when a VPN user gets, changes or loses its reserved IP, as it commits on its own +- at boot, by the `address-groups` service (`START=95`), before netifyd starts (`START=99`) + +Each file starts with a comment holding the object name, when the object has one, followed by a comment +holding the object id and `generated from the firewall objects: do not edit`. A file is rewritten only when +its content changes. The `30-` prefix belongs to the writer: every `30-*.conf` file whose object is gone, +or has no address, is removed; files with other prefixes are never touched. An object with no address has +no file: a rule referencing it matches no host, as a missing group matches nothing. The reserved IP of a +VPN user can't be removed while the user is used as an object (`ns.ovpnrw edit-user` fails with +`reserved_ip_is_used`), so a rule can lose its addresses only when the configuration is changed outside +the API, e.g. when a whole user database is deleted. + +The `30-*.conf` files are listed in `/lib/upgrade/keep.d/ns-dpi`, so they are part of the backup, of the +HA configuration sync and survive an image upgrade, always matching the configuration they come with. netifyd keeps the groups it loaded in memory, a reload doesn't drop the ones whose file was removed, and -when it stops it saves all of them back to the directory, without comments. So a group removed from every -rule comes back as a file when netifyd restarts: no rule references it, so it matches nothing, and the -next DPI reload removes the file again. Known limitation: the group stays in the agent memory until it is -flushed. +when it stops it saves all of them back to the directory, without comments. So after a netifyd restart +the files lose their header until the next write, and the group of a deleted object can come back as a +file: no rule references it, and the next write removes it. The write at boot runs after the stop that saved it and before the start that would load it again, +dropping it from memory too. The addresses are written the way an address group can match them: - ranges become CIDR blocks, as address groups ignore them. A range whose first address is greater than - its last is skipped and logged + its last becomes the CIDR blocks of the ordered range; the host set itself is left as entered - references to other objects are resolved - IPv4-mapped IPv6 addresses (`::ffff:a.b.c.d`) become IPv4 addresses, as they never match IPv4 flows - `0.0.0.0/0` and `::/0` become their two `/1` halves, as a zero length prefix matches nothing - the zone of link-local addresses is dropped -An object with no address, e.g. a VPN user with no reserved IP, gets an empty group: the rule matches no -host instead of every host. - -When an object changes, the `reload-dpi.py` post-commit hook of `ns.commit` reloads the DPI if any rule -references an object, so the group follows the object. - ## Migration from the previous schema On upgrade, and every time the DPI service starts, `/usr/libexec/ns-dpi/dpi-migrate` converts the @@ -131,11 +142,16 @@ cat /etc/netifyd/netify-proc-flow-actions.json nft list chain inet fw4 dpi_actions ``` -Check the address groups of the objects used as source: +Check the address groups of the objects: ``` head /etc/netifyd/address-groups.d/30-* ``` +Write them again from the configuration: +``` +/usr/libexec/ns-dpi/write-address-groups +``` + List the blocked connections: ``` conntrack -L -o label -l netify-blocked diff --git a/packages/ns-dpi/files/address-groups.init b/packages/ns-dpi/files/address-groups.init new file mode 100755 index 000000000..8af001cc1 --- /dev/null +++ b/packages/ns-dpi/files/address-groups.init @@ -0,0 +1,16 @@ +#!/bin/sh /etc/rc.common + +# +# Copyright (C) 2026 Nethesis S.r.l. +# SPDX-License-Identifier: GPL-2.0-only +# + +# Write the netifyd address groups of the firewall objects before netifyd starts (START=99). +# netifyd saves the groups it holds when it stops, including the ones of objects deleted while it was +# running: removing them here, before it loads them again, drops them for good. + +START=95 + +start() { + /usr/libexec/ns-dpi/write-address-groups +} diff --git a/packages/ns-dpi/files/address-groups.keep b/packages/ns-dpi/files/address-groups.keep new file mode 100644 index 000000000..c3c6512ad --- /dev/null +++ b/packages/ns-dpi/files/address-groups.keep @@ -0,0 +1 @@ +/etc/netifyd/address-groups.d/30-*.conf diff --git a/packages/ns-dpi/files/dpi-config b/packages/ns-dpi/files/dpi-config index 0cbe6c18f..fa3748b29 100755 --- a/packages/ns-dpi/files/dpi-config +++ b/packages/ns-dpi/files/dpi-config @@ -62,16 +62,6 @@ config = { u = EUci() -# address groups of the objects referenced by the rule sources: written before the criteria that -# reference them, and reloaded by the agent together with this file. If they can't be written, the -# rules using objects are skipped below: their criteria would reference groups that don't exist -try: - dpi.write_address_groups(u) - address_groups_ok = True -except OSError as error: - syslog.syslog(syslog.LOG_ERR, f"dpi-config: cannot write the address groups: {error}") - address_groups_ok = False - # a rule from the schema used before application groups existed carries at least one of these fields; # dpi.migrate_schema converts it, so one still here was not migrated yet legacy_fields = ('device', 'application', 'protocol', 'category') @@ -103,9 +93,6 @@ for section in u.get_all('dpi'): if criteria and not criteria.endswith(';'): criteria = f'{criteria};' else: - if rule.get('source_object') and not address_groups_ok: - syslog.syslog(syslog.LOG_WARNING, f"dpi-config: skipping {section}, its source objects are not available") - continue # application groups, optionally narrowed to a source, or a match-all rule criteria = dpi.build_rule_criteria(u, rule) if not criteria: diff --git a/packages/ns-dpi/files/write-address-groups b/packages/ns-dpi/files/write-address-groups new file mode 100755 index 000000000..47d44358f --- /dev/null +++ b/packages/ns-dpi/files/write-address-groups @@ -0,0 +1,13 @@ +#!/usr/bin/python3 + +# +# Copyright (C) 2026 Nethesis S.r.l. +# SPDX-License-Identifier: GPL-2.0-only +# + +# Write the netifyd address groups of the firewall objects, see nethsec.objects.write_address_groups + +from euci import EUci +from nethsec import objects + +objects.write_address_groups(EUci()) diff --git a/packages/python3-nethsec/src/nethsec/dpi/__init__.py b/packages/python3-nethsec/src/nethsec/dpi/__init__.py index a62d3577c..9943a0107 100644 --- a/packages/python3-nethsec/src/nethsec/dpi/__init__.py +++ b/packages/python3-nethsec/src/nethsec/dpi/__init__.py @@ -11,7 +11,6 @@ import ipaddress import json -import os import subprocess import syslog @@ -658,24 +657,10 @@ def expand_source(values: list[str]) -> list[str]: # Source objects: firewall objects resolving to IP addresses, referenced by a rule instead of typing the -# addresses in. Each one is written to a netifyd address group, `ADDRESS_GROUPS_DIR/30-.conf`, and -# the criteria matches it as `local_ip == @`: the criteria stays one term wide whatever the object -# holds, and a change to the object only rewrites its file. - -ADDRESS_GROUPS_DIR = '/etc/netifyd/address-groups.d' - -# prefixes below 20 belong to the agent itself, this one belongs to dpi-config: every file carrying it and -# not referenced by a rule is removed. The agent saves the groups it holds when it stops, without comments -# and including the ones whose file was removed while it was running, so the prefix is what tells a stale -# file apart. Such a file comes back on every agent restart until the agent drops the group from memory -ADDRESS_GROUP_FILE_PREFIX = '30-' - -# ending of the header comment of every file written here, for whoever reads it -ADDRESS_GROUP_FILE_MARKER = 'generated by dpi-config: do not edit' - -# (database, section type) of the objects a source can reference: everything resolving to addresses. -# Domain sets are left out: they describe destinations, while a source is matched against the local host -SOURCE_OBJECT_TYPES = (('objects', 'host'), ('dhcp', 'host'), ('dhcp', 'domain'), ('users', 'user')) +# addresses in. Every such object has its netifyd address group, written by `objects.write_address_groups` +# when the object is committed, and the criteria matches it as `local_ip == @`: the criteria stays one +# term wide whatever the object holds, and a change to the object only rewrites its file. A source can +# reference the objects with an address group, see `objects.ADDRESS_GROUP_TYPES`. def __validate_source_objects(e_uci: EUci, values: list[str], source: list[str]) -> list[str]: @@ -690,7 +675,7 @@ def __validate_source_objects(e_uci: EUci, values: list[str], source: list[str]) if not isinstance(value, str) or not objects.is_object_id(value): raise ValidationError('source_objects', 'invalid_source_object', value) database, _, section = value.partition('/') - if not section or (database, e_uci.get(database, section, default=None)) not in SOURCE_OBJECT_TYPES: + if not section or (database, e_uci.get(database, section, default=None)) not in objects.ADDRESS_GROUP_TYPES: raise ValidationError('source_objects', 'invalid_source_object', value) # a user is an object only with a VPN account holding a reserved address if database == 'users' and not e_uci.get('users', section, 'openvpn_ipaddr', default=None): @@ -700,104 +685,13 @@ def __validate_source_objects(e_uci: EUci, values: list[str], source: list[str]) return source_objects -def __strip_zone(value: str) -> str: - """Drop the zone of a link-local address, e.g. `fe80::1%eth0/64` becomes `fe80::1/64`.""" - if '%' not in value: - return value - address, _, rest = value.partition('%') - _, slash, prefix = rest.partition('/') - return f'{address}{slash}{prefix}' - - -def __address_group_entries(e_uci: EUci, object_id: str) -> list[str]: - """ - The entries of the address group of an object, see `write_address_groups`: empty when the object has - no address the agent can match, or is gone. - """ - entries = [] - for value in objects.get_object_ips(e_uci, object_id): - try: - if '-' in value: - first, last = (ipaddress.ip_address(__strip_zone(part.strip())) for part in value.split('-', 1)) - networks = list(ipaddress.summarize_address_range(first, last)) - else: - networks = [ipaddress.ip_network(__strip_zone(value.strip()), strict=False)] - except (ValueError, TypeError) as error: - syslog.syslog(syslog.LOG_WARNING, f"dpi: skipping {value!r} of {object_id}: {error}") - continue - for network in networks: - if network.version == 6 and network.prefixlen >= 96 and network.network_address.ipv4_mapped: - network = ipaddress.ip_network(f'{network.network_address.ipv4_mapped}/{network.prefixlen - 96}') - for entry in network.subnets(new_prefix=1) if network.prefixlen == 0 else [network]: - if str(entry) not in entries: - entries.append(str(entry)) - return entries - - -def write_address_groups(e_uci: EUci) -> list[str]: - """ - Write the address group of every object referenced by a rule source, and remove every other file with - the `ADDRESS_GROUP_FILE_PREFIX` prefix. A file is rewritten only when its content changes. - - Every referenced object gets its file, even an empty one: the criteria references it anyway, and an - empty group simply matches nothing, which is what a source with no address means. - - The addresses are written the way an address group can match them: ranges become CIDR blocks, as an - address group silently ignores them; an IPv4-mapped IPv6 network becomes the IPv4 network it maps, as - it never matches an IPv4 flow; a zero length prefix, which matches nothing, is split into its two - halves. A value that cannot be turned into an address, like a range whose first address is greater - than its last, is skipped with a log line: the object API accepts it, the agent would ignore it. - - Args: - - e_uci: euci instance - - Returns: - the tags written - """ - os.makedirs(ADDRESS_GROUPS_DIR, exist_ok=True) - wanted = {} - for rule in (utils.get_all_by_type(e_uci, 'dpi', 'rule') or {}).values(): - for object_id in rule.get('source_object', []): - tag = object_id.replace('/', '_') - if tag in wanted: - continue - # header: the object name, when it has one, on one line, then the id and the marker - database, _, section = object_id.partition('/') - name = e_uci.get(database, section, 'name', default='') or \ - e_uci.get(database, section, 'label', default='') - name = ' '.join(str(name).split()) - lines = [f'# {name}'] if name else [] - lines.append(f'# {object_id}, {ADDRESS_GROUP_FILE_MARKER}') - lines.extend(__address_group_entries(e_uci, object_id)) - wanted[tag] = ''.join(f'{line}\n' for line in lines) - - for filename in os.listdir(ADDRESS_GROUPS_DIR): - if not filename.startswith(ADDRESS_GROUP_FILE_PREFIX) or not filename.endswith('.conf'): - continue - if filename[len(ADDRESS_GROUP_FILE_PREFIX):-len('.conf')] not in wanted: - os.remove(os.path.join(ADDRESS_GROUPS_DIR, filename)) - - for tag, content in wanted.items(): - path = os.path.join(ADDRESS_GROUPS_DIR, f'{ADDRESS_GROUP_FILE_PREFIX}{tag}.conf') - try: - with open(path, 'r') as fp: - if fp.read() == content: - continue - except FileNotFoundError: - pass - with open(f'{path}.tmp', 'w') as fp: - fp.write(content) - os.replace(f'{path}.tmp', path) - - return list(wanted) - - def build_rule_criteria(e_uci: EUci, rule: dict) -> str: """ Build the criteria of a managed rule: the source, when set, ANDed with the union of its groups. The source is made of its addresses or of the address groups of its objects, see - `write_address_groups`; a rule holding both, e.g. edited by hand, matches either. + `objects.write_address_groups`; a rule holding both, e.g. edited by hand, matches either. An object + without addresses has no group file: the term stays, and a missing group matches nothing. Args: - e_uci: euci instance @@ -808,7 +702,7 @@ def build_rule_criteria(e_uci: EUci, rule: dict) -> str: """ match = expand_appgroups(e_uci, list(rule.get('appgroup', []))) sources = [f'local_ip == {source}' for source in expand_source(list(rule.get('source', [])))] - sources += [f"local_ip == @{object_id.replace('/', '_')}" for object_id in rule.get('source_object', [])] + sources += [f"local_ip == @{objects.address_group_tag(object_id)}" for object_id in rule.get('source_object', [])] if not match: if not sources: @@ -832,8 +726,7 @@ def list_rules(e_uci: EUci) -> list[dict]: Returns: list of dicts, each dict contains the property "id", "name", "enabled", "action", "source", "source_objects", "appgroups", "match_all", "managed" and "index", plus "criteria" for the rules - the API did not create. Each source object carries "id", "name", "type", "subtype" and "empty", true - when its address group holds no address + the API did not create. Each source object carries "id", "name", "type" and "subtype" """ groups = {section: group.get('ns_name', '') for section, group in (utils.get_all_by_type(e_uci, 'dpi', 'appgroup') or {}).items()} @@ -858,11 +751,9 @@ def list_rules(e_uci: EUci) -> list[dict]: for object_id in rule.get('source_object', []): # an object gone from the configuration is still listed, named after its id, so the rule can be fixed info = objects.get_info(e_uci, object_id) if objects.object_exists(e_uci, object_id) else None - # its address group matches nothing, e.g. a VPN user without a reserved IP anymore - empty = not __address_group_entries(e_uci, object_id) if info is None: data_rule['source_objects'].append( - {'id': object_id, 'name': object_id, 'type': None, 'subtype': None, 'empty': empty}) + {'id': object_id, 'name': object_id, 'type': None, 'subtype': None}) continue if info['database'] == 'objects': # same subtype `objects.list_host_sets` reports, so the client can reuse its icons and labels @@ -875,7 +766,7 @@ def list_rules(e_uci: EUci) -> list[dict]: else: object_type = subtype = 'vpn_user' data_rule['source_objects'].append( - {'id': object_id, 'name': info['name'], 'type': object_type, 'subtype': subtype, 'empty': empty}) + {'id': object_id, 'name': info['name'], 'type': object_type, 'subtype': subtype}) if 'criteria' in rule: data_rule['criteria'] = rule.get('criteria') rules.append(data_rule) @@ -928,7 +819,7 @@ def add_rule(e_uci: EUci, name: str, enabled: bool, action: str, source: list[st - match_all: the rule matches every flow, narrowed to `source` when one is given. Mutually exclusive with `appgroups` - source_objects: ids of the objects, in the form of `/`, whose addresses the rule is - narrowed to, as an alternative to `source`; see `SOURCE_OBJECT_TYPES` for the accepted ones + narrowed to, as an alternative to `source`; see `objects.ADDRESS_GROUP_TYPES` for the accepted ones Returns: config name of the rule created @@ -976,7 +867,7 @@ def edit_rule(e_uci: EUci, config_name: str, name: str, enabled: bool, action: s - match_all: the rule matches every flow, narrowed to `source` when one is given. Mutually exclusive with `appgroups` - source_objects: ids of the objects, in the form of `/`, whose addresses the rule is - narrowed to, as an alternative to `source`; see `SOURCE_OBJECT_TYPES` for the accepted ones + narrowed to, as an alternative to `source`; see `objects.ADDRESS_GROUP_TYPES` for the accepted ones Returns: config name of the rule edited diff --git a/packages/python3-nethsec/src/nethsec/objects/__init__.py b/packages/python3-nethsec/src/nethsec/objects/__init__.py index 4253abf82..56b9384b9 100644 --- a/packages/python3-nethsec/src/nethsec/objects/__init__.py +++ b/packages/python3-nethsec/src/nethsec/objects/__init__.py @@ -12,6 +12,7 @@ import json import os import subprocess +import syslog from euci import EUci @@ -886,3 +887,167 @@ def get_info(uci, database_id): except: return None + + +# Address groups + +# Every object resolving to IP addresses has its netifyd address group, `ADDRESS_GROUPS_DIR/30-.conf`, +# whether a DPI rule uses it or not: a rule source matches it as `local_ip == @`, and the files follow +# the objects as they are committed, not the rules. + +ADDRESS_GROUPS_DIR = '/etc/netifyd/address-groups.d' + +# prefixes below 20 belong to the agent itself, this one belongs to `write_address_groups`: every file +# carrying it whose object is gone, or has no address anymore, is removed. The agent saves the groups it +# holds when it stops, without comments and including the ones whose file was removed while it was running: +# the prefix is what tells such a stale file apart +ADDRESS_GROUP_FILE_PREFIX = '30-' + +# ending of the header comment of every file written here, for whoever reads it +ADDRESS_GROUP_FILE_MARKER = 'generated from the firewall objects: do not edit' + +# (database, section type) of the objects with an address group: everything resolving to addresses. +# Domain sets are left out: they resolve to addresses only at runtime +ADDRESS_GROUP_TYPES = (('objects', 'host'), ('dhcp', 'host'), ('dhcp', 'domain'), ('users', 'user')) + + +def address_group_tag(database_id): + """ + The tag of the address group of an object, e.g. `objects_ns_1234` for `objects/ns_1234`. + + Args: + database_id: id of the object in the form of `/` + + Returns: + the tag, as referenced by a criteria with `@` + """ + return database_id.replace('/', '_') + + +def _strip_zone(value): + """Drop the zone of a link-local address, e.g. `fe80::1%eth0/64` becomes `fe80::1/64`.""" + if '%' not in value: + return value + address, _, rest = value.partition('%') + _, slash, prefix = rest.partition('/') + return f'{address}{slash}{prefix}' + + +def address_group_entries(uci, database_id): + """ + The entries of the address group of an object, written the way an address group can match them: + ranges become CIDR blocks, as an address group silently ignores them, and a range whose first address + is greater than its last, which the object API accepts, covers the same addresses as the ordered one; an + IPv4-mapped IPv6 network becomes the IPv4 network it maps, as it never matches an IPv4 flow; a zero + length prefix, which matches nothing, is split into its two halves. A value that cannot be turned into an + address is skipped with a log line, as the agent would ignore it. + + Args: + uci: EUci pointer + database_id: id of the object in the form of `/` + + Returns: + the entries, empty when the object has no address the agent can match, or is gone + """ + entries = [] + for value in get_object_ips(uci, database_id): + try: + if '-' in value: + # the host set keeps the range as entered: only the written networks are ordered + first, last = sorted(ipaddress.ip_address(_strip_zone(part.strip())) for part in value.split('-', 1)) + networks = list(ipaddress.summarize_address_range(first, last)) + else: + networks = [ipaddress.ip_network(_strip_zone(value.strip()), strict=False)] + except (ValueError, TypeError) as error: + syslog.syslog(syslog.LOG_WARNING, f"objects: skipping {value!r} of {database_id}: {error}") + continue + for network in networks: + if network.version == 6 and network.prefixlen >= 96 and network.network_address.ipv4_mapped: + network = ipaddress.ip_network(f'{network.network_address.ipv4_mapped}/{network.prefixlen - 96}') + for entry in network.subnets(new_prefix=1) if network.prefixlen == 0 else [network]: + if str(entry) not in entries: + entries.append(str(entry)) + return entries + + +def write_address_groups(uci): + """ + Write the address group of every object resolving to addresses, and remove every other file with the + `ADDRESS_GROUP_FILE_PREFIX` prefix: the ones of objects that are gone or have no address anymore. A file + is rewritten only when its content changes. The agent loads the files on start and on reload. + + Args: + uci: EUci pointer + + Returns: + True when a file was written or removed + """ + os.makedirs(ADDRESS_GROUPS_DIR, exist_ok=True) + wanted = {} + for database in sorted({database for database, _ in ADDRESS_GROUP_TYPES}): + try: + sections = uci.get_all(database) + except Exception: + # the configuration doesn't exist + continue + for section in sections: + if (database, uci.get(database, section)) not in ADDRESS_GROUP_TYPES: + continue + database_id = f'{database}/{section}' + entries = address_group_entries(uci, database_id) + if not entries: + continue + # header: the object name, when it has one, on one line, then the id and the marker + name = ' '.join(str(uci.get(database, section, 'name', default='')).split()) + lines = [f'# {name}'] if name else [] + lines.append(f'# {database_id}, {ADDRESS_GROUP_FILE_MARKER}') + lines.extend(entries) + wanted[f'{ADDRESS_GROUP_FILE_PREFIX}{address_group_tag(database_id)}.conf'] = \ + ''.join(f'{line}\n' for line in lines) + + changed = False + for filename in os.listdir(ADDRESS_GROUPS_DIR): + if filename.startswith(ADDRESS_GROUP_FILE_PREFIX) and filename.endswith('.conf') and filename not in wanted: + os.remove(os.path.join(ADDRESS_GROUPS_DIR, filename)) + changed = True + + for filename, content in wanted.items(): + path = os.path.join(ADDRESS_GROUPS_DIR, filename) + try: + with open(path, 'r') as fp: + if fp.read() == content: + if os.stat(path).st_mode & 0o777 != 0o644: + os.chmod(path, 0o644) + continue + except FileNotFoundError: + pass + with open(f'{path}.tmp', 'w') as fp: + fp.write(content) + # readable by the agent whatever the umask of the caller, e.g. the API server + os.chmod(f'{path}.tmp', 0o644) + os.replace(f'{path}.tmp', path) + changed = True + + return changed + + +def update_address_groups(uci): + """ + Write the address groups, see `write_address_groups`, and reload the agent when a file changed and it is + running, so it loads them. To be called once the object changes are committed. + + Args: + uci: EUci pointer + + Returns: + True when a file was written or removed. A file that can't be written is logged, not raised: the + object changes are committed already, the next update or boot writes it again + """ + try: + changed = write_address_groups(uci) + except OSError as error: + syslog.syslog(syslog.LOG_ERR, f"objects: cannot write the address groups: {error}") + return False + if changed and subprocess.run(['/etc/init.d/netifyd', 'running'], capture_output=True).returncode == 0: + subprocess.run(['/etc/init.d/netifyd', 'reload'], capture_output=True) + return changed diff --git a/packages/python3-nethsec/tests/test_dpi.py b/packages/python3-nethsec/tests/test_dpi.py index b7ac083b3..d42d4045e 100644 --- a/packages/python3-nethsec/tests/test_dpi.py +++ b/packages/python3-nethsec/tests/test_dpi.py @@ -1353,22 +1353,16 @@ def test_migrate_schema_is_idempotent(e_uci_legacy, mock_reload): @pytest.fixture -def e_uci_sources(e_uci_rules, tmp_path, monkeypatch): - """Rules on top of a configuration holding every kind of object, address groups in a temp dir.""" +def e_uci_sources(e_uci_rules): + """Rules on top of a configuration holding every kind of object.""" conf_dir = pathlib.Path(e_uci_rules.confdir()) conf_dir.joinpath('objects').write_text(objects_config) conf_dir.joinpath('dhcp').write_text(dhcp_config) conf_dir.joinpath('users').write_text(users_config) conf_dir.joinpath('mwan3').write_text('') - groups_dir = tmp_path.joinpath('address-groups.d') - monkeypatch.setattr(dpi, 'ADDRESS_GROUPS_DIR', groups_dir.as_posix()) return e_uci_rules -def groups_dir(): - return pathlib.Path(dpi.ADDRESS_GROUPS_DIR) - - def test_add_rule_with_source_objects(e_uci_sources): group = group_of(e_uci_sources) rule_id = dpi.add_rule(e_uci_sources, 'Block hosts', True, 'block', [], [group], @@ -1431,13 +1425,13 @@ def test_list_rules_reports_source_objects(e_uci_sources): rule = dpi.list_rules(e_uci_sources)[0] assert rule['source'] == [] assert rule['source_objects'] == [ - {'id': 'objects/ns_host', 'name': 'host1', 'type': 'host_set', 'subtype': 'host', 'empty': False}, - {'id': 'objects/ns_cidr', 'name': 'cidr1', 'type': 'host_set', 'subtype': 'host_set', 'empty': False}, - {'id': 'objects/ns_range', 'name': 'range1', 'type': 'host_set', 'subtype': 'host_set', 'empty': False}, - {'id': 'objects/ns_nested', 'name': 'nested1', 'type': 'host_set', 'subtype': 'host_set', 'empty': False}, - {'id': 'dhcp/ns_lease', 'name': 'lease1', 'type': 'dhcp_static_lease', 'subtype': 'dhcp_static_lease', 'empty': False}, - {'id': 'dhcp/ns_record', 'name': 'record.lan', 'type': 'dns_record', 'subtype': 'dns_record', 'empty': False}, - {'id': 'users/ns_vpn', 'name': 'vpnuser', 'type': 'vpn_user', 'subtype': 'vpn_user', 'empty': False}, + {'id': 'objects/ns_host', 'name': 'host1', 'type': 'host_set', 'subtype': 'host'}, + {'id': 'objects/ns_cidr', 'name': 'cidr1', 'type': 'host_set', 'subtype': 'host_set'}, + {'id': 'objects/ns_range', 'name': 'range1', 'type': 'host_set', 'subtype': 'host_set'}, + {'id': 'objects/ns_nested', 'name': 'nested1', 'type': 'host_set', 'subtype': 'host_set'}, + {'id': 'dhcp/ns_lease', 'name': 'lease1', 'type': 'dhcp_static_lease', 'subtype': 'dhcp_static_lease'}, + {'id': 'dhcp/ns_record', 'name': 'record.lan', 'type': 'dns_record', 'subtype': 'dns_record'}, + {'id': 'users/ns_vpn', 'name': 'vpnuser', 'type': 'vpn_user', 'subtype': 'vpn_user'}, ] @@ -1446,20 +1440,7 @@ def test_list_rules_reports_a_source_object_gone_from_the_configuration(e_uci_so rule_id = dpi.add_rule(e_uci_sources, 'Rule', True, 'block', [], [group], source_objects=['objects/ns_host']) e_uci_sources.set('dpi', rule_id, 'source_object', ['objects/ns_gone']) assert dpi.list_rules(e_uci_sources)[0]['source_objects'] == [ - {'id': 'objects/ns_gone', 'name': 'objects/ns_gone', 'type': None, 'subtype': None, 'empty': True}] - - -def test_list_rules_reports_source_objects_with_an_empty_group(e_uci_sources): - group = group_of(e_uci_sources) - dpi.add_rule(e_uci_sources, 'Rule', True, 'block', [], [group], - source_objects=['objects/ns_host', 'objects/ns_with_domain', 'users/ns_vpn']) - # a host set holding only a domain set has no address - assert [(item['id'], item['empty']) for item in dpi.list_rules(e_uci_sources)[0]['source_objects']] == [ - ('objects/ns_host', False), ('objects/ns_with_domain', True), ('users/ns_vpn', False)] - # the VPN user loses its reserved IP: the rule stays, its group is empty - e_uci_sources.delete('users', 'ns_vpn', 'openvpn_ipaddr') - assert dpi.list_rules(e_uci_sources)[0]['source_objects'][2] == { - 'id': 'users/ns_vpn', 'name': 'vpnuser', 'type': 'vpn_user', 'subtype': 'vpn_user', 'empty': True} + {'id': 'objects/ns_gone', 'name': 'objects/ns_gone', 'type': None, 'subtype': None}] def test_list_rules_without_source_objects(e_uci_sources): @@ -1468,40 +1449,6 @@ def test_list_rules_without_source_objects(e_uci_sources): assert dpi.list_rules(e_uci_sources)[0]['source_objects'] == [] -@pytest.mark.parametrize('object_id, entries', [ - ('objects/ns_host', ['192.168.1.10/32']), - ('objects/ns_cidr', ['192.168.1.0/24']), - # an address group ignores ranges: they become CIDR blocks - ('objects/ns_range', ['192.168.1.10/31', '192.168.1.12/31']), - ('objects/ns_v6range', ['fd00::1/128', 'fd00::2/127', 'fd00::4/128', 'fd00::50/128']), - # the object API accepts a reversed range: it is skipped, the rest of the object is kept - ('objects/ns_reversed', ['192.168.1.30/32']), - # references are resolved, duplicates dropped - ('objects/ns_nested', ['192.168.1.10/32', '192.168.1.50/32', '10.0.0.1/32']), - # an IPv4-mapped address never matches the IPv4 flow it maps - ('objects/ns_mapped', ['192.168.1.10/32', '192.168.2.0/24']), - # a zero length prefix matches nothing in a group: its two halves match everything - ('objects/ns_all', ['0.0.0.0/1', '128.0.0.0/1']), - ('objects/ns_all6', ['::/1', '8000::/1']), - ('objects/ns_zone', ['fe80::1/128', 'fe80::10/127']), - ('dhcp/ns_lease', ['192.168.1.50/32']), - ('dhcp/ns_record', ['192.168.1.60/32']), - ('users/ns_vpn', ['10.9.0.2/32']), - # objects with no address: an empty group, matching nothing - ('users/ns_novpn', []), - ('objects/ns_with_domain', []), - ('objects/ns_domain', []), - ('objects/ns_missing', []), -]) -def test_write_address_groups_entries(e_uci_sources, object_id, entries): - # set directly: add_rule refuses some of these objects - e_uci_sources.set('dpi', 'ns_entries', 'rule') - e_uci_sources.set('dpi', 'ns_entries', 'source_object', [object_id]) - dpi.write_address_groups(e_uci_sources) - content = groups_dir().joinpath(f"30-{object_id.replace('/', '_')}.conf").read_text() - assert [line for line in content.splitlines() if not line.startswith('#')] == entries - - def test_build_rule_criteria_with_source_objects(e_uci_sources): group = group_of(e_uci_sources) rule_id = dpi.add_rule(e_uci_sources, 'Rule', True, 'block', [], [group], @@ -1537,67 +1484,6 @@ def test_build_rule_criteria_keeps_a_source_object_without_addresses(e_uci_sourc ) -def test_write_address_groups(e_uci_sources): - group = group_of(e_uci_sources) - dpi.add_rule(e_uci_sources, 'One', True, 'block', [], [group], source_objects=['objects/ns_range', 'objects/ns_with_domain']) - dpi.add_rule(e_uci_sources, 'Two', False, 'block', [], [group], source_objects=['objects/ns_range', 'dhcp/ns_lease']) - tags = dpi.write_address_groups(e_uci_sources) - assert sorted(tags) == ['dhcp_ns_lease', 'objects_ns_range', 'objects_ns_with_domain'] - assert sorted(path.name for path in groups_dir().iterdir()) == [ - '30-dhcp_ns_lease.conf', '30-objects_ns_range.conf', '30-objects_ns_with_domain.conf'] - assert groups_dir().joinpath('30-objects_ns_range.conf').read_text() == ( - '# range1\n# objects/ns_range, generated by dpi-config: do not edit\n192.168.1.10/31\n192.168.1.12/31\n') - # an object without addresses still gets its file: the criteria references it - assert groups_dir().joinpath('30-objects_ns_with_domain.conf').read_text() == ( - '# withdomain1\n# objects/ns_with_domain, generated by dpi-config: do not edit\n') - assert groups_dir().joinpath('30-dhcp_ns_lease.conf').read_text().startswith( - '# lease1\n# dhcp/ns_lease, generated by dpi-config: do not edit\n') - - -def test_write_address_groups_removes_only_its_own_stale_files(e_uci_sources): - group = group_of(e_uci_sources) - groups_dir().mkdir() - generated = '# objects/ns_old, generated by dpi-config: do not edit\n10.0.0.1/32\n' - # other prefixes or extensions: kept - for name in ('10-agent.conf', '20-other.conf', '30-objects_ns_old.txt'): - groups_dir().joinpath(name).write_text(generated) - # stale with the prefix: removed, with or without the header, as the agent saves its groups without it - groups_dir().joinpath('30-objects_ns_old.conf').write_text('# old1\n' + generated) - groups_dir().joinpath('30-objects_ns_saved.conf').write_text('10.0.0.1\n') - groups_dir().joinpath('30-dpi_objects_ns_old.conf').write_text('') - # referenced, as saved by the agent: rewritten with the header - groups_dir().joinpath('30-objects_ns_host.conf').write_text('192.168.1.10\n') - dpi.add_rule(e_uci_sources, 'One', True, 'block', [], [group], source_objects=['objects/ns_host']) - dpi.write_address_groups(e_uci_sources) - assert sorted(path.name for path in groups_dir().iterdir()) == [ - '10-agent.conf', '20-other.conf', '30-objects_ns_host.conf', '30-objects_ns_old.txt'] - assert groups_dir().joinpath('30-objects_ns_host.conf').read_text().splitlines()[1] == ( - '# objects/ns_host, generated by dpi-config: do not edit') - - -def test_write_address_groups_follows_the_object(e_uci_sources): - group = group_of(e_uci_sources) - rule_id = dpi.add_rule(e_uci_sources, 'One', True, 'block', [], [group], source_objects=['objects/ns_host']) - dpi.write_address_groups(e_uci_sources) - path = groups_dir().joinpath('30-objects_ns_host.conf') - inode = path.stat().st_ino - # unchanged: the file is left alone - dpi.write_address_groups(e_uci_sources) - assert path.stat().st_ino == inode - # the object changes: the file follows - e_uci_sources.set('objects', 'ns_host', 'ipaddr', ['192.168.1.11']) - dpi.write_address_groups(e_uci_sources) - assert path.read_text().splitlines()[2:] == ['192.168.1.11/32'] - # the object is renamed: the file follows - e_uci_sources.set('objects', 'ns_host', 'name', 'renamed') - dpi.write_address_groups(e_uci_sources) - assert path.read_text().splitlines()[0] == '# renamed' - # no rule references it anymore: the file goes - dpi.edit_rule(e_uci_sources, rule_id, 'One', True, 'block', [], [group]) - assert dpi.write_address_groups(e_uci_sources) == [] - assert not path.exists() - - def test_source_object_is_used(e_uci_sources): group = group_of(e_uci_sources) assert objects.is_used_object(e_uci_sources, 'objects/ns_cidr') == (False, []) @@ -1609,26 +1495,3 @@ def test_source_object_is_used(e_uci_sources): assert objects.is_used_object(e_uci_sources, 'dhcp/ns_record') == (False, []) # the usage is shown with the rule name assert objects.get_info(e_uci_sources, f'dpi/{rule_id}')['name'] == 'One' - - -def test_write_address_groups_header_without_name(e_uci_sources): - group = group_of(e_uci_sources) - dpi.add_rule(e_uci_sources, 'One', True, 'block', [], [group], source_objects=['objects/ns_host']) - # the object loses its name, or is gone altogether: the header holds only the id - e_uci_sources.delete('objects', 'ns_host', 'name') - dpi.write_address_groups(e_uci_sources) - assert groups_dir().joinpath('30-objects_ns_host.conf').read_text().splitlines()[0] == ( - '# objects/ns_host, generated by dpi-config: do not edit') - e_uci_sources.delete('objects', 'ns_host') - dpi.write_address_groups(e_uci_sources) - assert groups_dir().joinpath('30-objects_ns_host.conf').read_text() == ( - '# objects/ns_host, generated by dpi-config: do not edit\n') - - -def test_write_address_groups_header_name_on_one_line(e_uci_sources): - group = group_of(e_uci_sources) - dpi.add_rule(e_uci_sources, 'One', True, 'block', [], [group], source_objects=['objects/ns_host']) - e_uci_sources.set('objects', 'ns_host', 'name', 'two\nlines') - dpi.write_address_groups(e_uci_sources) - assert groups_dir().joinpath('30-objects_ns_host.conf').read_text().splitlines()[:2] == [ - '# two lines', '# objects/ns_host, generated by dpi-config: do not edit'] diff --git a/packages/python3-nethsec/tests/test_objects.py b/packages/python3-nethsec/tests/test_objects.py index aa57ee00c..39d49a946 100644 --- a/packages/python3-nethsec/tests/test_objects.py +++ b/packages/python3-nethsec/tests/test_objects.py @@ -1,3 +1,4 @@ +import os import pathlib from nethsec.utils import ValidationError import pytest @@ -378,4 +379,332 @@ def test_get_reference_info(u): def test_is_object_with_invalid_is(u): assert objects.is_object_id(None) == False - assert objects.is_object_id(1) == False \ No newline at end of file + assert objects.is_object_id(1) == False + +# Address groups + +groups_objects_db = """ +config host 'ns_host' + option name 'host1' + option family 'ipv4' + list ipaddr '192.168.1.10' + +config host 'ns_cidr' + option name 'cidr1' + option family 'ipv4' + list ipaddr '192.168.1.0/24' + +config host 'ns_range' + option name 'range1' + option family 'ipv4' + list ipaddr '192.168.1.10-192.168.1.13' + +config host 'ns_reversed' + option name 'reversed1' + option family 'ipv4' + list ipaddr '192.168.1.20-192.168.1.10' + list ipaddr '192.168.1.30' + +config host 'ns_nested' + option name 'nested1' + option family 'ipv4' + list ipaddr 'objects/ns_host' + list ipaddr 'dhcp/ns_lease' + list ipaddr '10.0.0.1' + list ipaddr '192.168.1.10' + +config host 'ns_mapped' + option name 'mapped1' + option family 'ipv6' + list ipaddr '::ffff:192.168.1.10' + list ipaddr '::ffff:192.168.2.0/120' + +config host 'ns_all' + option name 'all1' + option family 'ipv4' + list ipaddr '0.0.0.0/0' + +config host 'ns_all6' + option name 'all6' + option family 'ipv6' + list ipaddr '::-ffff:ffff:ffff:ffff:ffff:ffff:ffff:ffff' + +config host 'ns_zone' + option name 'zone1' + option family 'ipv6' + list ipaddr 'fe80::1%eth0' + list ipaddr 'fe80::10%eth0-fe80::11%eth0' + +config host 'ns_v6range' + option name 'v6range1' + option family 'ipv6' + list ipaddr 'fd00::1-fd00::4' + list ipaddr 'FD00::50' + +config host 'ns_with_domain' + option name 'withdomain1' + option family 'ipv4' + list ipaddr 'objects/ns_domain' + +config domain 'ns_domain' + option name 'domain1' + option family 'ipv4' + option timeout '600' + list domain 'example.com' +""" + +groups_dhcp_db = """ +config dnsmasq + option domain 'lan' + +config host 'ns_lease' + option name 'lease1' + option ip '192.168.1.50' + option mac '02:00:00:00:00:50' + +config domain 'ns_record' + option name 'record.lan' + option ip '192.168.1.60' +""" + +groups_users_db = """ +config local 'main' + option description 'Local users' + +config user 'ns_vpn' + option name 'vpnuser' + option database 'main' + option openvpn_ipaddr '10.9.0.2' + +config user 'ns_novpn' + option name 'novpnuser' + option database 'main' + +config user 'ns_noip' + option name 'noipuser' + option database 'main' + option openvpn_ipaddr '' +""" + +# the objects of the configuration above with at least one address, so with an address group file. +# Pending changes other tests leave in the default savedir can add more objects: assertions check these +groups_files = ['30-dhcp_ns_lease.conf', '30-dhcp_ns_record.conf', '30-objects_ns_all.conf', + '30-objects_ns_all6.conf', '30-objects_ns_cidr.conf', '30-objects_ns_host.conf', + '30-objects_ns_mapped.conf', '30-objects_ns_nested.conf', '30-objects_ns_range.conf', + '30-objects_ns_reversed.conf', '30-objects_ns_v6range.conf', '30-objects_ns_zone.conf', + '30-users_ns_vpn.conf'] + +# the objects of the configuration above without addresses, so without a file +groups_no_files = ['30-objects_ns_domain.conf', '30-objects_ns_with_domain.conf', '30-users_ns_novpn.conf', + '30-users_ns_noip.conf'] + + +@pytest.fixture +def g(tmp_path: pathlib.Path, monkeypatch) -> EUci: + """A configuration holding every kind of object, address groups in a temp dir.""" + conf_dir = tmp_path.joinpath('conf') + conf_dir.mkdir() + conf_dir.joinpath('objects').write_text(groups_objects_db) + conf_dir.joinpath('dhcp').write_text(groups_dhcp_db) + conf_dir.joinpath('users').write_text(groups_users_db) + save_dir = tmp_path.joinpath('save') + save_dir.mkdir() + monkeypatch.setattr(objects, 'ADDRESS_GROUPS_DIR', tmp_path.joinpath('address-groups.d').as_posix()) + return EUci(confdir=conf_dir.as_posix(), savedir=save_dir.as_posix()) + + +def groups_dir() -> pathlib.Path: + return pathlib.Path(objects.ADDRESS_GROUPS_DIR) + + +def group_file(name) -> pathlib.Path: + return groups_dir().joinpath(name) + + +def group_files() -> set: + return {path.name for path in groups_dir().iterdir()} + + +def test_address_group_tag(): + assert objects.address_group_tag('objects/ns_host') == 'objects_ns_host' + assert objects.address_group_tag('users/ns_vpn') == 'users_ns_vpn' + + +@pytest.mark.parametrize('object_id, entries', [ + ('objects/ns_host', ['192.168.1.10/32']), + ('objects/ns_cidr', ['192.168.1.0/24']), + # an address group ignores ranges: they become CIDR blocks + ('objects/ns_range', ['192.168.1.10/31', '192.168.1.12/31']), + ('objects/ns_v6range', ['fd00::1/128', 'fd00::2/127', 'fd00::4/128', 'fd00::50/128']), + # the object API accepts a reversed range: it covers the same addresses as the ordered one + ('objects/ns_reversed', ['192.168.1.10/31', '192.168.1.12/30', '192.168.1.16/30', '192.168.1.20/32', + '192.168.1.30/32']), + # references are resolved, duplicates dropped + ('objects/ns_nested', ['192.168.1.10/32', '192.168.1.50/32', '10.0.0.1/32']), + # an IPv4-mapped address never matches the IPv4 flow it maps + ('objects/ns_mapped', ['192.168.1.10/32', '192.168.2.0/24']), + # a zero length prefix matches nothing in a group: its two halves match everything + ('objects/ns_all', ['0.0.0.0/1', '128.0.0.0/1']), + ('objects/ns_all6', ['::/1', '8000::/1']), + ('objects/ns_zone', ['fe80::1/128', 'fe80::10/127']), + ('dhcp/ns_lease', ['192.168.1.50/32']), + ('dhcp/ns_record', ['192.168.1.60/32']), + ('users/ns_vpn', ['10.9.0.2/32']), + # objects with no address + ('users/ns_novpn', []), + ('users/ns_noip', []), + ('objects/ns_with_domain', []), + ('objects/ns_domain', []), + ('objects/ns_missing', []), +]) +def test_address_group_entries(g, object_id, entries): + assert objects.address_group_entries(g, object_id) == entries + + +def test_write_address_groups(g): + assert objects.write_address_groups(g) is True + # one file per object with addresses: no file for domain sets, users without a reserved IP and objects + # resolving to no address + assert set(groups_files) <= group_files() + assert not set(groups_no_files) & group_files() + assert all(name.startswith('30-') and name.endswith('.conf') for name in group_files()) + assert group_file('30-objects_ns_range.conf').read_text() == ( + '# range1\n# objects/ns_range, generated from the firewall objects: do not edit\n' + '192.168.1.10/31\n192.168.1.12/31\n') + assert group_file('30-users_ns_vpn.conf').read_text() == ( + '# vpnuser\n# users/ns_vpn, generated from the firewall objects: do not edit\n10.9.0.2/32\n') + # unchanged: nothing is written + inode = group_file('30-objects_ns_host.conf').stat().st_ino + assert objects.write_address_groups(g) is False + assert group_file('30-objects_ns_host.conf').stat().st_ino == inode + + +def test_write_address_groups_removes_only_its_own_stale_files(g): + groups_dir().mkdir() + # other prefixes or extensions: kept + for name in ('10-agent.conf', '20-other.conf', '30-objects_ns_gone.txt'): + group_file(name).write_text('10.0.0.1\n') + # objects gone, as written here or as saved by the agent without the header: removed + group_file('30-objects_ns_gone.conf').write_text( + '# gone1\n# objects/ns_gone, generated from the firewall objects: do not edit\n10.0.0.1/32\n') + group_file('30-objects_ns_saved.conf').write_text('10.0.0.1\n') + group_file('30-objects_ns_empty.conf').write_text('') + # an object without addresses: its file goes too + group_file('30-users_ns_novpn.conf').write_text('10.9.0.3\n') + # an existing object, as saved by the agent: rewritten with the header + group_file('30-objects_ns_host.conf').write_text('192.168.1.10\n') + objects.write_address_groups(g) + assert {'10-agent.conf', '20-other.conf', '30-objects_ns_gone.txt'} | set(groups_files) <= group_files() + assert not {'30-objects_ns_gone.conf', '30-objects_ns_saved.conf', '30-objects_ns_empty.conf', + '30-users_ns_novpn.conf'} & group_files() + assert group_file('30-objects_ns_host.conf').read_text().splitlines()[1] == ( + '# objects/ns_host, generated from the firewall objects: do not edit') + + +def test_write_address_groups_follows_the_objects(g): + objects.write_address_groups(g) + host = group_file('30-objects_ns_host.conf') + # the object changes: its file follows, and the one of the host set holding it too + g.set('objects', 'ns_host', 'ipaddr', ['192.168.1.11']) + assert objects.write_address_groups(g) is True + assert host.read_text().splitlines()[2:] == ['192.168.1.11/32'] + assert group_file('30-objects_ns_nested.conf').read_text().splitlines()[2:] == [ + '192.168.1.11/32', '192.168.1.50/32', '10.0.0.1/32', '192.168.1.10/32'] + # the object is renamed: the header follows + g.set('objects', 'ns_host', 'name', 'renamed') + objects.write_address_groups(g) + assert host.read_text().splitlines()[0] == '# renamed' + # the object is deleted: its file goes + g.delete('objects', 'ns_host') + assert objects.write_address_groups(g) is True + assert not host.exists() + # a VPN user loses its reserved IP: its file goes, and comes back with it + vpn = group_file('30-users_ns_vpn.conf') + g.delete('users', 'ns_vpn', 'openvpn_ipaddr') + objects.write_address_groups(g) + assert not vpn.exists() + g.set('users', 'ns_vpn', 'openvpn_ipaddr', '10.9.0.5') + objects.write_address_groups(g) + assert vpn.read_text().splitlines()[2:] == ['10.9.0.5/32'] + # a new object: a new file + g.set('dhcp', 'ns_new', 'host') + g.set('dhcp', 'ns_new', 'name', 'new1') + g.set('dhcp', 'ns_new', 'ip', '192.168.1.70') + objects.write_address_groups(g) + assert group_file('30-dhcp_ns_new.conf').read_text().splitlines()[2:] == ['192.168.1.70/32'] + + +def test_write_address_groups_files_are_readable_whatever_the_umask(g): + umask = os.umask(0o077) + try: + objects.write_address_groups(g) + finally: + os.umask(umask) + assert group_file('30-objects_ns_host.conf').stat().st_mode & 0o777 == 0o644 + # an unchanged file keeps its content, its mode is fixed + group_file('30-objects_ns_host.conf').chmod(0o600) + assert objects.write_address_groups(g) is False + assert group_file('30-objects_ns_host.conf').stat().st_mode & 0o777 == 0o644 + + +def test_write_address_groups_header(g): + # an object without a name: the header holds only the id + g.delete('objects', 'ns_host', 'name') + # a name on more lines: joined on one + g.set('objects', 'ns_cidr', 'name', 'two\nlines') + objects.write_address_groups(g) + assert group_file('30-objects_ns_host.conf').read_text() == ( + '# objects/ns_host, generated from the firewall objects: do not edit\n192.168.1.10/32\n') + assert group_file('30-objects_ns_cidr.conf').read_text().splitlines()[:2] == [ + '# two lines', '# objects/ns_cidr, generated from the firewall objects: do not edit'] + + +def test_write_address_groups_without_configurations(tmp_path, monkeypatch): + conf_dir = tmp_path.joinpath('conf') + conf_dir.mkdir() + save_dir = tmp_path.joinpath('save') + save_dir.mkdir() + monkeypatch.setattr(objects, 'ADDRESS_GROUPS_DIR', tmp_path.joinpath('address-groups.d').as_posix()) + objects.write_address_groups(EUci(confdir=conf_dir.as_posix(), savedir=save_dir.as_posix())) + assert not set(groups_files) & group_files() + + +def netifyd_calls(run): + return [call.args[0] for call in run.call_args_list] + + +def test_update_address_groups_reloads_a_running_agent(g, mocker): + run = mocker.patch('nethsec.objects.subprocess.run') + run.return_value.returncode = 0 + assert objects.update_address_groups(g) is True + assert netifyd_calls(run) == [['/etc/init.d/netifyd', 'running'], ['/etc/init.d/netifyd', 'reload']] + # nothing changed: no reload + run.reset_mock() + assert objects.update_address_groups(g) is False + assert netifyd_calls(run) == [] + + +def test_address_group_entries_skips_an_invalid_value(g, mocker): + log = mocker.patch('nethsec.objects.syslog.syslog') + # a range mixing the families can't become networks: it is skipped, the rest of the object is kept + g.set('objects', 'ns_reversed', 'ipaddr', ['192.168.1.10-fd00::1', '192.168.1.30']) + assert objects.address_group_entries(g, 'objects/ns_reversed') == ['192.168.1.30/32'] + assert "skipping '192.168.1.10-fd00::1' of objects/ns_reversed" in log.call_args.args[1] + # the host set itself is left as entered + assert g.get('objects', 'ns_reversed', 'ipaddr', list=True) == ('192.168.1.10-fd00::1', '192.168.1.30') + + +def test_update_address_groups_leaves_a_stopped_agent_alone(g, mocker): + run = mocker.patch('nethsec.objects.subprocess.run') + run.return_value.returncode = 1 + assert objects.update_address_groups(g) is True + assert netifyd_calls(run) == [['/etc/init.d/netifyd', 'running']] + + +def test_update_address_groups_logs_a_write_failure(g, mocker): + run = mocker.patch('nethsec.objects.subprocess.run') + mocker.patch('nethsec.objects.write_address_groups', side_effect=PermissionError('denied')) + log = mocker.patch('nethsec.objects.syslog.syslog') + assert objects.update_address_groups(g) is False + assert netifyd_calls(run) == [] + assert 'cannot write the address groups' in log.call_args.args[1] From e1254bec6a171f35e3665377f7b154ee177465ce Mon Sep 17 00:00:00 2001 From: Matteo Di Lorenzi Date: Tue, 17 Nov 2026 11:57:42 +0100 Subject: [PATCH 3/3] refactor(dpi): write address groups from the dpi service --- .agents/skills/netifyd/SKILL.md | 11 +- packages/ns-api/files/ns.ovpnrw | 8 +- .../post-commit/update-address-groups.py | 4 +- packages/ns-dpi/Makefile | 1 - packages/ns-dpi/README.md | 9 +- packages/ns-dpi/files/address-groups.init | 16 - packages/ns-dpi/files/dpi | 3 + packages/ns-dpi/files/write-address-groups | 6 +- .../src/nethsec/dpi/__init__.py | 259 +++++++++++--- .../src/nethsec/objects/__init__.py | 165 --------- packages/python3-nethsec/tests/test_dpi.py | 329 +++++++++++++++++ .../python3-nethsec/tests/test_objects.py | 331 +----------------- 12 files changed, 564 insertions(+), 578 deletions(-) delete mode 100755 packages/ns-dpi/files/address-groups.init diff --git a/.agents/skills/netifyd/SKILL.md b/.agents/skills/netifyd/SKILL.md index 645fbc016..9182069cc 100644 --- a/.agents/skills/netifyd/SKILL.md +++ b/.agents/skills/netifyd/SKILL.md @@ -104,9 +104,10 @@ until the next reload and then vanishes. Change the generator or its UCI input i | `table inet netifyd` (nftables) | `/usr/sbin/ns-netifyd-configure` (on start and reload) | `/etc/config/netifyd` → `ns_config` | | `netify-application-catalog.json` and the other catalog/category files | `dpi-data-update` (nightly cron) | Netify's data service | | `/usr/share/nftables.d/table-pre/` DPI chains | `/usr/sbin/dpi-nft` | `/etc/config/dpi` | -| `address-groups.d/30-*.conf` | `nethsec.objects.write_address_groups` (on commit, by `ns.ovpnrw`, at boot) | `/etc/config/objects`, `dhcp`, `users` | +| `address-groups.d/30-*.conf` | `nethsec.dpi.write_address_groups` (on commit, by `ns.ovpnrw`, by `/usr/sbin/dpi`) | `/etc/config/objects`, `dhcp`, `users` | -`/usr/sbin/dpi` is the whole DPI apply path: `dpi-config` → `dpi-nft` → `/etc/init.d/netifyd reload`. +`/usr/sbin/dpi` is the whole DPI apply path: `dpi-migrate` → `write-address-groups` → `dpi-config` → `dpi-nft` → +`/etc/init.d/netifyd reload`. Run it after changing `/etc/config/dpi`; don't reproduce its steps by hand. --- @@ -205,12 +206,12 @@ Two operational facts: MAC members only match via `mac ==`, so don't put them in a group a `local_ip` rule references. -The `30-` prefix belongs to `nethsec.objects.write_address_groups`: one `30-_.conf` group +The `30-` prefix belongs to `nethsec.dpi.write_address_groups`: one `30-_.conf` group per firewall object resolving to addresses, used by a DPI rule or not, with a `# ` and a `# , generated from the firewall objects: do not edit` header, and every other `30-*.conf` file is removed. It runs from the `update-address-groups.py` post-commit hook (`objects`, `dhcp`, `users`), from -`ns.ovpnrw` (reserved IP of a VPN user) and at boot (`/etc/init.d/address-groups`, `START=95`, before -netifyd); `dpi-config` only references the groups. The `30-*.conf` files are in +`ns.ovpnrw` (reserved IP of a VPN user) and from `/usr/sbin/dpi`, before `dpi-config`: at boot the `dpi` +service (`START=40`) runs it before netifyd (`START=99`); `dpi-config` only references the groups. The `30-*.conf` files are in `/lib/upgrade/keep.d/ns-dpi`, so backups and the HA sync carry them. The agent keeps the groups it loaded in memory, a reload doesn't drop the ones whose file was removed (it drops their single addresses, not their networks), and on stop it saves all of them back, without comments: that's why ownership goes by diff --git a/packages/ns-api/files/ns.ovpnrw b/packages/ns-api/files/ns.ovpnrw index dbc1a32bd..164ccee78 100755 --- a/packages/ns-api/files/ns.ovpnrw +++ b/packages/ns-api/files/ns.ovpnrw @@ -16,7 +16,7 @@ import pyotp import ipaddress import subprocess from euci import EUci -from nethsec import utils, ovpn, firewall, users, objects +from nethsec import utils, ovpn, firewall, users, objects, dpi from datetime import datetime, timezone import tarfile import io @@ -808,7 +808,7 @@ def add_user(args): users.edit_local_user(u, args['username'], extra_fields=ovpn_config) u.commit("users") # add related address groups used by DPI rules - objects.update_address_groups(u) + dpi.update_address_groups(u) return {"result": "success"} def import_users(ovpninstance): @@ -865,7 +865,7 @@ def edit_user(args): u.set("users", user_id, "openvpn_enabled", args["enabled"]) u.commit("users") # update related address groups used by DPI rules - objects.update_address_groups(u) + dpi.update_address_groups(u) return {"result": "success"} def delete_user(ovpninstance, username): @@ -900,7 +900,7 @@ def delete_user(ovpninstance, username): except: pass # delete related address groups used by DPI rules - objects.update_address_groups(u) + dpi.update_address_groups(u) try: revoke_user_certificate(ovpninstance, username) except: diff --git a/packages/ns-api/files/post-commit/update-address-groups.py b/packages/ns-api/files/post-commit/update-address-groups.py index 2f8bcae22..d0e2db2fa 100755 --- a/packages/ns-api/files/post-commit/update-address-groups.py +++ b/packages/ns-api/files/post-commit/update-address-groups.py @@ -10,7 +10,7 @@ # reloaded when a file changed. DPI rules match an object through its group. from euci import EUci -from nethsec import objects +from nethsec import dpi if "objects" in changes or "dhcp" in changes or "users" in changes: # noqa: F821 - objects.update_address_groups(EUci()) + dpi.update_address_groups(EUci()) diff --git a/packages/ns-dpi/Makefile b/packages/ns-dpi/Makefile index 78d028572..8377fdc2e 100644 --- a/packages/ns-dpi/Makefile +++ b/packages/ns-dpi/Makefile @@ -75,7 +75,6 @@ define Package/ns-dpi/install $(INSTALL_BIN) ./files/dpi-license-update.init $(1)/etc/init.d/dpi-license-update $(INSTALL_BIN) ./files/dpi-data-update.init $(1)/etc/init.d/dpi-data-update $(INSTALL_BIN) ./files/dpi-update.init $(1)/etc/init.d/dpi-update - $(INSTALL_BIN) ./files/address-groups.init $(1)/etc/init.d/address-groups $(INSTALL_BIN) ./files/dpi $(1)/usr/sbin/ $(INSTALL_BIN) ./files/dpi-nft $(1)/usr/sbin/ $(INSTALL_BIN) ./files/dpi-config $(1)/usr/sbin/ diff --git a/packages/ns-dpi/README.md b/packages/ns-dpi/README.md index 6a6705bab..658dff900 100644 --- a/packages/ns-dpi/README.md +++ b/packages/ns-dpi/README.md @@ -84,12 +84,13 @@ Every firewall object resolving to addresses has a netifyd address group, static leases, DNS records and VPN users with a reserved IP. A rule references the object as `local_ip == @_`, so `dpi-config` only builds the criteria and never writes a group. -The files follow the objects, not the rules. They are written by `nethsec.objects.write_address_groups`: +The files follow the objects, not the rules. They are written by `nethsec.dpi.write_address_groups`: - on commit, by the `update-address-groups.py` post-commit hook of `ns.commit`, when `objects`, `dhcp` or `users` change; netifyd is reloaded if a file changed - by `ns.ovpnrw` when a VPN user gets, changes or loses its reserved IP, as it commits on its own -- at boot, by the `address-groups` service (`START=95`), before netifyd starts (`START=99`) +- by `/usr/sbin/dpi`, so at boot by the `dpi` service (`START=40`), before netifyd starts (`START=99`), and + on every DPI reload Each file starts with a comment holding the object name, when the object has one, followed by a comment holding the object id and `generated from the firewall objects: do not edit`. A file is rewritten only when @@ -106,8 +107,8 @@ HA configuration sync and survive an image upgrade, always matching the configur netifyd keeps the groups it loaded in memory, a reload doesn't drop the ones whose file was removed, and when it stops it saves all of them back to the directory, without comments. So after a netifyd restart the files lose their header until the next write, and the group of a deleted object can come back as a -file: no rule references it, and the next write removes it. The write at boot runs after the stop that saved it and before the start that would load it again, -dropping it from memory too. +file: no rule references it, and the next write removes it. The write at boot runs after the stop that +saved it and before the start that would load it again, dropping it from memory too. The addresses are written the way an address group can match them: diff --git a/packages/ns-dpi/files/address-groups.init b/packages/ns-dpi/files/address-groups.init deleted file mode 100755 index 8af001cc1..000000000 --- a/packages/ns-dpi/files/address-groups.init +++ /dev/null @@ -1,16 +0,0 @@ -#!/bin/sh /etc/rc.common - -# -# Copyright (C) 2026 Nethesis S.r.l. -# SPDX-License-Identifier: GPL-2.0-only -# - -# Write the netifyd address groups of the firewall objects before netifyd starts (START=99). -# netifyd saves the groups it holds when it stops, including the ones of objects deleted while it was -# running: removing them here, before it loads them again, drops them for good. - -START=95 - -start() { - /usr/libexec/ns-dpi/write-address-groups -} diff --git a/packages/ns-dpi/files/dpi b/packages/ns-dpi/files/dpi index 228d33859..cd7c79f75 100755 --- a/packages/ns-dpi/files/dpi +++ b/packages/ns-dpi/files/dpi @@ -8,6 +8,9 @@ # Convert a configuration still on the previous schema, e.g. restored from an old backup or synced # by an HA peer: a no-op when there is nothing to migrate /usr/libexec/ns-dpi/dpi-migrate +# Write the address groups of the firewall objects, referenced by the rules with a source object. At boot +# this runs before netifyd starts, dropping the stale groups it saved when it stopped +/usr/libexec/ns-dpi/write-address-groups # Generate netify flow actions config file /usr/sbin/dpi-config # Apply nftables rules diff --git a/packages/ns-dpi/files/write-address-groups b/packages/ns-dpi/files/write-address-groups index 47d44358f..030b5192b 100755 --- a/packages/ns-dpi/files/write-address-groups +++ b/packages/ns-dpi/files/write-address-groups @@ -5,9 +5,9 @@ # SPDX-License-Identifier: GPL-2.0-only # -# Write the netifyd address groups of the firewall objects, see nethsec.objects.write_address_groups +# Write the netifyd address groups of the firewall objects, see nethsec.dpi.write_address_groups from euci import EUci -from nethsec import objects +from nethsec import dpi -objects.write_address_groups(EUci()) +dpi.write_address_groups(EUci()) diff --git a/packages/python3-nethsec/src/nethsec/dpi/__init__.py b/packages/python3-nethsec/src/nethsec/dpi/__init__.py index 9943a0107..d92fda6c0 100644 --- a/packages/python3-nethsec/src/nethsec/dpi/__init__.py +++ b/packages/python3-nethsec/src/nethsec/dpi/__init__.py @@ -11,6 +11,7 @@ import ipaddress import json +import os import subprocess import syslog @@ -20,6 +21,62 @@ from nethsec import objects, utils from nethsec.utils import ValidationError +NETIFYD_DATA_DIR = '/etc/netifyd' + +# UCI list name of every member kind, mapped to the API parameter it is fed by +APPGROUP_MEMBERS = { + 'app': 'applications', + 'app_category': 'application_categories', + 'proto': 'protocols', + 'proto_category': 'protocol_categories' +} + +# validation error message of every member kind +__APPGROUP_MEMBER_ERRORS = { + 'app': 'invalid_application', + 'app_category': 'invalid_application_category', + 'proto': 'invalid_protocol', + 'proto_category': 'invalid_protocol_category' +} + +# characters that would let a member value escape its quoted literal, or terminate the expression +__APPGROUP_FORBIDDEN_CHARS = '\'"\\;()\n\r\t' + +APPGROUP_NAME_MAX_LENGTH = 64 + +APPGROUP_CATALOG_FILES = { + 'applications': 'netify-application-catalog.json', + 'protocols': 'netify-protocol-catalog.json' +} + +UNCATEGORIZED_TAG = '' + +# 'allow' attaches a label no nft rule matches: it exists so a rule can win the first-match race and +# shield its traffic from the block rules below it +DPI_RULE_ACTIONS = ('block', 'allow') + +DPI_RULE_NAME_MAX_LENGTH = 64 + +DPI_MATCH_ALL_CRITERIA = '*' + +DPI_RULE_POSITIONS = ('top', 'bottom') + +# netifyd address groups, one file for every object resolving to addresses, see `write_address_groups` +ADDRESS_GROUPS_DIR = '/etc/netifyd/address-groups.d' + +# prefixes below 20 belong to the agent itself, this one belongs to `write_address_groups`: every file +# carrying it whose object is gone, or has no address anymore, is removed. The agent saves the groups it +# holds when it stops, without comments and including the ones whose file was removed while it was running: +# the prefix is what tells such a stale file apart +_ADDRESS_GROUP_FILE_PREFIX = '30-' + +# ending of the header comment of every file written by `write_address_groups`, for whoever reads it +_ADDRESS_GROUP_FILE_MARKER = 'generated from the firewall objects: do not edit' + +# (database, section type) of the objects with an address group, so the ones a rule source can reference: +# everything resolving to addresses. Domain sets are left out: they resolve to addresses only at runtime +_ADDRESS_GROUP_TYPES = (('objects', 'host'), ('dhcp', 'host'), ('dhcp', 'domain'), ('users', 'user')) + def load_applications() -> dict[int, str]: """ @@ -69,30 +126,6 @@ def load_protocols() -> dict[int, str]: # Application groups: a NethSecurity abstraction, the netifyd plugin has no group primitive. # A group is a named set of match members, expanded into an inline expression at generation time. -NETIFYD_DATA_DIR = '/etc/netifyd' - -# UCI list name of every member kind, mapped to the API parameter it is fed by -APPGROUP_MEMBERS = { - 'app': 'applications', - 'app_category': 'application_categories', - 'proto': 'protocols', - 'proto_category': 'protocol_categories' -} - -# validation error message of every member kind -__APPGROUP_MEMBER_ERRORS = { - 'app': 'invalid_application', - 'app_category': 'invalid_application_category', - 'proto': 'invalid_protocol', - 'proto_category': 'invalid_protocol_category' -} - -# characters that would let a member value escape its quoted literal, or terminate the expression -__APPGROUP_FORBIDDEN_CHARS = '\'"\\;()\n\r\t' - -APPGROUP_NAME_MAX_LENGTH = 64 - - def load_categories() -> dict[str, dict[int, str]]: """ Reads the categories loaded in memory by the engine, using the netifyd --dump-categories command. @@ -177,13 +210,6 @@ def __appgroup_vocabulary(kind: str) -> set[str] | None: # an unknown value never matches, so a missing vocabulary is a reason to skip the check, not to refuse return vocabulary if vocabulary else None -APPGROUP_CATALOG_FILES = { - 'applications': 'netify-application-catalog.json', - 'protocols': 'netify-protocol-catalog.json' -} - -UNCATEGORIZED_TAG = '' - def list_appgroup_catalog() -> dict[str, list[dict]]: """ @@ -540,16 +566,6 @@ def expand_appgroups(e_uci: EUci, config_names: list[str]) -> str: # Rules: ordered by priority, first match wins. A rule matches application groups only, optionally # narrowed to a source; what it does is decided by its action. -# 'allow' attaches a label no nft rule matches: it exists so a rule can win the first-match race and -# shield its traffic from the block rules below it -DPI_RULE_ACTIONS = ('block', 'allow') - -DPI_RULE_NAME_MAX_LENGTH = 64 - -DPI_MATCH_ALL_CRITERIA = '*' - -DPI_RULE_POSITIONS = ('top', 'bottom') - def __sorted_rules(e_uci: EUci) -> list[tuple[str, dict]]: """ @@ -656,11 +672,158 @@ def expand_source(values: list[str]) -> list[str]: return expanded +# Address groups: every object resolving to IP addresses has its netifyd address group, +# `ADDRESS_GROUPS_DIR/30-.conf`, whether a rule uses it or not: a rule source matches it as +# `local_ip == @`, and the files follow the objects as they are committed, not the rules. + +def _address_group_tag(database_id: str) -> str: + """ + The tag of the address group of an object, e.g. `objects_ns_1234` for `objects/ns_1234`. + + Args: + - database_id: id of the object in the form of `/` + + Returns: + the tag, as referenced by a criteria with `@` + """ + return database_id.replace('/', '_') + + +def _strip_zone(value: str) -> str: + """Drop the zone of a link-local address, e.g. `fe80::1%eth0/64` becomes `fe80::1/64`.""" + if '%' not in value: + return value + address, _, rest = value.partition('%') + _, slash, prefix = rest.partition('/') + return f'{address}{slash}{prefix}' + + +def _address_group_entries(e_uci: EUci, database_id: str) -> list[str]: + """ + The entries of the address group of an object, written the way an address group can match them: + ranges become CIDR blocks, as an address group silently ignores them, and a range whose first address + is greater than its last, which the object API accepts, covers the same addresses as the ordered one; an + IPv4-mapped IPv6 network becomes the IPv4 network it maps, as it never matches an IPv4 flow; a zero + length prefix, which matches nothing, is split into its two halves. A value that cannot be turned into an + address is skipped with a log line, as the agent would ignore it. + + Args: + - e_uci: euci instance + - database_id: id of the object in the form of `/` + + Returns: + the entries, empty when the object has no address the agent can match, or is gone + """ + entries = [] + for value in objects.get_object_ips(e_uci, database_id): + try: + if '-' in value: + # the host set keeps the range as entered: only the written networks are ordered + bounds = (ipaddress.ip_address(_strip_zone(part.strip())) for part in value.split('-', 1)) + first, last = sorted(bounds) + networks = list(ipaddress.summarize_address_range(first, last)) + else: + networks = [ipaddress.ip_network(_strip_zone(value.strip()), strict=False)] + except (ValueError, TypeError) as error: + syslog.syslog(syslog.LOG_WARNING, f"dpi: skipping {value!r} of {database_id}: {error}") + continue + for network in networks: + if network.version == 6 and network.prefixlen >= 96 and network.network_address.ipv4_mapped: + network = ipaddress.ip_network(f'{network.network_address.ipv4_mapped}/{network.prefixlen - 96}') + for entry in network.subnets(new_prefix=1) if network.prefixlen == 0 else [network]: + if str(entry) not in entries: + entries.append(str(entry)) + return entries + + +def write_address_groups(e_uci: EUci) -> bool: + """ + Write the address group of every object resolving to addresses, and remove every other file with the + `_ADDRESS_GROUP_FILE_PREFIX` prefix: the ones of objects that are gone or have no address anymore. A file + is rewritten only when its content changes. The agent loads the files on start and on reload. + + Args: + - e_uci: euci instance + + Returns: + True when a file was written or removed + """ + os.makedirs(ADDRESS_GROUPS_DIR, exist_ok=True) + wanted = {} + for database in sorted({database for database, _ in _ADDRESS_GROUP_TYPES}): + try: + sections = e_uci.get_all(database) + except Exception: + # the configuration doesn't exist + continue + for section in sections: + if (database, e_uci.get(database, section)) not in _ADDRESS_GROUP_TYPES: + continue + database_id = f'{database}/{section}' + entries = _address_group_entries(e_uci, database_id) + if not entries: + continue + # header: the object name, when it has one, on one line, then the id and the marker + name = ' '.join(str(e_uci.get(database, section, 'name', default='')).split()) + lines = [f'# {name}'] if name else [] + lines.append(f'# {database_id}, {_ADDRESS_GROUP_FILE_MARKER}') + lines.extend(entries) + filename = f'{_ADDRESS_GROUP_FILE_PREFIX}{_address_group_tag(database_id)}.conf' + wanted[filename] = ''.join(f'{line}\n' for line in lines) + + changed = False + for filename in os.listdir(ADDRESS_GROUPS_DIR): + if filename.startswith(_ADDRESS_GROUP_FILE_PREFIX) and filename.endswith('.conf') and filename not in wanted: + os.remove(os.path.join(ADDRESS_GROUPS_DIR, filename)) + changed = True + + for filename, content in wanted.items(): + path = os.path.join(ADDRESS_GROUPS_DIR, filename) + try: + with open(path, 'r') as fp: + if fp.read() == content: + if os.stat(path).st_mode & 0o777 != 0o644: + os.chmod(path, 0o644) + continue + except FileNotFoundError: + pass + with open(f'{path}.tmp', 'w') as fp: + fp.write(content) + # readable by the agent whatever the umask of the caller, e.g. the API server + os.chmod(f'{path}.tmp', 0o644) + os.replace(f'{path}.tmp', path) + changed = True + + return changed + + +def update_address_groups(e_uci: EUci) -> bool: + """ + Write the address groups, see `write_address_groups`, and reload the agent when a file changed and it is + running, so it loads them. To be called once the object changes are committed. + + Args: + - e_uci: euci instance + + Returns: + True when a file was written or removed. A file that can't be written is logged, not raised: the + object changes are committed already, the next update or boot writes it again + """ + try: + changed = write_address_groups(e_uci) + except OSError as error: + syslog.syslog(syslog.LOG_ERR, f"dpi: cannot write the address groups: {error}") + return False + if changed and subprocess.run(['/etc/init.d/netifyd', 'running'], capture_output=True).returncode == 0: + subprocess.run(['/etc/init.d/netifyd', 'reload'], capture_output=True) + return changed + + # Source objects: firewall objects resolving to IP addresses, referenced by a rule instead of typing the -# addresses in. Every such object has its netifyd address group, written by `objects.write_address_groups` +# addresses in. Every such object has its netifyd address group, written by `write_address_groups` # when the object is committed, and the criteria matches it as `local_ip == @`: the criteria stays one # term wide whatever the object holds, and a change to the object only rewrites its file. A source can -# reference the objects with an address group, see `objects.ADDRESS_GROUP_TYPES`. +# reference the objects with an address group, see `_ADDRESS_GROUP_TYPES`. def __validate_source_objects(e_uci: EUci, values: list[str], source: list[str]) -> list[str]: @@ -675,7 +838,7 @@ def __validate_source_objects(e_uci: EUci, values: list[str], source: list[str]) if not isinstance(value, str) or not objects.is_object_id(value): raise ValidationError('source_objects', 'invalid_source_object', value) database, _, section = value.partition('/') - if not section or (database, e_uci.get(database, section, default=None)) not in objects.ADDRESS_GROUP_TYPES: + if not section or (database, e_uci.get(database, section, default=None)) not in _ADDRESS_GROUP_TYPES: raise ValidationError('source_objects', 'invalid_source_object', value) # a user is an object only with a VPN account holding a reserved address if database == 'users' and not e_uci.get('users', section, 'openvpn_ipaddr', default=None): @@ -690,7 +853,7 @@ def build_rule_criteria(e_uci: EUci, rule: dict) -> str: Build the criteria of a managed rule: the source, when set, ANDed with the union of its groups. The source is made of its addresses or of the address groups of its objects, see - `objects.write_address_groups`; a rule holding both, e.g. edited by hand, matches either. An object + `write_address_groups`; a rule holding both, e.g. edited by hand, matches either. An object without addresses has no group file: the term stays, and a missing group matches nothing. Args: @@ -702,7 +865,7 @@ def build_rule_criteria(e_uci: EUci, rule: dict) -> str: """ match = expand_appgroups(e_uci, list(rule.get('appgroup', []))) sources = [f'local_ip == {source}' for source in expand_source(list(rule.get('source', [])))] - sources += [f"local_ip == @{objects.address_group_tag(object_id)}" for object_id in rule.get('source_object', [])] + sources += [f"local_ip == @{_address_group_tag(object_id)}" for object_id in rule.get('source_object', [])] if not match: if not sources: @@ -819,7 +982,7 @@ def add_rule(e_uci: EUci, name: str, enabled: bool, action: str, source: list[st - match_all: the rule matches every flow, narrowed to `source` when one is given. Mutually exclusive with `appgroups` - source_objects: ids of the objects, in the form of `/`, whose addresses the rule is - narrowed to, as an alternative to `source`; see `objects.ADDRESS_GROUP_TYPES` for the accepted ones + narrowed to, as an alternative to `source`; see `_ADDRESS_GROUP_TYPES` for the accepted ones Returns: config name of the rule created @@ -867,7 +1030,7 @@ def edit_rule(e_uci: EUci, config_name: str, name: str, enabled: bool, action: s - match_all: the rule matches every flow, narrowed to `source` when one is given. Mutually exclusive with `appgroups` - source_objects: ids of the objects, in the form of `/`, whose addresses the rule is - narrowed to, as an alternative to `source`; see `objects.ADDRESS_GROUP_TYPES` for the accepted ones + narrowed to, as an alternative to `source`; see `_ADDRESS_GROUP_TYPES` for the accepted ones Returns: config name of the rule edited diff --git a/packages/python3-nethsec/src/nethsec/objects/__init__.py b/packages/python3-nethsec/src/nethsec/objects/__init__.py index 56b9384b9..4253abf82 100644 --- a/packages/python3-nethsec/src/nethsec/objects/__init__.py +++ b/packages/python3-nethsec/src/nethsec/objects/__init__.py @@ -12,7 +12,6 @@ import json import os import subprocess -import syslog from euci import EUci @@ -887,167 +886,3 @@ def get_info(uci, database_id): except: return None - - -# Address groups - -# Every object resolving to IP addresses has its netifyd address group, `ADDRESS_GROUPS_DIR/30-.conf`, -# whether a DPI rule uses it or not: a rule source matches it as `local_ip == @`, and the files follow -# the objects as they are committed, not the rules. - -ADDRESS_GROUPS_DIR = '/etc/netifyd/address-groups.d' - -# prefixes below 20 belong to the agent itself, this one belongs to `write_address_groups`: every file -# carrying it whose object is gone, or has no address anymore, is removed. The agent saves the groups it -# holds when it stops, without comments and including the ones whose file was removed while it was running: -# the prefix is what tells such a stale file apart -ADDRESS_GROUP_FILE_PREFIX = '30-' - -# ending of the header comment of every file written here, for whoever reads it -ADDRESS_GROUP_FILE_MARKER = 'generated from the firewall objects: do not edit' - -# (database, section type) of the objects with an address group: everything resolving to addresses. -# Domain sets are left out: they resolve to addresses only at runtime -ADDRESS_GROUP_TYPES = (('objects', 'host'), ('dhcp', 'host'), ('dhcp', 'domain'), ('users', 'user')) - - -def address_group_tag(database_id): - """ - The tag of the address group of an object, e.g. `objects_ns_1234` for `objects/ns_1234`. - - Args: - database_id: id of the object in the form of `/` - - Returns: - the tag, as referenced by a criteria with `@` - """ - return database_id.replace('/', '_') - - -def _strip_zone(value): - """Drop the zone of a link-local address, e.g. `fe80::1%eth0/64` becomes `fe80::1/64`.""" - if '%' not in value: - return value - address, _, rest = value.partition('%') - _, slash, prefix = rest.partition('/') - return f'{address}{slash}{prefix}' - - -def address_group_entries(uci, database_id): - """ - The entries of the address group of an object, written the way an address group can match them: - ranges become CIDR blocks, as an address group silently ignores them, and a range whose first address - is greater than its last, which the object API accepts, covers the same addresses as the ordered one; an - IPv4-mapped IPv6 network becomes the IPv4 network it maps, as it never matches an IPv4 flow; a zero - length prefix, which matches nothing, is split into its two halves. A value that cannot be turned into an - address is skipped with a log line, as the agent would ignore it. - - Args: - uci: EUci pointer - database_id: id of the object in the form of `/` - - Returns: - the entries, empty when the object has no address the agent can match, or is gone - """ - entries = [] - for value in get_object_ips(uci, database_id): - try: - if '-' in value: - # the host set keeps the range as entered: only the written networks are ordered - first, last = sorted(ipaddress.ip_address(_strip_zone(part.strip())) for part in value.split('-', 1)) - networks = list(ipaddress.summarize_address_range(first, last)) - else: - networks = [ipaddress.ip_network(_strip_zone(value.strip()), strict=False)] - except (ValueError, TypeError) as error: - syslog.syslog(syslog.LOG_WARNING, f"objects: skipping {value!r} of {database_id}: {error}") - continue - for network in networks: - if network.version == 6 and network.prefixlen >= 96 and network.network_address.ipv4_mapped: - network = ipaddress.ip_network(f'{network.network_address.ipv4_mapped}/{network.prefixlen - 96}') - for entry in network.subnets(new_prefix=1) if network.prefixlen == 0 else [network]: - if str(entry) not in entries: - entries.append(str(entry)) - return entries - - -def write_address_groups(uci): - """ - Write the address group of every object resolving to addresses, and remove every other file with the - `ADDRESS_GROUP_FILE_PREFIX` prefix: the ones of objects that are gone or have no address anymore. A file - is rewritten only when its content changes. The agent loads the files on start and on reload. - - Args: - uci: EUci pointer - - Returns: - True when a file was written or removed - """ - os.makedirs(ADDRESS_GROUPS_DIR, exist_ok=True) - wanted = {} - for database in sorted({database for database, _ in ADDRESS_GROUP_TYPES}): - try: - sections = uci.get_all(database) - except Exception: - # the configuration doesn't exist - continue - for section in sections: - if (database, uci.get(database, section)) not in ADDRESS_GROUP_TYPES: - continue - database_id = f'{database}/{section}' - entries = address_group_entries(uci, database_id) - if not entries: - continue - # header: the object name, when it has one, on one line, then the id and the marker - name = ' '.join(str(uci.get(database, section, 'name', default='')).split()) - lines = [f'# {name}'] if name else [] - lines.append(f'# {database_id}, {ADDRESS_GROUP_FILE_MARKER}') - lines.extend(entries) - wanted[f'{ADDRESS_GROUP_FILE_PREFIX}{address_group_tag(database_id)}.conf'] = \ - ''.join(f'{line}\n' for line in lines) - - changed = False - for filename in os.listdir(ADDRESS_GROUPS_DIR): - if filename.startswith(ADDRESS_GROUP_FILE_PREFIX) and filename.endswith('.conf') and filename not in wanted: - os.remove(os.path.join(ADDRESS_GROUPS_DIR, filename)) - changed = True - - for filename, content in wanted.items(): - path = os.path.join(ADDRESS_GROUPS_DIR, filename) - try: - with open(path, 'r') as fp: - if fp.read() == content: - if os.stat(path).st_mode & 0o777 != 0o644: - os.chmod(path, 0o644) - continue - except FileNotFoundError: - pass - with open(f'{path}.tmp', 'w') as fp: - fp.write(content) - # readable by the agent whatever the umask of the caller, e.g. the API server - os.chmod(f'{path}.tmp', 0o644) - os.replace(f'{path}.tmp', path) - changed = True - - return changed - - -def update_address_groups(uci): - """ - Write the address groups, see `write_address_groups`, and reload the agent when a file changed and it is - running, so it loads them. To be called once the object changes are committed. - - Args: - uci: EUci pointer - - Returns: - True when a file was written or removed. A file that can't be written is logged, not raised: the - object changes are committed already, the next update or boot writes it again - """ - try: - changed = write_address_groups(uci) - except OSError as error: - syslog.syslog(syslog.LOG_ERR, f"objects: cannot write the address groups: {error}") - return False - if changed and subprocess.run(['/etc/init.d/netifyd', 'running'], capture_output=True).returncode == 0: - subprocess.run(['/etc/init.d/netifyd', 'reload'], capture_output=True) - return changed diff --git a/packages/python3-nethsec/tests/test_dpi.py b/packages/python3-nethsec/tests/test_dpi.py index d42d4045e..b5e6e1994 100644 --- a/packages/python3-nethsec/tests/test_dpi.py +++ b/packages/python3-nethsec/tests/test_dpi.py @@ -1,3 +1,4 @@ +import os import pathlib import subprocess @@ -1495,3 +1496,331 @@ def test_source_object_is_used(e_uci_sources): assert objects.is_used_object(e_uci_sources, 'dhcp/ns_record') == (False, []) # the usage is shown with the rule name assert objects.get_info(e_uci_sources, f'dpi/{rule_id}')['name'] == 'One' + +# Address groups + +groups_objects_db = """ +config host 'ns_host' + option name 'host1' + option family 'ipv4' + list ipaddr '192.168.1.10' + +config host 'ns_cidr' + option name 'cidr1' + option family 'ipv4' + list ipaddr '192.168.1.0/24' + +config host 'ns_range' + option name 'range1' + option family 'ipv4' + list ipaddr '192.168.1.10-192.168.1.13' + +config host 'ns_reversed' + option name 'reversed1' + option family 'ipv4' + list ipaddr '192.168.1.20-192.168.1.10' + list ipaddr '192.168.1.30' + +config host 'ns_nested' + option name 'nested1' + option family 'ipv4' + list ipaddr 'objects/ns_host' + list ipaddr 'dhcp/ns_lease' + list ipaddr '10.0.0.1' + list ipaddr '192.168.1.10' + +config host 'ns_mapped' + option name 'mapped1' + option family 'ipv6' + list ipaddr '::ffff:192.168.1.10' + list ipaddr '::ffff:192.168.2.0/120' + +config host 'ns_all' + option name 'all1' + option family 'ipv4' + list ipaddr '0.0.0.0/0' + +config host 'ns_all6' + option name 'all6' + option family 'ipv6' + list ipaddr '::-ffff:ffff:ffff:ffff:ffff:ffff:ffff:ffff' + +config host 'ns_zone' + option name 'zone1' + option family 'ipv6' + list ipaddr 'fe80::1%eth0' + list ipaddr 'fe80::10%eth0-fe80::11%eth0' + +config host 'ns_v6range' + option name 'v6range1' + option family 'ipv6' + list ipaddr 'fd00::1-fd00::4' + list ipaddr 'FD00::50' + +config host 'ns_with_domain' + option name 'withdomain1' + option family 'ipv4' + list ipaddr 'objects/ns_domain' + +config domain 'ns_domain' + option name 'domain1' + option family 'ipv4' + option timeout '600' + list domain 'example.com' +""" + +groups_dhcp_db = """ +config dnsmasq + option domain 'lan' + +config host 'ns_lease' + option name 'lease1' + option ip '192.168.1.50' + option mac '02:00:00:00:00:50' + +config domain 'ns_record' + option name 'record.lan' + option ip '192.168.1.60' +""" + +groups_users_db = """ +config local 'main' + option description 'Local users' + +config user 'ns_vpn' + option name 'vpnuser' + option database 'main' + option openvpn_ipaddr '10.9.0.2' + +config user 'ns_novpn' + option name 'novpnuser' + option database 'main' + +config user 'ns_noip' + option name 'noipuser' + option database 'main' + option openvpn_ipaddr '' +""" + +# the objects of the configuration above with at least one address, so with an address group file. +# Pending changes other tests leave in the default savedir can add more objects: assertions check these +groups_files = ['30-dhcp_ns_lease.conf', '30-dhcp_ns_record.conf', '30-objects_ns_all.conf', + '30-objects_ns_all6.conf', '30-objects_ns_cidr.conf', '30-objects_ns_host.conf', + '30-objects_ns_mapped.conf', '30-objects_ns_nested.conf', '30-objects_ns_range.conf', + '30-objects_ns_reversed.conf', '30-objects_ns_v6range.conf', '30-objects_ns_zone.conf', + '30-users_ns_vpn.conf'] + +# the objects of the configuration above without addresses, so without a file +groups_no_files = ['30-objects_ns_domain.conf', '30-objects_ns_with_domain.conf', '30-users_ns_novpn.conf', + '30-users_ns_noip.conf'] + + +@pytest.fixture +def g(tmp_path: pathlib.Path, monkeypatch) -> EUci: + """A configuration holding every kind of object, address groups in a temp dir.""" + conf_dir = tmp_path.joinpath('conf') + conf_dir.mkdir() + conf_dir.joinpath('objects').write_text(groups_objects_db) + conf_dir.joinpath('dhcp').write_text(groups_dhcp_db) + conf_dir.joinpath('users').write_text(groups_users_db) + save_dir = tmp_path.joinpath('save') + save_dir.mkdir() + monkeypatch.setattr(dpi, 'ADDRESS_GROUPS_DIR', tmp_path.joinpath('address-groups.d').as_posix()) + return EUci(confdir=conf_dir.as_posix(), savedir=save_dir.as_posix()) + + +def groups_dir() -> pathlib.Path: + return pathlib.Path(dpi.ADDRESS_GROUPS_DIR) + + +def group_file(name) -> pathlib.Path: + return groups_dir().joinpath(name) + + +def group_files() -> set: + return {path.name for path in groups_dir().iterdir()} + + +def test_address_group_tag(): + assert dpi._address_group_tag('objects/ns_host') == 'objects_ns_host' + assert dpi._address_group_tag('users/ns_vpn') == 'users_ns_vpn' + + +@pytest.mark.parametrize('object_id, entries', [ + ('objects/ns_host', ['192.168.1.10/32']), + ('objects/ns_cidr', ['192.168.1.0/24']), + # an address group ignores ranges: they become CIDR blocks + ('objects/ns_range', ['192.168.1.10/31', '192.168.1.12/31']), + ('objects/ns_v6range', ['fd00::1/128', 'fd00::2/127', 'fd00::4/128', 'fd00::50/128']), + # the object API accepts a reversed range: it covers the same addresses as the ordered one + ('objects/ns_reversed', ['192.168.1.10/31', '192.168.1.12/30', '192.168.1.16/30', '192.168.1.20/32', + '192.168.1.30/32']), + # references are resolved, duplicates dropped + ('objects/ns_nested', ['192.168.1.10/32', '192.168.1.50/32', '10.0.0.1/32']), + # an IPv4-mapped address never matches the IPv4 flow it maps + ('objects/ns_mapped', ['192.168.1.10/32', '192.168.2.0/24']), + # a zero length prefix matches nothing in a group: its two halves match everything + ('objects/ns_all', ['0.0.0.0/1', '128.0.0.0/1']), + ('objects/ns_all6', ['::/1', '8000::/1']), + ('objects/ns_zone', ['fe80::1/128', 'fe80::10/127']), + ('dhcp/ns_lease', ['192.168.1.50/32']), + ('dhcp/ns_record', ['192.168.1.60/32']), + ('users/ns_vpn', ['10.9.0.2/32']), + # objects with no address + ('users/ns_novpn', []), + ('users/ns_noip', []), + ('objects/ns_with_domain', []), + ('objects/ns_domain', []), + ('objects/ns_missing', []), +]) +def test_address_group_entries(g, object_id, entries): + assert dpi._address_group_entries(g, object_id) == entries + + +def test_write_address_groups(g): + assert dpi.write_address_groups(g) is True + # one file per object with addresses: no file for domain sets, users without a reserved IP and objects + # resolving to no address + assert set(groups_files) <= group_files() + assert not set(groups_no_files) & group_files() + assert all(name.startswith('30-') and name.endswith('.conf') for name in group_files()) + assert group_file('30-objects_ns_range.conf').read_text() == ( + '# range1\n# objects/ns_range, generated from the firewall objects: do not edit\n' + '192.168.1.10/31\n192.168.1.12/31\n') + assert group_file('30-users_ns_vpn.conf').read_text() == ( + '# vpnuser\n# users/ns_vpn, generated from the firewall objects: do not edit\n10.9.0.2/32\n') + # unchanged: nothing is written + inode = group_file('30-objects_ns_host.conf').stat().st_ino + assert dpi.write_address_groups(g) is False + assert group_file('30-objects_ns_host.conf').stat().st_ino == inode + + +def test_write_address_groups_removes_only_its_own_stale_files(g): + groups_dir().mkdir() + # other prefixes or extensions: kept + for name in ('10-agent.conf', '20-other.conf', '30-objects_ns_gone.txt'): + group_file(name).write_text('10.0.0.1\n') + # objects gone, as written here or as saved by the agent without the header: removed + group_file('30-objects_ns_gone.conf').write_text( + '# gone1\n# objects/ns_gone, generated from the firewall objects: do not edit\n10.0.0.1/32\n') + group_file('30-objects_ns_saved.conf').write_text('10.0.0.1\n') + group_file('30-objects_ns_empty.conf').write_text('') + # an object without addresses: its file goes too + group_file('30-users_ns_novpn.conf').write_text('10.9.0.3\n') + # an existing object, as saved by the agent: rewritten with the header + group_file('30-objects_ns_host.conf').write_text('192.168.1.10\n') + dpi.write_address_groups(g) + assert {'10-agent.conf', '20-other.conf', '30-objects_ns_gone.txt'} | set(groups_files) <= group_files() + assert not {'30-objects_ns_gone.conf', '30-objects_ns_saved.conf', '30-objects_ns_empty.conf', + '30-users_ns_novpn.conf'} & group_files() + assert group_file('30-objects_ns_host.conf').read_text().splitlines()[1] == ( + '# objects/ns_host, generated from the firewall objects: do not edit') + + +def test_write_address_groups_follows_the_objects(g): + dpi.write_address_groups(g) + host = group_file('30-objects_ns_host.conf') + # the object changes: its file follows, and the one of the host set holding it too + g.set('objects', 'ns_host', 'ipaddr', ['192.168.1.11']) + assert dpi.write_address_groups(g) is True + assert host.read_text().splitlines()[2:] == ['192.168.1.11/32'] + assert group_file('30-objects_ns_nested.conf').read_text().splitlines()[2:] == [ + '192.168.1.11/32', '192.168.1.50/32', '10.0.0.1/32', '192.168.1.10/32'] + # the object is renamed: the header follows + g.set('objects', 'ns_host', 'name', 'renamed') + dpi.write_address_groups(g) + assert host.read_text().splitlines()[0] == '# renamed' + # the object is deleted: its file goes + g.delete('objects', 'ns_host') + assert dpi.write_address_groups(g) is True + assert not host.exists() + # a VPN user loses its reserved IP: its file goes, and comes back with it + vpn = group_file('30-users_ns_vpn.conf') + g.delete('users', 'ns_vpn', 'openvpn_ipaddr') + dpi.write_address_groups(g) + assert not vpn.exists() + g.set('users', 'ns_vpn', 'openvpn_ipaddr', '10.9.0.5') + dpi.write_address_groups(g) + assert vpn.read_text().splitlines()[2:] == ['10.9.0.5/32'] + # a new object: a new file + g.set('dhcp', 'ns_new', 'host') + g.set('dhcp', 'ns_new', 'name', 'new1') + g.set('dhcp', 'ns_new', 'ip', '192.168.1.70') + dpi.write_address_groups(g) + assert group_file('30-dhcp_ns_new.conf').read_text().splitlines()[2:] == ['192.168.1.70/32'] + + +def test_write_address_groups_files_are_readable_whatever_the_umask(g): + umask = os.umask(0o077) + try: + dpi.write_address_groups(g) + finally: + os.umask(umask) + assert group_file('30-objects_ns_host.conf').stat().st_mode & 0o777 == 0o644 + # an unchanged file keeps its content, its mode is fixed + group_file('30-objects_ns_host.conf').chmod(0o600) + assert dpi.write_address_groups(g) is False + assert group_file('30-objects_ns_host.conf').stat().st_mode & 0o777 == 0o644 + + +def test_write_address_groups_header(g): + # an object without a name: the header holds only the id + g.delete('objects', 'ns_host', 'name') + # a name on more lines: joined on one + g.set('objects', 'ns_cidr', 'name', 'two\nlines') + dpi.write_address_groups(g) + assert group_file('30-objects_ns_host.conf').read_text() == ( + '# objects/ns_host, generated from the firewall objects: do not edit\n192.168.1.10/32\n') + assert group_file('30-objects_ns_cidr.conf').read_text().splitlines()[:2] == [ + '# two lines', '# objects/ns_cidr, generated from the firewall objects: do not edit'] + + +def test_write_address_groups_without_configurations(tmp_path, monkeypatch): + conf_dir = tmp_path.joinpath('conf') + conf_dir.mkdir() + save_dir = tmp_path.joinpath('save') + save_dir.mkdir() + monkeypatch.setattr(dpi, 'ADDRESS_GROUPS_DIR', tmp_path.joinpath('address-groups.d').as_posix()) + dpi.write_address_groups(EUci(confdir=conf_dir.as_posix(), savedir=save_dir.as_posix())) + assert not set(groups_files) & group_files() + + +def netifyd_calls(run): + return [call.args[0] for call in run.call_args_list] + + +def test_update_address_groups_reloads_a_running_agent(g, mocker): + run = mocker.patch('nethsec.dpi.subprocess.run') + run.return_value.returncode = 0 + assert dpi.update_address_groups(g) is True + assert netifyd_calls(run) == [['/etc/init.d/netifyd', 'running'], ['/etc/init.d/netifyd', 'reload']] + # nothing changed: no reload + run.reset_mock() + assert dpi.update_address_groups(g) is False + assert netifyd_calls(run) == [] + + +def test_address_group_entries_skips_an_invalid_value(g, mocker): + log = mocker.patch('nethsec.dpi.syslog.syslog') + # a range mixing the families can't become networks: it is skipped, the rest of the object is kept + g.set('objects', 'ns_reversed', 'ipaddr', ['192.168.1.10-fd00::1', '192.168.1.30']) + assert dpi._address_group_entries(g, 'objects/ns_reversed') == ['192.168.1.30/32'] + assert "skipping '192.168.1.10-fd00::1' of objects/ns_reversed" in log.call_args.args[1] + # the host set itself is left as entered + assert g.get('objects', 'ns_reversed', 'ipaddr', list=True) == ('192.168.1.10-fd00::1', '192.168.1.30') + + +def test_update_address_groups_leaves_a_stopped_agent_alone(g, mocker): + run = mocker.patch('nethsec.dpi.subprocess.run') + run.return_value.returncode = 1 + assert dpi.update_address_groups(g) is True + assert netifyd_calls(run) == [['/etc/init.d/netifyd', 'running']] + + +def test_update_address_groups_logs_a_write_failure(g, mocker): + run = mocker.patch('nethsec.dpi.subprocess.run') + mocker.patch('nethsec.dpi.write_address_groups', side_effect=PermissionError('denied')) + log = mocker.patch('nethsec.dpi.syslog.syslog') + assert dpi.update_address_groups(g) is False + assert netifyd_calls(run) == [] + assert 'cannot write the address groups' in log.call_args.args[1] diff --git a/packages/python3-nethsec/tests/test_objects.py b/packages/python3-nethsec/tests/test_objects.py index 39d49a946..aa57ee00c 100644 --- a/packages/python3-nethsec/tests/test_objects.py +++ b/packages/python3-nethsec/tests/test_objects.py @@ -1,4 +1,3 @@ -import os import pathlib from nethsec.utils import ValidationError import pytest @@ -379,332 +378,4 @@ def test_get_reference_info(u): def test_is_object_with_invalid_is(u): assert objects.is_object_id(None) == False - assert objects.is_object_id(1) == False - -# Address groups - -groups_objects_db = """ -config host 'ns_host' - option name 'host1' - option family 'ipv4' - list ipaddr '192.168.1.10' - -config host 'ns_cidr' - option name 'cidr1' - option family 'ipv4' - list ipaddr '192.168.1.0/24' - -config host 'ns_range' - option name 'range1' - option family 'ipv4' - list ipaddr '192.168.1.10-192.168.1.13' - -config host 'ns_reversed' - option name 'reversed1' - option family 'ipv4' - list ipaddr '192.168.1.20-192.168.1.10' - list ipaddr '192.168.1.30' - -config host 'ns_nested' - option name 'nested1' - option family 'ipv4' - list ipaddr 'objects/ns_host' - list ipaddr 'dhcp/ns_lease' - list ipaddr '10.0.0.1' - list ipaddr '192.168.1.10' - -config host 'ns_mapped' - option name 'mapped1' - option family 'ipv6' - list ipaddr '::ffff:192.168.1.10' - list ipaddr '::ffff:192.168.2.0/120' - -config host 'ns_all' - option name 'all1' - option family 'ipv4' - list ipaddr '0.0.0.0/0' - -config host 'ns_all6' - option name 'all6' - option family 'ipv6' - list ipaddr '::-ffff:ffff:ffff:ffff:ffff:ffff:ffff:ffff' - -config host 'ns_zone' - option name 'zone1' - option family 'ipv6' - list ipaddr 'fe80::1%eth0' - list ipaddr 'fe80::10%eth0-fe80::11%eth0' - -config host 'ns_v6range' - option name 'v6range1' - option family 'ipv6' - list ipaddr 'fd00::1-fd00::4' - list ipaddr 'FD00::50' - -config host 'ns_with_domain' - option name 'withdomain1' - option family 'ipv4' - list ipaddr 'objects/ns_domain' - -config domain 'ns_domain' - option name 'domain1' - option family 'ipv4' - option timeout '600' - list domain 'example.com' -""" - -groups_dhcp_db = """ -config dnsmasq - option domain 'lan' - -config host 'ns_lease' - option name 'lease1' - option ip '192.168.1.50' - option mac '02:00:00:00:00:50' - -config domain 'ns_record' - option name 'record.lan' - option ip '192.168.1.60' -""" - -groups_users_db = """ -config local 'main' - option description 'Local users' - -config user 'ns_vpn' - option name 'vpnuser' - option database 'main' - option openvpn_ipaddr '10.9.0.2' - -config user 'ns_novpn' - option name 'novpnuser' - option database 'main' - -config user 'ns_noip' - option name 'noipuser' - option database 'main' - option openvpn_ipaddr '' -""" - -# the objects of the configuration above with at least one address, so with an address group file. -# Pending changes other tests leave in the default savedir can add more objects: assertions check these -groups_files = ['30-dhcp_ns_lease.conf', '30-dhcp_ns_record.conf', '30-objects_ns_all.conf', - '30-objects_ns_all6.conf', '30-objects_ns_cidr.conf', '30-objects_ns_host.conf', - '30-objects_ns_mapped.conf', '30-objects_ns_nested.conf', '30-objects_ns_range.conf', - '30-objects_ns_reversed.conf', '30-objects_ns_v6range.conf', '30-objects_ns_zone.conf', - '30-users_ns_vpn.conf'] - -# the objects of the configuration above without addresses, so without a file -groups_no_files = ['30-objects_ns_domain.conf', '30-objects_ns_with_domain.conf', '30-users_ns_novpn.conf', - '30-users_ns_noip.conf'] - - -@pytest.fixture -def g(tmp_path: pathlib.Path, monkeypatch) -> EUci: - """A configuration holding every kind of object, address groups in a temp dir.""" - conf_dir = tmp_path.joinpath('conf') - conf_dir.mkdir() - conf_dir.joinpath('objects').write_text(groups_objects_db) - conf_dir.joinpath('dhcp').write_text(groups_dhcp_db) - conf_dir.joinpath('users').write_text(groups_users_db) - save_dir = tmp_path.joinpath('save') - save_dir.mkdir() - monkeypatch.setattr(objects, 'ADDRESS_GROUPS_DIR', tmp_path.joinpath('address-groups.d').as_posix()) - return EUci(confdir=conf_dir.as_posix(), savedir=save_dir.as_posix()) - - -def groups_dir() -> pathlib.Path: - return pathlib.Path(objects.ADDRESS_GROUPS_DIR) - - -def group_file(name) -> pathlib.Path: - return groups_dir().joinpath(name) - - -def group_files() -> set: - return {path.name for path in groups_dir().iterdir()} - - -def test_address_group_tag(): - assert objects.address_group_tag('objects/ns_host') == 'objects_ns_host' - assert objects.address_group_tag('users/ns_vpn') == 'users_ns_vpn' - - -@pytest.mark.parametrize('object_id, entries', [ - ('objects/ns_host', ['192.168.1.10/32']), - ('objects/ns_cidr', ['192.168.1.0/24']), - # an address group ignores ranges: they become CIDR blocks - ('objects/ns_range', ['192.168.1.10/31', '192.168.1.12/31']), - ('objects/ns_v6range', ['fd00::1/128', 'fd00::2/127', 'fd00::4/128', 'fd00::50/128']), - # the object API accepts a reversed range: it covers the same addresses as the ordered one - ('objects/ns_reversed', ['192.168.1.10/31', '192.168.1.12/30', '192.168.1.16/30', '192.168.1.20/32', - '192.168.1.30/32']), - # references are resolved, duplicates dropped - ('objects/ns_nested', ['192.168.1.10/32', '192.168.1.50/32', '10.0.0.1/32']), - # an IPv4-mapped address never matches the IPv4 flow it maps - ('objects/ns_mapped', ['192.168.1.10/32', '192.168.2.0/24']), - # a zero length prefix matches nothing in a group: its two halves match everything - ('objects/ns_all', ['0.0.0.0/1', '128.0.0.0/1']), - ('objects/ns_all6', ['::/1', '8000::/1']), - ('objects/ns_zone', ['fe80::1/128', 'fe80::10/127']), - ('dhcp/ns_lease', ['192.168.1.50/32']), - ('dhcp/ns_record', ['192.168.1.60/32']), - ('users/ns_vpn', ['10.9.0.2/32']), - # objects with no address - ('users/ns_novpn', []), - ('users/ns_noip', []), - ('objects/ns_with_domain', []), - ('objects/ns_domain', []), - ('objects/ns_missing', []), -]) -def test_address_group_entries(g, object_id, entries): - assert objects.address_group_entries(g, object_id) == entries - - -def test_write_address_groups(g): - assert objects.write_address_groups(g) is True - # one file per object with addresses: no file for domain sets, users without a reserved IP and objects - # resolving to no address - assert set(groups_files) <= group_files() - assert not set(groups_no_files) & group_files() - assert all(name.startswith('30-') and name.endswith('.conf') for name in group_files()) - assert group_file('30-objects_ns_range.conf').read_text() == ( - '# range1\n# objects/ns_range, generated from the firewall objects: do not edit\n' - '192.168.1.10/31\n192.168.1.12/31\n') - assert group_file('30-users_ns_vpn.conf').read_text() == ( - '# vpnuser\n# users/ns_vpn, generated from the firewall objects: do not edit\n10.9.0.2/32\n') - # unchanged: nothing is written - inode = group_file('30-objects_ns_host.conf').stat().st_ino - assert objects.write_address_groups(g) is False - assert group_file('30-objects_ns_host.conf').stat().st_ino == inode - - -def test_write_address_groups_removes_only_its_own_stale_files(g): - groups_dir().mkdir() - # other prefixes or extensions: kept - for name in ('10-agent.conf', '20-other.conf', '30-objects_ns_gone.txt'): - group_file(name).write_text('10.0.0.1\n') - # objects gone, as written here or as saved by the agent without the header: removed - group_file('30-objects_ns_gone.conf').write_text( - '# gone1\n# objects/ns_gone, generated from the firewall objects: do not edit\n10.0.0.1/32\n') - group_file('30-objects_ns_saved.conf').write_text('10.0.0.1\n') - group_file('30-objects_ns_empty.conf').write_text('') - # an object without addresses: its file goes too - group_file('30-users_ns_novpn.conf').write_text('10.9.0.3\n') - # an existing object, as saved by the agent: rewritten with the header - group_file('30-objects_ns_host.conf').write_text('192.168.1.10\n') - objects.write_address_groups(g) - assert {'10-agent.conf', '20-other.conf', '30-objects_ns_gone.txt'} | set(groups_files) <= group_files() - assert not {'30-objects_ns_gone.conf', '30-objects_ns_saved.conf', '30-objects_ns_empty.conf', - '30-users_ns_novpn.conf'} & group_files() - assert group_file('30-objects_ns_host.conf').read_text().splitlines()[1] == ( - '# objects/ns_host, generated from the firewall objects: do not edit') - - -def test_write_address_groups_follows_the_objects(g): - objects.write_address_groups(g) - host = group_file('30-objects_ns_host.conf') - # the object changes: its file follows, and the one of the host set holding it too - g.set('objects', 'ns_host', 'ipaddr', ['192.168.1.11']) - assert objects.write_address_groups(g) is True - assert host.read_text().splitlines()[2:] == ['192.168.1.11/32'] - assert group_file('30-objects_ns_nested.conf').read_text().splitlines()[2:] == [ - '192.168.1.11/32', '192.168.1.50/32', '10.0.0.1/32', '192.168.1.10/32'] - # the object is renamed: the header follows - g.set('objects', 'ns_host', 'name', 'renamed') - objects.write_address_groups(g) - assert host.read_text().splitlines()[0] == '# renamed' - # the object is deleted: its file goes - g.delete('objects', 'ns_host') - assert objects.write_address_groups(g) is True - assert not host.exists() - # a VPN user loses its reserved IP: its file goes, and comes back with it - vpn = group_file('30-users_ns_vpn.conf') - g.delete('users', 'ns_vpn', 'openvpn_ipaddr') - objects.write_address_groups(g) - assert not vpn.exists() - g.set('users', 'ns_vpn', 'openvpn_ipaddr', '10.9.0.5') - objects.write_address_groups(g) - assert vpn.read_text().splitlines()[2:] == ['10.9.0.5/32'] - # a new object: a new file - g.set('dhcp', 'ns_new', 'host') - g.set('dhcp', 'ns_new', 'name', 'new1') - g.set('dhcp', 'ns_new', 'ip', '192.168.1.70') - objects.write_address_groups(g) - assert group_file('30-dhcp_ns_new.conf').read_text().splitlines()[2:] == ['192.168.1.70/32'] - - -def test_write_address_groups_files_are_readable_whatever_the_umask(g): - umask = os.umask(0o077) - try: - objects.write_address_groups(g) - finally: - os.umask(umask) - assert group_file('30-objects_ns_host.conf').stat().st_mode & 0o777 == 0o644 - # an unchanged file keeps its content, its mode is fixed - group_file('30-objects_ns_host.conf').chmod(0o600) - assert objects.write_address_groups(g) is False - assert group_file('30-objects_ns_host.conf').stat().st_mode & 0o777 == 0o644 - - -def test_write_address_groups_header(g): - # an object without a name: the header holds only the id - g.delete('objects', 'ns_host', 'name') - # a name on more lines: joined on one - g.set('objects', 'ns_cidr', 'name', 'two\nlines') - objects.write_address_groups(g) - assert group_file('30-objects_ns_host.conf').read_text() == ( - '# objects/ns_host, generated from the firewall objects: do not edit\n192.168.1.10/32\n') - assert group_file('30-objects_ns_cidr.conf').read_text().splitlines()[:2] == [ - '# two lines', '# objects/ns_cidr, generated from the firewall objects: do not edit'] - - -def test_write_address_groups_without_configurations(tmp_path, monkeypatch): - conf_dir = tmp_path.joinpath('conf') - conf_dir.mkdir() - save_dir = tmp_path.joinpath('save') - save_dir.mkdir() - monkeypatch.setattr(objects, 'ADDRESS_GROUPS_DIR', tmp_path.joinpath('address-groups.d').as_posix()) - objects.write_address_groups(EUci(confdir=conf_dir.as_posix(), savedir=save_dir.as_posix())) - assert not set(groups_files) & group_files() - - -def netifyd_calls(run): - return [call.args[0] for call in run.call_args_list] - - -def test_update_address_groups_reloads_a_running_agent(g, mocker): - run = mocker.patch('nethsec.objects.subprocess.run') - run.return_value.returncode = 0 - assert objects.update_address_groups(g) is True - assert netifyd_calls(run) == [['/etc/init.d/netifyd', 'running'], ['/etc/init.d/netifyd', 'reload']] - # nothing changed: no reload - run.reset_mock() - assert objects.update_address_groups(g) is False - assert netifyd_calls(run) == [] - - -def test_address_group_entries_skips_an_invalid_value(g, mocker): - log = mocker.patch('nethsec.objects.syslog.syslog') - # a range mixing the families can't become networks: it is skipped, the rest of the object is kept - g.set('objects', 'ns_reversed', 'ipaddr', ['192.168.1.10-fd00::1', '192.168.1.30']) - assert objects.address_group_entries(g, 'objects/ns_reversed') == ['192.168.1.30/32'] - assert "skipping '192.168.1.10-fd00::1' of objects/ns_reversed" in log.call_args.args[1] - # the host set itself is left as entered - assert g.get('objects', 'ns_reversed', 'ipaddr', list=True) == ('192.168.1.10-fd00::1', '192.168.1.30') - - -def test_update_address_groups_leaves_a_stopped_agent_alone(g, mocker): - run = mocker.patch('nethsec.objects.subprocess.run') - run.return_value.returncode = 1 - assert objects.update_address_groups(g) is True - assert netifyd_calls(run) == [['/etc/init.d/netifyd', 'running']] - - -def test_update_address_groups_logs_a_write_failure(g, mocker): - run = mocker.patch('nethsec.objects.subprocess.run') - mocker.patch('nethsec.objects.write_address_groups', side_effect=PermissionError('denied')) - log = mocker.patch('nethsec.objects.syslog.syslog') - assert objects.update_address_groups(g) is False - assert netifyd_calls(run) == [] - assert 'cannot write the address groups' in log.call_args.args[1] + assert objects.is_object_id(1) == False \ No newline at end of file