fix(snmp): open udp/161 in firewalld, not behind it #79
No files matched your search
@@ -47,6 +47,13 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
|
|||||||
### Changed
|
### Changed
|
||||||
- Needs napalm-device-types 4.35.0.
|
- Needs napalm-device-types 4.35.0.
|
||||||
|
|
||||||
|
### Fixed
|
||||||
|
- `configure_snmp_agent()` opens udp/161 on a host running firewalld (Oracle Linux, RHEL,
|
||||||
|
Fedora): a rich rule per allowed source in the default zone and every active zone, at
|
||||||
|
runtime and permanently, without a reload. It used to insert an iptables rule there,
|
||||||
|
which firewalld's own reject overrides, so the fix reported the port open while SNMP
|
||||||
|
stayed blocked (#77).
|
||||||
|
|
||||||
## [0.17.0] - 2026-11-04
|
## [0.17.0] - 2026-11-04
|
||||||
|
|
||||||
### Added
|
### Added
|
||||||
|
|||||||
@@ -0,0 +1,80 @@
|
|||||||
|
"""The SNMP agent a fix sets up: net-snmp's configuration and the firewall rule for it."""
|
||||||
|
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
import ipaddress
|
||||||
|
import re
|
||||||
|
from shlex import quote as _shlex_quote
|
||||||
|
|
||||||
|
from napalm_device_types.models import SnmpAgentSettingsDict
|
||||||
|
|
||||||
|
#: Where net-snmp reads its configuration, and how each package manager installs it.
|
||||||
|
_SNMPD_CONF = "/etc/snmp/snmpd.conf"
|
||||||
|
_SNMP_INSTALL = {
|
||||||
|
"apt": (
|
||||||
|
"apt-get update -y >/dev/null 2>&1; "
|
||||||
|
"DEBIAN_FRONTEND=noninteractive apt-get install -y snmpd snmp 2>&1"
|
||||||
|
),
|
||||||
|
"dnf": "dnf install -y net-snmp net-snmp-utils 2>&1",
|
||||||
|
"yum": "yum install -y net-snmp net-snmp-utils 2>&1",
|
||||||
|
"apk": "apk add --no-cache net-snmp net-snmp-tools 2>&1",
|
||||||
|
"pacman": "pacman -Sy --noconfirm net-snmp 2>&1",
|
||||||
|
}
|
||||||
|
#: What may stand in an snmpd.conf value: no whitespace, no quote, no comment.
|
||||||
|
_SNMP_WORD = re.compile(r"^[^\s\"#]+$")
|
||||||
|
|
||||||
|
|
||||||
|
def _source(value: str) -> str:
|
||||||
|
"""An allowed source as an address or network, or ValueError."""
|
||||||
|
return str(ipaddress.ip_network(value.strip(), strict=False))
|
||||||
|
|
||||||
|
|
||||||
|
#: The zones a firewalld rule must reach: the default one, which takes every interface
|
||||||
|
#: in no zone (a WireGuard ``wg0``), and each zone holding an interface or a source.
|
||||||
|
_FIREWALLD_ZONES = (
|
||||||
|
"$( { firewall-cmd --get-default-zone;"
|
||||||
|
" firewall-cmd --get-active-zones | grep -v '^[[:space:]]'; } | sort -u )"
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
def firewalld_allow_snmp(sources: list[str]) -> str:
|
||||||
|
"""The shell that opens udp/161 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.
|
||||||
|
"""
|
||||||
|
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'
|
||||||
|
)
|
||||||
|
for scope in ("", "--permanent "):
|
||||||
|
zone = f'firewall-cmd {scope}--zone="$z"'
|
||||||
|
steps.append(
|
||||||
|
f"{{ {zone} --query-rich-rule={rule} >/dev/null 2>&1"
|
||||||
|
f" || {zone} --add-rich-rule={rule}; }}"
|
||||||
|
)
|
||||||
|
return f"for z in {_FIREWALLD_ZONES}; do {' && '.join(steps)} || exit 1; done"
|
||||||
|
|
||||||
|
|
||||||
|
def render_snmpd_conf(settings: SnmpAgentSettingsDict) -> str:
|
||||||
|
"""net-snmp's configuration for *settings*: read-only v2c, per allowed source."""
|
||||||
|
community = settings["community"]
|
||||||
|
if not _SNMP_WORD.match(community):
|
||||||
|
raise ValueError("the community must be one word without quotes or #")
|
||||||
|
listen = settings.get("listen")
|
||||||
|
lines = [f"agentAddress udp:{listen + ':' if listen else ''}161"]
|
||||||
|
sources = [_source(s) for s in settings.get("allowed_sources", [])]
|
||||||
|
lines += [f"rocommunity {community} {s}" for s in sources] or [f"rocommunity {community}"]
|
||||||
|
for key, directive, value in (
|
||||||
|
("location", "sysLocation", settings.get("location", "")),
|
||||||
|
("contact", "sysContact", settings.get("contact", "")),
|
||||||
|
):
|
||||||
|
if value:
|
||||||
|
if "\n" in value:
|
||||||
|
raise ValueError(f"{key} must be one line")
|
||||||
|
lines.append(f"{directive} {value}")
|
||||||
|
return "\n".join(lines) + "\n"
|
||||||
+12
-37
@@ -84,6 +84,13 @@ from napalm_linux._readings import LinuxProcessReadingsMixin
|
|||||||
from napalm_linux._routes import IP_ROUTE_COMMANDS, IpRoute, parse_ip_route, with_length
|
from napalm_linux._routes import IP_ROUTE_COMMANDS, IpRoute, parse_ip_route, with_length
|
||||||
from napalm_linux._rpm import RPM_QUERY_COMMAND, parse_rpm_query
|
from napalm_linux._rpm import RPM_QUERY_COMMAND, parse_rpm_query
|
||||||
from napalm_linux._shell import expect_for, prepare_shell, sudo_without_password
|
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._sudo_history import LinuxSudoHistoryMixin
|
||||||
|
|
||||||
logger = logging.getLogger("napalm_linux")
|
logger = logging.getLogger("napalm_linux")
|
||||||
@@ -258,44 +265,7 @@ def _arm_vendor_from_model(model: str) -> str:
|
|||||||
return " ".join(brand)
|
return " ".join(brand)
|
||||||
|
|
||||||
|
|
||||||
#: Where net-snmp reads its configuration, and how each package manager installs it.
|
|
||||||
_SNMPD_CONF = "/etc/snmp/snmpd.conf"
|
|
||||||
_SNMP_INSTALL = {
|
|
||||||
"apt": (
|
|
||||||
"apt-get update -y >/dev/null 2>&1; "
|
|
||||||
"DEBIAN_FRONTEND=noninteractive apt-get install -y snmpd snmp 2>&1"
|
|
||||||
),
|
|
||||||
"dnf": "dnf install -y net-snmp net-snmp-utils 2>&1",
|
|
||||||
"yum": "yum install -y net-snmp net-snmp-utils 2>&1",
|
|
||||||
"apk": "apk add --no-cache net-snmp net-snmp-tools 2>&1",
|
|
||||||
"pacman": "pacman -Sy --noconfirm net-snmp 2>&1",
|
|
||||||
}
|
|
||||||
_USER_NAME = re.compile(r"^[a-z_][a-z0-9_.\-]{0,31}$")
|
_USER_NAME = re.compile(r"^[a-z_][a-z0-9_.\-]{0,31}$")
|
||||||
#: What may stand in an snmpd.conf value: no whitespace, no quote, no comment.
|
|
||||||
_SNMP_WORD = re.compile(r"^[^\s\"#]+$")
|
|
||||||
|
|
||||||
|
|
||||||
def _source(value: str) -> str:
|
|
||||||
"""An allowed source as an address or network, or ValueError."""
|
|
||||||
return str(ipaddress.ip_network(value.strip(), strict=False))
|
|
||||||
|
|
||||||
|
|
||||||
def render_snmpd_conf(settings: SnmpAgentSettingsDict) -> str:
|
|
||||||
"""net-snmp's configuration for *settings*: read-only v2c, per allowed source."""
|
|
||||||
community = settings["community"]
|
|
||||||
if not _SNMP_WORD.match(community):
|
|
||||||
raise ValueError("the community must be one word without quotes or #")
|
|
||||||
listen = settings.get("listen")
|
|
||||||
lines = [f"agentAddress udp:{listen + ':' if listen else ''}161"]
|
|
||||||
sources = [_source(s) for s in settings.get("allowed_sources", [])]
|
|
||||||
lines += [f"rocommunity {community} {s}" for s in sources] or [f"rocommunity {community}"]
|
|
||||||
for key, directive in (("location", "sysLocation"), ("contact", "sysContact")):
|
|
||||||
value = settings.get(key, "")
|
|
||||||
if value:
|
|
||||||
if "\n" in value:
|
|
||||||
raise ValueError(f"{key} must be one line")
|
|
||||||
lines.append(f"{directive} {value}")
|
|
||||||
return "\n".join(lines) + "\n"
|
|
||||||
|
|
||||||
|
|
||||||
class LinuxDriver(
|
class LinuxDriver(
|
||||||
@@ -1829,6 +1799,11 @@ class LinuxDriver(
|
|||||||
sources = [_source(s) for s in settings.get("allowed_sources", [])]
|
sources = [_source(s) for s in settings.get("allowed_sources", [])]
|
||||||
if not sources:
|
if not sources:
|
||||||
return {"ok": True, "output": "no sources given; firewall unchanged"}
|
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"):
|
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]
|
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"):
|
elif self._send("command -v iptables 2>/dev/null"):
|
||||||
|
|||||||
@@ -20,7 +20,7 @@
|
|||||||
"napalm_linux.linux"
|
"napalm_linux.linux"
|
||||||
],
|
],
|
||||||
"python_file_lines": {
|
"python_file_lines": {
|
||||||
"napalm_linux/linux.py": 2034
|
"napalm_linux/linux.py": 2009
|
||||||
},
|
},
|
||||||
"untyped_public": []
|
"untyped_public": []
|
||||||
}
|
}
|
||||||
@@ -69,17 +69,22 @@ def driver():
|
|||||||
class TestSnmpAgentSteps:
|
class TestSnmpAgentSteps:
|
||||||
SETTINGS = {"community": "c0mm", "allowed_sources": ["10.0.0.5"]}
|
SETTINGS = {"community": "c0mm", "allowed_sources": ["10.0.0.5"]}
|
||||||
|
|
||||||
def _record(self, driver, status=0, firewall="ufw"):
|
def _record(self, driver, status=0, firewall="ufw", firewalld=False):
|
||||||
ran: list[str] = []
|
ran: list[str] = []
|
||||||
|
|
||||||
def sudo_status(command, read_timeout=100):
|
def sudo_status(command, read_timeout=100):
|
||||||
ran.append(command)
|
ran.append(command)
|
||||||
return ("", status)
|
return ("", status)
|
||||||
|
|
||||||
|
def send(command, read_timeout=100):
|
||||||
|
if command == "systemctl is-active firewalld 2>/dev/null":
|
||||||
|
return "active" if firewalld else "inactive"
|
||||||
|
return (
|
||||||
|
f"/usr/sbin/{firewall}" if command == f"command -v {firewall} 2>/dev/null" else ""
|
||||||
|
)
|
||||||
|
|
||||||
driver._sudo_status = sudo_status
|
driver._sudo_status = sudo_status
|
||||||
driver._send = lambda command, read_timeout=100: (
|
driver._send = send
|
||||||
f"/usr/sbin/{firewall}" if command == f"command -v {firewall} 2>/dev/null" else ""
|
|
||||||
)
|
|
||||||
driver._install_file_as_root = MagicMock(
|
driver._install_file_as_root = MagicMock(
|
||||||
return_value=MagicMock(exit_code=0, stdout="", stderr="")
|
return_value=MagicMock(exit_code=0, stdout="", stderr="")
|
||||||
)
|
)
|
||||||
@@ -105,6 +110,88 @@ class TestSnmpAgentSteps:
|
|||||||
|
|
||||||
assert "iptables -I INPUT -s 10.0.0.5/32 -p udp --dport 161 -j ACCEPT" in ran[1]
|
assert "iptables -I INPUT -s 10.0.0.5/32 -p udp --dport 161 -j ACCEPT" in ran[1]
|
||||||
|
|
||||||
|
def test_a_running_firewalld_gets_a_rich_rule_not_an_iptables_one(self, driver):
|
||||||
|
"""An iptables ACCEPT does not lift firewalld's reject: with nftables both
|
||||||
|
tables see the packet, and the drop in either wins (Oracle Linux, RHEL)."""
|
||||||
|
ran = self._record(driver, firewall="iptables", firewalld=True)
|
||||||
|
|
||||||
|
result = driver.configure_snmp_agent(self.SETTINGS)
|
||||||
|
|
||||||
|
assert result["success"] is True
|
||||||
|
assert "iptables" not in ran[1]
|
||||||
|
assert (
|
||||||
|
'rule family="ipv4" source address="10.0.0.5/32" port port="161" protocol="udp" accept'
|
||||||
|
) in ran[1]
|
||||||
|
assert "--permanent" in ran[1]
|
||||||
|
assert "--reload" not in ran[1]
|
||||||
|
|
||||||
|
def test_the_firewalld_rule_goes_to_the_default_and_every_active_zone(self, tmp_path):
|
||||||
|
"""An interface in no zone (a WireGuard wg0) is the default zone's; one in a
|
||||||
|
zone of its own is that zone's. The rule goes in now and stays after a reload."""
|
||||||
|
from napalm_linux._snmp_agent import firewalld_allow_snmp
|
||||||
|
|
||||||
|
log = tmp_path / "calls"
|
||||||
|
fake = tmp_path / "firewall-cmd"
|
||||||
|
fake.write_text(
|
||||||
|
"#!/bin/sh\n"
|
||||||
|
f'echo "$*" >> {log}\n'
|
||||||
|
'case "$*" in\n'
|
||||||
|
" --get-default-zone) echo public ;;\n"
|
||||||
|
' --get-active-zones) printf "docker\\n interfaces: docker0\\n'
|
||||||
|
'public\\n interfaces: enp0s6\\n" ;;\n'
|
||||||
|
" *--query-rich-rule*) exit 1 ;;\n"
|
||||||
|
"esac\n"
|
||||||
|
)
|
||||||
|
fake.chmod(0o755)
|
||||||
|
|
||||||
|
import os
|
||||||
|
import subprocess
|
||||||
|
|
||||||
|
done = subprocess.run(
|
||||||
|
["sh", "-c", firewalld_allow_snmp(["10.0.0.5/32", "fd00::/64"])],
|
||||||
|
env={**os.environ, "PATH": f"{tmp_path}:{os.environ['PATH']}"},
|
||||||
|
capture_output=True,
|
||||||
|
text=True,
|
||||||
|
)
|
||||||
|
|
||||||
|
assert done.returncode == 0, done.stdout + done.stderr
|
||||||
|
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'
|
||||||
|
for zone in ("public", "docker"):
|
||||||
|
for rule in (v4, v6):
|
||||||
|
assert f"--zone={zone} --add-rich-rule={rule}" in adds
|
||||||
|
assert f"--permanent --zone={zone} --add-rich-rule={rule}" in adds
|
||||||
|
assert len(adds) == 8
|
||||||
|
|
||||||
|
def test_a_rule_firewalld_holds_already_is_not_added_twice(self, tmp_path):
|
||||||
|
from napalm_linux._snmp_agent import firewalld_allow_snmp
|
||||||
|
|
||||||
|
log = tmp_path / "calls"
|
||||||
|
fake = tmp_path / "firewall-cmd"
|
||||||
|
fake.write_text(
|
||||||
|
"#!/bin/sh\n"
|
||||||
|
f'echo "$*" >> {log}\n'
|
||||||
|
'case "$*" in\n'
|
||||||
|
" --get-default-zone) echo public ;;\n"
|
||||||
|
" --get-active-zones) ;;\n"
|
||||||
|
"esac\n"
|
||||||
|
)
|
||||||
|
fake.chmod(0o755)
|
||||||
|
|
||||||
|
import os
|
||||||
|
import subprocess
|
||||||
|
|
||||||
|
done = subprocess.run(
|
||||||
|
["sh", "-c", firewalld_allow_snmp(["10.0.0.5/32"])],
|
||||||
|
env={**os.environ, "PATH": f"{tmp_path}:{os.environ['PATH']}"},
|
||||||
|
capture_output=True,
|
||||||
|
text=True,
|
||||||
|
)
|
||||||
|
|
||||||
|
assert done.returncode == 0
|
||||||
|
assert "--add-rich-rule" not in log.read_text()
|
||||||
|
|
||||||
def test_no_sources_change_no_firewall(self, driver):
|
def test_no_sources_change_no_firewall(self, driver):
|
||||||
ran = self._record(driver)
|
ran = self._record(driver)
|
||||||
|
|
||||||
|
|||||||
Reference in new issue
Block a user