From 370aeed482038814116d4e74f6b88c2992e82eee Mon Sep 17 00:00:00 2001 From: Christian Manivong Date: Thu, 26 Nov 2026 08:21:53 +0100 Subject: [PATCH 1/2] feat(zabbix): an active-only agent closes the port netOrk opened for it (NetOrk/netork#2693) Every rule the firewall step adds in ufw is recorded in napalm-device-types' opened_ports record, only when ufw did not have it before. For an active-only agent, _revoke_zabbix_agent_sources removes exactly the agent's recorded rules and reports what ufw has left for the port. --- CHANGELOG.md | 12 +++++ napalm_proxmox/host_mixin.py | 60 +++++++++++++++++++-- napalm_proxmox/system_mixin.py | 5 +- napalm_proxmox/zabbix_agent.py | 14 ++++- tests/test_fix_templates.py | 3 +- tests/test_zabbix_agent.py | 97 ++++++++++++++++++++++++++++++++++ 6 files changed, 183 insertions(+), 8 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 7e493ab..37ee2cc 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -7,6 +7,18 @@ 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). ufw does 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 ufw 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, 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. pve-firewall's + rules stay the operator's. + ## [0.12.0] - 2026-11-26 ### Fixed diff --git a/napalm_proxmox/host_mixin.py b/napalm_proxmox/host_mixin.py index 7eba099..c0466d5 100644 --- a/napalm_proxmox/host_mixin.py +++ b/napalm_proxmox/host_mixin.py @@ -17,7 +17,18 @@ import re import shlex from typing import TYPE_CHECKING, Any, cast -from napalm_device_types import APT_UPGRADABLE_COMMAND, parse_apt_upgradable +from napalm_device_types import ( + APT_UPGRADABLE_COMMAND, + OPENED_PORTS_RECORD, + OpenedRuleDict, + parse_apt_upgradable, + parse_opened_ports_record, + read_opened_ports_command, + revoke_recorded_rules, + revoked_output, + ufw_allow_recorded_command, + ufw_delete_command, +) from napalm_device_types.models import ( FixStepOutcomeDict, LicenseDict, @@ -231,17 +242,58 @@ class ProxmoxHostMixin: def _write_apt_file(self, path: str, content: str) -> FixStepOutcomeDict: return self._write_root_file(path, content) - def _allow_sources(self, allowed: list[str], port: int, proto: str) -> FixStepOutcomeDict: + def _allow_sources( + self, allowed: list[str], port: int, proto: str, purpose: str + ) -> FixStepOutcomeDict: """Open *proto*/*port* in ufw for *allowed*; ``ok`` with nothing to do for no - sources or no ufw -- pve-firewall's rules are the operator's.""" + sources or no ufw -- pve-firewall's rules are the operator's. Each rule ufw adds + is recorded under *purpose* (napalm-device-types ``opened_ports``, + NetOrk/netork#2693); one ufw had is not.""" sources = [str(ipaddress.ip_network(s.strip(), strict=False)) for s in allowed] if not sources: return {"ok": True, "output": "no sources given; firewall unchanged"} if self._rc("command -v ufw")[1] != 0: return {"ok": True, "output": "no ufw; pve-firewall rules are the operator's"} - rules = " && ".join(f"ufw allow from {s} to any port {port} proto {proto}" for s in sources) + rules = " && ".join(ufw_allow_recorded_command(s, port, proto, purpose) for s in sources) return self._step(rules, f"{proto}/{port} open for {', '.join(sources)}") + def _revoke_sources(self, purpose: str, port: int, proto: str) -> FixStepOutcomeDict: + """Remove the ufw rules recorded under *purpose*, whatever port they opened, and + nothing else; report what ufw has left for *proto*/*port*. Not ``ok`` where + the record may not be trusted -- nothing is removed then -- or a rule would not + go, which stays in the record.""" + read, status = self._rc(read_opened_ports_command()) + 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"]} + done = revoke_recorded_rules(record, purpose, self._remove_recorded_rule) + failed = done["failed"] + if done["removed"]: + written = self._write_root_file(OPENED_PORTS_RECORD, done["record"]) + if not written["ok"]: + failed.append(f"writing {OPENED_PORTS_RECORD}: {written['output']}") + left = 0 + if self._rc("command -v ufw")[1] == 0: + counted, _ = self._rc( + f"LC_ALL=C ufw show added" + f" | grep -cE '(port {port} proto {proto}| {port}/{proto})( |$)'" + ) + last = counted.strip().splitlines()[-1:] or ["0"] + left = int(last[0]) if last[0].isdigit() else 0 + output = revoked_output( + done["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 _remove_recorded_rule(self, rule: OpenedRuleDict) -> FixStepOutcomeDict: + if rule["backend"] != "ufw": + return {"ok": False, "output": f"a {rule['backend']} rule; a node's rules are ufw's"} + return self._step(ufw_delete_command(rule), "") + def _write_root_file(self, path: str, content: str) -> FixStepOutcomeDict: """Write *content* to *path* as root, mode 644, through a temporary file.""" encoded = base64.b64encode(content.encode()).decode() diff --git a/napalm_proxmox/system_mixin.py b/napalm_proxmox/system_mixin.py index 093ed9c..90f875a 100644 --- a/napalm_proxmox/system_mixin.py +++ b/napalm_proxmox/system_mixin.py @@ -27,6 +27,7 @@ import shlex from typing import Any from napalm.base.exceptions import CommandErrorException +from napalm_device_types import SNMP_PURPOSE from napalm_proxmox.ntp import NTP_STATS_COMMAND, parse_ntp_stats @@ -362,7 +363,9 @@ class ProxmoxSystemMixin: return self._write_root_file(_SNMPD_CONF, render_snmpd_conf(settings)) def _allow_snmp_sources(self, settings: dict) -> dict: - return dict(self._allow_sources(settings.get("allowed_sources", []), 161, "udp")) + return dict( + self._allow_sources(settings.get("allowed_sources", []), 161, "udp", SNMP_PURPOSE) + ) def _start_snmp_agent(self) -> dict: return self._step( diff --git a/napalm_proxmox/zabbix_agent.py b/napalm_proxmox/zabbix_agent.py index ca1bc25..ced9a46 100644 --- a/napalm_proxmox/zabbix_agent.py +++ b/napalm_proxmox/zabbix_agent.py @@ -13,6 +13,7 @@ from __future__ import annotations from typing import TYPE_CHECKING from napalm_device_types import ( + ZABBIX_AGENT_PURPOSE, FixStepOutcomeDict, ZabbixAgentMixin, ZabbixAgentSettingsDict, @@ -53,7 +54,14 @@ class ProxmoxZabbixAgentMixin(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 ufw 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 - ProxmoxHostMixin's @@ -64,5 +72,7 @@ class ProxmoxZabbixAgentMixin(ZabbixAgentMixin): def _write_root_file(self, path: str, content: str) -> FixStepOutcomeDict: ... 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/tests/test_fix_templates.py b/tests/test_fix_templates.py index 09511d5..1e31c67 100644 --- a/tests/test_fix_templates.py +++ b/tests/test_fix_templates.py @@ -82,7 +82,8 @@ class TestSnmpAgent: def test_no_temp_file_with_an_application_name(self, driver, node): driver.configure_snmp_agent(SETTINGS) - assert not any("netork" in c for c in node.ran) + # The record of opened rules (/var/lib/netork, NetOrk/netork#2693) is no temp file. + assert not any(re.search(r"/tmp/\S*netork", c) for c in node.ran) def test_ufw_opens_only_for_the_allowed_sources(self, driver, node): node.status["command -v ufw"] = 0 diff --git a/tests/test_zabbix_agent.py b/tests/test_zabbix_agent.py index ed5a387..905b865 100644 --- a/tests/test_zabbix_agent.py +++ b/tests/test_zabbix_agent.py @@ -12,6 +12,7 @@ import base64 import re import pytest +from napalm_device_types import OPENED_PORTS_RECORD from napalm_proxmox import ProxmoxBackupDriver, ProxmoxDriver @@ -38,6 +39,11 @@ class _Node: self.installed = False self.refuse = refuse self.ran: list[str] = [] + #: 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" + self.record_written: str | None = None def __call__(self, command: str) -> str: self.ran.append(command) @@ -50,6 +56,14 @@ class _Node: def _answer(self, command: str) -> tuple[str, int]: if self.refuse and self.refuse in command: return "E: refused", 1 + if "stat -c" in command and OPENED_PORTS_RECORD in command: + return self.record, 0 + if "grep -c" in command: + return self.left, 0 + if "base64 -d" in command and OPENED_PORTS_RECORD in command: + written = re.search(r"echo (\S*) \|", command).group(1) + self.record_written = base64.b64decode(written).decode() + return "", 0 if command.startswith("dpkg-query"): return ("zabbix-agent\tinstalled\n" if self.installed else "curl\tinstalled\n"), 0 if f"cat {CONFIG}" in command: @@ -144,3 +158,86 @@ def test_a_config_that_cannot_be_read_stops_the_fix(driver, node): assert result["success"] is False assert result["steps"][-1]["step"] == "configure" + + +# --- 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.40.100.254/32" +SNMP_UFW = "v1 snmp ufw udp 161 10.40.100.254/32" + + +def test_ufw_records_the_rule_it_added_under_the_agent(driver, node): + driver.configure_zabbix_agent(SETTINGS) + + opened = next(c for c in node.ran if "ufw allow" in c) + assert "*Skipping*) ;;" in opened + assert f'"{ZABBIX_UFW}" >> {OPENED_PORTS_RECORD}' in opened + + +def test_the_snmp_rule_is_recorded_under_snmp(node): + driver = ProxmoxDriver("pve", "root@pam", "pw") + driver._exec_ssh_command = node + + driver.configure_snmp_agent({"community": "c0mm", "allowed_sources": ["10.40.100.254"]}) + + assert any(f'"{SNMP_UFW}" >>' in c for c in node.ran) + + +def test_active_only_removes_the_agent_s_recorded_rules_and_keeps_the_rest(driver, node): + node.record = ROOT + f"{ZABBIX_UFW}\n{SNMP_UFW}\n" + + result = driver.configure_zabbix_agent(ACTIVE_ONLY) + + assert result["success"] is True, result["output"] + deletes = [c for c in node.ran if "ufw delete" in c] + assert len(deletes) == 1 + assert "ufw delete allow from 10.40.100.254/32 to any port 10050 proto tcp" in deletes[0] + assert node.record_written == f"{SNMP_UFW}\n" + assert "removed" in result["steps"][2]["output"] + assert not any("ufw allow" in c for c in node.ran) + + +def test_without_a_record_nothing_is_removed_and_what_is_left_is_reported(driver, node): + node.left = "1" + + result = driver.configure_zabbix_agent(ACTIVE_ONLY) + + assert result["success"] is True + assert not any("ufw delete" in c for c in node.ran) + assert node.record_written is None + 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, node): + node.record = f"0 755 directory\n0 666 regular file\n{ZABBIX_UFW}\n" + + result = driver.configure_zabbix_agent(ACTIVE_ONLY) + + assert result["success"] is False + assert "writable" in result["output"] + assert not any("ufw delete" in c for c in node.ran) + + +def test_a_rule_that_will_not_go_stays_in_the_record(driver, node): + node.record = ROOT + f"{ZABBIX_UFW}\n" + node.refuse = "ufw delete" + + result = driver.configure_zabbix_agent(ACTIVE_ONLY) + + assert result["success"] is False + assert node.record_written is None + + +def test_a_recorded_rule_of_another_firewall_is_not_touched(driver, node): + """A node's rules are ufw's; a firewalld line is not one this driver removes.""" + node.record = ROOT + "v1 zabbix-agent iptables tcp 10050 10.40.100.254/32\n" + + result = driver.configure_zabbix_agent(ACTIVE_ONLY) + + assert result["success"] is False + assert "iptables" in result["output"] + assert node.record_written is None From 685e99507348f3d3decfb1551e49cdb0b7fc77d0 Mon Sep 17 00:00:00 2001 From: Christian Manivong Date: Thu, 26 Nov 2026 08:26:35 +0100 Subject: [PATCH 2/2] chore(release): 0.13.0 --- CHANGELOG.md | 2 ++ pyproject.toml | 4 ++-- 2 files changed, 4 insertions(+), 2 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 37ee2cc..ed7f09d 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.13.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 14b22a4..ccffe74 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -4,7 +4,7 @@ build-backend = "setuptools.build_meta" [project] name = "napalm-proxmox" -version = "0.12.0" +version = "0.13.0" description = "NAPALM drivers for Proxmox VE (classic Linux networking, SDN, OVS) and Proxmox Backup Server" readme = "README.md" license = "Apache-2.0" @@ -21,7 +21,7 @@ classifiers = [ requires-python = ">=3.12" dependencies = [ "napalm>=5.0.0", - "napalm_device_types>=4.40.0", # ZabbixAgentMixin + "napalm_device_types>=4.43.0", # ZabbixAgentMixin, opened_ports "paramiko>=5.0.0", # CVE-2026-44405; imported directly for the node's SSH session (_base.py) "proxmoxer>=2.0.0", "netaddr>=0.9.0",