7 Commits
Author SHA1 Message Date
christianmanivong dfe084c4ad Merge pull request 'chore(release): 0.18.0' (#85) from chore/release-0.18.0 into main
driver / types (push) Successful in 1m5s
driver / standard (push) Successful in 16s
driver / lint (push) Successful in 14s
driver / test (3.12) (push) Successful in 59s
driver / test (3.13) (push) Successful in 56s
driver / lowest (push) Successful in 41s
driver / build (push) Successful in 32s
driver / security (push) Successful in 1m19s
driver / publish (push) Successful in 27s
CI / driver (push) Successful in 4m35s
2026-11-26 11:42:10 +00:00
Christian Manivong fc4f08302c refactor(firewall): SNMP's firewall step lives with the others in OpenPortMixin
driver / lint (pull_request) Successful in 13s
driver / standard (pull_request) Successful in 16s
driver / types (pull_request) Successful in 1m0s
driver / test (3.13) (pull_request) Successful in 1m2s
driver / test (3.12) (pull_request) Successful in 1m6s
driver / lowest (pull_request) Successful in 28s
driver / build (pull_request) Successful in 30s
driver / security (pull_request) Successful in 1m7s
CI / driver (pull_request) Successful in 2m26s
driver / publish (pull_request) Skipped
2026-11-26 12:24:14 +01:00
Christian Manivong 70b605d05b chore(release): 0.18.0
driver / standard (pull_request) Failing after 14s
driver / lint (pull_request) Successful in 11s
driver / test (3.12) (pull_request) Failing after 40s
driver / types (pull_request) Failing after 48s
driver / test (3.13) (pull_request) Failing after 35s
driver / lowest (pull_request) Failing after 17s
driver / build (pull_request) Successful in 26s
driver / security (pull_request) Failing after 54s
CI / driver (pull_request) Failing after 2m8s
driver / publish (pull_request) Skipped
2026-11-26 08:26:35 +01:00
Christian Manivong 1f19a9a8dd refactor(firewall): the revoke loop is napalm-device-types' revoke_recorded_rules 2026-11-26 08:20:09 +01:00
Christian Manivong a3b9e4a02d 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.
2026-11-26 08:19:19 +01:00
christianmanivong 04ff633290 Merge pull request 'feat(zabbix): a native Zabbix agent through ZabbixAgentMixin (NetOrk/netork#2571)' (#84) from feat/zabbix-agent-native into main
driver / standard (push) Successful in 17s
driver / lint (push) Successful in 13s
driver / test (3.13) (push) Successful in 1m6s
driver / types (push) Successful in 1m18s
driver / test (3.12) (push) Successful in 1m19s
driver / lowest (push) Successful in 33s
driver / build (push) Successful in 31s
driver / security (push) Successful in 1m7s
CI / driver (push) Successful in 2m49s
driver / publish (push) Skipped
2026-11-17 04:17:02 +00:00
Christian Manivong 2521f9f462 feat(zabbix): a native Zabbix agent through ZabbixAgentMixin (NetOrk/netork#2571)
driver / lint (pull_request) Successful in 14s
driver / standard (pull_request) Successful in 17s
driver / types (pull_request) Successful in 59s
driver / test (3.13) (pull_request) Successful in 57s
driver / test (3.12) (pull_request) Successful in 1m2s
driver / lowest (pull_request) Successful in 40s
driver / build (pull_request) Successful in 37s
driver / security (pull_request) Successful in 1m17s
CI / driver (pull_request) Successful in 2m32s
driver / publish (pull_request) Skipped
configure_zabbix_agent(settings) installs zabbix-agent from the host's packages,
and where they have none, from Zabbix's repository for the server's release
line. It writes the caller's values into /etc/zabbix/zabbix_agentd.conf (the old
file stays as .bak) and opens tcp/ListenPort for the allowed sources in
firewalld, ufw or iptables.

The firewall step of the SNMP agent is the shared _allow_sources(allowed, port,
proto) now, in _open_port.py; the rules it writes for udp/161 are the same.
Needs napalm-device-types 4.40.0.
2026-11-17 04:58:46 +01:00
10 changed files with 846 additions and 37 deletions

No files matched your search

+22
View File
@@ -7,7 +7,26 @@ 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`,
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
the server's release line, from Zabbix's repository (`zabbix-release` for Debian, Ubuntu,
Raspberry Pi OS and the RHEL family). It writes the caller's values into
`/etc/zabbix/zabbix_agentd.conf` (the old file stays as `.bak`), opens tcp/`listen_port`
for the allowed sources in firewalld, ufw or iptables, enables and restarts the service.
- On an rpm host each package names the source rpm it was built from, as `source_rpm`
(`perf` → `kernel`); absent where rpm names none (`gpg-pubkey`). Red Hat lists `perf`,
`python3-perf` and `bpftool` in every kernel CVE, and the source is what tells them apart
@@ -21,6 +40,9 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
`NotImplementedError`.
### Changed
- Needs napalm-device-types 4.40.0 or later (`ZabbixAgentMixin`).
- The SNMP agent's firewall step is the shared `_allow_sources(allowed, port, proto)`; the
rules it writes for udp/161 are the same.
- `load_replace_candidate` is `None` instead of a method that raises
`NotImplementedError`, so a caller that asks whether the driver can replace a
configuration gets no. netOrk offered a config restore for these devices that
+174
View File
@@ -0,0 +1,174 @@
"""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``), 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, Literal
from napalm_device_types import (
OPENED_PORTS_RECORD,
SNMP_PURPOSE,
FixStepOutcomeDict,
OpenedRuleDict,
opened_rule_line,
parse_opened_ports_record,
read_opened_ports_command,
record_opened_rule_command,
revoke_recorded_rules,
revoked_output,
ufw_allow_recorded_command,
ufw_delete_command,
)
from napalm_device_types.models import SnmpAgentSettingsDict
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`` 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
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.
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"}
firewall = self._firewall()
if firewall == "firewalld":
done = f"{proto}/{port} open in firewalld for {', '.join(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 _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*.
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"]}
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, done["record"])
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: ...
+63 -8
View File
@@ -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.
@@ -38,28 +44,77 @@ _FIREWALLD_ZONES = (
def firewalld_allow_snmp(sources: list[str]) -> str:
"""The shell that opens udp/161 for *sources* (already normalised) in firewalld.
"""The shell that opens udp/161 for *sources* (already normalised) in firewalld."""
return firewalld_allow_port(sources, 161, "udp")
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}"'
' port port="161" protocol="udp" 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"]
+91
View File
@@ -0,0 +1,91 @@
"""A native Zabbix agent, the steps of napalm-device-types' ``ZabbixAgentMixin``.
For a host without a container engine (NetOrk/netork#2571). The template installs
``zabbix-agent`` -- the C agent every distribution that packages Zabbix has, and
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 -- or, for an active-only agent, closes what netOrk opened
for it before.
"""
from __future__ import annotations
from typing import TYPE_CHECKING
from napalm_device_types import (
ZABBIX_AGENT_PURPOSE,
FixStepOutcomeDict,
ZabbixAgentMixin,
ZabbixAgentSettingsDict,
zabbix_agent_config,
zabbix_repository_command,
)
if TYPE_CHECKING: # pragma: no cover
from napalm_device_types import CommandResult
CONFIG = "/etc/zabbix/zabbix_agentd.conf"
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 LinuxZabbixAgentMixin(ZabbixAgentMixin):
"""``zabbix-agent`` from the distribution, or else from Zabbix's repository."""
def _add_zabbix_repository(self, release: str) -> FixStepOutcomeDict:
os_release = self.run_command("cat /etc/os-release", timeout=30)
try:
command = zabbix_repository_command(os_release.stdout, release)
except ValueError as exc:
return {"ok": False, "output": str(exc)}
return self._root_outcome(command, 300, f"Zabbix {release} repository added")
def _write_zabbix_agent_config(self, settings: ZabbixAgentSettingsDict) -> FixStepOutcomeDict:
read = self.run_command(f"cat {CONFIG}", privileged=True, timeout=30)
if read.exit_code:
return _failed(read, f"reading {CONFIG}")
text, changes = zabbix_agent_config(read.stdout, settings)
if not changes:
return {"ok": True, "output": f"{CONFIG} already says it"}
kept = self._root_outcome(f"cp -p {CONFIG} {CONFIG}.bak", 30, "")
if not kept["ok"]:
return kept
written = self._install_file_as_root(CONFIG, text)
if written.exit_code:
return _failed(written, f"writing {CONFIG}")
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", 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
def run_command(
self,
command: str,
*,
privileged: bool = False,
timeout: float = 60,
stdin: bytes | None = None,
) -> CommandResult: ...
def _root_outcome(self, command: str, timeout: float, done: str) -> FixStepOutcomeDict: ...
def _install_file_as_root(self, path: str, content: str) -> CommandResult: ...
def _allow_sources(
self, allowed: list[str], port: int, proto: str, purpose: str
) -> FixStepOutcomeDict: ...
def _revoke_sources(self, purpose: str, port: int, proto: str) -> FixStepOutcomeDict: ...
+4 -23
View File
@@ -78,6 +78,7 @@ from netmiko.exceptions import NetmikoAuthenticationException, NetmikoTimeoutExc
from napalm_linux._dpkg import DPKG_QUERY_COMMAND, parse_dpkg_query
from napalm_linux._hostname import HostnameMixin
from napalm_linux._local_accounts import LinuxLocalAccountsMixin
from napalm_linux._open_port import OpenPortMixin
from napalm_linux._ping import parse_ping, ping_command
from napalm_linux._posix import LinuxPosixMixin
from napalm_linux._readings import LinuxProcessReadingsMixin
@@ -87,11 +88,10 @@ from napalm_linux._shell import expect_for, prepare_shell, sudo_without_password
from napalm_linux._snmp_agent import (
_SNMP_INSTALL,
_SNMPD_CONF,
_source,
firewalld_allow_snmp,
render_snmpd_conf,
)
from napalm_linux._sudo_history import LinuxSudoHistoryMixin
from napalm_linux._zabbix_agent import LinuxZabbixAgentMixin
logger = logging.getLogger("napalm_linux")
@@ -272,6 +272,8 @@ class LinuxDriver(
LinuxSudoHistoryMixin,
LinuxLocalAccountsMixin,
SnmpAgentMixin,
LinuxZabbixAgentMixin,
OpenPortMixin,
EnsurePackageMixin,
AptProxyMixin,
KernelFactsMixin,
@@ -1795,27 +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:
sources = [_source(s) for s in settings.get("allowed_sources", [])]
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":
done = f"udp/161 open in firewalld for {', '.join(sources)}"
return self._root_outcome(firewalld_allow_snmp(sources), 60, done)
if self._send("command -v ufw 2>/dev/null"):
rules = [f"ufw allow from {s} to any port 161 proto udp" for s in sources]
elif self._send("command -v iptables 2>/dev/null"):
rules = [
f"{{ iptables -C INPUT -s {s} -p udp --dport 161 -j ACCEPT 2>/dev/null"
f" || iptables -I INPUT -s {s} -p udp --dport 161 -j ACCEPT; }}"
for s in sources
]
else:
return {"ok": True, "output": "no host firewall (ufw, iptables); nothing to open"}
return self._root_outcome(" && ".join(rules), 30, f"udp/161 open for {', '.join(sources)}")
def _start_snmp_agent(self) -> FixStepOutcomeDict:
return self._root_outcome(
"systemctl enable snmpd && systemctl restart snmpd && systemctl is-active snmpd",
+2 -2
View File
@@ -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.37.0",
"napalm-device-types>=4.43.0", # ZabbixAgentMixin, opened_ports
"netmiko>=4.0.0",
"paramiko>=5.0.0", # CVE-2026-44405
]
+1 -1
View File
@@ -20,7 +20,7 @@
"napalm_linux.linux"
],
"python_file_lines": {
"napalm_linux/linux.py": 2009
"napalm_linux/linux.py": 1990
},
"untyped_public": []
}
+21 -3
View File
@@ -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)
+114
View File
@@ -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"
+354
View File
@@ -0,0 +1,354 @@
"""configure_zabbix_agent on a Linux host without a container engine (NetOrk/netork#2571).
The template (napalm-device-types ``ZabbixAgentMixin``) installs ``zabbix-agent`` from
the host's packages, and from Zabbix's repository where those have none; this driver
adds that repository, writes ``/etc/zabbix/zabbix_agentd.conf`` and opens the port.
"""
from __future__ import annotations
from unittest.mock import MagicMock
import pytest
from napalm_device_types import (
OPENED_PORTS_RECORD,
CommandResult,
read_opened_ports_command,
)
from napalm_linux import LinuxDriver
CONFIG = "/etc/zabbix/zabbix_agentd.conf"
STOCK = "PidFile=/run/zabbix/zabbix_agentd.pid\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": ["10.0.0.5"],
"hostname": "web-01",
"release": "7.4",
}
UBUNTU = 'ID=ubuntu\nVERSION_ID="24.04"\nID_LIKE=debian\n'
class _Host:
"""A Linux host: what runs as root, the files it reads, its packages and services."""
def __init__(self, *, config=STOCK, os_release=UBUNTU, firewall="ufw", firewalld=False):
self.config = config
self.os_release = os_release
self.firewall = firewall
self.firewalld = firewalld
self.root: list[str] = []
self.written: list[tuple[str, str]] = []
self.services: list[tuple[str, str]] = []
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)
def send(self, command, read_timeout=100):
if command == "systemctl is-active firewalld 2>/dev/null":
return "active" if self.firewalld else "inactive"
if command == f"command -v {self.firewall} 2>/dev/null":
return f"/usr/sbin/{self.firewall}"
return ""
def run_command(self, command, *, privileged=False, timeout=60, stdin=None):
if self.refuse and self.refuse in command:
return CommandResult("", "Permission denied", 1)
if command == "cat /etc/os-release":
return CommandResult(self.os_release, "", 0)
if command == f"cat {CONFIG}" and privileged:
return CommandResult(self.config, "", 0)
return CommandResult("", "", 0)
def install_file(self, path, content):
self.written.append((path, content))
self.config = content
return CommandResult("", "", 0)
def ensure_package(self, name):
self.packages.append(name)
ok = self.distribution_has_it
return {"success": ok, "steps": [], "output": "installed" if ok else "E: Unable to locate"}
def manage_service(self, name, action):
self.services.append((action, name))
return {"success": True, "output": ""}
@pytest.fixture
def host():
return _Host()
@pytest.fixture
def driver(host):
d = LinuxDriver("h", "admin", "p")
d._device = MagicMock()
d._pkg_manager = "apt"
d._root = True
d._sudo_status = host.sudo_status
d._send = host.send
d.run_command = host.run_command
d._install_file_as_root = host.install_file
d.ensure_package = host.ensure_package
d.manage_service = host.manage_service
d.refresh_available_updates = lambda: {"success": True, "output": ""}
return d
def test_installs_writes_opens_and_starts(driver, host):
result = driver.configure_zabbix_agent(SETTINGS)
assert result["success"] is True, result["output"]
assert [s["step"] for s in result["steps"]] == ["install", "configure", "firewall", "start"]
assert host.packages == ["zabbix-agent"]
assert host.services == [("enable", "zabbix-agent"), ("restart", "zabbix-agent")]
def test_the_config_gets_the_caller_s_values_and_keeps_the_rest(driver, host):
driver.configure_zabbix_agent(SETTINGS)
path, content = host.written[0]
assert path == CONFIG
assert "Server=zabbix.example.com\n" in content
assert "Hostname=web-01\n" in content
assert content.startswith("PidFile=/run/zabbix/zabbix_agentd.pid\n")
assert f"cp -p {CONFIG} {CONFIG}.bak" in host.root
def test_a_config_that_already_says_it_is_not_written(driver, host):
driver.configure_zabbix_agent(SETTINGS)
host.written.clear()
result = driver.configure_zabbix_agent(SETTINGS)
assert result["success"] is True
assert host.written == []
def test_a_config_that_cannot_be_read_stops_the_fix(driver, host):
host.refuse = f"cat {CONFIG}"
result = driver.configure_zabbix_agent(SETTINGS)
assert result["success"] is False
assert result["steps"][-1]["step"] == "configure"
assert host.services == []
def test_without_the_distribution_s_package_zabbix_s_repository_is_added(driver, host):
host.distribution_has_it = False
result = driver.configure_zabbix_agent(SETTINGS)
assert result["success"] is True, result["output"]
repository = next(c for c in host.root if "repo.zabbix.com" in c)
assert (
"https://repo.zabbix.com/zabbix/7.4/release/ubuntu/pool/main/z/zabbix-release/"
"zabbix-release_latest_7.4+ubuntu24.04_all.deb"
) in repository
assert "dpkg -i" in repository
assert host.packages == ["zabbix-agent", "zabbix-agent"]
def test_a_distribution_zabbix_publishes_nothing_for_fails_the_install(driver, host):
host.distribution_has_it = False
host.os_release = 'ID=arch\nVERSION_ID="rolling"\n'
result = driver.configure_zabbix_agent(SETTINGS)
assert result["success"] is False
assert "Zabbix publishes no repository for arch" in result["output"]
assert not any("repo.zabbix.com" in c for c in host.root)
def test_ufw_opens_the_listen_port_for_the_sources(driver, host):
driver.configure_zabbix_agent(SETTINGS)
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):
host.firewall = "iptables"
driver.configure_zabbix_agent(SETTINGS)
assert any(
"iptables -I INPUT -s 10.0.0.5/32 -p tcp --dport 10050 -j ACCEPT" in c for c in host.root
)
def test_a_running_firewalld_gets_a_rich_rule_for_tcp(driver, host):
host.firewalld = True
driver.configure_zabbix_agent(SETTINGS)
rule = next(c for c in host.root if "firewall-cmd" in c)
assert (
'rule family="ipv4" source address="10.0.0.5/32" port port="10050" protocol="tcp" accept'
in rule
)
def test_no_sources_change_no_firewall(driver, host):
result = driver.configure_zabbix_agent({**SETTINGS, "allowed_sources": []})
assert result["success"] is True
assert not any("ufw" in c or "iptables" in c or "firewall-cmd" in c for c in host.root)
def test_the_snmp_rule_is_still_udp_161(driver, host):
driver.configure_snmp_agent({"community": "c0mm", "allowed_sources": ["10.0.0.5"]})
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 == []