feat(zabbix): the feed's Zabbix agent through ZabbixAgentMixin (NetOrk/netork#2571)
driver / lint (pull_request) Successful in 15s
driver / standard (pull_request) Successful in 18s
driver / types (pull_request) Successful in 1m7s
driver / test (3.13) (pull_request) Successful in 1m1s
driver / test (3.12) (pull_request) Successful in 1m10s
driver / lowest (pull_request) Successful in 39s
driver / build (pull_request) Successful in 38s
driver / security (pull_request) Successful in 1m11s
CI / driver (pull_request) Successful in 2m30s
driver / publish (pull_request) Skipped

An access point runs no container engine. configure_zabbix_agent(settings)
installs zabbix-agentd from the feed after loading the package index, writes the
caller's values into /etc/zabbix_agentd.conf (the old file stays as .bak),
enables the agent in UCI, without which its init script does not start it, and
opens tcp/ListenPort for the allowed sources in the zone that owns the
management address where a firewall runs. Zabbix publishes no repository for
OpenWrt; the feed is the only source.

The SNMP agent's firewall step writes its rule through _allow_in_management_zone
now, split into the zone, the rule and the reload; the rule is the same.
Needs napalm-device-types 4.40.0.
This commit is contained in:
Christian Manivong committed 2026-11-17 04:50:55 +01:00
1 parent c4434cf54b
commit 053137aff7
7 files changed
+478 -46

No files matched your search

