feat(zabbix): an active-only agent closes the port netOrk opened for it (NetOrk/netork#2693)
ufw, iptables and firewalld do not say who wrote a rule. opened_ports keeps a root-owned record of the rules a driver opened, written only when the firewall did not have the rule before, and read strictly. ZabbixAgentMixin's firewall step calls the driver's optional _revoke_zabbix_agent_sources for an active-only agent; a driver without it changes nothing and says why.
This commit is contained in:
1 parent
fb927e7255
commit
ebd3255e5a
6 files changed
+570
-8
No files matched your search
@@ -7,6 +7,22 @@ recorded here; their history is the git log.
|
||||
|
||||
## [Unreleased]
|
||||
|
||||
### Added
|
||||
- `opened_ports`: the record of the firewall rules netOrk opened on a host
|
||||
(NetOrk/netork#2693). ufw, iptables and firewalld do not say who wrote a rule, so a
|
||||
driver that opens a port in one of them appends the rule to `/var/lib/netork/opened-ports`
|
||||
(root's, mode 644) -- only when the firewall did not have it before, so an identical rule
|
||||
the operator wrote is never recorded. `parse_opened_ports_record` reads it strictly: not at
|
||||
all where the directory or the file is not root's alone or is a symbolic link, and a line
|
||||
that is not exactly a rule is reported, never acted on. `ufw_allow_recorded_command` and
|
||||
`ufw_delete_command` are ufw's commands, which napalm-linux and napalm-proxmox share;
|
||||
`revoked_output` says what closing removed and what it left for the port.
|
||||
- `ZabbixAgentMixin._revoke_zabbix_agent_sources(settings)`, optional: for an `active_only`
|
||||
agent, `configure_zabbix_agent`'s firewall step has the driver close what netOrk opened
|
||||
for the agent on an earlier passive run, and nothing else (NetOrk/netork#2693). A driver
|
||||
without it changes nothing and says that it cannot tell netOrk's rule from the
|
||||
operator's.
|
||||
|
||||
## [4.42.0] - 2026-11-25
|
||||
|
||||
### Added
|
||||
|
||||
@@ -229,6 +229,21 @@ from napalm_device_types.models import (
|
||||
UpdateProgressDict,
|
||||
)
|
||||
from napalm_device_types.nat_vpn import NatVpnMixin
|
||||
from napalm_device_types.opened_ports import (
|
||||
OPENED_PORTS_RECORD,
|
||||
SNMP_PURPOSE,
|
||||
ZABBIX_AGENT_PURPOSE,
|
||||
OpenedPortsRecordDict,
|
||||
OpenedRuleDict,
|
||||
opened_rule_line,
|
||||
opened_rules_text,
|
||||
parse_opened_ports_record,
|
||||
read_opened_ports_command,
|
||||
record_opened_rule_command,
|
||||
revoked_output,
|
||||
ufw_allow_recorded_command,
|
||||
ufw_delete_command,
|
||||
)
|
||||
from napalm_device_types.os import OSDriver
|
||||
from napalm_device_types.ospf import OspfMixin
|
||||
from napalm_device_types.package_updates import (
|
||||
@@ -420,6 +435,19 @@ __all__ = [
|
||||
"check_zabbix_agent_settings",
|
||||
"zabbix_agent_config",
|
||||
"zabbix_repository_command",
|
||||
"OPENED_PORTS_RECORD",
|
||||
"SNMP_PURPOSE",
|
||||
"ZABBIX_AGENT_PURPOSE",
|
||||
"OpenedPortsRecordDict",
|
||||
"OpenedRuleDict",
|
||||
"opened_rule_line",
|
||||
"opened_rules_text",
|
||||
"parse_opened_ports_record",
|
||||
"read_opened_ports_command",
|
||||
"record_opened_rule_command",
|
||||
"revoked_output",
|
||||
"ufw_allow_recorded_command",
|
||||
"ufw_delete_command",
|
||||
"SnmpHealthProfile",
|
||||
"SnmpInterfacesSpec",
|
||||
"SnmpMemorySpec",
|
||||
|
||||
@@ -23,7 +23,7 @@ They replace ``run_device_action`` (docs/STRUCTURE.md):
|
||||
from __future__ import annotations
|
||||
|
||||
from collections.abc import Callable, Sequence
|
||||
from typing import TYPE_CHECKING, Any, ClassVar
|
||||
from typing import TYPE_CHECKING, Any, ClassVar, cast
|
||||
|
||||
from napalm_device_types.models import (
|
||||
FixResultDict,
|
||||
@@ -215,8 +215,9 @@ class ZabbixAgentMixin:
|
||||
where those have none, from Zabbix's repository for ``settings["release"]``
|
||||
(:func:`~napalm_device_types.zabbix_agent.zabbix_repository_command`) --, write
|
||||
its configuration (:func:`~napalm_device_types.zabbix_agent.zabbix_agent_config`),
|
||||
let the allowed sources through the host's firewall -- not for an agent that is
|
||||
``active_only``, which listens on no port --, enable and restart it.
|
||||
let the allowed sources through the host's firewall -- for an agent that is
|
||||
``active_only``, which listens on no port, close what netOrk opened for it
|
||||
earlier instead --, enable and restart it.
|
||||
Installing and starting are generic, over ``ensure_package`` and
|
||||
``manage_service`` with ``ZABBIX_AGENT_PACKAGE`` and ``ZABBIX_AGENT_SERVICE``.
|
||||
Whether Zabbix reaches it is the caller's to ask Zabbix.
|
||||
@@ -278,11 +279,20 @@ class ZabbixAgentMixin:
|
||||
return f"package index not loaded: {str(loaded.get('output', '')).strip()}"
|
||||
|
||||
def _open_zabbix_agent_port(self, settings: ZabbixAgentSettingsDict) -> FixStepOutcomeDict:
|
||||
"""The driver's firewall step; nothing for an agent that only connects out,
|
||||
which listens on no port (NetOrk/netork#2683)."""
|
||||
if settings.get("active_only"):
|
||||
return {"ok": True, "output": "active only: the agent listens on no port"}
|
||||
return self._allow_zabbix_agent_sources(settings)
|
||||
"""The driver's firewall step. An agent that only connects out listens on no
|
||||
port (NetOrk/netork#2683): nothing is opened, and the driver closes what netOrk
|
||||
opened for the agent earlier (``_revoke_zabbix_agent_sources``,
|
||||
NetOrk/netork#2693). A driver without it changes nothing and says why."""
|
||||
if not settings.get("active_only"):
|
||||
return self._allow_zabbix_agent_sources(settings)
|
||||
revoke = getattr(self, "_revoke_zabbix_agent_sources", None)
|
||||
if callable(revoke):
|
||||
return cast(FixStepOutcomeDict, revoke(settings))
|
||||
return {
|
||||
"ok": True,
|
||||
"output": "active only: the agent listens on no port; this driver cannot tell"
|
||||
" a rule netOrk opened for it from the operator's, so the firewall is unchanged",
|
||||
}
|
||||
|
||||
def _start_zabbix_agent(self) -> FixStepOutcomeDict:
|
||||
return enable_and_restart(self.manage_service, self.ZABBIX_AGENT_SERVICE)
|
||||
@@ -318,6 +328,18 @@ class ZabbixAgentMixin:
|
||||
called for an ``active_only`` agent."""
|
||||
...
|
||||
|
||||
# Optional: a driver that can tell its own rules from the operator's.
|
||||
|
||||
def _revoke_zabbix_agent_sources(
|
||||
self, settings: ZabbixAgentSettingsDict
|
||||
) -> FixStepOutcomeDict:
|
||||
"""Close what ``_allow_zabbix_agent_sources`` opened for the agent on an
|
||||
earlier run, for an ``active_only`` agent, and nothing else: a rule the
|
||||
operator wrote stays, however alike (NetOrk/netork#2693). ``ok`` where
|
||||
nothing was opened. Where the firewall itself does not say who wrote a
|
||||
rule, the driver keeps :mod:`~napalm_device_types.opened_ports`' record."""
|
||||
...
|
||||
|
||||
|
||||
class PackageProxyMixin:
|
||||
"""Point the device's package manager at a caching proxy."""
|
||||
|
||||
@@ -0,0 +1,274 @@
|
||||
"""The record of the firewall rules netOrk opened on a host (NetOrk/netork#2693).
|
||||
|
||||
ufw, iptables and firewalld do not say who wrote a rule: a rule netOrk added to let an
|
||||
agent's server through looks exactly like one the operator wrote. To close it again --
|
||||
when a Zabbix agent becomes active only, say, and listens on no port any more -- a
|
||||
driver needs to know which rules are netOrk's. So a driver that opens a port in one of
|
||||
them records the rule in :data:`OPENED_PORTS_RECORD`, a file only root may write, and
|
||||
**only when the firewall did not have the rule before**: an identical rule the operator
|
||||
wrote earlier is never recorded, and so never removed. Closing removes exactly the
|
||||
recorded rules and leaves every other one in place; what it left for the same port is
|
||||
reported (:func:`revoked_output`). Rules opened before a driver recorded them have no
|
||||
line here and stay, reported.
|
||||
|
||||
**The line.** One rule per line, whitespace-separated, read strictly::
|
||||
|
||||
v1 <purpose> <backend> <proto> <port> <source> # ufw, iptables
|
||||
v1 <purpose> firewalld <proto> <port> <source> <zone> <runtime|permanent>
|
||||
|
||||
``purpose`` says which agent opened it (``zabbix-agent``, ``snmp``), ``source`` is a
|
||||
network in its normal form (``10.0.0.1/32``). A line that is not exactly that is
|
||||
reported and never acted on; it stays in the file.
|
||||
|
||||
**The file.** It is read only when the directory and the file are root's, are not
|
||||
writable by anyone else and are what they claim to be (no symbolic link): a record
|
||||
someone else could have written could name the operator's rules.
|
||||
|
||||
What is the same on every host and needs no I/O lives here: the line, reading it,
|
||||
the shell that records a rule, and ufw's commands, which napalm-linux and
|
||||
napalm-proxmox share. A driver runs them as root.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import ipaddress
|
||||
import re
|
||||
from typing import Literal, TypedDict, cast
|
||||
|
||||
#: Where a host keeps the rules netOrk opened, root's and outside every account's home.
|
||||
OPENED_PORTS_DIRECTORY = "/var/lib/netork"
|
||||
OPENED_PORTS_RECORD = f"{OPENED_PORTS_DIRECTORY}/opened-ports"
|
||||
|
||||
#: The purposes the drivers record their rules under.
|
||||
ZABBIX_AGENT_PURPOSE = "zabbix-agent"
|
||||
SNMP_PURPOSE = "snmp"
|
||||
|
||||
Backend = Literal["ufw", "iptables", "firewalld"]
|
||||
_BACKENDS = ("ufw", "iptables", "firewalld")
|
||||
|
||||
_PURPOSE = re.compile(r"^[a-z][a-z0-9-]{0,31}$")
|
||||
_ZONE = re.compile(r"^[A-Za-z0-9_-]{1,32}$")
|
||||
#: What :func:`record_opened_rule_command` puts between double quotes: the line's own
|
||||
#: characters, and ``$z`` for a zone the shell loops over.
|
||||
_RECORDABLE = re.compile(r"^v1( (\$z|[A-Za-z0-9./:_-]+))+$")
|
||||
|
||||
|
||||
class OpenedRuleDict(TypedDict):
|
||||
"""One rule netOrk opened, as its record line says."""
|
||||
|
||||
purpose: str
|
||||
backend: Backend
|
||||
proto: Literal["tcp", "udp"]
|
||||
port: int
|
||||
#: The network in its normal form, ``10.0.0.1/32``.
|
||||
source: str
|
||||
#: firewalld's zone; "" for ufw and iptables.
|
||||
zone: str
|
||||
#: firewalld: the permanent configuration, not the runtime one. True for the others.
|
||||
permanent: bool
|
||||
|
||||
|
||||
class OpenedPortsRecordDict(TypedDict):
|
||||
"""What :func:`parse_opened_ports_record` read."""
|
||||
|
||||
rules: list[OpenedRuleDict]
|
||||
#: Lines that are not exactly a rule: reported, never acted on.
|
||||
unknown: list[str]
|
||||
#: Why the record was not read at all; "" when it was, or when there is none.
|
||||
problem: str
|
||||
|
||||
|
||||
def opened_rule_line(rule: OpenedRuleDict) -> str:
|
||||
"""The record's line for *rule*."""
|
||||
fields = ["v1", rule["purpose"], rule["backend"], rule["proto"], str(rule["port"])]
|
||||
fields.append(rule["source"])
|
||||
if rule["backend"] == "firewalld":
|
||||
fields += [rule["zone"], "permanent" if rule["permanent"] else "runtime"]
|
||||
return " ".join(fields)
|
||||
|
||||
|
||||
def _rule(line: str) -> OpenedRuleDict | None:
|
||||
"""The rule *line* says, or None where it is not exactly one."""
|
||||
fields = line.split(" ")
|
||||
if len(fields) < 6 or fields[0] != "v1" or fields[2] not in _BACKENDS:
|
||||
return None
|
||||
backend = fields[2]
|
||||
if len(fields) != (8 if backend == "firewalld" else 6):
|
||||
return None
|
||||
purpose, proto, port, source = fields[1], fields[3], fields[4], fields[5]
|
||||
if not _PURPOSE.match(purpose) or proto not in ("tcp", "udp"):
|
||||
return None
|
||||
if not port.isdigit() or not 0 < int(port) < 65536 or port != str(int(port)):
|
||||
return None
|
||||
try:
|
||||
if str(ipaddress.ip_network(source)) != source or "/" not in source:
|
||||
return None
|
||||
except ValueError:
|
||||
return None
|
||||
zone, permanent = "", True
|
||||
if backend == "firewalld":
|
||||
zone, scope = fields[6], fields[7]
|
||||
if not _ZONE.match(zone) or scope not in ("runtime", "permanent"):
|
||||
return None
|
||||
permanent = scope == "permanent"
|
||||
return {
|
||||
"purpose": purpose,
|
||||
"backend": cast(Backend, backend),
|
||||
"proto": cast(Literal["tcp", "udp"], proto),
|
||||
"port": int(port),
|
||||
"source": source,
|
||||
"zone": zone,
|
||||
"permanent": permanent,
|
||||
}
|
||||
|
||||
|
||||
def read_opened_ports_command() -> str:
|
||||
"""The shell, as root, that prints owner, mode and kind of the directory and the
|
||||
record, then the record; nothing where there is no record."""
|
||||
return (
|
||||
f"if [ -e {OPENED_PORTS_RECORD} ] || [ -L {OPENED_PORTS_RECORD} ]; then"
|
||||
f" stat -c '%u %a %F' {OPENED_PORTS_DIRECTORY} {OPENED_PORTS_RECORD}"
|
||||
f" && cat {OPENED_PORTS_RECORD}; fi"
|
||||
)
|
||||
|
||||
|
||||
def _untrusted(stat_line: str, kind: str) -> str:
|
||||
"""Why the path *stat_line* describes may not be trusted; "" where it may."""
|
||||
parts = stat_line.split(" ", 2)
|
||||
if len(parts) != 3 or not parts[1].isdigit():
|
||||
return "owner and mode unknown"
|
||||
owner, mode, actual = parts
|
||||
if actual != kind:
|
||||
return f"not a {kind}"
|
||||
if owner != "0":
|
||||
return "not root's"
|
||||
if int(mode, 8) & 0o022:
|
||||
return "writable by others than root"
|
||||
return ""
|
||||
|
||||
|
||||
def parse_opened_ports_record(output: str) -> OpenedPortsRecordDict:
|
||||
"""The rules the output of :func:`read_opened_ports_command` names.
|
||||
|
||||
Nothing at all where the directory or the record is not root's alone; lines that
|
||||
are not exactly a rule go to ``unknown``.
|
||||
"""
|
||||
if not output.strip():
|
||||
return {"rules": [], "unknown": [], "problem": ""}
|
||||
lines = output.split("\n")
|
||||
for path, stat_line, kind in (
|
||||
(OPENED_PORTS_DIRECTORY, lines[0], "directory"),
|
||||
(OPENED_PORTS_RECORD, lines[1] if len(lines) > 1 else "", "regular file"),
|
||||
):
|
||||
why = _untrusted(stat_line.strip(), kind)
|
||||
if why:
|
||||
return {"rules": [], "unknown": [], "problem": f"{path}: {why}; not read"}
|
||||
rules: list[OpenedRuleDict] = []
|
||||
unknown: list[str] = []
|
||||
for line in lines[2:]:
|
||||
if not line.strip():
|
||||
continue
|
||||
rule = _rule(line)
|
||||
if rule is None:
|
||||
unknown.append(line)
|
||||
else:
|
||||
rules.append(rule)
|
||||
return {"rules": rules, "unknown": unknown, "problem": ""}
|
||||
|
||||
|
||||
def opened_rules_text(lines: list[str]) -> str:
|
||||
"""The record holding *lines*, as a driver writes it back after closing rules."""
|
||||
return "".join(f"{line}\n" for line in lines)
|
||||
|
||||
|
||||
def record_opened_rule_command(line: str) -> str:
|
||||
"""The shell, as root, that appends *line* to the record, creating root's
|
||||
directory and file where they are missing.
|
||||
|
||||
*line* is :func:`opened_rule_line`'s, where firewalld's zone may be ``$z``, the
|
||||
variable of a shell loop over the zones.
|
||||
|
||||
:raises ValueError: for anything else.
|
||||
"""
|
||||
if not _RECORDABLE.match(line):
|
||||
raise ValueError(f"not a record line: {line!r}")
|
||||
return (
|
||||
f"install -d -m 755 -o root -g root {OPENED_PORTS_DIRECTORY}"
|
||||
f" && printf '%s\\n' \"{line}\" >> {OPENED_PORTS_RECORD}"
|
||||
f" && chmod 644 {OPENED_PORTS_RECORD}"
|
||||
)
|
||||
|
||||
|
||||
def _ufw_rule(source: str, port: int, proto: str) -> str:
|
||||
return f"from {source} to any port {port} proto {proto}"
|
||||
|
||||
|
||||
def ufw_allow_recorded_command(source: str, port: int, proto: str, purpose: str) -> str:
|
||||
"""The shell, as root, that lets *source* reach *proto*/*port* in ufw and records
|
||||
the rule when ufw added it.
|
||||
|
||||
ufw answers "Skipping adding existing rule" for a rule it had -- someone else's,
|
||||
which is not recorded -- and "Rule added" (active) or "Rules updated" (inactive)
|
||||
for a new one. ``LC_ALL=C`` keeps those words English.
|
||||
"""
|
||||
line = opened_rule_line(
|
||||
{
|
||||
"purpose": purpose,
|
||||
"backend": "ufw",
|
||||
"proto": cast(Literal["tcp", "udp"], proto),
|
||||
"port": port,
|
||||
"source": source,
|
||||
"zone": "",
|
||||
"permanent": True,
|
||||
}
|
||||
)
|
||||
return (
|
||||
f'{{ o=$(LC_ALL=C ufw allow {_ufw_rule(source, port, proto)} 2>&1) && echo "$o"'
|
||||
f' && case "$o" in *Skipping*) ;;'
|
||||
f" *'Rule added'*|*'Rules updated'*) {record_opened_rule_command(line)};; esac; }}"
|
||||
)
|
||||
|
||||
|
||||
def ufw_delete_command(rule: OpenedRuleDict) -> str:
|
||||
"""The shell, as root, that deletes *rule* from ufw."""
|
||||
return f"LC_ALL=C ufw delete allow {_ufw_rule(rule['source'], rule['port'], rule['proto'])}"
|
||||
|
||||
|
||||
def revoked_output(
|
||||
removed: list[OpenedRuleDict], *, unknown: list[str], left: int, proto: str, port: int
|
||||
) -> str:
|
||||
"""What closing said: the rules it *removed*, the record lines it could not read,
|
||||
and the *left* rules for *proto*/*port* that netOrk did not record."""
|
||||
parts = []
|
||||
if removed:
|
||||
sources = ", ".join(sorted({r["source"] for r in removed}))
|
||||
ports = ", ".join(sorted({f"{r['proto']}/{r['port']}" for r in removed}))
|
||||
parts.append(f"removed the rules netOrk opened for {ports} from {sources}")
|
||||
else:
|
||||
parts.append("netOrk recorded no rule it opened; nothing removed")
|
||||
if unknown:
|
||||
parts.append(f"record lines not understood, left alone: {'; '.join(unknown)}")
|
||||
if left:
|
||||
parts.append(
|
||||
f"{left} rule(s) for {proto}/{port} that netOrk did not record are left in place"
|
||||
" -- the operator's, or opened before netOrk recorded its rules"
|
||||
)
|
||||
return "; ".join(parts)
|
||||
|
||||
|
||||
__all__ = [
|
||||
"OPENED_PORTS_DIRECTORY",
|
||||
"OPENED_PORTS_RECORD",
|
||||
"SNMP_PURPOSE",
|
||||
"ZABBIX_AGENT_PURPOSE",
|
||||
"OpenedPortsRecordDict",
|
||||
"OpenedRuleDict",
|
||||
"opened_rule_line",
|
||||
"opened_rules_text",
|
||||
"parse_opened_ports_record",
|
||||
"read_opened_ports_command",
|
||||
"record_opened_rule_command",
|
||||
"revoked_output",
|
||||
"ufw_allow_recorded_command",
|
||||
"ufw_delete_command",
|
||||
]
|
||||
@@ -0,0 +1,187 @@
|
||||
"""The record of the firewall rules netOrk opened on a host (NetOrk/netork#2693)."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import pytest
|
||||
|
||||
from napalm_device_types.opened_ports import (
|
||||
OPENED_PORTS_RECORD,
|
||||
OpenedRuleDict,
|
||||
opened_rule_line,
|
||||
opened_rules_text,
|
||||
parse_opened_ports_record,
|
||||
read_opened_ports_command,
|
||||
record_opened_rule_command,
|
||||
revoked_output,
|
||||
ufw_allow_recorded_command,
|
||||
ufw_delete_command,
|
||||
)
|
||||
|
||||
UFW: OpenedRuleDict = {
|
||||
"purpose": "zabbix-agent",
|
||||
"backend": "ufw",
|
||||
"proto": "tcp",
|
||||
"port": 10050,
|
||||
"source": "10.40.100.254/32",
|
||||
"zone": "",
|
||||
"permanent": True,
|
||||
}
|
||||
FIREWALLD: OpenedRuleDict = {**UFW, "backend": "firewalld", "zone": "public", "permanent": False}
|
||||
|
||||
ROOT_DIR = "0 755 directory"
|
||||
ROOT_FILE = "0 644 regular file"
|
||||
|
||||
|
||||
def _read(*lines: str, directory: str = ROOT_DIR, record: str = ROOT_FILE) -> str:
|
||||
return "\n".join([directory, record, *lines]) + "\n"
|
||||
|
||||
|
||||
class TestTheLine:
|
||||
def test_ufw(self):
|
||||
assert opened_rule_line(UFW) == "v1 zabbix-agent ufw tcp 10050 10.40.100.254/32"
|
||||
|
||||
def test_firewalld_names_zone_and_configuration(self):
|
||||
assert opened_rule_line(FIREWALLD) == (
|
||||
"v1 zabbix-agent firewalld tcp 10050 10.40.100.254/32 public runtime"
|
||||
)
|
||||
|
||||
def test_a_line_reads_back_as_the_rule(self):
|
||||
for rule in (UFW, FIREWALLD, {**UFW, "backend": "iptables", "source": "2001:db8::/64"}):
|
||||
record = parse_opened_ports_record(_read(opened_rule_line(rule)))
|
||||
assert record["rules"] == [rule]
|
||||
assert record["unknown"] == []
|
||||
assert record["problem"] == ""
|
||||
|
||||
|
||||
class TestStrictReading:
|
||||
@pytest.mark.parametrize(
|
||||
"line",
|
||||
[
|
||||
"v2 zabbix-agent ufw tcp 10050 10.0.0.1/32",
|
||||
"v1 zabbix-agent nft tcp 10050 10.0.0.1/32",
|
||||
"v1 zabbix-agent ufw icmp 10050 10.0.0.1/32",
|
||||
"v1 zabbix-agent ufw tcp 0 10.0.0.1/32",
|
||||
"v1 zabbix-agent ufw tcp 70000 10.0.0.1/32",
|
||||
"v1 zabbix-agent ufw tcp 10050 10.0.0.1",
|
||||
"v1 zabbix-agent ufw tcp 10050 10.0.0.0/8;reboot",
|
||||
"v1 zabbix-agent ufw tcp 10050 any",
|
||||
"v1 Zabbix_Agent ufw tcp 10050 10.0.0.1/32",
|
||||
"v1 zabbix-agent ufw tcp 10050 10.0.0.1/32 public runtime",
|
||||
"v1 zabbix-agent firewalld tcp 10050 10.0.0.1/32",
|
||||
"v1 zabbix-agent firewalld tcp 10050 10.0.0.1/32 $(id) runtime",
|
||||
"v1 zabbix-agent firewalld tcp 10050 10.0.0.1/32 public sometimes",
|
||||
"v1 zabbix-agent ufw tcp 10050 10.0.0.1/32",
|
||||
],
|
||||
)
|
||||
def test_a_line_that_is_not_exactly_a_rule_is_not_acted_on(self, line):
|
||||
record = parse_opened_ports_record(_read(line))
|
||||
|
||||
assert record["rules"] == []
|
||||
assert record["unknown"] == [line]
|
||||
|
||||
def test_blank_lines_are_neither(self):
|
||||
record = parse_opened_ports_record(_read("", opened_rule_line(UFW), " "))
|
||||
|
||||
assert record["rules"] == [UFW]
|
||||
assert record["unknown"] == []
|
||||
|
||||
def test_no_record_is_no_rules(self):
|
||||
record = parse_opened_ports_record("")
|
||||
|
||||
assert record == {"rules": [], "unknown": [], "problem": ""}
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
("directory", "record", "why"),
|
||||
[
|
||||
("1000 755 directory", ROOT_FILE, "not root's"),
|
||||
("0 775 directory", ROOT_FILE, "writable"),
|
||||
(ROOT_DIR, "1000 644 regular file", "not root's"),
|
||||
(ROOT_DIR, "0 666 regular file", "writable"),
|
||||
(ROOT_DIR, "0 777 symbolic link", "not a regular file"),
|
||||
("0 755 symbolic link", ROOT_FILE, "not a directory"),
|
||||
],
|
||||
)
|
||||
def test_a_record_others_could_have_written_is_not_read(self, directory, record, why):
|
||||
read = parse_opened_ports_record(
|
||||
_read(opened_rule_line(UFW), directory=directory, record=record)
|
||||
)
|
||||
|
||||
assert read["rules"] == []
|
||||
assert why in read["problem"]
|
||||
|
||||
def test_a_read_that_says_nothing_about_owner_and_mode_is_not_trusted(self):
|
||||
read = parse_opened_ports_record("v1 zabbix-agent ufw tcp 10050 10.0.0.1/32\n")
|
||||
|
||||
assert read["rules"] == []
|
||||
assert read["problem"]
|
||||
|
||||
|
||||
class TestCommands:
|
||||
def test_reading_says_owner_mode_and_kind_of_the_directory_and_the_file(self):
|
||||
command = read_opened_ports_command()
|
||||
|
||||
assert "stat -c '%u %a %F' /var/lib/netork " + OPENED_PORTS_RECORD in command
|
||||
assert f"cat {OPENED_PORTS_RECORD}" in command
|
||||
assert "exit" not in command
|
||||
|
||||
def test_recording_creates_root_s_directory_and_appends_the_line(self):
|
||||
command = record_opened_rule_command(opened_rule_line(UFW))
|
||||
|
||||
assert command.startswith("install -d -m 755 -o root -g root /var/lib/netork")
|
||||
assert f"printf '%s\\n' \"{opened_rule_line(UFW)}\" >> {OPENED_PORTS_RECORD}" in command
|
||||
assert f"chmod 644 {OPENED_PORTS_RECORD}" in command
|
||||
|
||||
def test_recording_takes_a_firewalld_zone_from_the_shell(self):
|
||||
line = opened_rule_line({**FIREWALLD, "zone": "$z"})
|
||||
|
||||
assert '"v1 zabbix-agent firewalld tcp 10050 10.40.100.254/32 $z runtime"' in (
|
||||
record_opened_rule_command(line)
|
||||
)
|
||||
|
||||
@pytest.mark.parametrize("line", ['v1 "; rm -rf /', "v1 `id`", "v1 a\nb", "v1 $(id)"])
|
||||
def test_recording_refuses_what_is_not_a_line(self, line):
|
||||
with pytest.raises(ValueError):
|
||||
record_opened_rule_command(line)
|
||||
|
||||
def test_ufw_records_a_rule_only_when_ufw_added_it(self):
|
||||
command = ufw_allow_recorded_command("10.40.100.254/32", 10050, "tcp", "zabbix-agent")
|
||||
|
||||
assert "LC_ALL=C ufw allow from 10.40.100.254/32 to any port 10050 proto tcp" in command
|
||||
# ufw says "Skipping adding existing rule" for a rule it had: someone else's.
|
||||
assert "*Skipping*) ;;" in command
|
||||
assert "*'Rule added'*|*'Rules updated'*)" in command
|
||||
assert opened_rule_line(UFW) in command
|
||||
assert "exit" not in command
|
||||
|
||||
def test_ufw_delete(self):
|
||||
assert ufw_delete_command(UFW) == (
|
||||
"LC_ALL=C ufw delete allow from 10.40.100.254/32 to any port 10050 proto tcp"
|
||||
)
|
||||
|
||||
def test_rules_text_keeps_what_it_is_given_one_per_line(self):
|
||||
assert opened_rules_text([]) == ""
|
||||
assert opened_rules_text(["a", "b"]) == "a\nb\n"
|
||||
|
||||
|
||||
class TestReport:
|
||||
def test_removed_rules_are_named(self):
|
||||
output = revoked_output([UFW], unknown=[], left=0, proto="tcp", port=10050)
|
||||
|
||||
assert "removed" in output
|
||||
assert "10.40.100.254/32" in output
|
||||
|
||||
def test_without_a_recorded_rule_it_says_so(self):
|
||||
assert "netOrk recorded no rule" in revoked_output(
|
||||
[], unknown=[], left=0, proto="tcp", port=10050
|
||||
)
|
||||
|
||||
def test_rules_netork_did_not_record_are_reported_not_removed(self):
|
||||
output = revoked_output([], unknown=[], left=2, proto="tcp", port=10050)
|
||||
|
||||
assert "2 rule(s) for tcp/10050" in output
|
||||
assert "left in place" in output
|
||||
|
||||
def test_lines_it_could_not_read_are_reported(self):
|
||||
output = revoked_output([], unknown=["v9 x"], left=0, proto="tcp", port=10050)
|
||||
|
||||
assert "v9 x" in output
|
||||
@@ -407,6 +407,41 @@ class TestZabbixAgentMixin:
|
||||
assert [s["step"] for s in result["steps"]] == ["install", "configure", "firewall", "start"]
|
||||
assert "active only" in result["steps"][2]["output"]
|
||||
|
||||
def test_an_active_only_agent_has_the_driver_revoke_what_netork_opened(self):
|
||||
"""NetOrk/netork#2693: a rule an earlier passive install opened is closed."""
|
||||
agent = _Agent()
|
||||
agent._revoke_zabbix_agent_sources = lambda settings: ( # type: ignore[attr-defined]
|
||||
agent.calls.append(("revoke", settings["listen_port"]))
|
||||
or {"ok": True, "output": "removed tcp/10050"}
|
||||
)
|
||||
|
||||
result = agent.configure_zabbix_agent(ACTIVE_ONLY)
|
||||
|
||||
assert result["success"] is True
|
||||
assert ("revoke", ACTIVE_ONLY["listen_port"]) in agent.calls
|
||||
assert not [c for c in agent.calls if c[0] == "firewall"]
|
||||
assert result["steps"][2]["output"] == "removed tcp/10050"
|
||||
|
||||
def test_a_driver_that_cannot_tell_its_rules_apart_changes_nothing_and_says_so(self):
|
||||
agent = _Agent()
|
||||
|
||||
result = agent.configure_zabbix_agent(ACTIVE_ONLY)
|
||||
|
||||
assert result["success"] is True
|
||||
assert "cannot tell" in result["steps"][2]["output"]
|
||||
|
||||
def test_a_revoke_that_fails_starts_nothing(self):
|
||||
agent = _Agent()
|
||||
agent._revoke_zabbix_agent_sources = lambda settings: { # type: ignore[attr-defined]
|
||||
"ok": False,
|
||||
"output": "ufw: permission denied",
|
||||
}
|
||||
|
||||
result = agent.configure_zabbix_agent(ACTIVE_ONLY)
|
||||
|
||||
assert result["success"] is False
|
||||
assert ("restart", "zabbix-agent") not in agent.calls
|
||||
|
||||
def test_a_closed_firewall_starts_nothing(self):
|
||||
agent = _Agent(refuse=frozenset({"firewall"}))
|
||||
|
||||
|
||||
Reference in new issue
Block a user