feat(zabbix): the feed's Zabbix agent through ZabbixAgentMixin (NetOrk/netork#2571) #48

Merged
christianmanivong merged 1 commits from feat/zabbix-agent-native into main 2026-11-17 04:32:23 +00:00
7 changed files with 478 additions and 46 deletions

No files matched your search

+8 -1
View File
@@ -8,7 +8,9 @@ recorded here; their history is the git log.
## [Unreleased]
### Changed
- Needs napalm-device-types 4.39.0 or later (`PackageIndexMissing`).
- Needs napalm-device-types 4.40.0 or later (`ZabbixAgentMixin`).
- The SNMP agent's firewall step writes its rule through `_allow_in_management_zone`, which
the Zabbix agent's step shares; the rule it writes is the same.
- `get_available_updates()` raises napalm-device-types' `PackageIndexMissing` when the
package index is not in RAM (after a reboot), for apk and opkg alike, instead of a bare
`RuntimeError`: a caller can load the index instead of reporting a failed read
@@ -17,6 +19,11 @@ recorded here; their history is the git log.
a router that commit wrote keeps `use_dhcp=0` until it is set back.
### Added
- Zabbix agent (napalm-device-types `ZabbixAgentMixin`, NetOrk/netork#2571):
`configure_zabbix_agent(settings)` installs the feed's `zabbix-agentd` after loading the
package index, writes the caller's values into `/etc/zabbix_agentd.conf`, enables it in
UCI, opens tcp/`listen_port` for the allowed sources where a firewall runs (an access
point often runs none), enables and restarts it.
- Time sync (napalm-device-types `TimeSyncMixin`, NetOrk/netork#2364): `get_time_sync()`
reads the router's NTP servers and its zone from `uci -q show system`;
`configure_time_sync()` writes both. The servers replace `system.ntp.server` and enable
+11
View File
@@ -116,6 +116,17 @@ to the interfaces given, enables it at boot and restarts it. A VLAN device such
`br-ap.10` is written as the device under it (`br-ap`): lldpd sends on the L2 device.
Which interfaces is the caller's choice; at least one is required.
## Zabbix agent
`configure_zabbix_agent(settings)` (napalm-device-types `ZabbixAgentMixin`) runs the
feed's C agent, `zabbix-agentd`: it loads the package index (it lives in RAM), installs
the package where it is missing, writes `Server`, `ServerActive`, `ListenPort` and
`Hostname` into `/etc/zabbix_agentd.conf` (the old file stays as `.bak`), enables the
agent in UCI (`zabbix_agentd.general.enabled`, without which the init script does not
start it), opens tcp/`listen_port` for the allowed sources in the zone that owns the
management address where a firewall runs, then enables and restarts it. Zabbix publishes
no repository for OpenWrt; the feed is the only source.
## Wireless writes
`push_mac_acl(ssid_name, mode, macs)` (napalm-device-types `MacAclMixin`) rewrites the
+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(
+119
View File
@@ -0,0 +1,119 @@
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""The feed's Zabbix agent, the steps of napalm-device-types' ``ZabbixAgentMixin``.
OpenWrt's feed has the C agent, ``zabbix-agentd`` (NetOrk/netork#2571). Its
configuration is ``/etc/zabbix_agentd.conf``; its init script starts it only while
UCI says ``zabbix_agentd.general.enabled=1``, and runs it as ``zabbix-agent``.
Zabbix publishes no repository for OpenWrt, so the feed is the only source.
The package index lives in RAM and is gone after every restart; the template loads
it first (``refresh_available_updates``). The firewall step opens tcp/``listen_port``
in the zone that owns the management address, the way the SNMP agent's step opens
udp/161 -- and only where a firewall runs: an access point often runs none.
"""
from __future__ import annotations
import ipaddress
from typing import TYPE_CHECKING, Any
from napalm_device_types import (
FixStepOutcomeDict,
ZabbixAgentMixin,
ZabbixAgentSettingsDict,
zabbix_agent_config,
)
if TYPE_CHECKING: # pragma: no cover
from napalm_device_types import CommandResult
CONFIG = "/etc/zabbix_agentd.conf"
#: UCI's switch the init script reads; the section is made where it is missing.
_ENABLE = (
"uci -q get zabbix_agentd.general >/dev/null || uci set zabbix_agentd.general=zabbix_agentd; "
"uci set zabbix_agentd.general.enabled='1' && uci commit zabbix_agentd"
)
#: Prints ``on`` while a packet filter runs: fw4's table, or fw3's enabled service.
_FIREWALL_RUNS = (
"{ nft list table inet fw4 >/dev/null 2>&1 || /etc/init.d/firewall enabled; } && echo on"
)
def _failed(result: CommandResult, what: str) -> FixStepOutcomeDict:
detail = (result.stderr or result.stdout or "").strip()[-300:]
return {"ok": False, "output": f"{what}: {detail or result.exit_code}"}
class OpenWrtZabbixAgentMixin(ZabbixAgentMixin):
"""``zabbix-agentd`` from the feed, enabled in UCI."""
ZABBIX_AGENT_PACKAGE = "zabbix-agentd"
ZABBIX_AGENT_SERVICE = "zabbix_agentd"
#: The feed is the only source.
_add_zabbix_repository = None # type: ignore[assignment]
def _write_zabbix_agent_config(self, settings: ZabbixAgentSettingsDict) -> FixStepOutcomeDict:
read = self.run_command(f"cat {CONFIG}", privileged=True)
if read.exit_code:
return _failed(read, f"reading {CONFIG}")
text, changes = zabbix_agent_config(read.stdout, settings)
if changes:
# The old file next to it; cat keeps owner and mode (zabbix-agent's).
written = self.run_command(
f"cp -p {CONFIG} {CONFIG}.bak && cat > {CONFIG}",
privileged=True,
stdin=text.encode(),
)
if written.exit_code:
return _failed(written, f"writing {CONFIG}")
enabled = self.run_command(_ENABLE, privileged=True)
if enabled.exit_code:
return _failed(enabled, "enabling the agent in UCI")
said = "; ".join(changes) if changes else f"{CONFIG} already says it"
return {"ok": True, "output": f"{said}; enabled in UCI"}
def _allow_zabbix_agent_sources(self, settings: ZabbixAgentSettingsDict) -> FixStepOutcomeDict:
sources = [
str(ipaddress.ip_network(s.strip(), strict=False)) for s in settings["allowed_sources"]
]
if not sources:
return {"ok": True, "output": "no sources given; firewall unchanged"}
if self._send_command(_FIREWALL_RUNS).strip() != "on":
return {"ok": True, "output": "no firewall runs; nothing to open"}
outcome = self._allow_in_management_zone(
key="allow_zabbix_agent",
name="Allow-Zabbix-Agent",
proto="tcp",
port=int(settings["listen_port"]),
sources=sources,
word="zabbix",
)
return {"ok": bool(outcome["ok"]), "output": str(outcome["output"])}
if TYPE_CHECKING: # pragma: no cover - the driver's
def run_command(
self,
command: str,
*,
privileged: bool = False,
timeout: float = 60,
stdin: bytes | None = None,
) -> CommandResult: ...
def _send_command(self, command: str) -> str: ...
def _allow_in_management_zone(
self, *, key: str, name: str, proto: str, port: int, sources: list[str], word: str
) -> dict[str, Any]: ...
+1 -1
View File
@@ -21,7 +21,7 @@ classifiers = [
]
dependencies = [
"napalm>=5.1", # older releases import pkg_resources, which a 3.12 venv lacks
"napalm_device_types>=4.39.0", # PackageIndexMissing
"napalm_device_types>=4.40.0", # ZabbixAgentMixin
"netmiko>=4.0.0",
"paramiko>=5.0.0", # CVE-2026-44405
"netaddr>=0.7.19", # IPAddress; below it the package has none (CI lowest job)
-2
View File
@@ -3,7 +3,6 @@
"function_complexity": {
"napalm_openwrt/config_mixin.py::OpenWrtConfigMixin.commit_config": 14,
"napalm_openwrt/interfaces_mixin.py::OpenWrtInterfaceMixin.get_arp_table": 13,
"napalm_openwrt/openwrt.py::OpenWrtDriver._allow_snmp_sources": 22,
"napalm_openwrt/openwrt.py::OpenWrtDriver._write_snmp_agent_config": 22,
"napalm_openwrt/packages_mixin.py::OpenWrtPackageMixin.search_packages": 12,
"napalm_openwrt/routing_mixin.py::OpenWrtRoutingMixin._parse_traceroute_output": 12,
@@ -21,7 +20,6 @@
"napalm_openwrt/interfaces_mixin.py::OpenWrtInterfaceMixin.get_arp_table": 85,
"napalm_openwrt/interfaces_mixin.py::OpenWrtInterfaceMixin.get_interfaces_ip": 55,
"napalm_openwrt/interfaces_mixin.py::OpenWrtInterfaceMixin.get_mac_address_table": 53,
"napalm_openwrt/openwrt.py::OpenWrtDriver._allow_snmp_sources": 90,
"napalm_openwrt/openwrt.py::OpenWrtDriver.get_facts": 53,
"napalm_openwrt/packages_mixin.py::OpenWrtPackageMixin.search_packages": 59,
"napalm_openwrt/routing_mixin.py::OpenWrtRoutingMixin._parse_traceroute_output": 67,
+236
View File
@@ -0,0 +1,236 @@
"""configure_zabbix_agent: the feed's C agent on an access point (NetOrk/netork#2571).
An AP has no container engine, so the agent cannot run as a container there; the
feed has ``zabbix-agentd``. Its init script starts it only while UCI enables it,
and the package index lives in RAM, gone after every restart.
"""
from __future__ import annotations
import pytest
from napalm_device_types import CommandResult
from napalm_openwrt import OpenWrtDriver
from tests.unit.test_driver import UCI_FIREWALL_HEALTHY, UCI_NETWORK_STATIC
CONFIG = "/etc/zabbix_agentd.conf"
STOCK = "LogFile=/tmp/zabbix_agentd.log\nServer=127.0.0.1\nServerActive=127.0.0.1\nHostname=Zabbix server\n"
SETTINGS = {
"server": "zabbix.example.com",
"server_active": "zabbix.example.com",
"listen_port": 10050,
"allowed_sources": ["198.51.100.20"],
"hostname": "ap-1og",
"release": "7.4",
}
class _Shell:
"""The interactive shell: package manager, init scripts, UCI, the firewall."""
def __init__(self, *, firewall_runs=True, fail="", installed=False, nft_hits="1"):
self.firewall_runs = firewall_runs
self.fail = fail
self.installed = installed
self.nft_hits = nft_hits
self.issued: list[str] = []
def __call__(self, cmd, **kw):
self.issued.append(cmd)
if "command -v apk" in cmd:
return "/usr/bin/apk"
if "apk list --installed" in cmd:
return (
"zabbix-agentd-7.0.32-r1 mips_24kc {zabbix} (GPL) [installed]"
if self.installed
else ""
)
if "nft list table inet fw4" in cmd:
return "on" if self.firewall_runs else ""
if "__OWRT_RC" in cmd:
if self.fail and self.fail in cmd:
return f"failed: {self.fail}\n__OWRT_RC=1"
if cmd.startswith("apk add"):
self.installed = True
return "ok\n__OWRT_RC=0"
if cmd.startswith("uci show firewall"):
return UCI_FIREWALL_HEALTHY
if cmd.startswith("uci show network"):
return UCI_NETWORK_STATIC
if "$SSH_CONNECTION" in cmd:
return "198.51.100.20 51234 192.0.2.1 22"
if "dport 10050" in cmd:
return self.nft_hits
return ""
class _Channel:
"""The exec channel: the config file and UCI's enable, as root."""
def __init__(self, config=STOCK, refuse=""):
self.config = config
self.refuse = refuse
self.calls: list[tuple[str, bool, bytes | None]] = []
def __call__(self, command, *, privileged=False, timeout=60, stdin=None):
self.calls.append((command, privileged, stdin))
if self.refuse and self.refuse in command:
return CommandResult("", f"{self.refuse}: refused", 1)
if command == f"cat {CONFIG}":
return CommandResult(self.config, "", 0)
if f"cat > {CONFIG}" in command:
self.config = (stdin or b"").decode()
return CommandResult("", "", 0)
@pytest.fixture
def shell():
return _Shell()
@pytest.fixture
def channel():
return _Channel()
@pytest.fixture
def owrt(shell, channel):
d = OpenWrtDriver("ap", "root", "pw")
d._send_command = shell
d.run_command = channel
return d
def test_install_configure_open_and_start(owrt, shell, channel):
result = owrt.configure_zabbix_agent(SETTINGS)
assert result["success"] is True, result["output"]
assert [s["step"] for s in result["steps"]] == ["install", "configure", "firewall", "start"]
init = [c.split(" 2>")[0] for c in shell.issued if c.startswith("/etc/init.d/zabbix_agentd")]
assert init == ["/etc/init.d/zabbix_agentd enable", "/etc/init.d/zabbix_agentd restart"]
def test_the_index_is_loaded_before_the_feed_s_package_is_added(owrt, shell):
owrt.configure_zabbix_agent(SETTINGS)
pkg = [c.split(" 2>")[0] for c in shell.issued if c.startswith("apk ")]
assert pkg[0] == "apk update"
assert "apk add zabbix-agentd" in pkg
def test_an_index_that_will_not_load_is_named_when_the_install_fails(owrt, shell):
shell.fail = "apk "
result = owrt.configure_zabbix_agent(SETTINGS)
assert result["success"] is False
assert "package index not loaded" in result["output"]
def test_there_is_no_repository_to_fall_back_to(owrt, shell):
shell.fail = "apk add"
result = owrt.configure_zabbix_agent(SETTINGS)
assert result["success"] is False
assert [s["step"] for s in result["steps"]] == ["install"]
def test_the_config_gets_the_caller_s_values_and_keeps_the_rest(owrt, channel):
owrt.configure_zabbix_agent(SETTINGS)
assert "Server=zabbix.example.com\n" in channel.config
assert "Hostname=ap-1og\n" in channel.config
assert channel.config.startswith("LogFile=/tmp/zabbix_agentd.log\n")
write = next(c for c in channel.calls if f"cat > {CONFIG}" in c[0])
assert write[1] is True
assert f"cp -p {CONFIG} {CONFIG}.bak" in write[0]
def test_the_agent_is_enabled_in_uci(owrt, channel):
owrt.configure_zabbix_agent(SETTINGS)
uci = next(c[0] for c in channel.calls if "uci commit zabbix_agentd" in c[0])
assert "uci set zabbix_agentd.general.enabled='1'" in uci
def test_a_config_that_already_says_it_is_not_written(owrt, channel):
owrt.configure_zabbix_agent(SETTINGS)
channel.calls.clear()
result = owrt.configure_zabbix_agent(SETTINGS)
assert result["success"] is True
assert not any(f"cat > {CONFIG}" in c[0] for c in channel.calls)
def test_a_config_that_cannot_be_read_stops_the_fix(owrt, channel, shell):
channel.refuse = f"cat {CONFIG}"
result = owrt.configure_zabbix_agent(SETTINGS)
assert result["success"] is False
assert result["steps"][-1]["step"] == "configure"
assert not any(c.startswith("/etc/init.d/zabbix_agentd") for c in shell.issued)
def test_the_firewall_rule_is_tcp_on_the_listen_port_for_the_sources(owrt, shell):
owrt.configure_zabbix_agent(SETTINGS)
uci = " ".join(shell.issued)
assert "uci set firewall.allow_zabbix_agent_from_lan=rule" in uci
assert "firewall.allow_zabbix_agent_from_lan.proto='tcp'" in uci
assert "firewall.allow_zabbix_agent_from_lan.dest_port='10050'" in uci
assert "uci add_list firewall.allow_zabbix_agent_from_lan.src_ip='198.51.100.20/32'" in uci
assert "netork" not in uci.lower()
def test_without_a_running_firewall_nothing_is_opened(owrt, shell):
shell.firewall_runs = False
result = owrt.configure_zabbix_agent(SETTINGS)
assert result["success"] is True
assert not any("firewall.allow_zabbix_agent" in c for c in shell.issued)
assert "no firewall runs" in result["output"]
def test_without_sources_the_firewall_is_left_alone(owrt, shell):
result = owrt.configure_zabbix_agent({**SETTINGS, "allowed_sources": []})
assert result["success"] is True
assert not any("firewall.allow_zabbix_agent" in c for c in shell.issued)
def test_a_rule_that_does_not_reach_the_packet_filter_fails(owrt, shell):
shell.nft_hits = "0"
result = owrt.configure_zabbix_agent(SETTINGS)
assert result["success"] is False
assert result["steps"][-1]["step"] == "firewall"
def test_the_snmp_rule_is_written_as_before(owrt, shell):
shell.nft_hits = "1"
owrt._send_command = _SnmpShell(shell)
owrt._allow_snmp_sources({"community": "c", "allowed_sources": ["198.51.100.20"]})
uci = " ".join(shell.issued)
assert "firewall.allow_snmp_from_lan.proto='udp'" in uci
assert "firewall.allow_snmp_from_lan.dest_port='161'" in uci
assert "firewall.allow_snmp_from_lan.name='Allow-SNMP'" in uci
class _SnmpShell:
"""The same shell, answering the SNMP rule's live check."""
def __init__(self, shell):
self.shell = shell
def __call__(self, cmd, **kw):
if "dport 161" in cmd:
self.shell.issued.append(cmd)
return "1"
return self.shell(cmd, **kw)