+103 -42
View File
@@ -53,6 +53,7 @@ from napalm_openwrt.system_mixin import _RC_MARKER, OpenWrtSystemMixin, _split_s
from napalm_openwrt.time_sync_mixin import OpenWrtTimeSyncMixin
from napalm_openwrt.vlan_mixin import OpenWrtVLANMixin
from napalm_openwrt.wireless_mixin import OpenWrtWirelessMixin
from napalm_openwrt.zabbix_agent import OpenWrtZabbixAgentMixin
#: What may stand in a UCI value written in single quotes: no whitespace, quote or #.
_SNMP_WORD = re.compile(r"^[^\s'\"#]+$")
@@ -86,6 +87,7 @@ class OpenWrtDriver(
HostStatusMixin,
SnmpAgentMixin,
OpenWrtLldpAgentMixin,
OpenWrtZabbixAgentMixin,
EnsurePackageMixin,
AccessPointDriver,
):
@@ -518,15 +520,23 @@ class OpenWrtDriver(
@classmethod
def _stale_snmp_rules(cls, fw_sections: dict[str, dict[str, str]], keep: str) -> list[str]:
"""Return every SNMP rule section except ``keep``, in delete-safe order."""
return cls._stale_rules(fw_sections, keep, word="snmp", port=161)
@classmethod
def _stale_rules(
cls, fw_sections: dict[str, dict[str, str]], keep: str, *, word: str, port: int
) -> list[str]:
"""Every rule section for an agent except ``keep``, in delete-safe order: its
name or key says *word*, or it opens *port*."""
hits = [
key
for key, opts in fw_sections.items()
if opts.get("_type") == "rule"
and key != keep
and (
"snmp" in cls._uci_scalar(opts.get("name", "")).lower()
or "snmp" in key.lower()
or cls._uci_scalar(opts.get("dest_port", "")) == "161"
word in cls._uci_scalar(opts.get("name", "")).lower()
or word in key.lower()
or cls._uci_scalar(opts.get("dest_port", "")) == str(port)
)
]
return sorted(hits, key=cls._uci_delete_order)
@@ -614,40 +624,59 @@ class OpenWrtDriver(
return self._rc_step("; ".join(cmds), done)
def _allow_snmp_sources(self, settings: dict) -> dict[str, Any]:
"""A udp/161 accept rule in the zone that owns the management address.
"""A udp/161 accept rule in the zone that owns the management address."""
return self._allow_in_management_zone(
key="allow_snmp",
name="Allow-SNMP",
proto="udp",
port=161,
sources=_sources(settings),
word="snmp",
)
def _allow_in_management_zone(
self, *, key: str, name: str, proto: str, port: int, sources: list[str], word: str
) -> dict[str, Any]:
"""An accept rule for *proto*/*port* in the zone that owns the management address.
The zone is resolved from ``$SSH_CONNECTION`` → its ``network`` section →
the zone listing it, not guessed from rule names. A zone without ``option
name`` is skipped by fw4, so the step fails with how to fix it instead of
writing a dead rule. Stale SNMP rules go (highest anonymous index first);
the rule is written in full every run and limited to the allowed sources
(``src_ip``); the reload and the live packet filter decide success.
writing a dead rule. Stale rules for the same agent go (``word`` in their
name, or *port*; highest anonymous index first); the rule, ``<key>_from_<zone>``
named *name*, is written in full every run and limited to *sources*
(``src_ip``; none: every source in the zone); the reload and the live packet
filter decide success.
"""
lines: list[str] = []
sources = _sources(settings)
fw_sections = self._parse_uci_sections(self._send_command("uci show firewall 2>/dev/null"))
zone = self._management_zone(fw_sections, lines)
if zone is None:
return {"ok": False, "output": "\n".join(lines)}
named_key = f"{key}_from_{zone}" if zone else key
stale = self._stale_rules(fw_sections, keep=named_key, word=word, port=port)
if stale:
deletes = "; ".join(f"uci -q delete firewall.{section}" for section in stale)
self._send_command(f"{deletes}; uci commit firewall")
lines.append(f"Removed stale {name} rule(s): {', '.join(stale)}")
self._write_accept_rule(named_key, name, proto, port, sources, zone, lines)
ok = self._reload_and_count(proto, port, lines)
return {"ok": ok, "output": "\n".join(lines)}
def _management_zone(
self, fw_sections: dict[str, dict[str, str]], lines: list[str]
) -> str | None:
"""The zone that owns the management address; ``""`` where no zone is
configured (the rule goes unscoped); None where no rule may be written.
What it found goes into *lines*."""
zones, nameless = self._firewall_zones(fw_sections)
address = self._mgmt_address()
net_sections = self._parse_uci_sections(self._send_command("uci show network 2>/dev/null"))
mgmt_net = self._mgmt_network(net_sections, address)
lines.append(f"Management address {address} on network {mgmt_net or '<unknown>'}")
broken_zone = (
self._zone_for_network(fw_sections, {key: key for key in nameless}, mgmt_net)
if mgmt_net
else ""
)
if broken_zone:
lines.append(
f"Zone {broken_zone} owns network {mgmt_net!r} but has no 'name' option — "
"fw4 skips the section and drops every rule that references it. "
"Fix on the device, then re-run:"
)
lines.append(
f" uci set firewall.{broken_zone}.name='{mgmt_net}'"
" && uci commit firewall && fw4 reload"
)
return {"ok": False, "output": "\n".join(lines)}
if self._nameless_zone_owns(fw_sections, nameless, mgmt_net, lines):
return None
mgmt_zone = self._zone_for_network(fw_sections, zones, mgmt_net) if mgmt_net else ""
if not mgmt_zone and "lan" in zones:
@@ -656,31 +685,61 @@ class OpenWrtDriver(
mgmt_zone = next(iter(zones))
if mgmt_zone:
lines.append(f"Management zone: {mgmt_zone!r}")
elif zones:
return mgmt_zone
if zones:
present = ", ".join(sorted(zones))
lines.append(f"No zone covers the management network — zones present: {present}")
return {"ok": False, "output": "\n".join(lines)}
else:
lines.append("No zones configured — writing an unscoped rule")
return None
lines.append("No zones configured — writing an unscoped rule")
return ""
named_key = f"allow_snmp_from_{mgmt_zone}" if mgmt_zone else "allow_snmp"
stale = self._stale_snmp_rules(fw_sections, keep=named_key)
if stale:
deletes = "; ".join(f"uci -q delete firewall.{key}" for key in stale)
self._send_command(f"{deletes}; uci commit firewall")
lines.append(f"Removed stale SNMP rule(s): {', '.join(stale)}")
def _nameless_zone_owns(
self,
fw_sections: dict[str, dict[str, str]],
nameless: list[str],
mgmt_net: str,
lines: list[str],
) -> bool:
"""Whether a zone without ``option name`` owns *mgmt_net*: fw4 skips it, so a
rule there would be dead. How to fix it goes into *lines*."""
if not mgmt_net:
return False
broken_zone = self._zone_for_network(fw_sections, {key: key for key in nameless}, mgmt_net)
if not broken_zone:
return False
lines.append(
f"Zone {broken_zone} owns network {mgmt_net!r} but has no 'name' option — "
"fw4 skips the section and drops every rule that references it. "
"Fix on the device, then re-run:"
)
lines.append(
f" uci set firewall.{broken_zone}.name='{mgmt_net}'"
" && uci commit firewall && fw4 reload"
)
return True
def _write_accept_rule(
self,
named_key: str,
name: str,
proto: str,
port: int,
sources: list[str],
zone: str,
lines: list[str],
) -> None:
"""Write the rule *named_key* in full: *proto*/*port* from *sources* in *zone*."""
rule_cmds = [
f"uci set firewall.{named_key}=rule",
f"uci set firewall.{named_key}.name='Allow-SNMP'",
f"uci set firewall.{named_key}.name='{name}'",
f"uci set firewall.{named_key}.target='ACCEPT'",
f"uci set firewall.{named_key}.proto='udp'",
f"uci set firewall.{named_key}.dest_port='161'",
f"uci set firewall.{named_key}.proto='{proto}'",
f"uci set firewall.{named_key}.dest_port='{port}'",
f"uci -q delete firewall.{named_key}.src_ip",
*(f"uci add_list firewall.{named_key}.src_ip='{net}'" for net in sources),
]
if mgmt_zone:
rule_cmds.append(f"uci set firewall.{named_key}.src='{mgmt_zone}'")
if zone:
rule_cmds.append(f"uci set firewall.{named_key}.src='{zone}'")
else:
rule_cmds.append(f"uci -q delete firewall.{named_key}.src")
rule_cmds.append("uci commit firewall")
@@ -688,6 +747,8 @@ class OpenWrtDriver(
scope = ", ".join(sources) or "every source in the zone"
lines.append(f"Wrote rule {named_key!r} for {scope}: {rule_out or 'ok'}")
def _reload_and_count(self, proto: str, port: int, lines: list[str]) -> bool:
"""Reload the firewall; True when it took the ruleset and a rule for *port* is live."""
reload_out = self._send_command(
"fw4 reload 2>&1 || /etc/init.d/firewall reload 2>&1"
).strip()
@@ -698,11 +759,11 @@ class OpenWrtDriver(
live = self._grep_count(
self._send_command(
"{ nft list ruleset 2>/dev/null || iptables-save 2>/dev/null; }"
" | grep -c 'dport 161'"
f" | grep -c 'dport {port}'"
)
)
lines.append(f"udp/161 accept rules live in the packet filter: {live}")
return {"ok": fw_ok and bool(live), "output": "\n".join(lines)}
lines.append(f"{proto}/{port} accept rules live in the packet filter: {live}")
return fw_ok and bool(live)
def _start_snmp_agent(self) -> dict[str, Any]:
self._send_command(