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.
This commit is contained in:
Christian Manivong committed 2026-11-26 08:21:53 +01:00
1 parent bc3eb86723
commit 370aeed482
6 files changed
+183 -8

No files matched your search

+56 -4
View File
@@ -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()
+4 -1
View File
@@ -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(
+12 -2
View File
@@ -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: ...