Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
04ff633290 | ||
|
|
2521f9f462 | ||
|
|
0e1c4e7927 | ||
|
|
98157f3673 | ||
|
|
69c43d3288 | ||
|
|
553b4d5153 | ||
|
|
647a5cc857 | ||
|
|
94badd0e23 | ||
|
|
4db8b05ab4 | ||
|
|
de91b1a918 | ||
|
|
c9a9d532aa | ||
|
|
5f6595d160 | ||
|
|
4ba81cc90e | ||
|
|
92ca800026 | ||
|
|
655d115324 | ||
|
|
6e5b0ea2ec | ||
|
|
bc7162affd | ||
|
|
3683c85f21 | ||
|
|
aab25fb049 | ||
|
|
1d377acc5f | ||
|
|
257efdef8e | ||
|
|
235c1e9a91 | ||
|
|
c2e7ea5789 | ||
|
|
10240c20bb | ||
|
|
78374cfb42 | ||
|
|
ea82d43bd4 | ||
|
|
c532a66260 | ||
|
|
2b153cd61c | ||
|
|
249046512d | ||
|
|
60ccea9a98 | ||
|
|
5c13ce1a8b | ||
|
|
1c8b1b1c60 | ||
|
|
bd17fbd84d | ||
|
|
d03fe2a2ba |
No files matched your search
@@ -7,6 +7,94 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
|
||||
|
||||
## [Unreleased]
|
||||
|
||||
### Added
|
||||
- A native Zabbix agent (napalm-device-types `ZabbixAgentMixin`, NetOrk/netork#2571), for a
|
||||
host without a container engine: `configure_zabbix_agent(settings)` installs
|
||||
`zabbix-agent` from the host's packages, and where they have none and the caller names
|
||||
the server's release line, from Zabbix's repository (`zabbix-release` for Debian, Ubuntu,
|
||||
Raspberry Pi OS and the RHEL family). It writes the caller's values into
|
||||
`/etc/zabbix/zabbix_agentd.conf` (the old file stays as `.bak`), opens tcp/`listen_port`
|
||||
for the allowed sources in firewalld, ufw or iptables, enables and restarts the service.
|
||||
- On an rpm host each package names the source rpm it was built from, as `source_rpm`
|
||||
(`perf` → `kernel`); absent where rpm names none (`gpg-pubkey`). Red Hat lists `perf`,
|
||||
`python3-perf` and `bpftool` in every kernel CVE, and the source is what tells them apart
|
||||
from user space (NetOrk/netork#2394). Not dpkg's `source_package`: netOrk reads that as
|
||||
the name a distribution files its verdicts under, and Oracle's and Red Hat's name the
|
||||
binary.
|
||||
- `get_installed_advisory_cves()` through napalm-device-types' `UpdateMixin` (4.37.0): the
|
||||
CVEs a dnf host's installed security advisories close, per package, read as root from
|
||||
the cache. netOrk reads it where its knowledge base holds no records of the host's
|
||||
release (NetOrk/netork#2394). dnf only; other package managers raise
|
||||
`NotImplementedError`.
|
||||
|
||||
### Changed
|
||||
- Needs napalm-device-types 4.40.0 or later (`ZabbixAgentMixin`).
|
||||
- The SNMP agent's firewall step is the shared `_allow_sources(allowed, port, proto)`; the
|
||||
rules it writes for udp/161 are the same.
|
||||
- `load_replace_candidate` is `None` instead of a method that raises
|
||||
`NotImplementedError`, so a caller that asks whether the driver can replace a
|
||||
configuration gets no. netOrk offered a config restore for these devices that
|
||||
could only fail (NetOrk/netork#2503).
|
||||
- On an rpm host a package's version carries its epoch where it has one
|
||||
(`1:6.2.0-13.el9`), as on a dpkg host. Oracle's and Red Hat's fixes name it, and without
|
||||
it an epoch-1 fix read as newer than every installed build (NetOrk/netork#2394).
|
||||
|
||||
### Fixed
|
||||
- `open_stream(privileged=True)` with a sudo password asks sudo first whether it wants it
|
||||
(`sudo -n sh -c true`). A sudo that does not prompt (NOPASSWD, a cached timestamp) used to
|
||||
get the password on stdin anyway, where it went to the command as the first bytes of the
|
||||
stream: into the Podman API, over `sudo podman system dial-stdio` (NetOrk/netork#818).
|
||||
Such a sudo now gets the command through `sudo -n`, and only one that asks gets the
|
||||
password.
|
||||
|
||||
### Added
|
||||
- `get_time_sync()` and `configure_time_sync()` through napalm-device-types'
|
||||
`PosixTimeSyncMixin` (4.35.0): the host's NTP servers in its client's order, its time zone,
|
||||
whether the clock is synchronised and which client keeps it (chrony, systemd-timesyncd,
|
||||
ntpd, OpenNTPD), read in one round trip as the login user. The zone is set with
|
||||
`timedatectl set-timezone`; chrony's servers go to `/etc/chrony/sources.d/netork.sources`
|
||||
(else a `confdir` or an included file) with every other source commented out,
|
||||
systemd-timesyncd's to `/etc/systemd/timesyncd.conf.d/netork.conf`. The host ends up with
|
||||
exactly the servers given (NetOrk/netork#2361). OpenMediaVault and QNAP inherit it.
|
||||
- `get_running_backups()` through napalm-device-types' `RunningBackupsMixin` (4.34.0): the
|
||||
host's own backups a restart would abort -- a process of restic, resticprofile, autorestic,
|
||||
borg, borgmatic, duplicity, duply, rsnapshot, rdiff-backup, proxmox-backup-client, kopia or
|
||||
btrbk doing a backup, prune, check or copy (not a mount, a restore or a listing), with the
|
||||
systemd service it runs in as its job (a timer's service; none for a cron or a login
|
||||
session), its process id and when it started. One round trip as the login user; a `ps`
|
||||
without `etimes` fails the reading (NetOrk/netork#2318). OpenMediaVault and QNAP inherit it.
|
||||
- `get_log_sources()` through napalm-device-types' `LogSourcesMixin` (4.30.0): the units
|
||||
journald holds entries for and the log files running processes hold open, with the service
|
||||
or container writing each, as root, and without root what the login user may see
|
||||
(NetOrk/netork#2049). OpenMediaVault and QNAP inherit it.
|
||||
- A deleted key can take the password with it (NetOrk/netork#2033): through
|
||||
napalm-device-types' `remove_local_account_keys(..., clear_password=True)` the keys go
|
||||
as the person, the password goes (`usermod -p '*'`), and so do the sudo rule and the
|
||||
admin groups. The account stays open and logs in with its other keys only.
|
||||
|
||||
### Changed
|
||||
- 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
|
||||
|
||||
### Added
|
||||
- Personal accounts follow what the person changes (NetOrk/netork#2013):
|
||||
`add_local_account(..., replaces=[...])` takes the old keys out of the account's key
|
||||
files as the new one goes in, `remove_local_account_keys` takes deleted keys out and
|
||||
leaves the account open, and `add_local_account(..., clear_password=True)` removes the
|
||||
password (`usermod -p '*'`): the account logs in with its key only and has no sudo.
|
||||
Keys the person added on the host stay.
|
||||
|
||||
### Changed
|
||||
- Needs napalm-device-types 4.28.0.
|
||||
|
||||
## [0.16.0] - 2026-11-03
|
||||
|
||||
### Added
|
||||
|
||||
@@ -91,7 +91,7 @@ with Driver(
|
||||
| `get_config()` | ✅ | Returns `ip addr` + `ip route` output |
|
||||
| `ping()` | ✅ | Executes `ping` on the remote host |
|
||||
| `load_merge_candidate()` | ❌ | Not applicable for generic Linux |
|
||||
| `load_replace_candidate()` | ❌ | Not applicable for generic Linux |
|
||||
| `load_replace_candidate()` | ❌ | Not applicable for generic Linux; `None`, so a caller can tell |
|
||||
| `compare_config()` | ❌ | Not applicable for generic Linux |
|
||||
| `commit_config()` | ❌ | Not applicable for generic Linux |
|
||||
| `discard_config()` | ❌ | Not applicable for generic Linux |
|
||||
|
||||
@@ -5,6 +5,13 @@ commands. A locked account is an expired one (``usermod -L -e 1``): PAM's
|
||||
account check refuses it every login, a key's too, where a ``!`` in front of
|
||||
the password -- ``usermod -L`` alone -- stops only the password. Opening it
|
||||
again lifts the expiry and gives the old password back.
|
||||
|
||||
An account whose password is removed (NetOrk/netork#2013) gets ``*`` as its
|
||||
password field, which no hash matches: it logs in with a key only. Not an
|
||||
empty field (``passwd -d``), which pam_unix's ``nullok`` -- on by default on
|
||||
Debian and Ubuntu -- takes as "no password needed" for ``su`` and the console.
|
||||
Not ``!``, which sshd takes for a locked account and refuses a key too where
|
||||
PAM is off (``UsePAM no``). And not the expiry, which is the lock.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
@@ -16,6 +23,8 @@ from napalm_device_types import LocalAccountsMixin
|
||||
|
||||
#: What the password field holds when the account never had a password.
|
||||
_NO_PASSWORD = frozenset({"", "!", "!!", "!*", "*"})
|
||||
#: The password field of an account that logs in with a key only: no hash matches it.
|
||||
_KEY_ONLY = "*"
|
||||
|
||||
|
||||
class LinuxLocalAccountsMixin(LocalAccountsMixin):
|
||||
@@ -53,6 +62,11 @@ class LinuxLocalAccountsMixin(LocalAccountsMixin):
|
||||
def _account_leave_group(self, name: str, group: str, groups: list[str]) -> list[str]:
|
||||
return ["gpasswd", "-d", name, group]
|
||||
|
||||
def _account_clear_password(self, name: str) -> list[list[str]]:
|
||||
# usermod -p leaves the expiry -- the lock -- alone, and dates the change today,
|
||||
# so pam_unix asks for no new password at the next key login.
|
||||
return [["usermod", "-p", _KEY_ONLY, name]]
|
||||
|
||||
def _shadow(self, name: str) -> list[str]:
|
||||
"""*name*'s shadow entry, split; only the lock and the expiry are looked at.
|
||||
|
||||
|
||||
@@ -0,0 +1,47 @@
|
||||
"""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``).
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from typing import TYPE_CHECKING
|
||||
|
||||
from napalm_device_types import FixStepOutcomeDict
|
||||
|
||||
from napalm_linux._snmp_agent import _source, firewalld_allow_port
|
||||
|
||||
|
||||
class OpenPortMixin:
|
||||
"""``_allow_sources``: the shared firewall step."""
|
||||
|
||||
def _allow_sources(self, allowed: list[str], port: int, proto: 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."""
|
||||
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":
|
||||
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
|
||||
]
|
||||
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)
|
||||
|
||||
if TYPE_CHECKING: # pragma: no cover - the driver's
|
||||
|
||||
def _send(self, command: str, read_timeout: float = 100) -> str: ...
|
||||
|
||||
def _root_outcome(self, command: str, timeout: float, done: str) -> FixStepOutcomeDict: ...
|
||||
@@ -0,0 +1,15 @@
|
||||
"""What napalm-device-types implements for any POSIX host over ``run_command``.
|
||||
|
||||
The driver supplies ``run_command``; the readings, their parses and the writes are
|
||||
the mixins': scheduled jobs (cron, anacron, systemd timers) and time sync (chrony,
|
||||
systemd-timesyncd, ``timedatectl``). Their default paths are Debian's, which a
|
||||
Linux host shares.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from napalm_device_types import PosixScheduledJobsMixin, PosixTimeSyncMixin
|
||||
|
||||
|
||||
class LinuxPosixMixin(PosixScheduledJobsMixin, PosixTimeSyncMixin):
|
||||
"""Scheduled jobs and time sync of the host, over the driver's ``run_command``."""
|
||||
@@ -0,0 +1,42 @@
|
||||
"""Readings of the host's processes: listening sockets, log sources, running backups.
|
||||
|
||||
The first two commands are napalm-device-types' and read-only. Root only widens
|
||||
what they see -- ``ss`` names every process behind a socket, ``/proc/<pid>/fd`` shows every
|
||||
process's open files -- so both go through sudo where the driver can, and as the
|
||||
login user where it cannot; the mixins then say the reading is not ``attributed``.
|
||||
The running backups need no root: every process's command line and cgroup are
|
||||
readable to the login user (``_running_backups``).
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from typing import TYPE_CHECKING
|
||||
|
||||
from napalm_device_types import ListeningSocketsMixin, LogSourcesMixin
|
||||
|
||||
from napalm_linux._running_backups import LinuxRunningBackupsMixin
|
||||
|
||||
#: Seconds either reading may take; a busy host lists thousands of descriptors.
|
||||
_READ_TIMEOUT = 60
|
||||
|
||||
|
||||
class LinuxProcessReadingsMixin(ListeningSocketsMixin, LogSourcesMixin, LinuxRunningBackupsMixin):
|
||||
"""The transports for ``get_listening_sockets`` and ``get_log_sources``, and
|
||||
``get_running_backups``."""
|
||||
|
||||
if TYPE_CHECKING: # pragma: no cover - the driver's own, declared for type checkers
|
||||
|
||||
def _send(self, command: str, read_timeout: float = 100) -> str: ...
|
||||
|
||||
def _run_privileged(self, command: str, timeout: float = 100) -> str: ...
|
||||
|
||||
def _read_as_root_if_possible(self, command: str, privileged: bool) -> str:
|
||||
if privileged:
|
||||
return self._run_privileged(command, _READ_TIMEOUT)
|
||||
return self._send(command, read_timeout=_READ_TIMEOUT)
|
||||
|
||||
def _run_listening_sockets_command(self, command: str, *, privileged: bool) -> str:
|
||||
return self._read_as_root_if_possible(command, privileged)
|
||||
|
||||
def _run_log_sources_command(self, command: str, *, privileged: bool) -> str:
|
||||
return self._read_as_root_if_possible(command, privileged)
|
||||
@@ -0,0 +1,69 @@
|
||||
"""The packages rpm has on a dnf or yum host: the query and its parse."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from typing import NotRequired
|
||||
|
||||
from napalm_device_types.models import PackageDict
|
||||
|
||||
#: One line per package, the version as ``[epoch:]version-release`` the way dpkg
|
||||
#: writes it: the epoch only where the package has one. Oracle's and Red Hat's
|
||||
#: fixes name it (``1:6.2.0-13.el9``), and without it an epoch-1 fix reads as newer
|
||||
#: than every installed build (NetOrk/netork#2394). The source rpm before the
|
||||
#: summary, which stays last and keeps whatever it contains.
|
||||
RPM_QUERY_COMMAND = (
|
||||
"rpm -qa --queryformat "
|
||||
"'%{NAME}\\t%|EPOCH?{%{EPOCH}:}:{}|%{VERSION}-%{RELEASE}\\t%{SIZE}\\t%{SOURCERPM}"
|
||||
"\\t%{SUMMARY}\\n'"
|
||||
" 2>/dev/null"
|
||||
)
|
||||
|
||||
|
||||
class RpmPackageDict(PackageDict):
|
||||
"""An rpm package with the name of the source rpm it was built from.
|
||||
|
||||
``perf``, ``python3-perf`` and ``bpftool`` come from ``kernel``, and Red Hat
|
||||
lists them in every kernel CVE; their source is what tells them apart from
|
||||
user space (NetOrk/netork#2394). Deliberately not dpkg's ``source_package``:
|
||||
netOrk reads that as the name a distribution files its verdicts under, which
|
||||
holds for Debian and not for Oracle or Red Hat, whose records name the binary.
|
||||
Absent where rpm names none (``gpg-pubkey``).
|
||||
"""
|
||||
|
||||
source_rpm: NotRequired[str]
|
||||
|
||||
|
||||
def source_rpm_name(sourcerpm: str) -> str | None:
|
||||
"""``kernel-5.14.0-687.66.1.el9_8.src.rpm`` → ``kernel``; ``None`` for ``(none)``."""
|
||||
stem = sourcerpm.strip()
|
||||
for suffix in (".src.rpm", ".nosrc.rpm"):
|
||||
if stem.endswith(suffix):
|
||||
stem = stem.removesuffix(suffix)
|
||||
break
|
||||
else:
|
||||
return None
|
||||
name, *version_release = stem.rsplit("-", 2)
|
||||
return name if len(version_release) == 2 and name else None
|
||||
|
||||
|
||||
def parse_rpm_query(out: str, source: str) -> list[PackageDict]:
|
||||
"""The packages in ``RPM_QUERY_COMMAND``'s output, each marked as *source*'s."""
|
||||
packages: list[PackageDict] = []
|
||||
for line in out.splitlines():
|
||||
parts = line.split("\t", 4)
|
||||
if len(parts) < 2:
|
||||
continue
|
||||
size = parts[2].strip() if len(parts) > 2 else ""
|
||||
package: RpmPackageDict = {
|
||||
"name": parts[0].strip(),
|
||||
"version": parts[1].strip(),
|
||||
"installed": True,
|
||||
"description": parts[4].strip() if len(parts) > 4 else "",
|
||||
"size": int(size) if size.isdigit() else 0,
|
||||
"source": source,
|
||||
}
|
||||
built_from = source_rpm_name(parts[3]) if len(parts) > 3 else None
|
||||
if built_from:
|
||||
package["source_rpm"] = built_from
|
||||
packages.append(package)
|
||||
return packages
|
||||
@@ -0,0 +1,188 @@
|
||||
"""The host's own backups a restart would abort (napalm-device-types' ``RunningBackupsMixin``).
|
||||
|
||||
A file-level backup on a Linux host is a process of a backup tool -- restic, borg,
|
||||
borgmatic, duplicity, rsnapshot and the like -- started by a systemd timer, a cron
|
||||
line or by hand. One round trip, as the login user (every process's command line
|
||||
and cgroup are readable to it), reads the host's clock, the processes with their
|
||||
age, and each one's cgroup; the systemd service a backup runs in is its job, the
|
||||
service a timer starts, which is how netOrk shows the timer's scheduled job.
|
||||
|
||||
What a tool is doing is read from its subcommand: ``restic backup`` is a backup,
|
||||
``restic forget`` a prune, ``restic mount`` none. ``borg serve`` counts: it is the
|
||||
receiving end of another host's backup.
|
||||
|
||||
A ``ps`` without ``etimes`` (busybox) fails the reading rather than report nothing.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import posixpath
|
||||
import re
|
||||
from typing import TYPE_CHECKING, NamedTuple
|
||||
|
||||
from napalm_device_types import RunningBackupDict, RunningBackupKind, RunningBackupsMixin
|
||||
|
||||
#: ``NOW <epoch>``, one ``pid<TAB>elapsed<TAB>cgroup<TAB>args`` line per process, ``END``.
|
||||
RUNNING_BACKUPS_COMMAND = (
|
||||
'echo "NOW $(date +%s)"; '
|
||||
"out=$(LC_ALL=C ps -eo pid=,etimes=,args= 2>/dev/null) || exit 1; "
|
||||
"printf '%s\\n' \"$out\" | while read -r pid et args; do "
|
||||
'printf \'%s\\t%s\\t%s\\t%s\\n\' "$pid" "$et" '
|
||||
'"$(tail -n 1 /proc/$pid/cgroup 2>/dev/null)" "$args"; '
|
||||
"done; echo END"
|
||||
)
|
||||
|
||||
_READ_TIMEOUT = 30
|
||||
|
||||
|
||||
class _Tool(NamedTuple):
|
||||
#: subcommand -> what it does; None: not a backup (a mount, a restore, a listing).
|
||||
subcommands: dict[str, RunningBackupKind | None]
|
||||
#: What the tool does when no listed subcommand is given; None: nothing to stop for.
|
||||
default: RunningBackupKind | None = None
|
||||
|
||||
|
||||
_RESTIC: dict[str, RunningBackupKind | None] = {
|
||||
"backup": "backup",
|
||||
"forget": "prune",
|
||||
"prune": "prune",
|
||||
"check": "verify",
|
||||
"copy": "sync",
|
||||
}
|
||||
_BORG: dict[str, RunningBackupKind | None] = {
|
||||
"create": "backup",
|
||||
"serve": "backup",
|
||||
"prune": "prune",
|
||||
"compact": "prune",
|
||||
"check": "verify",
|
||||
}
|
||||
|
||||
_TOOLS: dict[str, _Tool] = {
|
||||
"restic": _Tool(_RESTIC),
|
||||
"resticprofile": _Tool(_RESTIC),
|
||||
"autorestic": _Tool({"backup": "backup", "forget": "prune", "check": "verify"}),
|
||||
"borg": _Tool(_BORG),
|
||||
"borgbackup": _Tool(_BORG),
|
||||
"borgmatic": _Tool(
|
||||
{"extract": None, "list": None, "info": None, "restore": None, "mount": None},
|
||||
"backup",
|
||||
),
|
||||
"duplicity": _Tool(
|
||||
{
|
||||
"restore": None,
|
||||
"collection-status": None,
|
||||
"list-current-files": None,
|
||||
"verify": "verify",
|
||||
"cleanup": "prune",
|
||||
"remove-older-than": "prune",
|
||||
"remove-all-but-n-full": "prune",
|
||||
"remove-all-inc-of-but-n-full": "prune",
|
||||
},
|
||||
"backup",
|
||||
),
|
||||
"duply": _Tool(
|
||||
{
|
||||
"backup": "backup",
|
||||
"bkp": "backup",
|
||||
"incr": "backup",
|
||||
"full": "backup",
|
||||
"purge": "prune",
|
||||
"verify": "verify",
|
||||
}
|
||||
),
|
||||
"rsnapshot": _Tool({}, "backup"),
|
||||
"rdiff-backup": _Tool(
|
||||
{"-r": None, "--restore-as-of": None, "restore": None, "list": None}, "backup"
|
||||
),
|
||||
"proxmox-backup-client": _Tool({"backup": "backup"}),
|
||||
"kopia": _Tool({"snapshot": "backup", "maintenance": "prune"}),
|
||||
"btrbk": _Tool({"run": "backup", "resume": "backup", "snapshot": "backup", "prune": "prune"}),
|
||||
}
|
||||
|
||||
#: What may stand before the tool on its command line: an interpreter or a wrapper,
|
||||
#: their options and plain numbers or durations ("nice -n 19", "timeout 3h").
|
||||
_WRAPPERS = frozenset(
|
||||
{"sh", "bash", "dash", "env", "nice", "ionice", "nocache", "timeout", "chrt", "perl"}
|
||||
)
|
||||
_PYTHON = re.compile(r"python[0-9.]*")
|
||||
_ARGUMENT = re.compile(r"-.*|\d+[smhd]?")
|
||||
|
||||
#: Services that start other people's commands: a backup run from them has no job of its own.
|
||||
_NOT_JOBS = frozenset(
|
||||
{"cron.service", "crond.service", "cronie.service", "anacron.service", "atd.service"}
|
||||
| {"ssh.service", "sshd.service"}
|
||||
)
|
||||
|
||||
|
||||
def _tool(args: str) -> tuple[_Tool, list[str]] | None:
|
||||
"""The backup tool *args* runs and its arguments, or None for any other process."""
|
||||
words = args.split()
|
||||
for index, word in enumerate(words):
|
||||
name = posixpath.basename(word)
|
||||
if name in _TOOLS:
|
||||
return _TOOLS[name], words[index + 1 :]
|
||||
if not (name in _WRAPPERS or _PYTHON.fullmatch(name) or _ARGUMENT.fullmatch(word)):
|
||||
return None
|
||||
return None
|
||||
|
||||
|
||||
def backup_kind(args: str) -> RunningBackupKind | None:
|
||||
"""What the process with command line *args* is doing for a backup, or None."""
|
||||
found = _tool(args)
|
||||
if found is None:
|
||||
return None
|
||||
tool, rest = found
|
||||
for word in rest:
|
||||
if word in tool.subcommands:
|
||||
return tool.subcommands[word]
|
||||
return tool.default
|
||||
|
||||
|
||||
def _job(cgroup: str) -> str | None:
|
||||
"""The systemd service a process runs in, when that service is its own job."""
|
||||
unit = posixpath.basename(cgroup.rsplit(":", 1)[-1])
|
||||
return unit if unit.endswith(".service") and unit not in _NOT_JOBS else None
|
||||
|
||||
|
||||
def _clock(lines: list[str]) -> int:
|
||||
if not lines or not lines[0].startswith("NOW "):
|
||||
raise RuntimeError("get_running_backups: the host did not say what time it is")
|
||||
try:
|
||||
return int(lines[0].split()[1])
|
||||
except (IndexError, ValueError) as exc:
|
||||
raise RuntimeError(f"get_running_backups: not a time: {lines[0]!r}") from exc
|
||||
|
||||
|
||||
def parse_running_backups(output: str) -> list[RunningBackupDict]:
|
||||
"""The backups in ``RUNNING_BACKUPS_COMMAND``'s *output*.
|
||||
|
||||
:raises RuntimeError: when the reading was cut short or never had the clock.
|
||||
"""
|
||||
lines = output.splitlines()
|
||||
now = _clock(lines)
|
||||
if lines[-1].strip() != "END":
|
||||
raise RuntimeError("get_running_backups: the process list was cut short")
|
||||
found: list[RunningBackupDict] = []
|
||||
for line in lines[1:-1]:
|
||||
parts = line.split("\t", 3)
|
||||
if len(parts) != 4 or not parts[1].isdigit():
|
||||
continue
|
||||
pid, elapsed, cgroup, args = parts
|
||||
kind = backup_kind(args)
|
||||
if kind is not None:
|
||||
since = now - int(elapsed)
|
||||
found.append(
|
||||
{"kind": kind, "job": _job(cgroup), "task": pid, "guests": [], "since": since}
|
||||
)
|
||||
return found
|
||||
|
||||
|
||||
class LinuxRunningBackupsMixin(RunningBackupsMixin):
|
||||
"""``get_running_backups`` over the driver's own session, as the login user."""
|
||||
|
||||
if TYPE_CHECKING: # pragma: no cover - the driver's own, declared for type checkers
|
||||
|
||||
def _send(self, command: str, read_timeout: float = 100) -> str: ...
|
||||
|
||||
def get_running_backups(self) -> list[RunningBackupDict]:
|
||||
return parse_running_backups(self._send(RUNNING_BACKUPS_COMMAND, _READ_TIMEOUT))
|
||||
@@ -7,6 +7,8 @@ import re
|
||||
from shlex import quote
|
||||
from typing import Any
|
||||
|
||||
from napalm_device_types import run_on_transport
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
#: The end of a command's output when nothing better is known: a line that looks
|
||||
@@ -54,6 +56,30 @@ def sudo_without_password(command: str) -> str:
|
||||
return f"sudo -n sh -c {quote(body)}{tail}"
|
||||
|
||||
|
||||
#: Whether sudo runs a command for the login user without a password now: in
|
||||
#: the shape every privileged command takes (``sh -c``), so a sudoers rule that
|
||||
#: covers one covers the other.
|
||||
SUDO_ASKS_NOTHING = "sudo -n sh -c true"
|
||||
|
||||
|
||||
def unprompted_stream(
|
||||
transport: Any, command: str, line: str, prefix: bytes | None
|
||||
) -> tuple[str, bytes | None]:
|
||||
"""The line and stdin prefix a privileged stream of *command* starts with.
|
||||
|
||||
With a sudo password (*prefix*) sudo is asked first whether it wants it: a
|
||||
sudo that does not prompt -- NOPASSWD, a cached timestamp -- would leave the
|
||||
password on stdin, where the stream's own data follows it, the Podman API
|
||||
over ``sudo podman system dial-stdio`` say (NetOrk/netork#818). Such a sudo
|
||||
gets *command* through ``sudo -n`` and no password; one that asks gets it.
|
||||
"""
|
||||
if not prefix:
|
||||
return line, prefix
|
||||
if run_on_transport(transport, SUDO_ASKS_NOTHING, timeout=15).exit_code == 0:
|
||||
return f"sudo -n sh -c {quote(command)}", None
|
||||
return line, prefix
|
||||
|
||||
|
||||
#: Sent before anything else in the interactive session (NetOrk/netork#1039):
|
||||
#: the shell writes no history file and records nothing more. The leading space
|
||||
#: keeps this line itself out of a history under ``HISTCONTROL=ignorespace``;
|
||||
|
||||
@@ -0,0 +1,85 @@
|
||||
"""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."""
|
||||
return firewalld_allow_port(sources, 161, "udp")
|
||||
|
||||
|
||||
def firewalld_allow_port(sources: list[str], port: int, proto: str) -> 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.
|
||||
"""
|
||||
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'
|
||||
)
|
||||
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"
|
||||
@@ -0,0 +1,80 @@
|
||||
"""A native Zabbix agent, the steps of napalm-device-types' ``ZabbixAgentMixin``.
|
||||
|
||||
For a host without a container engine (NetOrk/netork#2571). The template installs
|
||||
``zabbix-agent`` -- the C agent every distribution that packages Zabbix has, and
|
||||
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.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from typing import TYPE_CHECKING
|
||||
|
||||
from napalm_device_types import (
|
||||
FixStepOutcomeDict,
|
||||
ZabbixAgentMixin,
|
||||
ZabbixAgentSettingsDict,
|
||||
zabbix_agent_config,
|
||||
zabbix_repository_command,
|
||||
)
|
||||
|
||||
if TYPE_CHECKING: # pragma: no cover
|
||||
from napalm_device_types import CommandResult
|
||||
|
||||
CONFIG = "/etc/zabbix/zabbix_agentd.conf"
|
||||
|
||||
|
||||
def _failed(result: CommandResult, what: str) -> FixStepOutcomeDict:
|
||||
detail = (result.stderr or result.stdout or "").strip()[-300:]
|
||||
return {"ok": False, "output": f"{what}: {detail or result.exit_code}"}
|
||||
|
||||
|
||||
class LinuxZabbixAgentMixin(ZabbixAgentMixin):
|
||||
"""``zabbix-agent`` from the distribution, or else from Zabbix's repository."""
|
||||
|
||||
def _add_zabbix_repository(self, release: str) -> FixStepOutcomeDict:
|
||||
os_release = self.run_command("cat /etc/os-release", timeout=30)
|
||||
try:
|
||||
command = zabbix_repository_command(os_release.stdout, release)
|
||||
except ValueError as exc:
|
||||
return {"ok": False, "output": str(exc)}
|
||||
return self._root_outcome(command, 300, f"Zabbix {release} repository added")
|
||||
|
||||
def _write_zabbix_agent_config(self, settings: ZabbixAgentSettingsDict) -> FixStepOutcomeDict:
|
||||
read = self.run_command(f"cat {CONFIG}", privileged=True, timeout=30)
|
||||
if read.exit_code:
|
||||
return _failed(read, f"reading {CONFIG}")
|
||||
text, changes = zabbix_agent_config(read.stdout, settings)
|
||||
if not changes:
|
||||
return {"ok": True, "output": f"{CONFIG} already says it"}
|
||||
kept = self._root_outcome(f"cp -p {CONFIG} {CONFIG}.bak", 30, "")
|
||||
if not kept["ok"]:
|
||||
return kept
|
||||
written = self._install_file_as_root(CONFIG, text)
|
||||
if written.exit_code:
|
||||
return _failed(written, f"writing {CONFIG}")
|
||||
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")
|
||||
|
||||
if TYPE_CHECKING: # pragma: no cover - the driver's
|
||||
|
||||
def run_command(
|
||||
self,
|
||||
command: str,
|
||||
*,
|
||||
privileged: bool = False,
|
||||
timeout: float = 60,
|
||||
stdin: bytes | None = None,
|
||||
) -> CommandResult: ...
|
||||
|
||||
def _root_outcome(self, command: str, timeout: float, done: str) -> FixStepOutcomeDict: ...
|
||||
|
||||
def _install_file_as_root(self, path: str, content: str) -> CommandResult: ...
|
||||
|
||||
def _allow_sources(
|
||||
self, allowed: list[str], port: int, proto: str
|
||||
) -> FixStepOutcomeDict: ...
|
||||
+39
-94
@@ -27,6 +27,7 @@ from napalm.base.exceptions import ConnectionClosedException, ConnectionExceptio
|
||||
from napalm.base.netmiko_helpers import netmiko_args
|
||||
from napalm_device_types import (
|
||||
APT_UPGRADABLE_COMMAND,
|
||||
DNF_INSTALLED_CVES_COMMAND,
|
||||
DNF_SECURITY_COMMAND,
|
||||
LLDPCTL_KEYVALUE_COMMAND,
|
||||
AptProxyMixin,
|
||||
@@ -38,11 +39,9 @@ from napalm_device_types import (
|
||||
HostFirewallMixin,
|
||||
HostStatusMixin,
|
||||
KernelFactsMixin,
|
||||
ListeningSocketsMixin,
|
||||
LldpNeighborDict,
|
||||
OpenSshServerMixin,
|
||||
OSDriver,
|
||||
PosixScheduledJobsMixin,
|
||||
ServiceClustersMixin,
|
||||
ServicePackagesMixin,
|
||||
SnmpAgentMixin,
|
||||
@@ -53,6 +52,7 @@ from napalm_device_types import (
|
||||
lldp_neighbors,
|
||||
open_stream_on_transport,
|
||||
parse_apt_upgradable,
|
||||
parse_dnf_installed_cves,
|
||||
parse_dnf_security,
|
||||
parse_lldpctl_keyvalue,
|
||||
run_fix_steps,
|
||||
@@ -78,10 +78,20 @@ from netmiko.exceptions import NetmikoAuthenticationException, NetmikoTimeoutExc
|
||||
from napalm_linux._dpkg import DPKG_QUERY_COMMAND, parse_dpkg_query
|
||||
from napalm_linux._hostname import HostnameMixin
|
||||
from napalm_linux._local_accounts import LinuxLocalAccountsMixin
|
||||
from napalm_linux._open_port import OpenPortMixin
|
||||
from napalm_linux._ping import parse_ping, ping_command
|
||||
from napalm_linux._posix import LinuxPosixMixin
|
||||
from napalm_linux._readings import LinuxProcessReadingsMixin
|
||||
from napalm_linux._routes import IP_ROUTE_COMMANDS, IpRoute, parse_ip_route, with_length
|
||||
from napalm_linux._shell import expect_for, prepare_shell, sudo_without_password
|
||||
from napalm_linux._rpm import RPM_QUERY_COMMAND, parse_rpm_query
|
||||
from napalm_linux._shell import expect_for, prepare_shell, sudo_without_password, unprompted_stream
|
||||
from napalm_linux._snmp_agent import (
|
||||
_SNMP_INSTALL,
|
||||
_SNMPD_CONF,
|
||||
render_snmpd_conf,
|
||||
)
|
||||
from napalm_linux._sudo_history import LinuxSudoHistoryMixin
|
||||
from napalm_linux._zabbix_agent import LinuxZabbixAgentMixin
|
||||
|
||||
logger = logging.getLogger("napalm_linux")
|
||||
|
||||
@@ -255,62 +265,27 @@ def _arm_vendor_from_model(model: str) -> str:
|
||||
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}$")
|
||||
#: 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(
|
||||
LinuxSudoHistoryMixin,
|
||||
LinuxLocalAccountsMixin,
|
||||
SnmpAgentMixin,
|
||||
LinuxZabbixAgentMixin,
|
||||
OpenPortMixin,
|
||||
EnsurePackageMixin,
|
||||
AptProxyMixin,
|
||||
KernelFactsMixin,
|
||||
ServicePackagesMixin,
|
||||
ListeningSocketsMixin,
|
||||
LinuxProcessReadingsMixin,
|
||||
HostFirewallMixin,
|
||||
VirtualIpsMixin,
|
||||
ServiceClustersMixin,
|
||||
SystemIdentityMixin,
|
||||
OpenSshServerMixin,
|
||||
SystemdServicesMixin,
|
||||
PosixScheduledJobsMixin,
|
||||
LinuxPosixMixin,
|
||||
HostStatusMixin,
|
||||
ContainerEngineMixin,
|
||||
HostnameMixin,
|
||||
@@ -585,12 +560,12 @@ class LinuxDriver(
|
||||
def open_stream(self, command: str, *, privileged: bool = False) -> ByteStream:
|
||||
"""Start *command* on an exec channel and return a stream to it.
|
||||
|
||||
A privileged stream with a sudo password starts with that password, for
|
||||
``sudo -S``; a sudo that does not prompt leaves it for *command*. Write
|
||||
nothing to such a stream that must not follow the password, as
|
||||
``_PRIVILEGED_STDIN`` says for ``run_command``.
|
||||
A privileged stream with a sudo password gets it first only from a sudo
|
||||
that asks for it; one that does not would hand it to *command* as the
|
||||
stream's first bytes (``unprompted_stream``, NetOrk/netork#818).
|
||||
"""
|
||||
line, prefix = self._privileged(command, privileged)
|
||||
line, prefix = unprompted_stream(self._transport(), command, line, prefix)
|
||||
return open_stream_on_transport(self._transport(), line, stdin_prefix=prefix)
|
||||
|
||||
def reboot_host(self) -> None:
|
||||
@@ -1036,8 +1011,8 @@ class LinuxDriver(
|
||||
def load_merge_candidate(self, filename: str = None, config: str = None) -> None: # type: ignore[override]
|
||||
raise NotImplementedError("Config management is not supported for Linux hosts")
|
||||
|
||||
def load_replace_candidate(self, filename: str = None, config: str = None) -> None: # type: ignore[override]
|
||||
raise NotImplementedError("Config management is not supported for Linux hosts")
|
||||
#: No config replace, switched off so a capability check says no (NetOrk/netork#2503).
|
||||
load_replace_candidate = None # type: ignore[assignment]
|
||||
|
||||
def compare_config(self) -> str:
|
||||
raise NotImplementedError("Config management is not supported for Linux hosts")
|
||||
@@ -1086,18 +1061,9 @@ class LinuxDriver(
|
||||
return self.run_command(f"sh -c {_shlex_quote(command)}", timeout=120).stdout
|
||||
|
||||
# ------------------------------------------------------------------
|
||||
# ListeningSocketsMixin – the transport for get_listening_sockets
|
||||
# HostFirewallMixin – the transport for get_host_firewall
|
||||
# ------------------------------------------------------------------
|
||||
|
||||
def _run_listening_sockets_command(self, command: str, *, privileged: bool) -> str:
|
||||
"""The transport for ``ListeningSocketsMixin.get_listening_sockets``.
|
||||
|
||||
Read-only either way; root only so that ``ss`` names every process.
|
||||
"""
|
||||
if privileged:
|
||||
return self._run_privileged(command, 60)
|
||||
return self._send(command, read_timeout=60)
|
||||
|
||||
def _run_host_firewall_command(self, command: str, *, privileged: bool) -> str:
|
||||
"""The transport for ``HostFirewallMixin.get_host_firewall``: an exec channel.
|
||||
|
||||
@@ -1147,28 +1113,7 @@ class LinuxDriver(
|
||||
return parse_dpkg_query(self._send(DPKG_QUERY_COMMAND))
|
||||
|
||||
def _get_packages_rpm(self) -> list[PackageDict]:
|
||||
out = self._send(
|
||||
"rpm -qa --queryformat "
|
||||
"'%{NAME}\\t%{VERSION}-%{RELEASE}\\t%{SIZE}\\t%{SUMMARY}\\n' 2>/dev/null"
|
||||
)
|
||||
packages: list[PackageDict] = []
|
||||
for line in out.splitlines():
|
||||
parts = line.split("\t", 3)
|
||||
if len(parts) < 2:
|
||||
continue
|
||||
packages.append(
|
||||
{
|
||||
"name": parts[0].strip(),
|
||||
"version": parts[1].strip(),
|
||||
"installed": True,
|
||||
"description": parts[3].strip() if len(parts) > 3 else "",
|
||||
"size": int(parts[2].strip())
|
||||
if len(parts) > 2 and parts[2].strip().isdigit()
|
||||
else 0,
|
||||
"source": self._pkg_manager or "rpm",
|
||||
}
|
||||
)
|
||||
return packages
|
||||
return parse_rpm_query(self._send(RPM_QUERY_COMMAND), self._pkg_manager or "rpm")
|
||||
|
||||
def _get_packages_apk(self) -> list[PackageDict]:
|
||||
out = self._send("apk info -v 2>/dev/null")
|
||||
@@ -1486,6 +1431,19 @@ class LinuxDriver(
|
||||
except ValueError:
|
||||
return None
|
||||
|
||||
def get_installed_advisory_cves(self) -> dict[str, list[str]]:
|
||||
"""The CVEs the installed advisories close, per package: dnf only, as root and
|
||||
from the cache like the security read, with a longer budget for its 90 000
|
||||
lines on Oracle Linux 9 (NetOrk/netork#2394)."""
|
||||
if self._pkg_manager != "dnf":
|
||||
raise NotImplementedError(f"No installed advisories for {self._pkg_manager!r}")
|
||||
cmd = DNF_INSTALLED_CVES_COMMAND
|
||||
output, status = _split_status(self._run_privileged(f"{cmd}; echo {_RC_MARKER}$?", 300))
|
||||
if status != 0:
|
||||
hint = f"\n{_SUDO_PASSWORD_HINT}" if "password is required" in output else ""
|
||||
raise RuntimeError(f"dnf updateinfo failed (exit {status}): {output[-200:]}{hint}")
|
||||
return parse_dnf_installed_cves(output)
|
||||
|
||||
def refresh_available_updates(self) -> dict[str, Any]:
|
||||
"""Refresh the package index (apt-get update, dnf makecache, apk update)."""
|
||||
cmd = _REFRESH.get(self._pkg_manager or "")
|
||||
@@ -1840,20 +1798,7 @@ class LinuxDriver(
|
||||
return {"ok": True, "output": f"wrote {_SNMPD_CONF}"}
|
||||
|
||||
def _allow_snmp_sources(self, settings: SnmpAgentSettingsDict) -> FixStepOutcomeDict:
|
||||
sources = [_source(s) for s in settings.get("allowed_sources", [])]
|
||||
if not sources:
|
||||
return {"ok": True, "output": "no sources given; firewall unchanged"}
|
||||
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]
|
||||
elif self._send("command -v iptables 2>/dev/null"):
|
||||
rules = [
|
||||
f"{{ iptables -C INPUT -s {s} -p udp --dport 161 -j ACCEPT 2>/dev/null"
|
||||
f" || iptables -I INPUT -s {s} -p udp --dport 161 -j ACCEPT; }}"
|
||||
for s in sources
|
||||
]
|
||||
else:
|
||||
return {"ok": True, "output": "no host firewall (ufw, iptables); nothing to open"}
|
||||
return self._root_outcome(" && ".join(rules), 30, f"udp/161 open for {', '.join(sources)}")
|
||||
return self._allow_sources(settings.get("allowed_sources", []), 161, "udp")
|
||||
|
||||
def _start_snmp_agent(self) -> FixStepOutcomeDict:
|
||||
return self._root_outcome(
|
||||
|
||||
+2
-2
@@ -4,7 +4,7 @@ build-backend = "setuptools.build_meta"
|
||||
|
||||
[project]
|
||||
name = "napalm-linux"
|
||||
version = "0.16.0"
|
||||
version = "0.17.0"
|
||||
description = "NAPALM driver for generic Linux systems via SSH"
|
||||
readme = "README.md"
|
||||
requires-python = ">=3.12"
|
||||
@@ -34,7 +34,7 @@ classifiers = [
|
||||
]
|
||||
dependencies = [
|
||||
"napalm>=4.0",
|
||||
"napalm-device-types>=4.27.0",
|
||||
"napalm-device-types>=4.40.0", # ZabbixAgentMixin
|
||||
"netmiko>=4.0.0",
|
||||
"paramiko>=5.0.0", # CVE-2026-44405
|
||||
]
|
||||
|
||||
@@ -20,7 +20,7 @@
|
||||
"napalm_linux.linux"
|
||||
],
|
||||
"python_file_lines": {
|
||||
"napalm_linux/linux.py": 2048
|
||||
"napalm_linux/linux.py": 1993
|
||||
},
|
||||
"untyped_public": []
|
||||
}
|
||||
@@ -17,12 +17,14 @@ import pytest
|
||||
from napalm.base.exceptions import ConnectionClosedException
|
||||
|
||||
from napalm_linux import LinuxDriver
|
||||
from napalm_linux._shell import SUDO_ASKS_NOTHING
|
||||
|
||||
|
||||
class FakeChannel:
|
||||
def __init__(self):
|
||||
def __init__(self, exits):
|
||||
self.command = None
|
||||
self.sent = b""
|
||||
self._exits = exits
|
||||
|
||||
def exec_command(self, command):
|
||||
self.command = command
|
||||
@@ -55,21 +57,28 @@ class FakeChannel:
|
||||
return True
|
||||
|
||||
def recv_exit_status(self):
|
||||
return 0
|
||||
return self._exits.get(self.command, 0)
|
||||
|
||||
|
||||
#: The probe a privileged stream sends first, and how a sudo that asks for its
|
||||
#: password answers it.
|
||||
SUDO_PROBE = SUDO_ASKS_NOTHING
|
||||
ASKS = {SUDO_PROBE: 1}
|
||||
|
||||
|
||||
class FakeTransport:
|
||||
def __init__(self):
|
||||
def __init__(self, exits=None):
|
||||
self.channels = []
|
||||
self.exits = ASKS if exits is None else exits
|
||||
|
||||
def open_session(self):
|
||||
self.channels.append(FakeChannel())
|
||||
self.channels.append(FakeChannel(self.exits))
|
||||
return self.channels[-1]
|
||||
|
||||
|
||||
def _driver(*, root=False, sudo_password=None):
|
||||
def _driver(*, root=False, sudo_password=None, exits=None):
|
||||
driver = LinuxDriver("h", "u", "p", optional_args={"sudo_password": sudo_password})
|
||||
transport = FakeTransport()
|
||||
transport = FakeTransport(exits)
|
||||
driver._device = SimpleNamespace(
|
||||
remote_conn_pre=SimpleNamespace(get_transport=lambda: transport)
|
||||
)
|
||||
@@ -166,6 +175,54 @@ def test_a_privileged_stream_gets_the_password_first():
|
||||
assert channel.sent == b"pw\n"
|
||||
|
||||
|
||||
class TestNoPasswordIntoAStream:
|
||||
"""A privileged stream carries data after the password: the Podman API over
|
||||
``sudo podman system dial-stdio`` (NetOrk/netork#818). A sudo that does not ask
|
||||
-- NOPASSWD, a cached timestamp -- would hand the password to the command as
|
||||
the first bytes of that data. So the stream asks sudo first, and sends the
|
||||
password only to a sudo that wants it."""
|
||||
|
||||
def test_sudo_is_asked_first(self):
|
||||
driver, transport = _driver(sudo_password="pw")
|
||||
|
||||
driver.open_stream("podman system dial-stdio", privileged=True)
|
||||
|
||||
assert transport.channels[0].command == SUDO_PROBE
|
||||
assert transport.channels[0].sent == b""
|
||||
|
||||
def test_a_sudo_that_asks_nothing_gets_no_password(self):
|
||||
driver, transport = _driver(sudo_password="pw", exits={})
|
||||
|
||||
driver.open_stream("podman system dial-stdio", privileged=True)
|
||||
|
||||
channel = transport.channels[-1]
|
||||
assert channel.command == "sudo -n sh -c 'podman system dial-stdio'"
|
||||
assert channel.sent == b""
|
||||
|
||||
def test_without_a_password_there_is_nothing_to_ask(self):
|
||||
driver, transport = _driver()
|
||||
|
||||
driver.open_stream("podman system dial-stdio", privileged=True)
|
||||
|
||||
assert [c.command for c in transport.channels] == [
|
||||
"sudo -n sh -c 'podman system dial-stdio'"
|
||||
]
|
||||
|
||||
def test_a_root_login_asks_nothing_either(self):
|
||||
driver, transport = _driver(root=True, sudo_password="pw")
|
||||
|
||||
driver.open_stream("podman system dial-stdio", privileged=True)
|
||||
|
||||
assert [c.command for c in transport.channels] == ["podman system dial-stdio"]
|
||||
|
||||
def test_podman_is_reached_as_root(self):
|
||||
driver, transport = _driver(root=True)
|
||||
|
||||
driver.open_container_engine("podman").open_api()
|
||||
|
||||
assert transport.channels[-1].command == "podman system dial-stdio"
|
||||
|
||||
|
||||
def test_the_container_engine_api_is_a_stream_over_dial_stdio():
|
||||
driver, transport = _driver()
|
||||
|
||||
|
||||
@@ -0,0 +1,17 @@
|
||||
"""The driver cannot replace a device's configuration, and says so by not having the method.
|
||||
|
||||
A ``load_replace_candidate`` that only raises looks like a replace to anyone who asks
|
||||
whether the driver has one: netOrk offered a config restore for these devices that
|
||||
could only fail (NetOrk/netork#2503). ``None`` is how a driver switches off a method
|
||||
it would otherwise inherit, the convention of napalm-device-types and netOrk's
|
||||
capability checks.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from napalm_linux import LinuxDriver
|
||||
|
||||
|
||||
def test_the_driver_has_no_config_replace():
|
||||
assert LinuxDriver.load_replace_candidate is None
|
||||
assert not callable(getattr(LinuxDriver, "load_replace_candidate", None))
|
||||
@@ -69,17 +69,22 @@ def driver():
|
||||
class TestSnmpAgentSteps:
|
||||
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] = []
|
||||
|
||||
def sudo_status(command, read_timeout=100):
|
||||
ran.append(command)
|
||||
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._send = lambda command, read_timeout=100: (
|
||||
f"/usr/sbin/{firewall}" if command == f"command -v {firewall} 2>/dev/null" else ""
|
||||
)
|
||||
driver._send = send
|
||||
driver._install_file_as_root = MagicMock(
|
||||
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]
|
||||
|
||||
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):
|
||||
ran = self._record(driver)
|
||||
|
||||
|
||||
+161
-1
@@ -4,8 +4,10 @@ import re
|
||||
from unittest.mock import MagicMock, patch
|
||||
|
||||
import pytest
|
||||
from napalm_device_types import DNF_INSTALLED_CVES_COMMAND
|
||||
|
||||
from napalm_linux._routes import IpRoute, parse_ip_route
|
||||
from napalm_linux._rpm import source_rpm_name
|
||||
from napalm_linux.linux import (
|
||||
_YUM_SECURITY_COMMAND,
|
||||
LinuxDriver,
|
||||
@@ -1955,6 +1957,58 @@ class TestGetListeningSockets:
|
||||
assert plain.startswith("sh -c '")
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# Log sources: journald units and the log files processes hold open (#2049)
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
_LOGS = (
|
||||
"LOGS_BEGIN\n[journald]\nnginx.service\n"
|
||||
"[open]\n/proc/900/fd/5 /var/log/nginx/access.log\n"
|
||||
"[stat]\n/proc/900/fd/5 2048 1762250200\n"
|
||||
"[cgroups]\n900 0::/system.slice/nginx.service\n"
|
||||
"[comm]\n900 nginx\n"
|
||||
"LOGS_END\n"
|
||||
)
|
||||
|
||||
|
||||
class TestGetLogSources:
|
||||
def _sent(self, driver) -> list[str]:
|
||||
return [c[0][0] for c in driver._device.send_command.call_args_list]
|
||||
|
||||
def test_it_reads_with_the_shared_command_as_root(self, driver):
|
||||
from napalm_device_types import LogSourcesMixin
|
||||
|
||||
assert isinstance(driver, LogSourcesMixin)
|
||||
driver._root = True
|
||||
driver._device.send_command.return_value = _LOGS
|
||||
|
||||
reading = driver.get_log_sources()
|
||||
|
||||
assert (reading["attributed"], reading["journald"]) == (True, True)
|
||||
access = [s for s in reading["sources"] if s["kind"] == "file"]
|
||||
assert [(s["path"], s["unit"]) for s in access] == [("/var/log/nginx/access.log", "nginx")]
|
||||
assert self._sent(driver)[0].startswith("sh -c '")
|
||||
|
||||
def test_without_a_sudo_password_the_whole_script_runs_under_sudo_n(self, driver):
|
||||
driver._root = False
|
||||
driver._device.send_command.return_value = _LOGS
|
||||
|
||||
driver.get_log_sources()
|
||||
|
||||
assert self._sent(driver)[0].startswith("sudo -n sh -c '")
|
||||
|
||||
def test_when_sudo_refuses_it_reads_what_the_user_may_see(self, driver):
|
||||
driver._root = False
|
||||
driver._device.send_command.side_effect = ["sudo: a password is required", _LOGS]
|
||||
|
||||
reading = driver.get_log_sources()
|
||||
|
||||
assert reading["attributed"] is False
|
||||
refused, plain = self._sent(driver)
|
||||
assert refused.startswith("sudo -n sh -c '")
|
||||
assert plain.startswith("sh -c '")
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# get_system_identity (napalm-device-types SystemIdentityMixin)
|
||||
# ---------------------------------------------------------------------------
|
||||
@@ -1979,7 +2033,8 @@ class TestGetSystemIdentity:
|
||||
|
||||
identity = driver.get_system_identity()
|
||||
|
||||
assert identity == {
|
||||
# The identity's keys only: napalm-device-types reads more in the same round trip.
|
||||
assert {k: identity[k] for k in ("system_uuid", "product_serial", "board_serial")} == {
|
||||
"system_uuid": "31303043-534d-c40c-7a72-6f1300000000",
|
||||
"product_serial": "", # Supermicro's placeholder
|
||||
"board_serial": "ZM155S026022",
|
||||
@@ -2539,3 +2594,108 @@ class TestIpv6NextHops:
|
||||
out = "10.50.0.0/16 via inet 192.0.2.1 dev eth0\n"
|
||||
|
||||
assert [r.nexthop for r in parse_ip_route(out, "ipv4")] == ["192.0.2.1"]
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# get_packages (rpm) and the installed advisories (NetOrk/netork#2394)
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
# rpm -qa on Oracle Linux 9.8 (aarch64): gmp and openssl carry epoch 1; perf is
|
||||
# built from the kernel's source rpm; gpg-pubkey has none.
|
||||
RPM_QA = (
|
||||
"glibc-common\t2.34-284.0.1.el9_8.4\t1210460\tglibc-2.34-284.0.1.el9_8.4.src.rpm"
|
||||
"\tCommon binaries and locale data for glibc\n"
|
||||
"gmp\t1:6.2.0-13.el9\t805146\tgmp-6.2.0-13.el9.src.rpm\tA GNU arbitrary precision library\n"
|
||||
"openssl\t1:3.5.8-2.0.1.el9_8\t2106925\topenssl-3.5.8-2.0.1.el9_8.src.rpm"
|
||||
"\tUtilities from the general purpose cryptography library\n"
|
||||
"perf\t5.14.0-687.66.1.el9_8\t5401292\tkernel-5.14.0-687.66.1.el9_8.src.rpm"
|
||||
"\tPerformance monitoring for the Linux kernel\n"
|
||||
"gpg-pubkey\t8d8b756f-629e59ec\t0\t(none)\tOracle OSS group (Open Source Software group)\n"
|
||||
)
|
||||
|
||||
|
||||
class TestRpmPackages:
|
||||
def test_the_version_carries_the_epoch_where_the_package_has_one(self, driver):
|
||||
"""Oracle's and Red Hat's fixes name it (`1:6.2.0-13.el9`); without it an
|
||||
epoch-1 fix reads as newer than every installed build."""
|
||||
driver._pkg_manager = "dnf"
|
||||
with patch.object(driver, "_send", return_value=RPM_QA) as send:
|
||||
pkgs = {p["name"]: p for p in driver.get_packages()}
|
||||
|
||||
assert "%|EPOCH?{%{EPOCH}:}:{}|%{VERSION}-%{RELEASE}" in send.call_args.args[0]
|
||||
assert pkgs["gmp"]["version"] == "1:6.2.0-13.el9"
|
||||
assert pkgs["openssl"]["version"] == "1:3.5.8-2.0.1.el9_8"
|
||||
assert pkgs["glibc-common"]["version"] == "2.34-284.0.1.el9_8.4"
|
||||
assert pkgs["glibc-common"]["source"] == "dnf"
|
||||
assert pkgs["glibc-common"]["size"] == 1210460
|
||||
assert pkgs["openssl"]["description"] == (
|
||||
"Utilities from the general purpose cryptography library"
|
||||
)
|
||||
|
||||
def test_each_package_names_the_source_rpm_it_was_built_from(self, driver):
|
||||
"""perf, python3-perf and bpftool are built from the kernel's source rpm,
|
||||
and Red Hat lists them in every kernel CVE: netOrk tells them apart from
|
||||
user space by that name (NetOrk/netork#2394)."""
|
||||
driver._pkg_manager = "dnf"
|
||||
with patch.object(driver, "_send", return_value=RPM_QA) as send:
|
||||
pkgs = {p["name"]: p for p in driver.get_packages()}
|
||||
|
||||
assert "%{SOURCERPM}" in send.call_args.args[0]
|
||||
assert pkgs["perf"]["source_rpm"] == "kernel"
|
||||
assert pkgs["glibc-common"]["source_rpm"] == "glibc"
|
||||
assert pkgs["openssl"]["source_rpm"] == "openssl"
|
||||
assert "source_rpm" not in pkgs["gpg-pubkey"]
|
||||
# Not `source_package`: netOrk reads that as the name a distribution
|
||||
# files its verdicts under, and Oracle's and Red Hat's name the binary.
|
||||
assert all("source_package" not in p for p in pkgs.values())
|
||||
|
||||
|
||||
class TestInstalledAdvisoryCves:
|
||||
def test_dnf_reads_the_installed_advisories_as_root(self, driver):
|
||||
driver._pkg_manager = "dnf"
|
||||
driver._device.send_command.side_effect = [
|
||||
"0", # id -u
|
||||
(
|
||||
"CVE-2023-4911 Important/Sec. glibc-common-2.34-60.0.3.el9_2.7.aarch64\n"
|
||||
"CVE-2023-38545 Important/Sec. curl-7.76.1-26.el9_3.2.aarch64\n"
|
||||
"__DNF_RC=0\n__NETORK_RC=0"
|
||||
),
|
||||
]
|
||||
|
||||
assert driver.get_installed_advisory_cves() == {
|
||||
"glibc-common": ["CVE-2023-4911"],
|
||||
"curl": ["CVE-2023-38545"],
|
||||
}
|
||||
sent = driver._device.send_command.call_args.args[0]
|
||||
assert DNF_INSTALLED_CVES_COMMAND in sent
|
||||
|
||||
def test_a_failed_dnf_raises_instead_of_reading_as_nothing_installed(self, driver):
|
||||
driver._pkg_manager = "dnf"
|
||||
driver._device.send_command.side_effect = ["0", "__DNF_RC=1\n__NETORK_RC=0"]
|
||||
|
||||
with pytest.raises(ValueError, match="exit status 1"):
|
||||
driver.get_installed_advisory_cves()
|
||||
|
||||
@pytest.mark.parametrize("manager", ["yum", "apt", "apk", "pacman"])
|
||||
def test_other_package_managers_keep_no_such_advisories(self, driver, manager):
|
||||
driver._pkg_manager = manager
|
||||
|
||||
with pytest.raises(NotImplementedError):
|
||||
driver.get_installed_advisory_cves()
|
||||
|
||||
|
||||
class TestSourceRpmName:
|
||||
@pytest.mark.parametrize(
|
||||
("sourcerpm", "name"),
|
||||
[
|
||||
("kernel-5.14.0-687.66.1.el9_8.src.rpm", "kernel"),
|
||||
("kernel-uek-6.12.0-104.43.4.3.el9uek.src.rpm", "kernel-uek"),
|
||||
("python-dateutil-2.8.1-7.el9.src.rpm", "python-dateutil"),
|
||||
("dummy-1.0-1.nosrc.rpm", "dummy"),
|
||||
("(none)", None),
|
||||
("", None),
|
||||
("broken.src.rpm", None),
|
||||
],
|
||||
)
|
||||
def test_the_name_is_what_precedes_version_and_release(self, sourcerpm, name):
|
||||
assert source_rpm_name(sourcerpm) == name
|
||||
@@ -8,6 +8,7 @@ stops only the password.
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import shlex
|
||||
import time
|
||||
|
||||
import pytest
|
||||
@@ -108,3 +109,124 @@ def test_netorks_own_account_is_made_with_its_uid() -> None:
|
||||
assert _Driver()._account_create_with_uid("netork", 900) == [
|
||||
["useradd", "-m", "-u", "900", "-s", "/bin/bash", "netork"]
|
||||
]
|
||||
|
||||
|
||||
# -- what a person changes follows them (NetOrk/netork#2013) ----------------------------
|
||||
|
||||
ALICE_KEY = "ssh-ed25519 AAAAC3NzaC1lZDI1NTE5AAAAIAlice alice@laptop"
|
||||
OLD_KEY = "ssh-ed25519 AAAAC3NzaC1lZDI1NTE5AAAAIOld alice@lost-laptop"
|
||||
OWN_KEY = "ssh-rsa AAAAB3NzaC1yc2EAAAADAQABAAABAQOwn own@desktop"
|
||||
_KEYS = "/home/alice/.ssh/authorized_keys"
|
||||
|
||||
|
||||
class _Host(LinuxDriver):
|
||||
"""A Linux host with Alice's account, her key files and what ran as whom."""
|
||||
|
||||
def __init__(self, shadow: str, keys: str) -> None:
|
||||
super().__init__("host", "netadmin", "pw")
|
||||
self.shadow = shadow
|
||||
self.files = {_KEYS: keys}
|
||||
self.ran: list[tuple[str, bool]] = []
|
||||
|
||||
def run_command(self, command, *, privileged=False, timeout=60, stdin=None):
|
||||
self.ran.append((command, privileged))
|
||||
if stdin is not None:
|
||||
self.files["/tmp/staged"] = stdin.decode()
|
||||
return CommandResult("/tmp/staged", "", 0)
|
||||
argv = shlex.split(command)
|
||||
answers = {
|
||||
"id -un": "netadmin\n",
|
||||
"getent passwd alice": "alice:x:1001:1001::/home/alice:/bin/bash\n",
|
||||
"getent shadow alice": self.shadow + "\n",
|
||||
"id -Gn alice": "alice sudo\n",
|
||||
"sudo -l -U alice": "User alice is not allowed to run sudo on host.\n",
|
||||
}
|
||||
if command in answers:
|
||||
return CommandResult(answers[command], "", 0)
|
||||
if argv[:2] == ["test", "-e"]:
|
||||
return CommandResult("", "", 0 if argv[2] in self.files else 1)
|
||||
if argv[:4] == ["sudo", "-n", "-u", "alice"]:
|
||||
return self._as_alice(argv[4:])
|
||||
return CommandResult("", "", 0)
|
||||
|
||||
def _as_alice(self, argv: list[str]) -> CommandResult:
|
||||
if argv[0] == "cat":
|
||||
return CommandResult(self.files.get(argv[-1], ""), "", 0)
|
||||
if argv[0] == "install":
|
||||
self.files[argv[-1]] = self.files[argv[-2]]
|
||||
return CommandResult("", "", 0)
|
||||
|
||||
def as_root(self) -> list[list[str]]:
|
||||
"""What root ran that changes something: no reads, nothing as Alice."""
|
||||
reads = ("getent", "id", "test")
|
||||
words = [shlex.split(c) for c, privileged in self.ran if privileged]
|
||||
return [
|
||||
w for w in words if w[0] not in reads and w[:2] not in (["sudo", "-n"], ["sudo", "-l"])
|
||||
]
|
||||
|
||||
|
||||
_OPEN = "alice:$6$old:20000:0:99999:7:::"
|
||||
|
||||
|
||||
def test_clearing_the_password_is_a_star_no_hash_matches() -> None:
|
||||
# Not passwd -d: an empty password and pam_unix's nullok let anyone su to it.
|
||||
# Not "!": sshd without PAM takes it for a lock and refuses the key too.
|
||||
# Not an expiry: that is the lock, and PAM refuses a key of an expired account.
|
||||
assert _Driver()._account_clear_password("alice") == [["usermod", "-p", "*", "alice"]]
|
||||
|
||||
|
||||
def test_a_key_only_account_opens_again_without_its_password_coming_back() -> None:
|
||||
d = _Driver(shadow="alice:!*:20000:0:99999:7::1:")
|
||||
assert d._account_open("alice", None, locked=True) == [["usermod", "-e", "", "alice"]]
|
||||
|
||||
|
||||
def test_removing_the_password_runs_usermod_and_takes_sudo_away() -> None:
|
||||
host = _Host(_OPEN, keys=ALICE_KEY + "\n")
|
||||
|
||||
result = host.add_local_account("alice", ALICE_KEY, clear_password=True)
|
||||
|
||||
assert result["success"], result["output"]
|
||||
assert host.as_root() == [
|
||||
["usermod", "-U", "-e", "", "alice"],
|
||||
["rm", "-f", "--", "/etc/sudoers.d/80-account-alice"],
|
||||
["gpasswd", "-d", "alice", "sudo"],
|
||||
["usermod", "-p", "*", "alice"],
|
||||
]
|
||||
|
||||
|
||||
def test_a_replaced_key_is_written_out_of_the_key_file_as_the_person() -> None:
|
||||
host = _Host(_OPEN, keys=f"{OLD_KEY}\n{OWN_KEY}\n")
|
||||
|
||||
result = host.add_local_account("alice", ALICE_KEY, replaces=[OLD_KEY])
|
||||
|
||||
assert result["success"], result["output"]
|
||||
assert host.files[_KEYS] == f"{OWN_KEY}\n{ALICE_KEY}\n"
|
||||
installs = [c for c, _ in host.ran if "install -m 600" in c]
|
||||
assert installs and all(c.startswith("sudo -n -u alice install") for c in installs)
|
||||
|
||||
|
||||
def test_a_deleted_key_takes_the_password_and_sudo_with_it_when_asked() -> None:
|
||||
"""NetOrk/netork#2033: the password went with the person's key, so it goes from the
|
||||
host too, with sudo; the account stays open."""
|
||||
host = _Host(_OPEN, keys=f"{ALICE_KEY}\n{OWN_KEY}\n")
|
||||
|
||||
result = host.remove_local_account_keys("alice", [ALICE_KEY], clear_password=True)
|
||||
|
||||
assert result["success"], result["output"]
|
||||
assert [s["step"] for s in result["steps"]] == ["keys", "password", "sudo"]
|
||||
assert host.files[_KEYS] == f"{OWN_KEY}\n"
|
||||
assert host.as_root() == [
|
||||
["usermod", "-p", "*", "alice"],
|
||||
["rm", "-f", "--", "/etc/sudoers.d/80-account-alice"],
|
||||
["gpasswd", "-d", "alice", "sudo"],
|
||||
]
|
||||
|
||||
|
||||
def test_a_deleted_key_goes_and_the_account_stays_open() -> None:
|
||||
host = _Host(_OPEN, keys=f"{ALICE_KEY}\n{OWN_KEY}\n")
|
||||
|
||||
result = host.remove_local_account_keys("alice", [ALICE_KEY])
|
||||
|
||||
assert result["success"], result["output"]
|
||||
assert host.files[_KEYS] == f"{OWN_KEY}\n"
|
||||
assert host.as_root() == []
|
||||
@@ -0,0 +1,141 @@
|
||||
"""get_running_backups: the host's own file-level backups that a restart would abort.
|
||||
|
||||
A restic, borg, borgmatic, duplicity ... run -- from a systemd timer, a cron line
|
||||
or by hand -- is a process of a backup tool. The driver reads the processes, the
|
||||
host's clock and each process's cgroup in one round trip, and names a backup by
|
||||
the systemd service it runs in, which is the scheduled job netOrk shows for the
|
||||
timer (NetOrk/netork#2318, #1933). A failed read raises: an empty list would say
|
||||
nothing runs.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from unittest.mock import MagicMock
|
||||
|
||||
import pytest
|
||||
|
||||
from napalm_linux import LinuxDriver
|
||||
from napalm_linux._running_backups import RUNNING_BACKUPS_COMMAND, parse_running_backups
|
||||
|
||||
NOW = 1793664000
|
||||
|
||||
|
||||
def _reading(*rows: str, now: int = NOW, end: bool = True) -> str:
|
||||
lines = [f"NOW {now}", *rows]
|
||||
if end:
|
||||
lines.append("END")
|
||||
return "\n".join(lines)
|
||||
|
||||
|
||||
def _row(pid: int, elapsed: int, cgroup: str, args: str) -> str:
|
||||
return f"{pid}\t{elapsed}\t{cgroup}\t{args}"
|
||||
|
||||
|
||||
def test_nothing_runs():
|
||||
out = _reading(
|
||||
_row(1, 99999, "0::/init.scope", "/sbin/init"),
|
||||
_row(812, 3600, "0::/system.slice/ssh.service", "sshd: /usr/sbin/sshd -D"),
|
||||
)
|
||||
assert parse_running_backups(out) == []
|
||||
|
||||
|
||||
def test_a_timers_restic_backup_is_named_by_its_service():
|
||||
out = _reading(
|
||||
_row(4242, 600, "0::/system.slice/restic-backup.service", "/usr/bin/restic backup /srv")
|
||||
)
|
||||
assert parse_running_backups(out) == [
|
||||
{
|
||||
"kind": "backup",
|
||||
"job": "restic-backup.service",
|
||||
"task": "4242",
|
||||
"guests": [],
|
||||
"since": NOW - 600,
|
||||
}
|
||||
]
|
||||
|
||||
|
||||
def test_a_cron_run_has_no_job_of_its_own():
|
||||
out = _reading(_row(77, 30, "0::/system.slice/cron.service", "borg create ::{now} /etc"))
|
||||
[backup] = parse_running_backups(out)
|
||||
assert backup["job"] is None
|
||||
assert backup["kind"] == "backup"
|
||||
|
||||
|
||||
def test_cgroup_v1_is_read_too():
|
||||
out = _reading(_row(9, 5, "1:name=systemd:/system.slice/borgmatic.service", "borgmatic"))
|
||||
assert parse_running_backups(out)[0]["job"] == "borgmatic.service"
|
||||
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
("args", "kind"),
|
||||
[
|
||||
("/usr/bin/restic backup --files-from /etc/restic/files", "backup"),
|
||||
("restic forget --prune --keep-daily 7", "prune"),
|
||||
("restic -r s3:example check", "verify"),
|
||||
("restic copy --from-repo /srv/a", "sync"),
|
||||
("/usr/bin/borg create --stats ::{now} /home", "backup"),
|
||||
("borg --lock-wait 60 prune --keep-daily 7", "prune"),
|
||||
("borg compact", "prune"),
|
||||
("borg check --verify-data", "verify"),
|
||||
("borg serve --restrict-to-path /srv/borg", "backup"),
|
||||
("/usr/bin/python3 /usr/bin/borgmatic --verbosity 1", "backup"),
|
||||
("duplicity incremental /home file:///mnt/b", "backup"),
|
||||
("/bin/bash /usr/bin/duply home backup", "backup"),
|
||||
("rsnapshot daily", "backup"),
|
||||
("rdiff-backup /home /mnt/b", "backup"),
|
||||
("proxmox-backup-client backup root.pxar:/", "backup"),
|
||||
("kopia snapshot create /home", "backup"),
|
||||
("btrbk run", "backup"),
|
||||
("resticprofile backup", "backup"),
|
||||
("autorestic backup -a", "backup"),
|
||||
],
|
||||
)
|
||||
def test_the_tools_and_what_they_do(args, kind):
|
||||
[backup] = parse_running_backups(_reading(_row(1, 1, "0::/user.slice", args)))
|
||||
assert backup["kind"] == kind
|
||||
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
"args",
|
||||
[
|
||||
"restic mount /mnt/restic",
|
||||
"restic snapshots",
|
||||
"restic restore latest --target /",
|
||||
"borg mount ::archive /mnt",
|
||||
"borg list",
|
||||
"kopia server start",
|
||||
"vim /etc/restic/backup.sh",
|
||||
"grep borg /var/log/syslog",
|
||||
],
|
||||
)
|
||||
def test_what_is_no_backup(args):
|
||||
assert parse_running_backups(_reading(_row(1, 1, "0::/user.slice", args))) == []
|
||||
|
||||
|
||||
def test_a_session_or_scope_is_no_job():
|
||||
out = _reading(_row(5, 1, "0::/user.slice/user-1000.slice/session-3.scope", "restic backup /"))
|
||||
assert parse_running_backups(out)[0]["job"] is None
|
||||
|
||||
|
||||
def test_a_reading_cut_short_raises():
|
||||
with pytest.raises(RuntimeError):
|
||||
parse_running_backups(_reading(_row(1, 1, "", "restic backup /"), end=False))
|
||||
|
||||
|
||||
def test_no_clock_raises():
|
||||
with pytest.raises(RuntimeError):
|
||||
parse_running_backups("END")
|
||||
|
||||
|
||||
def test_the_driver_reads_as_the_login_user_in_one_round_trip():
|
||||
drv = LinuxDriver.__new__(LinuxDriver)
|
||||
drv._send = MagicMock(return_value=_reading())
|
||||
assert drv.get_running_backups() == []
|
||||
drv._send.assert_called_once()
|
||||
assert drv._send.call_args.args[0] == RUNNING_BACKUPS_COMMAND
|
||||
|
||||
|
||||
def test_the_command_says_when_ps_failed():
|
||||
"""Busybox's ps knows no etimes: the reading must not end as if nothing ran."""
|
||||
assert "|| exit" in RUNNING_BACKUPS_COMMAND
|
||||
assert RUNNING_BACKUPS_COMMAND.rstrip().endswith("echo END")
|
||||
@@ -0,0 +1,104 @@
|
||||
"""Time sync on a Linux host: napalm-device-types' POSIX implementation (NetOrk/netork#2361).
|
||||
|
||||
The reading, its parse and every write are ``PosixTimeSyncMixin``'s; the driver
|
||||
carries the commands across ``run_command`` -- the reading as the login user in one
|
||||
round trip, the writes as root, and root never reads stdin.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from napalm_device_types import CommandResult, PosixTimeSyncMixin, TimeSyncMixin
|
||||
|
||||
from napalm_linux import LinuxDriver
|
||||
|
||||
#: Debian 12 with chrony: the reading as PosixTimeSyncMixin's command prints it.
|
||||
READING = """\
|
||||
@@ts timedatectl
|
||||
Timezone=Europe/Berlin
|
||||
NTP=yes
|
||||
NTPSynchronized=yes
|
||||
@@ts zone
|
||||
Europe/Berlin
|
||||
@@ts active
|
||||
chrony chrony active
|
||||
chronyd chrony active
|
||||
systemd-timesyncd systemd-timesyncd inactive
|
||||
@@ts timesync
|
||||
@@ts chronyc
|
||||
MS Name/IP address Stratum Poll Reach LastRx Last sample
|
||||
===============================================================================
|
||||
^* 192.168.1.1 2 6 377 40 -45us[ -63us] +/- 10ms
|
||||
@@ts chrony 0 main /etc/chrony/chrony.conf
|
||||
pool 2.debian.pool.ntp.org iburst
|
||||
sourcedir /etc/chrony/sources.d
|
||||
|
||||
@@ts end
|
||||
"""
|
||||
|
||||
|
||||
class _Channel:
|
||||
"""Records every command; answers the reading, and a staged file's path."""
|
||||
|
||||
def __init__(self) -> None:
|
||||
self.calls: list[tuple[str, bool, bytes | None]] = []
|
||||
|
||||
def __call__(self, command, *, privileged=False, timeout=60, stdin=None): # type: ignore[no-untyped-def]
|
||||
self.calls.append((command, privileged, stdin))
|
||||
if "@@ts" in command:
|
||||
return CommandResult(READING, "", 0)
|
||||
if "mktemp" in command:
|
||||
return CommandResult("/tmp/tmp.abc123", "", 0)
|
||||
return CommandResult("", "", 0)
|
||||
|
||||
|
||||
def _driver() -> tuple[LinuxDriver, _Channel]:
|
||||
driver = LinuxDriver("host", "user", "pw", optional_args={"sudo_password": "pw"})
|
||||
channel = _Channel()
|
||||
driver.run_command = channel # type: ignore[method-assign]
|
||||
return driver, channel
|
||||
|
||||
|
||||
def test_a_linux_host_keeps_its_clock_through_the_posix_mixin():
|
||||
assert issubclass(LinuxDriver, PosixTimeSyncMixin)
|
||||
assert issubclass(LinuxDriver, TimeSyncMixin)
|
||||
assert callable(getattr(LinuxDriver, "get_time_sync", None))
|
||||
assert callable(getattr(LinuxDriver, "configure_time_sync", None))
|
||||
assert LinuxDriver.time_sync_writes == frozenset({"ntp_servers", "timezone"})
|
||||
|
||||
|
||||
def test_the_reading_is_one_round_trip_as_the_login_user():
|
||||
driver, channel = _driver()
|
||||
|
||||
assert driver.get_time_sync() == {
|
||||
"ntp_servers": ["2.debian.pool.ntp.org"],
|
||||
"timezone": "Europe/Berlin",
|
||||
"synchronized": True,
|
||||
"daemon": "chrony",
|
||||
# napalm-device-types 4.36.0: the servers it got by DHCP, none here (#75).
|
||||
"dhcp_ntp_servers": [],
|
||||
}
|
||||
assert [privileged for _, privileged, _ in channel.calls] == [False]
|
||||
|
||||
|
||||
def test_the_zone_is_set_as_root():
|
||||
driver, channel = _driver()
|
||||
result = driver.configure_time_sync(timezone="Europe/Berlin")
|
||||
|
||||
assert result["success"] is True, result["output"]
|
||||
assert ("timedatectl set-timezone Europe/Berlin", True, None) in channel.calls
|
||||
|
||||
|
||||
def test_root_never_reads_stdin():
|
||||
# With a sudo password, sudo -S reads it from stdin: a privileged command given
|
||||
# stdin as well would hand the password on (LinuxDriver refuses it).
|
||||
driver, channel = _driver()
|
||||
result = driver.configure_time_sync(["ntp1.example.org"], "UTC")
|
||||
|
||||
assert result["steps"][0]["step"] == "ntp_servers"
|
||||
assert result["steps"][0]["ok"] is True, result["output"]
|
||||
assert any(stdin for _, privileged, stdin in channel.calls if not privileged)
|
||||
assert all(stdin is None for _, privileged, stdin in channel.calls if privileged)
|
||||
installed = [c for c, privileged, _ in channel.calls if privileged and c.startswith("install")]
|
||||
assert installed == [
|
||||
"install -D -m 644 -- /tmp/tmp.abc123 /etc/chrony/sources.d/netork.sources"
|
||||
]
|
||||
@@ -0,0 +1,209 @@
|
||||
"""configure_zabbix_agent on a Linux host without a container engine (NetOrk/netork#2571).
|
||||
|
||||
The template (napalm-device-types ``ZabbixAgentMixin``) installs ``zabbix-agent`` from
|
||||
the host's packages, and from Zabbix's repository where those have none; this driver
|
||||
adds that repository, writes ``/etc/zabbix/zabbix_agentd.conf`` and opens the port.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from unittest.mock import MagicMock
|
||||
|
||||
import pytest
|
||||
from napalm_device_types import CommandResult
|
||||
|
||||
from napalm_linux import LinuxDriver
|
||||
|
||||
CONFIG = "/etc/zabbix/zabbix_agentd.conf"
|
||||
STOCK = "PidFile=/run/zabbix/zabbix_agentd.pid\nServer=127.0.0.1\nServerActive=127.0.0.1\nHostname=Zabbix server\n"
|
||||
SETTINGS = {
|
||||
"server": "zabbix.example.com",
|
||||
"server_active": "zabbix.example.com",
|
||||
"listen_port": 10050,
|
||||
"allowed_sources": ["10.0.0.5"],
|
||||
"hostname": "web-01",
|
||||
"release": "7.4",
|
||||
}
|
||||
UBUNTU = 'ID=ubuntu\nVERSION_ID="24.04"\nID_LIKE=debian\n'
|
||||
|
||||
|
||||
class _Host:
|
||||
"""A Linux host: what runs as root, the files it reads, its packages and services."""
|
||||
|
||||
def __init__(self, *, config=STOCK, os_release=UBUNTU, firewall="ufw", firewalld=False):
|
||||
self.config = config
|
||||
self.os_release = os_release
|
||||
self.firewall = firewall
|
||||
self.firewalld = firewalld
|
||||
self.root: list[str] = []
|
||||
self.written: list[tuple[str, str]] = []
|
||||
self.services: list[tuple[str, str]] = []
|
||||
self.packages: list[str] = []
|
||||
self.distribution_has_it = True
|
||||
self.refuse = ""
|
||||
|
||||
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 "repo.zabbix.com" in command:
|
||||
self.distribution_has_it = True
|
||||
return ("", 0)
|
||||
|
||||
def send(self, command, read_timeout=100):
|
||||
if command == "systemctl is-active firewalld 2>/dev/null":
|
||||
return "active" if self.firewalld else "inactive"
|
||||
if command == f"command -v {self.firewall} 2>/dev/null":
|
||||
return f"/usr/sbin/{self.firewall}"
|
||||
return ""
|
||||
|
||||
def run_command(self, command, *, privileged=False, timeout=60, stdin=None):
|
||||
if self.refuse and self.refuse in command:
|
||||
return CommandResult("", "Permission denied", 1)
|
||||
if command == "cat /etc/os-release":
|
||||
return CommandResult(self.os_release, "", 0)
|
||||
if command == f"cat {CONFIG}" and privileged:
|
||||
return CommandResult(self.config, "", 0)
|
||||
return CommandResult("", "", 0)
|
||||
|
||||
def install_file(self, path, content):
|
||||
self.written.append((path, content))
|
||||
self.config = content
|
||||
return CommandResult("", "", 0)
|
||||
|
||||
def ensure_package(self, name):
|
||||
self.packages.append(name)
|
||||
ok = self.distribution_has_it
|
||||
return {"success": ok, "steps": [], "output": "installed" if ok else "E: Unable to locate"}
|
||||
|
||||
def manage_service(self, name, action):
|
||||
self.services.append((action, name))
|
||||
return {"success": True, "output": ""}
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def host():
|
||||
return _Host()
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def driver(host):
|
||||
d = LinuxDriver("h", "admin", "p")
|
||||
d._device = MagicMock()
|
||||
d._pkg_manager = "apt"
|
||||
d._root = True
|
||||
d._sudo_status = host.sudo_status
|
||||
d._send = host.send
|
||||
d.run_command = host.run_command
|
||||
d._install_file_as_root = host.install_file
|
||||
d.ensure_package = host.ensure_package
|
||||
d.manage_service = host.manage_service
|
||||
d.refresh_available_updates = lambda: {"success": True, "output": ""}
|
||||
return d
|
||||
|
||||
|
||||
def test_installs_writes_opens_and_starts(driver, host):
|
||||
result = driver.configure_zabbix_agent(SETTINGS)
|
||||
|
||||
assert result["success"] is True, result["output"]
|
||||
assert [s["step"] for s in result["steps"]] == ["install", "configure", "firewall", "start"]
|
||||
assert host.packages == ["zabbix-agent"]
|
||||
assert host.services == [("enable", "zabbix-agent"), ("restart", "zabbix-agent")]
|
||||
|
||||
|
||||
def test_the_config_gets_the_caller_s_values_and_keeps_the_rest(driver, host):
|
||||
driver.configure_zabbix_agent(SETTINGS)
|
||||
|
||||
path, content = host.written[0]
|
||||
assert path == CONFIG
|
||||
assert "Server=zabbix.example.com\n" in content
|
||||
assert "Hostname=web-01\n" in content
|
||||
assert content.startswith("PidFile=/run/zabbix/zabbix_agentd.pid\n")
|
||||
assert f"cp -p {CONFIG} {CONFIG}.bak" in host.root
|
||||
|
||||
|
||||
def test_a_config_that_already_says_it_is_not_written(driver, host):
|
||||
driver.configure_zabbix_agent(SETTINGS)
|
||||
host.written.clear()
|
||||
|
||||
result = driver.configure_zabbix_agent(SETTINGS)
|
||||
|
||||
assert result["success"] is True
|
||||
assert host.written == []
|
||||
|
||||
|
||||
def test_a_config_that_cannot_be_read_stops_the_fix(driver, host):
|
||||
host.refuse = f"cat {CONFIG}"
|
||||
|
||||
result = driver.configure_zabbix_agent(SETTINGS)
|
||||
|
||||
assert result["success"] is False
|
||||
assert result["steps"][-1]["step"] == "configure"
|
||||
assert host.services == []
|
||||
|
||||
|
||||
def test_without_the_distribution_s_package_zabbix_s_repository_is_added(driver, host):
|
||||
host.distribution_has_it = False
|
||||
|
||||
result = driver.configure_zabbix_agent(SETTINGS)
|
||||
|
||||
assert result["success"] is True, result["output"]
|
||||
repository = next(c for c in host.root if "repo.zabbix.com" in c)
|
||||
assert (
|
||||
"https://repo.zabbix.com/zabbix/7.4/release/ubuntu/pool/main/z/zabbix-release/"
|
||||
"zabbix-release_latest_7.4+ubuntu24.04_all.deb"
|
||||
) in repository
|
||||
assert "dpkg -i" in repository
|
||||
assert host.packages == ["zabbix-agent", "zabbix-agent"]
|
||||
|
||||
|
||||
def test_a_distribution_zabbix_publishes_nothing_for_fails_the_install(driver, host):
|
||||
host.distribution_has_it = False
|
||||
host.os_release = 'ID=arch\nVERSION_ID="rolling"\n'
|
||||
|
||||
result = driver.configure_zabbix_agent(SETTINGS)
|
||||
|
||||
assert result["success"] is False
|
||||
assert "Zabbix publishes no repository for arch" in result["output"]
|
||||
assert not any("repo.zabbix.com" in c for c in host.root)
|
||||
|
||||
|
||||
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
|
||||
|
||||
|
||||
def test_iptables_opens_the_listen_port_for_the_sources(driver, host):
|
||||
host.firewall = "iptables"
|
||||
|
||||
driver.configure_zabbix_agent(SETTINGS)
|
||||
|
||||
assert any(
|
||||
"iptables -I INPUT -s 10.0.0.5/32 -p tcp --dport 10050 -j ACCEPT" in c for c in host.root
|
||||
)
|
||||
|
||||
|
||||
def test_a_running_firewalld_gets_a_rich_rule_for_tcp(driver, host):
|
||||
host.firewalld = True
|
||||
|
||||
driver.configure_zabbix_agent(SETTINGS)
|
||||
|
||||
rule = next(c for c in host.root if "firewall-cmd" in c)
|
||||
assert (
|
||||
'rule family="ipv4" source address="10.0.0.5/32" port port="10050" protocol="tcp" accept'
|
||||
in rule
|
||||
)
|
||||
|
||||
|
||||
def test_no_sources_change_no_firewall(driver, host):
|
||||
result = driver.configure_zabbix_agent({**SETTINGS, "allowed_sources": []})
|
||||
|
||||
assert result["success"] is True
|
||||
assert not any("ufw" in c or "iptables" in c or "firewall-cmd" in c for c in host.root)
|
||||
|
||||
|
||||
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
|
||||
Reference in new issue
Block a user