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.
178 lines
7.1 KiB
Python
178 lines
7.1 KiB
Python
"""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,
|
|
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,
|
|
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."""
|
|
|
|
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 _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: ...
|