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.
This commit is contained in:
1 parent
04ff633290
commit
a3b9e4a02d
8 files changed
+516
-37
No files matched your search
+149
-19
@@ -1,47 +1,177 @@
|
||||
"""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``).
|
||||
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
|
||||
from typing import TYPE_CHECKING, Literal
|
||||
|
||||
from napalm_device_types import FixStepOutcomeDict
|
||||
from napalm_device_types import (
|
||||
OPENED_PORTS_RECORD,
|
||||
FixStepOutcomeDict,
|
||||
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_linux._snmp_agent import _source, firewalld_allow_port
|
||||
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``: the shared firewall step."""
|
||||
"""``_allow_sources`` and ``_revoke_sources``: the shared firewall steps."""
|
||||
|
||||
def _allow_sources(self, allowed: list[str], port: int, proto: str) -> FixStepOutcomeDict:
|
||||
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."""
|
||||
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"}
|
||||
# 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":
|
||||
firewall = self._firewall()
|
||||
if firewall == "firewalld":
|
||||
done = f"{proto}/{port} open in firewalld for {', '.join(sources)}"
|
||||
return self._root_outcome(firewalld_allow_port(sources, port, proto), 60, done)
|
||||
if self._send("command -v ufw 2>/dev/null"):
|
||||
rules = [f"ufw allow from {s} to any port {port} proto {proto}" for s in sources]
|
||||
elif self._send("command -v iptables 2>/dev/null"):
|
||||
rules = [
|
||||
f"{{ iptables -C INPUT -s {s} -p {proto} --dport {port} -j ACCEPT 2>/dev/null"
|
||||
f" || iptables -I INPUT -s {s} -p {proto} --dport {port} -j ACCEPT; }}"
|
||||
for s in 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 _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"]}
|
||||
removed: list[OpenedRuleDict] = []
|
||||
kept: list[str] = []
|
||||
failed: list[str] = []
|
||||
for rule in record["rules"]:
|
||||
if rule["purpose"] == purpose:
|
||||
outcome = self._root_outcome(_remove_command(rule), 30, "")
|
||||
if outcome["ok"]:
|
||||
removed.append(rule)
|
||||
continue
|
||||
failed.append(f"{opened_rule_line(rule)}: {outcome['output']}")
|
||||
kept.append(opened_rule_line(rule))
|
||||
if removed:
|
||||
written = self._install_file_as_root(
|
||||
OPENED_PORTS_RECORD, opened_rules_text(kept + record["unknown"])
|
||||
)
|
||||
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: ...
|
||||
@@ -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.
|
||||
@@ -42,29 +48,73 @@ def firewalld_allow_snmp(sources: list[str]) -> str:
|
||||
return firewalld_allow_port(sources, 161, "udp")
|
||||
|
||||
|
||||
def firewalld_allow_port(sources: list[str], port: int, proto: str) -> str:
|
||||
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}"'
|
||||
f' port port="{port}" protocol="{proto}" 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"]
|
||||
|
||||
@@ -5,7 +5,8 @@ For a host without a container engine (NetOrk/netork#2571). The template install
|
||||
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.
|
||||
whichever firewall runs -- or, for an active-only agent, closes what netOrk opened
|
||||
for it before.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
@@ -13,6 +14,7 @@ from __future__ import annotations
|
||||
from typing import TYPE_CHECKING
|
||||
|
||||
from napalm_device_types import (
|
||||
ZABBIX_AGENT_PURPOSE,
|
||||
FixStepOutcomeDict,
|
||||
ZabbixAgentMixin,
|
||||
ZabbixAgentSettingsDict,
|
||||
@@ -58,7 +60,14 @@ class LinuxZabbixAgentMixin(ZabbixAgentMixin):
|
||||
return {"ok": True, "output": "; ".join(changes)}
|
||||
|
||||
def _allow_zabbix_agent_sources(self, settings: ZabbixAgentSettingsDict) -> FixStepOutcomeDict:
|
||||
return self._allow_sources(settings["allowed_sources"], int(settings["listen_port"]), "tcp")
|
||||
return self._allow_sources(
|
||||
settings["allowed_sources"], int(settings["listen_port"]), "tcp", ZABBIX_AGENT_PURPOSE
|
||||
)
|
||||
|
||||
def _revoke_zabbix_agent_sources(self, settings: ZabbixAgentSettingsDict) -> FixStepOutcomeDict:
|
||||
"""For an active-only agent: remove the 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
|
||||
|
||||
@@ -76,5 +85,7 @@ class LinuxZabbixAgentMixin(ZabbixAgentMixin):
|
||||
def _install_file_as_root(self, path: str, content: str) -> CommandResult: ...
|
||||
|
||||
def _allow_sources(
|
||||
self, allowed: list[str], port: int, proto: str
|
||||
self, allowed: list[str], port: int, proto: str, purpose: str
|
||||
) -> FixStepOutcomeDict: ...
|
||||
|
||||
def _revoke_sources(self, purpose: str, port: int, proto: str) -> FixStepOutcomeDict: ...
|
||||
@@ -30,6 +30,7 @@ from napalm_device_types import (
|
||||
DNF_INSTALLED_CVES_COMMAND,
|
||||
DNF_SECURITY_COMMAND,
|
||||
LLDPCTL_KEYVALUE_COMMAND,
|
||||
SNMP_PURPOSE,
|
||||
AptProxyMixin,
|
||||
ByteStream,
|
||||
CommandResult,
|
||||
@@ -1798,7 +1799,7 @@ class LinuxDriver(
|
||||
return {"ok": True, "output": f"wrote {_SNMPD_CONF}"}
|
||||
|
||||
def _allow_snmp_sources(self, settings: SnmpAgentSettingsDict) -> FixStepOutcomeDict:
|
||||
return self._allow_sources(settings.get("allowed_sources", []), 161, "udp")
|
||||
return self._allow_sources(settings.get("allowed_sources", []), 161, "udp", SNMP_PURPOSE)
|
||||
|
||||
def _start_snmp_agent(self) -> FixStepOutcomeDict:
|
||||
return self._root_outcome(
|
||||
|
||||
Reference in new issue
Block a user