diff --git a/.agents/skills/netifyd/SKILL.md b/.agents/skills/netifyd/SKILL.md index 48f2fe6c7..9182069cc 100644 --- a/.agents/skills/netifyd/SKILL.md +++ b/.agents/skills/netifyd/SKILL.md @@ -104,8 +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.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. --- @@ -204,6 +206,25 @@ 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.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 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 +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 +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..e87596cae 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/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 b356623ba..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 @@ -3801,6 +3803,9 @@ 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 - `index`: position of the rule in the list Example response: @@ -3813,7 +3818,15 @@ 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" + } + ], "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: @@ -7995,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.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..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 @@ -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 + dpi.update_address_groups(u) return {"result": "success"} def import_users(ovpninstance): @@ -841,6 +843,12 @@ def edit_user(args): if user_id == None: return utils.validation_error("username", "user_not_found", args["username"]) + # 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: @@ -856,6 +864,8 @@ def edit_user(args): pass u.set("users", user_id, "openvpn_enabled", args["enabled"]) u.commit("users") + # update related address groups used by DPI rules + dpi.update_address_groups(u) return {"result": "success"} def delete_user(ovpninstance, username): @@ -889,6 +899,8 @@ def delete_user(ovpninstance, username): u.commit("users") except: pass + # delete related address groups used by DPI rules + 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 new file mode 100755 index 000000000..d0e2db2fa --- /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 dpi + +if "objects" in changes or "dhcp" in changes or "users" in changes: # noqa: F821 + dpi.update_address_groups(EUci()) diff --git a/packages/ns-dpi/Makefile b/packages/ns-dpi/Makefile index 0931ef1bd..8377fdc2e 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,6 +68,7 @@ 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 @@ -81,6 +82,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 e5bbbe5ae..658dff900 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,51 @@ 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 + +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.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 +- 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 +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 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 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 + ## Migration from the previous schema On upgrade, and every time the DPI service starts, `/usr/libexec/ns-dpi/dpi-migrate` converts the @@ -98,6 +143,16 @@ cat /etc/netifyd/netify-proc-flow-actions.json nft list chain inet fw4 dpi_actions ``` +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.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 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 new file mode 100755 index 000000000..030b5192b --- /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.dpi.write_address_groups + +from euci import EUci +from nethsec import dpi + +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 7c640ca98..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,10 +672,190 @@ 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 `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 `_ADDRESS_GROUP_TYPES`. + + +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 _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): + raise ValidationError('source_objects', 'invalid_source_object', value) + if value not in source_objects: + source_objects.append(value) + return source_objects + + 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. An object + without addresses has no group file: the term stays, and a missing group matches nothing. + Args: - e_uci: euci instance - rule: the rule section, as returned by `uci.get_all` @@ -669,6 +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 == @{_address_group_tag(object_id)}" for object_id in rule.get('source_object', [])] if not match: if not sources: @@ -691,8 +888,8 @@ 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" and "subtype" """ groups = {section: group.get('ns_name', '') for section, group in (utils.get_all_by_type(e_uci, 'dpi', 'appgroup') or {}).items()} @@ -706,6 +903,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 +911,25 @@ 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 + if info is None: + data_rule['source_objects'].append( + {'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 + 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}) if 'criteria' in rule: data_rule['criteria'] = rule.get('criteria') rules.append(data_rule) @@ -721,7 +938,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 +958,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 +981,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 `_ADDRESS_GROUP_TYPES` for the accepted ones Returns: config name of the rule created @@ -771,11 +996,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 +1012,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 +1029,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 `_ADDRESS_GROUP_TYPES` for the accepted ones Returns: config name of the rule edited @@ -819,9 +1047,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..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 @@ -5,7 +6,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 +876,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 +1258,569 @@ 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): + """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('') + return e_uci_rules + + +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'}, + {'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'}, + ] + + +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}] + + +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'] == [] + + +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_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' + +# 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]