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:
Christian Manivong committed 2026-11-26 08:19:19 +01:00
1 parent 04ff633290
commit a3b9e4a02d
8 files changed
+516 -37

No files matched your search

+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"
+148 -3
View File
@@ -10,7 +10,11 @@ from __future__ import annotations
from unittest.mock import MagicMock
import pytest
from napalm_device_types import CommandResult
from napalm_device_types import (
OPENED_PORTS_RECORD,
CommandResult,
read_opened_ports_command,
)
from napalm_linux import LinuxDriver
@@ -41,11 +45,19 @@ class _Host:
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)
@@ -171,7 +183,7 @@ def test_a_distribution_zabbix_publishes_nothing_for_fails_the_install(driver, h
def test_ufw_opens_the_listen_port_for_the_sources(driver, host):
driver.configure_zabbix_agent(SETTINGS)
assert "ufw allow from 10.0.0.5/32 to any port 10050 proto tcp" in host.root
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):
@@ -206,4 +218,137 @@ def test_no_sources_change_no_firewall(driver, host):
def test_the_snmp_rule_is_still_udp_161(driver, host):
driver.configure_snmp_agent({"community": "c0mm", "allowed_sources": ["10.0.0.5"]})
assert "ufw allow from 10.0.0.5/32 to any port 161 proto udp" in host.root
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 == []