From a3b9e4a02d486b0bf0d366268e60520568878bdd Mon Sep 17 00:00:00 2001 From: Christian Manivong Date: Thu, 26 Nov 2026 08:19:19 +0100 Subject: [PATCH 1/4] feat(zabbix): an active-only agent closes the port netOrk opened for it (NetOrk/netork#2693) Every rule the firewall step adds in firewalld, ufw or iptables is recorded in napalm-device-types' opened_ports record, only when the firewall did not have it before. For an active-only agent, _revoke_zabbix_agent_sources removes exactly the agent's recorded rules and reports what is left for the port. --- CHANGELOG.md | 10 ++ napalm_linux/_open_port.py | 168 ++++++++++++++++++++++++++++++---- napalm_linux/_snmp_agent.py | 66 +++++++++++-- napalm_linux/_zabbix_agent.py | 17 +++- napalm_linux/linux.py | 3 +- tests/test_fix_templates.py | 24 ++++- tests/test_open_port.py | 114 +++++++++++++++++++++++ tests/test_zabbix_agent.py | 151 +++++++++++++++++++++++++++++- 8 files changed, 516 insertions(+), 37 deletions(-) create mode 100644 tests/test_open_port.py diff --git a/CHANGELOG.md b/CHANGELOG.md index 6dea9fd..00691bc 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -8,6 +8,16 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 ## [Unreleased] ### Added +- An active-only Zabbix agent closes the port netOrk opened for it on an earlier passive run + (`_revoke_zabbix_agent_sources`, napalm-device-types `ZabbixAgentMixin`, + NetOrk/netork#2693). firewalld, ufw and iptables do not say who wrote a rule, so every rule + the firewall step adds -- the Zabbix agent's tcp/`listen_port`, SNMP's udp/161 -- is now + recorded in `/var/lib/netork/opened-ports` (napalm-device-types `opened_ports`), and only + when the firewall did not have it before: an identical rule the operator wrote is never + recorded. Closing removes exactly the agent's recorded rules, whatever port they opened, + from the zone and configuration recorded (firewalld), and rewrites the record. It reads the + record only when it is root's alone, and reports the rules for the port it left in place: + the operator's, or ones opened before this version recorded them. - A native Zabbix agent (napalm-device-types `ZabbixAgentMixin`, NetOrk/netork#2571), for a host without a container engine: `configure_zabbix_agent(settings)` installs `zabbix-agent` from the host's packages, and where they have none and the caller names diff --git a/napalm_linux/_open_port.py b/napalm_linux/_open_port.py index 8a509dc..a8d98fe 100644 --- a/napalm_linux/_open_port.py +++ b/napalm_linux/_open_port.py @@ -1,47 +1,177 @@ """Opening a port in whichever firewall a Linux host runs: firewalld, ufw or iptables. The firewall step of the agents a fix sets up (SNMP's udp/161, the Zabbix agent's -tcp/``ListenPort``). +tcp/``ListenPort``), and closing it again. None of the three says who wrote a rule, so +each rule this adds is recorded (napalm-device-types ``opened_ports``, NetOrk/netork#2693) +-- only when the firewall did not have it before -- and closing removes exactly the +recorded rules. """ from __future__ import annotations -from typing import TYPE_CHECKING +from typing import TYPE_CHECKING, Literal -from napalm_device_types import FixStepOutcomeDict +from napalm_device_types import ( + OPENED_PORTS_RECORD, + FixStepOutcomeDict, + OpenedRuleDict, + opened_rule_line, + opened_rules_text, + parse_opened_ports_record, + read_opened_ports_command, + record_opened_rule_command, + revoked_output, + ufw_allow_recorded_command, + ufw_delete_command, +) -from napalm_linux._snmp_agent import _source, firewalld_allow_port +from napalm_linux._snmp_agent import ( + _source, + firewalld_allow_port, + firewalld_count_command, + firewalld_remove_command, +) + +if TYPE_CHECKING: # pragma: no cover + from napalm_device_types import CommandResult + +Firewall = Literal["firewalld", "ufw", "iptables", ""] + + +def _iptables_rule(source: str, port: int, proto: str) -> str: + return f"INPUT -s {source} -p {proto} --dport {port} -j ACCEPT" + + +def _iptables_allow(source: str, port: int, proto: str, purpose: str) -> str: + rule = _iptables_rule(source, port, proto) + line = opened_rule_line( + { + "purpose": purpose, + "backend": "iptables", + "proto": "udp" if proto == "udp" else "tcp", + "port": port, + "source": source, + "zone": "", + "permanent": True, + } + ) + return ( + f"{{ iptables -C {rule} 2>/dev/null" + f" || {{ iptables -I {rule} && {record_opened_rule_command(line)}; }}; }}" + ) + + +def _remove_command(rule: OpenedRuleDict) -> str: + """The shell that removes the recorded *rule*; done where it is gone already.""" + if rule["backend"] == "firewalld": + return firewalld_remove_command(rule) + if rule["backend"] == "ufw": + return ufw_delete_command(rule) + iptables = _iptables_rule(rule["source"], rule["port"], rule["proto"]) + return f"if iptables -C {iptables} 2>/dev/null; then iptables -D {iptables}; fi" + + +def _count_command(firewall: Firewall, port: int, proto: str) -> str: + """The shell that counts the rules for *proto*/*port* left in *firewall*.""" + if firewall == "firewalld": + return firewalld_count_command(port, proto) + if firewall == "ufw": + return ( + f"LC_ALL=C ufw show added | grep -cE '(port {port} proto {proto}| {port}/{proto})( |$)'" + ) + return f"iptables -S INPUT | grep -cE -- '-p {proto} .*--dport {port}( |$)'" class OpenPortMixin: - """``_allow_sources``: the shared firewall step.""" + """``_allow_sources`` and ``_revoke_sources``: the shared firewall steps.""" - def _allow_sources(self, allowed: list[str], port: int, proto: str) -> FixStepOutcomeDict: + def _firewall(self) -> Firewall: + """The firewall this host runs. firewalld first: its hosts have iptables too, and + an iptables ACCEPT does not lift firewalld's reject (both are nftables tables; a + drop in either wins).""" + if self._send("systemctl is-active firewalld 2>/dev/null") == "active": + return "firewalld" + if self._send("command -v ufw 2>/dev/null"): + return "ufw" + if self._send("command -v iptables 2>/dev/null"): + return "iptables" + return "" + + def _allow_sources( + self, allowed: list[str], port: int, proto: str, purpose: str + ) -> FixStepOutcomeDict: """Open *proto*/*port* for *allowed* in the host's firewall: firewalld, ufw or - iptables, whichever runs; ``ok`` with nothing to do for none or no sources.""" + iptables, whichever runs; ``ok`` with nothing to do for none or no sources. + Each rule it adds is recorded under *purpose*.""" sources = [_source(s) for s in allowed] if not sources: return {"ok": True, "output": "no sources given; firewall unchanged"} - # firewalld first: its hosts have iptables too, and an iptables ACCEPT does - # not lift firewalld's reject (both are nftables tables; a drop in either wins). - if self._send("systemctl is-active firewalld 2>/dev/null") == "active": + firewall = self._firewall() + if firewall == "firewalld": done = f"{proto}/{port} open in firewalld for {', '.join(sources)}" - return self._root_outcome(firewalld_allow_port(sources, port, proto), 60, done) - if self._send("command -v ufw 2>/dev/null"): - rules = [f"ufw allow from {s} to any port {port} proto {proto}" for s in sources] - elif self._send("command -v iptables 2>/dev/null"): - rules = [ - f"{{ iptables -C INPUT -s {s} -p {proto} --dport {port} -j ACCEPT 2>/dev/null" - f" || iptables -I INPUT -s {s} -p {proto} --dport {port} -j ACCEPT; }}" - for s in sources - ] + command = firewalld_allow_port(sources, port, proto, purpose) + return self._root_outcome(command, 60, done) + if firewall == "ufw": + rules = [ufw_allow_recorded_command(s, port, proto, purpose) for s in sources] + elif firewall == "iptables": + rules = [_iptables_allow(s, port, proto, purpose) for s in sources] else: return {"ok": True, "output": "no host firewall (ufw, iptables); nothing to open"} done = f"{proto}/{port} open for {', '.join(sources)}" return self._root_outcome(" && ".join(rules), 30, done) + def _revoke_sources(self, purpose: str, port: int, proto: str) -> FixStepOutcomeDict: + """Remove the rules recorded under *purpose*, whatever port they opened, and + nothing else; report what is left for *proto*/*port*. + + Not ``ok`` where the record may not be trusted -- then nothing is removed -- or a + rule would not go, which stays in the record. + """ + read, status = self._sudo_status(read_opened_ports_command(), 30) + if status != 0: + return {"ok": False, "output": f"reading {OPENED_PORTS_RECORD}: {read[-300:]}"} + record = parse_opened_ports_record(read) + if record["problem"]: + return {"ok": False, "output": record["problem"]} + removed: list[OpenedRuleDict] = [] + kept: list[str] = [] + failed: list[str] = [] + for rule in record["rules"]: + if rule["purpose"] == purpose: + outcome = self._root_outcome(_remove_command(rule), 30, "") + if outcome["ok"]: + removed.append(rule) + continue + failed.append(f"{opened_rule_line(rule)}: {outcome['output']}") + kept.append(opened_rule_line(rule)) + if removed: + written = self._install_file_as_root( + OPENED_PORTS_RECORD, opened_rules_text(kept + record["unknown"]) + ) + if written.exit_code: + failed.append(f"writing {OPENED_PORTS_RECORD}: {written.stderr.strip()[-300:]}") + firewall = self._firewall() + left = self._count(_count_command(firewall, port, proto)) if firewall else 0 + output = revoked_output( + removed, unknown=record["unknown"], left=left, proto=proto, port=port + ) + if failed: + output = f"{output}; not removed: {'; '.join(failed)}" + return {"ok": not failed, "output": output} + + def _count(self, command: str) -> int: + output, _ = self._sudo_status(command, 30) + last = output.strip().splitlines()[-1:] or ["0"] + return int(last[0]) if last[0].isdigit() else 0 + if TYPE_CHECKING: # pragma: no cover - the driver's def _send(self, command: str, read_timeout: float = 100) -> str: ... + def _sudo_status( + self, command: str, read_timeout: float = 100 + ) -> tuple[str, int | None]: ... + def _root_outcome(self, command: str, timeout: float, done: str) -> FixStepOutcomeDict: ... + + def _install_file_as_root(self, path: str, content: str) -> CommandResult: ... diff --git a/napalm_linux/_snmp_agent.py b/napalm_linux/_snmp_agent.py index 88ab551..5c277ae 100644 --- a/napalm_linux/_snmp_agent.py +++ b/napalm_linux/_snmp_agent.py @@ -6,6 +6,12 @@ import ipaddress import re from shlex import quote as _shlex_quote +from napalm_device_types import ( + SNMP_PURPOSE, + OpenedRuleDict, + opened_rule_line, + record_opened_rule_command, +) from napalm_device_types.models import SnmpAgentSettingsDict #: Where net-snmp reads its configuration, and how each package manager installs it. @@ -42,29 +48,73 @@ def firewalld_allow_snmp(sources: list[str]) -> str: return firewalld_allow_port(sources, 161, "udp") -def firewalld_allow_port(sources: list[str], port: int, proto: str) -> str: +def firewalld_rich_rule(source: str, port: int, proto: str) -> str: + """The rich rule that lets *source* (normalised) reach *proto*/*port*, shell-quoted.""" + family = f"ipv{ipaddress.ip_network(source).version}" + return _shlex_quote( + f'rule family="{family}" source address="{source}"' + f' port port="{port}" protocol="{proto}" accept' + ) + + +def firewalld_allow_port( + sources: list[str], port: int, proto: str, purpose: str = SNMP_PURPOSE +) -> str: """The shell that opens *proto*/*port* for *sources* (already normalised) in firewalld. A rich rule per source in every zone of ``_FIREWALLD_ZONES``, at runtime and permanently, each only when the zone lacks it -- no ``--reload``, which would drop - the runtime rules others (Docker) put there. + the runtime rules others (Docker) put there. Each rule it adds is recorded under + *purpose* with its zone and configuration; one the zone had is not + (napalm-device-types ``opened_ports``, NetOrk/netork#2693). """ steps = [] for source in sources: - family = f"ipv{ipaddress.ip_network(source).version}" - rule = _shlex_quote( - f'rule family="{family}" source address="{source}"' - f' port port="{port}" protocol="{proto}" accept' - ) + rule = firewalld_rich_rule(source, port, proto) for scope in ("", "--permanent "): zone = f'firewall-cmd {scope}--zone="$z"' + line = opened_rule_line( + { + "purpose": purpose, + "backend": "firewalld", + "proto": "udp" if proto == "udp" else "tcp", + "port": port, + "source": source, + "zone": "$z", + "permanent": bool(scope), + } + ) steps.append( f"{{ {zone} --query-rich-rule={rule} >/dev/null 2>&1" - f" || {zone} --add-rich-rule={rule}; }}" + f" || {{ {zone} --add-rich-rule={rule}" + f" && {record_opened_rule_command(line)}; }}; }}" ) return f"for z in {_FIREWALLD_ZONES}; do {' && '.join(steps)} || exit 1; done" +def firewalld_remove_command(rule: OpenedRuleDict) -> str: + """The shell that removes the recorded *rule* from its zone and configuration; + done where the zone no longer has it.""" + scope = "--permanent " if rule["permanent"] else "" + zone = f"firewall-cmd {scope}--zone={rule['zone']}" + rich = firewalld_rich_rule(rule["source"], rule["port"], rule["proto"]) + return ( + f"if {zone} --query-rich-rule={rich} >/dev/null 2>&1;" + f" then {zone} --remove-rich-rule={rich}; fi" + ) + + +def firewalld_count_command(port: int, proto: str) -> str: + """The shell that counts the rules for *proto*/*port* in firewalld's permanent + configuration, in every zone a rule would go to.""" + return ( + f"for z in {_FIREWALLD_ZONES}; do" + ' firewall-cmd --permanent --zone="$z" --list-rich-rules;' + " firewall-cmd --permanent --zone=\"$z\" --list-ports | tr ' ' '\\n'; done" + f' | grep -cE \'port="{port}" protocol="{proto}"|^{port}/{proto}$\'' + ) + + def render_snmpd_conf(settings: SnmpAgentSettingsDict) -> str: """net-snmp's configuration for *settings*: read-only v2c, per allowed source.""" community = settings["community"] diff --git a/napalm_linux/_zabbix_agent.py b/napalm_linux/_zabbix_agent.py index 9ad8592..4a6aa8e 100644 --- a/napalm_linux/_zabbix_agent.py +++ b/napalm_linux/_zabbix_agent.py @@ -5,7 +5,8 @@ For a host without a container engine (NetOrk/netork#2571). The template install Zabbix's own repository too -- and enables and restarts its service. This writes the caller's values into ``/etc/zabbix/zabbix_agentd.conf`` (where both put it), adds Zabbix's repository where the host's own packages have none, and opens the port in -whichever firewall runs. +whichever firewall runs -- or, for an active-only agent, closes what netOrk opened +for it before. """ from __future__ import annotations @@ -13,6 +14,7 @@ from __future__ import annotations from typing import TYPE_CHECKING from napalm_device_types import ( + ZABBIX_AGENT_PURPOSE, FixStepOutcomeDict, ZabbixAgentMixin, ZabbixAgentSettingsDict, @@ -58,7 +60,14 @@ class LinuxZabbixAgentMixin(ZabbixAgentMixin): return {"ok": True, "output": "; ".join(changes)} def _allow_zabbix_agent_sources(self, settings: ZabbixAgentSettingsDict) -> FixStepOutcomeDict: - return self._allow_sources(settings["allowed_sources"], int(settings["listen_port"]), "tcp") + return self._allow_sources( + settings["allowed_sources"], int(settings["listen_port"]), "tcp", ZABBIX_AGENT_PURPOSE + ) + + def _revoke_zabbix_agent_sources(self, settings: ZabbixAgentSettingsDict) -> FixStepOutcomeDict: + """For an active-only agent: remove the rules recorded for the agent on an + earlier passive run, whatever port they opened (NetOrk/netork#2693).""" + return self._revoke_sources(ZABBIX_AGENT_PURPOSE, int(settings["listen_port"]), "tcp") if TYPE_CHECKING: # pragma: no cover - the driver's @@ -76,5 +85,7 @@ class LinuxZabbixAgentMixin(ZabbixAgentMixin): def _install_file_as_root(self, path: str, content: str) -> CommandResult: ... def _allow_sources( - self, allowed: list[str], port: int, proto: str + self, allowed: list[str], port: int, proto: str, purpose: str ) -> FixStepOutcomeDict: ... + + def _revoke_sources(self, purpose: str, port: int, proto: str) -> FixStepOutcomeDict: ... diff --git a/napalm_linux/linux.py b/napalm_linux/linux.py index 1303525..b0903e4 100644 --- a/napalm_linux/linux.py +++ b/napalm_linux/linux.py @@ -30,6 +30,7 @@ from napalm_device_types import ( DNF_INSTALLED_CVES_COMMAND, DNF_SECURITY_COMMAND, LLDPCTL_KEYVALUE_COMMAND, + SNMP_PURPOSE, AptProxyMixin, ByteStream, CommandResult, @@ -1798,7 +1799,7 @@ class LinuxDriver( return {"ok": True, "output": f"wrote {_SNMPD_CONF}"} def _allow_snmp_sources(self, settings: SnmpAgentSettingsDict) -> FixStepOutcomeDict: - return self._allow_sources(settings.get("allowed_sources", []), 161, "udp") + return self._allow_sources(settings.get("allowed_sources", []), 161, "udp", SNMP_PURPOSE) def _start_snmp_agent(self) -> FixStepOutcomeDict: return self._root_outcome( diff --git a/tests/test_fix_templates.py b/tests/test_fix_templates.py index de495c6..036cf1e 100644 --- a/tests/test_fix_templates.py +++ b/tests/test_fix_templates.py @@ -15,6 +15,15 @@ from napalm_linux import LinuxDriver from napalm_linux.linux import render_snmpd_conf +def _local_record(command: str, record) -> str: + """*command* with the record of opened rules at *record* instead of root's path.""" + from napalm_device_types import OPENED_PORTS_RECORD + + return command.replace( + "install -d -m 755 -o root -g root /var/lib/netork", f"mkdir -p {record.parent}" + ).replace(OPENED_PORTS_RECORD, str(record)) + + class TestSnmpdConf: def test_one_read_only_line_per_allowed_source(self): conf = render_snmpd_conf( @@ -100,7 +109,7 @@ class TestSnmpAgentSteps: assert "apt-get install -y snmpd snmp" in ran[0] path, content = driver._install_file_as_root.call_args.args assert path == "/etc/snmp/snmpd.conf" and "rocommunity c0mm 10.0.0.5/32" in content - assert ran[1] == "ufw allow from 10.0.0.5/32 to any port 161 proto udp" + assert "LC_ALL=C ufw allow from 10.0.0.5/32 to any port 161 proto udp" in ran[1] assert "systemctl restart snmpd" in ran[2] def test_the_firewall_opens_only_for_the_given_sources_with_iptables(self, driver): @@ -147,14 +156,20 @@ class TestSnmpAgentSteps: import os import subprocess + record = tmp_path / "netork" / "opened-ports" done = subprocess.run( - ["sh", "-c", firewalld_allow_snmp(["10.0.0.5/32", "fd00::/64"])], + ["sh", "-c", _local_record(firewalld_allow_snmp(["10.0.0.5/32", "fd00::/64"]), record)], env={**os.environ, "PATH": f"{tmp_path}:{os.environ['PATH']}"}, capture_output=True, text=True, ) assert done.returncode == 0, done.stdout + done.stderr + # Each rule it added is recorded with its zone and configuration (#2693). + recorded = record.read_text().splitlines() + assert "v1 snmp firewalld udp 161 10.0.0.5/32 docker permanent" in recorded + assert "v1 snmp firewalld udp 161 fd00::/64 public runtime" in recorded + assert len(recorded) == 8 adds = [line for line in log.read_text().splitlines() if "--add-rich-rule" in line] v4 = 'rule family="ipv4" source address="10.0.0.5/32" port port="161" protocol="udp" accept' v6 = 'rule family="ipv6" source address="fd00::/64" port port="161" protocol="udp" accept' @@ -182,8 +197,9 @@ class TestSnmpAgentSteps: import os import subprocess + record = tmp_path / "netork" / "opened-ports" done = subprocess.run( - ["sh", "-c", firewalld_allow_snmp(["10.0.0.5/32"])], + ["sh", "-c", _local_record(firewalld_allow_snmp(["10.0.0.5/32"]), record)], env={**os.environ, "PATH": f"{tmp_path}:{os.environ['PATH']}"}, capture_output=True, text=True, @@ -191,6 +207,8 @@ class TestSnmpAgentSteps: assert done.returncode == 0 assert "--add-rich-rule" not in log.read_text() + # A rule the zone had is someone else's: not recorded (#2693). + assert not record.exists() def test_no_sources_change_no_firewall(self, driver): ran = self._record(driver) diff --git a/tests/test_open_port.py b/tests/test_open_port.py new file mode 100644 index 0000000..31a7fbb --- /dev/null +++ b/tests/test_open_port.py @@ -0,0 +1,114 @@ +"""The firewall step's shell, run with fake firewalls (NetOrk/netork#2693).""" + +from __future__ import annotations + +import os +import subprocess + +import pytest + +from napalm_linux._open_port import _count_command, _iptables_allow, _remove_command +from tests.test_fix_templates import _local_record + + +def _run(tmp_path, command: str, tools: dict[str, str]): + """Run *command* with each of *tools* a fake answering its shell body.""" + bin_dir = tmp_path / "bin" + bin_dir.mkdir(exist_ok=True) + for name, body in tools.items(): + fake = bin_dir / name + fake.write_text(f"#!/bin/sh\n{body}\n") + fake.chmod(0o755) + record = tmp_path / "netork" / "opened-ports" + done = subprocess.run( + ["sh", "-c", _local_record(command, record)], + env={**os.environ, "PATH": f"{bin_dir}:{os.environ['PATH']}"}, + capture_output=True, + text=True, + ) + return done, (record.read_text() if record.exists() else "") + + +class TestIptables: + def test_a_rule_the_check_did_not_find_is_added_and_recorded(self, tmp_path): + done, record = _run( + tmp_path, + _iptables_allow("10.0.0.5/32", 10050, "tcp", "zabbix-agent"), + {"iptables": 'case "$1" in -C) exit 1 ;; esac'}, + ) + + assert done.returncode == 0, done.stderr + assert record == "v1 zabbix-agent iptables tcp 10050 10.0.0.5/32\n" + + def test_a_rule_iptables_had_is_not_recorded(self, tmp_path): + done, record = _run( + tmp_path, + _iptables_allow("10.0.0.5/32", 10050, "tcp", "zabbix-agent"), + {"iptables": "exit 0"}, + ) + + assert done.returncode == 0 + assert record == "" + + def test_a_rule_that_is_gone_already_removes_as_done(self, tmp_path): + rule = { + "purpose": "zabbix-agent", + "backend": "iptables", + "proto": "tcp", + "port": 10050, + "source": "10.0.0.5/32", + "zone": "", + "permanent": True, + } + done, _ = _run( + tmp_path, _remove_command(rule), {"iptables": 'case "$1" in -C) exit 1 ;; esac'} + ) + + assert done.returncode == 0 + + +class TestCountingWhatIsLeft: + @pytest.mark.parametrize( + ("added", "count"), + [ + ("ufw allow from 10.0.0.9 to any port 10050 proto tcp", "1"), + ("ufw allow 10050/tcp", "1"), + ("ufw allow from 10.0.0.9 to any port 100500 proto tcp", "0"), + ("ufw allow from 10.0.0.9 to any port 10050 proto udp", "0"), + ], + ) + def test_ufw(self, tmp_path, added, count): + ufw = f"printf 'Added user rules (see ufw status for running firewall):\\n{added}\\n'" + done, _ = _run(tmp_path, _count_command("ufw", 10050, "tcp"), {"ufw": ufw}) + + assert done.stdout.strip() == count + + @pytest.mark.parametrize( + ("rule", "count"), + [ + ("-A INPUT -s 10.0.0.9/32 -p tcp -m tcp --dport 10050 -j ACCEPT", "1"), + ("-A INPUT -s 10.0.0.9/32 -p tcp -m tcp --dport 100500 -j ACCEPT", "0"), + ("-A INPUT -s 10.0.0.9/32 -p udp -m udp --dport 10050 -j ACCEPT", "0"), + ], + ) + def test_iptables(self, tmp_path, rule, count): + iptables = f"printf -- '-P INPUT ACCEPT\\n{rule}\\n'" + done, _ = _run(tmp_path, _count_command("iptables", 10050, "tcp"), {"iptables": iptables}) + + assert done.stdout.strip() == count + + def test_firewalld_counts_rich_rules_and_ports_in_each_zone(self, tmp_path): + firewall_cmd = ( + 'case "$*" in\n' + " --get-default-zone) echo public ;;\n" + " --get-active-zones) ;;\n" + ' *--list-rich-rules*) echo \'rule family="ipv4" source address="10.0.0.9/32"' + ' port port="10050" protocol="tcp" accept\' ;;\n' + " *--list-ports*) echo '22/tcp 10050/tcp 100500/tcp' ;;\n" + "esac" + ) + done, _ = _run( + tmp_path, _count_command("firewalld", 10050, "tcp"), {"firewall-cmd": firewall_cmd} + ) + + assert done.stdout.strip() == "2" diff --git a/tests/test_zabbix_agent.py b/tests/test_zabbix_agent.py index 9800ba9..afa3c9e 100644 --- a/tests/test_zabbix_agent.py +++ b/tests/test_zabbix_agent.py @@ -10,7 +10,11 @@ from __future__ import annotations from unittest.mock import MagicMock import pytest -from napalm_device_types import CommandResult +from napalm_device_types import ( + OPENED_PORTS_RECORD, + CommandResult, + read_opened_ports_command, +) from napalm_linux import LinuxDriver @@ -41,11 +45,19 @@ class _Host: self.packages: list[str] = [] self.distribution_has_it = True self.refuse = "" + #: What reading the record of opened rules prints (NetOrk/netork#2693). + self.record = "" + #: What counting the rules left for the port prints. + self.left = "0" def sudo_status(self, command, read_timeout=100): self.root.append(command) if self.refuse and self.refuse in command: return ("E: refused", 1) + if command == read_opened_ports_command(): + return (self.record.strip(), 0) + if "grep -c" in command: + return (self.left, 0) if "repo.zabbix.com" in command: self.distribution_has_it = True return ("", 0) @@ -171,7 +183,7 @@ def test_a_distribution_zabbix_publishes_nothing_for_fails_the_install(driver, h def test_ufw_opens_the_listen_port_for_the_sources(driver, host): driver.configure_zabbix_agent(SETTINGS) - assert "ufw allow from 10.0.0.5/32 to any port 10050 proto tcp" in host.root + assert any("ufw allow from 10.0.0.5/32 to any port 10050 proto tcp" in c for c in host.root) def test_iptables_opens_the_listen_port_for_the_sources(driver, host): @@ -206,4 +218,137 @@ def test_no_sources_change_no_firewall(driver, host): def test_the_snmp_rule_is_still_udp_161(driver, host): driver.configure_snmp_agent({"community": "c0mm", "allowed_sources": ["10.0.0.5"]}) - assert "ufw allow from 10.0.0.5/32 to any port 161 proto udp" in host.root + assert any("ufw allow from 10.0.0.5/32 to any port 161 proto udp" in c for c in host.root) + + +# --- The record of the rules netOrk opened (NetOrk/netork#2693) --------------------- + +ACTIVE_ONLY = {**SETTINGS, "active_only": True, "allowed_sources": []} +ROOT = "0 755 directory\n0 644 regular file\n" +ZABBIX_UFW = "v1 zabbix-agent ufw tcp 10050 10.0.0.5/32" +SNMP_UFW = "v1 snmp ufw udp 161 10.0.0.5/32" + + +def _opened(host) -> str: + return next(c for c in host.root if "allow" in c or "-I INPUT" in c or "--add-rich" in c) + + +def test_ufw_records_the_rule_it_added_under_the_agent(driver, host): + driver.configure_zabbix_agent(SETTINGS) + + opened = _opened(host) + assert "*Skipping*) ;;" in opened + assert f'"{ZABBIX_UFW}" >> {OPENED_PORTS_RECORD}' in opened + + +def test_iptables_records_the_rule_only_where_the_check_found_none(driver, host): + host.firewall = "iptables" + + driver.configure_zabbix_agent(SETTINGS) + + opened = _opened(host) + check = "iptables -C INPUT -s 10.0.0.5/32 -p tcp --dport 10050 -j ACCEPT 2>/dev/null ||" + assert check in opened + assert '"v1 zabbix-agent iptables tcp 10050 10.0.0.5/32" >>' in opened.split(check)[1] + + +def test_firewalld_records_each_zone_and_configuration_it_added_to(driver, host): + host.firewalld = True + + driver.configure_zabbix_agent(SETTINGS) + + opened = _opened(host) + assert '"v1 zabbix-agent firewalld tcp 10050 10.0.0.5/32 $z runtime"' in opened + assert '"v1 zabbix-agent firewalld tcp 10050 10.0.0.5/32 $z permanent"' in opened + + +def test_the_snmp_rule_is_recorded_under_snmp(driver, host): + driver.configure_snmp_agent({"community": "c0mm", "allowed_sources": ["10.0.0.5"]}) + + assert f'"{SNMP_UFW}" >>' in _opened(host) + + +def test_active_only_removes_the_agent_s_recorded_rules_and_keeps_the_rest(driver, host): + host.record = ROOT + f"{ZABBIX_UFW}\n{SNMP_UFW}\nv9 something else\n" + + result = driver.configure_zabbix_agent(ACTIVE_ONLY) + + assert result["success"] is True, result["output"] + deletes = [c for c in host.root if "ufw delete" in c] + assert len(deletes) == 1 + assert "ufw delete allow from 10.0.0.5/32 to any port 10050 proto tcp" in deletes[0] + assert host.written[-1] == (OPENED_PORTS_RECORD, f"{SNMP_UFW}\nv9 something else\n") + firewall = result["steps"][2]["output"] + assert "removed" in firewall and "10.0.0.5/32" in firewall + assert "v9 something else" in firewall + assert not any("ufw allow" in c for c in host.root) + + +def test_active_only_removes_firewalld_rules_from_the_zone_and_configuration_recorded(driver, host): + host.firewalld = True + host.record = ROOT + ( + "v1 zabbix-agent firewalld tcp 10050 10.0.0.5/32 public permanent\n" + "v1 zabbix-agent firewalld tcp 10050 10.0.0.5/32 public runtime\n" + ) + + result = driver.configure_zabbix_agent(ACTIVE_ONLY) + + assert result["success"] is True, result["output"] + removes = [c for c in host.root if "--remove-rich-rule" in c] + rule = 'rule family="ipv4" source address="10.0.0.5/32" port port="10050" protocol="tcp" accept' + assert any("--permanent --zone=public --remove-rich-rule=" in c and rule in c for c in removes) + assert any("firewall-cmd --zone=public --remove-rich-rule=" in c and rule in c for c in removes) + assert host.written[-1] == (OPENED_PORTS_RECORD, "") + + +def test_active_only_removes_a_recorded_iptables_rule(driver, host): + host.firewall = "iptables" + host.record = ROOT + "v1 zabbix-agent iptables tcp 10050 10.0.0.5/32\n" + + driver.configure_zabbix_agent(ACTIVE_ONLY) + + assert any( + "iptables -D INPUT -s 10.0.0.5/32 -p tcp --dport 10050 -j ACCEPT" in c for c in host.root + ) + + +def test_a_rule_recorded_under_an_earlier_port_is_removed_too(driver, host): + host.record = ROOT + "v1 zabbix-agent ufw tcp 10051 10.0.0.5/32\n" + + driver.configure_zabbix_agent(ACTIVE_ONLY) + + assert any("ufw delete allow from 10.0.0.5/32 to any port 10051" in c for c in host.root) + + +def test_without_a_record_nothing_is_removed_and_what_is_left_is_reported(driver, host): + host.left = "1" + + result = driver.configure_zabbix_agent(ACTIVE_ONLY) + + assert result["success"] is True + assert not any("ufw delete" in c for c in host.root) + assert host.written[-1][0] == CONFIG + firewall = result["steps"][2]["output"] + assert "netOrk recorded no rule" in firewall + assert "1 rule(s) for tcp/10050" in firewall + + +def test_a_record_someone_else_could_write_is_not_acted_on(driver, host): + host.record = f"1000 755 directory\n0 644 regular file\n{ZABBIX_UFW}\n" + + result = driver.configure_zabbix_agent(ACTIVE_ONLY) + + assert result["success"] is False + assert "not root's" in result["output"] + assert not any("ufw delete" in c for c in host.root) + + +def test_a_rule_that_will_not_go_stays_in_the_record(driver, host): + host.record = ROOT + f"{ZABBIX_UFW}\n" + host.refuse = "ufw delete" + + result = driver.configure_zabbix_agent(ACTIVE_ONLY) + + assert result["success"] is False + assert not any(path == OPENED_PORTS_RECORD for path, _ in host.written) + assert host.services == [] From 1f19a9a8dd569219c72d9821c9f8c2a8906828aa Mon Sep 17 00:00:00 2001 From: Christian Manivong Date: Thu, 26 Nov 2026 08:20:09 +0100 Subject: [PATCH 2/4] refactor(firewall): the revoke loop is napalm-device-types' revoke_recorded_rules --- napalm_linux/_open_port.py | 21 ++++++--------------- 1 file changed, 6 insertions(+), 15 deletions(-) diff --git a/napalm_linux/_open_port.py b/napalm_linux/_open_port.py index a8d98fe..dbf9082 100644 --- a/napalm_linux/_open_port.py +++ b/napalm_linux/_open_port.py @@ -16,10 +16,10 @@ from napalm_device_types import ( FixStepOutcomeDict, OpenedRuleDict, opened_rule_line, - opened_rules_text, parse_opened_ports_record, read_opened_ports_command, record_opened_rule_command, + revoke_recorded_rules, revoked_output, ufw_allow_recorded_command, ufw_delete_command, @@ -133,21 +133,12 @@ class OpenPortMixin: record = parse_opened_ports_record(read) if record["problem"]: return {"ok": False, "output": record["problem"]} - removed: list[OpenedRuleDict] = [] - kept: list[str] = [] - failed: list[str] = [] - for rule in record["rules"]: - if rule["purpose"] == purpose: - outcome = self._root_outcome(_remove_command(rule), 30, "") - if outcome["ok"]: - removed.append(rule) - continue - failed.append(f"{opened_rule_line(rule)}: {outcome['output']}") - kept.append(opened_rule_line(rule)) + done = revoke_recorded_rules( + record, purpose, lambda rule: self._root_outcome(_remove_command(rule), 30, "") + ) + removed, failed = done["removed"], done["failed"] if removed: - written = self._install_file_as_root( - OPENED_PORTS_RECORD, opened_rules_text(kept + record["unknown"]) - ) + written = self._install_file_as_root(OPENED_PORTS_RECORD, done["record"]) if written.exit_code: failed.append(f"writing {OPENED_PORTS_RECORD}: {written.stderr.strip()[-300:]}") firewall = self._firewall() From 70b605d05b88c02db52cc8c700323fc4911056c4 Mon Sep 17 00:00:00 2001 From: Christian Manivong Date: Thu, 26 Nov 2026 08:26:35 +0100 Subject: [PATCH 3/4] chore(release): 0.18.0 --- CHANGELOG.md | 2 ++ pyproject.toml | 4 ++-- 2 files changed, 4 insertions(+), 2 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 00691bc..53a6b0a 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -7,6 +7,8 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 ## [Unreleased] +## [0.18.0] - 2026-11-26 + ### Added - An active-only Zabbix agent closes the port netOrk opened for it on an earlier passive run (`_revoke_zabbix_agent_sources`, napalm-device-types `ZabbixAgentMixin`, diff --git a/pyproject.toml b/pyproject.toml index f32fb3a..c3b0d74 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -4,7 +4,7 @@ build-backend = "setuptools.build_meta" [project] name = "napalm-linux" -version = "0.17.0" +version = "0.18.0" description = "NAPALM driver for generic Linux systems via SSH" readme = "README.md" requires-python = ">=3.12" @@ -34,7 +34,7 @@ classifiers = [ ] dependencies = [ "napalm>=4.0", - "napalm-device-types>=4.40.0", # ZabbixAgentMixin + "napalm-device-types>=4.43.0", # ZabbixAgentMixin, opened_ports "netmiko>=4.0.0", "paramiko>=5.0.0", # CVE-2026-44405 ] From fc4f08302c3afd10f505e935a34d95bcf4a84993 Mon Sep 17 00:00:00 2001 From: Christian Manivong Date: Thu, 26 Nov 2026 12:24:14 +0100 Subject: [PATCH 4/4] refactor(firewall): SNMP's firewall step lives with the others in OpenPortMixin --- napalm_linux/_open_port.py | 8 +++++++- napalm_linux/linux.py | 4 ---- tests/quality_baseline.json | 2 +- 3 files changed, 8 insertions(+), 6 deletions(-) diff --git a/napalm_linux/_open_port.py b/napalm_linux/_open_port.py index dbf9082..0d2e52d 100644 --- a/napalm_linux/_open_port.py +++ b/napalm_linux/_open_port.py @@ -13,6 +13,7 @@ from typing import TYPE_CHECKING, Literal from napalm_device_types import ( OPENED_PORTS_RECORD, + SNMP_PURPOSE, FixStepOutcomeDict, OpenedRuleDict, opened_rule_line, @@ -24,6 +25,7 @@ from napalm_device_types import ( ufw_allow_recorded_command, ufw_delete_command, ) +from napalm_device_types.models import SnmpAgentSettingsDict from napalm_linux._snmp_agent import ( _source, @@ -83,7 +85,7 @@ def _count_command(firewall: Firewall, port: int, proto: str) -> str: class OpenPortMixin: - """``_allow_sources`` and ``_revoke_sources``: the shared firewall steps.""" + """``_allow_sources`` and ``_revoke_sources``: the shared firewall steps, and SNMP's.""" def _firewall(self) -> Firewall: """The firewall this host runs. firewalld first: its hosts have iptables too, and @@ -120,6 +122,10 @@ class OpenPortMixin: done = f"{proto}/{port} open for {', '.join(sources)}" return self._root_outcome(" && ".join(rules), 30, done) + def _allow_snmp_sources(self, settings: SnmpAgentSettingsDict) -> FixStepOutcomeDict: + """SNMP's firewall step (napalm-device-types ``SnmpAgentMixin``): udp/161.""" + return self._allow_sources(settings.get("allowed_sources", []), 161, "udp", SNMP_PURPOSE) + def _revoke_sources(self, purpose: str, port: int, proto: str) -> FixStepOutcomeDict: """Remove the rules recorded under *purpose*, whatever port they opened, and nothing else; report what is left for *proto*/*port*. diff --git a/napalm_linux/linux.py b/napalm_linux/linux.py index b0903e4..fe67862 100644 --- a/napalm_linux/linux.py +++ b/napalm_linux/linux.py @@ -30,7 +30,6 @@ from napalm_device_types import ( DNF_INSTALLED_CVES_COMMAND, DNF_SECURITY_COMMAND, LLDPCTL_KEYVALUE_COMMAND, - SNMP_PURPOSE, AptProxyMixin, ByteStream, CommandResult, @@ -1798,9 +1797,6 @@ class LinuxDriver( return {"ok": False, "output": (written.stdout or written.stderr).strip()[-300:]} return {"ok": True, "output": f"wrote {_SNMPD_CONF}"} - def _allow_snmp_sources(self, settings: SnmpAgentSettingsDict) -> FixStepOutcomeDict: - return self._allow_sources(settings.get("allowed_sources", []), 161, "udp", SNMP_PURPOSE) - def _start_snmp_agent(self) -> FixStepOutcomeDict: return self._root_outcome( "systemctl enable snmpd && systemctl restart snmpd && systemctl is-active snmpd", diff --git a/tests/quality_baseline.json b/tests/quality_baseline.json index 06ea2db..764b710 100644 --- a/tests/quality_baseline.json +++ b/tests/quality_baseline.json @@ -20,7 +20,7 @@ "napalm_linux.linux" ], "python_file_lines": { - "napalm_linux/linux.py": 1993 + "napalm_linux/linux.py": 1990 }, "untyped_public": [] }