Compare commits
57
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
61b7b68626 | ||
|
|
b9b6297815 | ||
|
|
14217b6eeb | ||
|
|
91b939236f | ||
|
|
07920941c8 | ||
|
|
92b1b6402b | ||
|
|
e4fde2283a | ||
|
|
419d3ee0e0 | ||
|
|
c93ceeb320 | ||
|
|
d77a8982a8 | ||
|
|
594cc5e486 | ||
|
|
e440bee9e1 | ||
|
|
3cd0e3621a | ||
|
|
3813aee3a8 | ||
|
|
e3420269b7 | ||
|
|
5985c87cc8 | ||
|
|
6c90373c80 | ||
|
|
ddc9316fb5 | ||
|
|
f8c456d784 | ||
|
|
a5275d4c4d | ||
|
|
a38f07513f | ||
|
|
ddcd9ebc0a | ||
|
|
494b9ed046 | ||
|
|
67ffee4e9e | ||
|
|
03ccae82e3 | ||
|
|
d561046802 | ||
|
|
53bc79098b | ||
|
|
5517464e1f | ||
|
|
9c889f3715 | ||
|
|
07fc7d0dd3 | ||
|
|
818016b717 | ||
|
|
66f26c3d8e | ||
|
|
507e9a8728 | ||
|
|
4df932e0ca | ||
|
|
cbd1cd3d11 | ||
|
|
ebd3255e5a | ||
|
|
fb927e7255 | ||
|
|
ae21c7fba7 | ||
|
|
784f7ac686 | ||
|
|
2412a99eeb | ||
|
|
cd47587e80 | ||
|
|
b1ea364674 | ||
|
|
e729b935a4 | ||
|
|
f654076560 | ||
|
|
2dea517e89 | ||
|
|
1a7885d22e | ||
|
|
71588613fb | ||
|
|
93ba335798 | ||
|
|
eb1964c4b3 | ||
|
|
3622d0f825 | ||
|
|
caf7ef4cc8 | ||
|
|
3422b7d030 | ||
|
|
f1940aa918 | ||
|
|
5217c6e333 | ||
|
|
7051199589 | ||
|
|
7c0e4fffc5 | ||
|
|
cb0f1cc05c |
No files matched your search
+239
@@ -7,6 +7,245 @@ recorded here; their history is the git log.
|
||||
|
||||
## [Unreleased]
|
||||
|
||||
## [4.51.0] - 2026-11-28
|
||||
|
||||
### Added
|
||||
- `get_kernel_facts()` reads the kernel's live patches (NetOrk/netork#2701), in the new
|
||||
`live_patches` key: `loaded`, every patch under `/sys/kernel/livepatch` with `enabled` and
|
||||
`transition` (None on a kernel without live patching); `kpatch`, `kpatch list`'s loaded
|
||||
modules with their state and the installed ones with their kernel (None without kpatch);
|
||||
`canonical`, Canonical Livepatch's status for the running kernel -- its kernel as Canonical
|
||||
names it, `state` (`applied`, ...), `check_state`, `version` and the CVEs it names with
|
||||
whether each is patched (`canonical-livepatch status --format json`, the 10.x client's list
|
||||
and the 9.x client's text; None when not installed or not read), and
|
||||
`canonical_installed`. Read-only: `status` reads the daemon's last state, `refresh` is never
|
||||
run. Where the client is installed and its status did not read without root, a driver that
|
||||
supplies `_run_livepatch_status_command(command)` has `LIVEPATCH_STATUS_COMMAND` read again
|
||||
as root; a refusal leaves it unread.
|
||||
- `parse_canonical_status`, `canonical_release` (Canonical's `5.15.0-91.101-generic` as
|
||||
`uname -r` names it), `LIVEPATCH_STATUS_COMMAND`, and the `LivePatchesDict` and
|
||||
`CanonicalLivepatchDict` shapes (in `livepatch`).
|
||||
|
||||
## [4.50.0] - 2026-11-28
|
||||
|
||||
### Added
|
||||
- `LoginAccountsMixin.get_login_accounts()`: every account on a Linux host a person can
|
||||
log in with, read with one fixed, read-only command (NetOrk/netork#2707). Root and UID
|
||||
1000 on with a login shell (`login_capable`), from `/etc/passwd` -- name, UID, home and
|
||||
shell only, never the comment field; accounts from a directory are not there and not
|
||||
read. Each with its last login (ISO, UTC), where it came from and which tool told it:
|
||||
the newest of `lastlog2`, `lastlog`, `wtmpdb last` and `last`, so a host upgraded to
|
||||
lastlog2 or a desktop login only wtmp saw still reads right. Its password state
|
||||
(`passwd -S`: `set`, `locked`, `none`), password change, password and account expiry
|
||||
(`chage -l`: an ISO date, `never`, `must_change`), and `locked` -- the password locked or
|
||||
the account expired on the host's date. The failed attempts since the last login as a
|
||||
number: from `lastb` (the newest `FAILED_LOGINS_READ`, 1000, per account;
|
||||
`failed_logins_capped` when reached), else `pam_faillock`'s tally. `LC_ALL=C`, no stdin,
|
||||
no password hash read. Root first; where root is refused, as the login user, when the
|
||||
lock, the expiry and the failures are `None`. A driver supplies
|
||||
`_run_login_accounts_command(command, *, privileged)`.
|
||||
- `parse_login_accounts`, `LOGIN_ACCOUNTS_COMMAND`, `login_capable`, and the
|
||||
`LoginAccountDict` and `LoginAccountsDict` shapes (in `login_accounts`).
|
||||
|
||||
## [4.49.0] - 2026-11-28
|
||||
|
||||
### Added
|
||||
- `RadioStatusDict` carries a radio's runtime state beside its configuration
|
||||
(NetOrk/netork#31): `up` (the radio runs), `pending` (the device is still bringing it
|
||||
up or down) and `setup_failed` (the device gave up bringing it up after its retries).
|
||||
All three are optional: a driver that cannot read the state leaves them out. A radio
|
||||
can be `enabled` and not run, as on 2026-07-16, when a rejected value kept every radio
|
||||
of a fleet in a restart loop the configuration never showed.
|
||||
|
||||
## [4.48.0] - 2026-11-27
|
||||
|
||||
### Added
|
||||
- `HardeningMixin.get_hardening()`: how a Linux host is hardened, read with one fixed,
|
||||
read-only command (NetOrk/netork#2706). The active security modules
|
||||
(`/sys/kernel/security/lsm`), SELinux's mode (`getenforce`, else
|
||||
`/sys/fs/selinux/enforce`) and its configured mode (`SELINUX=` in `/etc/selinux/config`),
|
||||
AppArmor's switch and, as root, its profiles per mode (`aa-status --json`), the crypto
|
||||
policy (`update-crypto-policies --show`) and FIPS mode (`/proc/sys/crypto/fips_enabled`),
|
||||
the kernel's text for each file under `/sys/devices/system/cpu/vulnerabilities`, the
|
||||
kernel command line with `mitigations=` (`auto` when not given) and `nosmt`, and
|
||||
`ID`/`ID_LIKE` from `/etc/os-release`. Read as root first; where root is refused, as the
|
||||
login user, without the profile counts. Anything not read is `None`, never "off". A
|
||||
driver supplies `_run_hardening_command(command, *, privileged)`.
|
||||
- `parse_hardening`, `HARDENING_COMMAND`, `cpu_vulnerability_state` (`not_affected`,
|
||||
`mitigated`, `vulnerable` or `unknown`, from the kernel's words), and the
|
||||
`HardeningDict`, `SelinuxDict` and `AppArmorDict` shapes (in `hardening`).
|
||||
|
||||
## [4.47.0] - 2026-11-26
|
||||
|
||||
### Added
|
||||
- `AptHistoryMixin.get_update_history(since)`: apt's own history log as past transactions
|
||||
(NetOrk/netork#2728), for every driver of a Debian-family host that has `run_command`.
|
||||
`APT_HISTORY_COMMAND` prints `/var/log/apt/history.log` and its rotations
|
||||
(`history.log.<n>.gz` through `zcat`) in one round trip, as the login user (the files
|
||||
are 0644), with the host's time zone (`/etc/localtime`'s link, `/etc/timezone`) and
|
||||
`date +%z` for a zone without a name; only a file that user may not read makes the
|
||||
mixin read it again as root. `parse_apt_history(text, since)` reads apt's dates in that
|
||||
zone and names each transaction as Proxmox VE 9.3's `GET /nodes/{node}/apt/history`
|
||||
does: start time and the number of earlier transactions with that start in the same
|
||||
file, so a node that moves to 9.3 keeps its ids. Strict: a block whose package lines
|
||||
do not read as apt writes them is left out (and still counted), one without
|
||||
`End-Date` has `end` None, a report cut short or a file that could not be read raises.
|
||||
- `apt_history_command(log_dir)`, `host_zone(name, offset)` and `AptHistoryUnreadable`
|
||||
(a `PermissionError`), in `apt_history`.
|
||||
|
||||
## [4.46.0] - 2026-11-26
|
||||
|
||||
### Fixed
|
||||
- `get_services_need_restart()` leaves an LXC container's processes out of the `/proc` scan,
|
||||
as it does Docker's and Podman's (NetOrk/netork#2750). On a Proxmox VE node a container
|
||||
updates itself, and its own systemd's units (`/lxc/<vmid>/ns/system.slice/nginx.service`)
|
||||
read as host services that need a restart. Left out: `/lxc/<name>/` (Proxmox VE, cgroup v1)
|
||||
and `/lxc.payload.<name>/` (LXC 4 and later); `/lxc.monitor/<name>` still counts, since
|
||||
`lxc-start` runs the host's binary.
|
||||
|
||||
## [4.45.0] - 2026-11-26
|
||||
|
||||
### Added
|
||||
- `ServicesRestartMixin.get_services_need_restart()`: the systemd services that still run
|
||||
code an update replaced on disk, so they keep the old library until they restart
|
||||
(NetOrk/netork#2700). One fixed, read-only command as root: `needs-restarting -s` (the dnf
|
||||
family), else `needrestart -b -r l` (Debian, Ubuntu; list only, by option and by
|
||||
`NEEDRESTART_MODE=l`, whatever `needrestart.conf` says), else a scan of
|
||||
`/proc/<pid>/maps` for executable mappings of deleted files under `/usr`, `/lib*`, `/bin`,
|
||||
`/sbin` or `/opt`, each process mapped to its service through `/proc/<pid>/cgroup` as the
|
||||
listening sockets do. A user's own systemd counts as `user@<uid>`, a container's process is
|
||||
left out, and a process in no service is listed under `processes`. A refused root gives
|
||||
no report and raises, never a clean reading. A driver supplies
|
||||
`_run_services_restart_command(command)`.
|
||||
- `parse_services_restart`, `SERVICES_RESTART_COMMAND`, `DELETED_CODE_PATTERN`, and the
|
||||
`ServicesRestartDict` and `RestartProcessDict` shapes (in `services_restart`).
|
||||
|
||||
## [4.44.0] - 2026-11-26
|
||||
|
||||
### Added
|
||||
- `VMDict.uid`, optional: an identity of the guest that survives a migration, a restore
|
||||
and a changed `vmid` (NetOrk/netork#2728). Proxmox VE 9.3 gives every guest one, VMware's
|
||||
instance UUID is one; a driver leaves it out where the platform has none, and a caller
|
||||
then knows the guest by `vmid` alone.
|
||||
- `CredentialExpiryMixin.get_credential_expiry()`: the credential the connection logged in
|
||||
with (`kind` `"api-token"` or `"account"`, its `name`) and when it expires, `None` for
|
||||
never (NetOrk/netork#2728). `PermissionError` where the platform will not tell the
|
||||
credential its own expiry.
|
||||
- `UpdateMixin.get_update_history(since)`: the package manager's past transactions, newest
|
||||
first, each with a stable `id`, start and end, the packages it changed (`action`, old and
|
||||
new version), who asked for it, the command line and the error it ended with
|
||||
(`UpdateHistoryDict`, `UpdateHistoryPackageDict`, NetOrk/netork#2728).
|
||||
|
||||
### Changed
|
||||
- `HypervisorDriver.resume_vm()`: the guest's clock is set to the host's time after it
|
||||
resumes, where the platform can (NetOrk/netork#2728). A documented expectation, not a
|
||||
parameter: no caller wants a guest that runs behind.
|
||||
|
||||
## [4.43.0] - 2026-11-26
|
||||
|
||||
### Added
|
||||
- `opened_ports`: the record of the firewall rules netOrk opened on a host
|
||||
(NetOrk/netork#2693). ufw, iptables and firewalld do not say who wrote a rule, so a
|
||||
driver that opens a port in one of them appends the rule to `/var/lib/netork/opened-ports`
|
||||
(root's, mode 644) -- only when the firewall did not have it before, so an identical rule
|
||||
the operator wrote is never recorded. `parse_opened_ports_record` reads it strictly: not at
|
||||
all where the directory or the file is not root's alone or is a symbolic link, and a line
|
||||
that is not exactly a rule is reported, never acted on. `ufw_allow_recorded_command` and
|
||||
`ufw_delete_command` are ufw's commands, which napalm-linux and napalm-proxmox share,
|
||||
`revoke_recorded_rules` removes the rules recorded under a purpose with the driver's own
|
||||
command and keeps every other line;
|
||||
`revoked_output` says what closing removed and what it left for the port.
|
||||
- `ZabbixAgentMixin._revoke_zabbix_agent_sources(settings)`, optional: for an `active_only`
|
||||
agent, `configure_zabbix_agent`'s firewall step has the driver close what netOrk opened
|
||||
for the agent on an earlier passive run, and nothing else (NetOrk/netork#2693). A driver
|
||||
without it changes nothing and says that it cannot tell netOrk's rule from the
|
||||
operator's.
|
||||
|
||||
## [4.42.0] - 2026-11-25
|
||||
|
||||
### Added
|
||||
- `AptReleaseMixin.get_apt_source_releases()`: the host's release from `/etc/os-release`
|
||||
(`ID`, `ID_LIKE`, `VERSION_CODENAME`, `UBUNTU_CODENAME`) and every enabled source apt
|
||||
reads, one-line and deb822, with its file, line, types, URI, suites and components
|
||||
(NetOrk/netork#2614). `AptProxyMixin` brings it, so every apt driver has it.
|
||||
- `AptReleaseMixin.set_apt_source_release(path, release, codename)`: every suite of
|
||||
*release* in one of apt's source files moved to *codename* (`focal-security` →
|
||||
`noble-security`), once each new suite's `InRelease` or `Release` is fetched with apt's
|
||||
downloader; nothing is written where the vendor has none.
|
||||
- `parse_apt_releases`, `rewrite_release`, `suite_release`, `APT_RELEASES_COMMAND`.
|
||||
- `ZabbixAgentSettingsDict.active_only`: an agent that only connects out
|
||||
(NetOrk/netork#2683). `zabbix_agent_config` writes `StartAgents=0` -- no passive
|
||||
checks, no listening port -- and comments `Server` out, which Zabbix requires only
|
||||
while `StartAgents` is not 0; `check_zabbix_agent_settings` then requires
|
||||
`server_active` instead of `server`. `configure_zabbix_agent`'s firewall step opens
|
||||
nothing for it and does not call the driver's `_allow_zabbix_agent_sources`, so no
|
||||
driver changes.
|
||||
- `HypervisorDriver.resume_vm(name)`: bring a paused or suspended VM back where it stopped,
|
||||
the counterpart of `suspend_vm` (NetOrk/netork#2658). Optional like every power action;
|
||||
a driver that can resume some guests but not others refuses the others with
|
||||
`RuntimeError`.
|
||||
|
||||
### Changed
|
||||
- `zabbix_agent_config` comments a `StartAgents=0` line out for an agent that is not
|
||||
active only, since it would keep the agent from listening; another count stays.
|
||||
- `HypervisorDriver.get_vms()`: a guest that is not executing is never `"running"`. It is
|
||||
`"paused"` while its process still holds its memory and `"suspended"` once its state was
|
||||
saved away (NetOrk/netork#2658). `suspend_vm` names `resume_vm`, not `start_vm`, as the
|
||||
way back.
|
||||
|
||||
## [4.41.0] - 2026-11-17
|
||||
|
||||
### Added
|
||||
- `FirmwareUpgradeMixin.start_firmware_upgrade(version)`: start installing the firmware a
|
||||
driver offers; the device runs it by itself and restarts at its end, and
|
||||
`UpdateMixin.get_update_progress` follows it until then (NetOrk/netork#2615, OpenWrt's
|
||||
sysupgrade through owut).
|
||||
- `FirmwareOfferDict.installable`: whether the driver can install `latest_version` itself
|
||||
now, False while the device lacks what that takes; and
|
||||
`FirmwareOfferDict.latest_major_version`, the newest of a later release line, shown and
|
||||
never crossed to by the driver.
|
||||
|
||||
## [4.40.0] - 2026-11-17
|
||||
|
||||
### Added
|
||||
- `ZabbixAgentMixin.configure_zabbix_agent(settings)`: a native Zabbix agent, for a host
|
||||
without a container engine (NetOrk/netork#2571). Install (`ensure_package` with
|
||||
`ZABBIX_AGENT_PACKAGE`, and where the host's own packages have none and
|
||||
`settings["release"]` names the server's release line, the driver's
|
||||
`_add_zabbix_repository(release)` and a second try), configure (the driver's
|
||||
`_write_zabbix_agent_config`), firewall (the driver's `_allow_zabbix_agent_sources`),
|
||||
start (`manage_service` enable and restart of `ZABBIX_AGENT_SERVICE`). Settings that do
|
||||
not hold raise `ValueError` before anything changes.
|
||||
- `ZabbixAgentSettingsDict`; `zabbix_agent_config(text, settings)`, the agent's
|
||||
configuration with `Server`, `ServerActive`, `ListenPort` and `Hostname` set and the rest
|
||||
kept; `zabbix_repository_command(os_release, release)`, the root command that adds
|
||||
Zabbix's repository for Debian, Ubuntu, Raspberry Pi OS, RHEL, CentOS, Oracle Linux,
|
||||
AlmaLinux and Rocky Linux, in the layout before and since 7.2;
|
||||
`check_zabbix_agent_settings(settings)`.
|
||||
- `fixes.enable_and_restart(manage_service, service)`, the start step `LldpAgentMixin` and
|
||||
`ZabbixAgentMixin` share.
|
||||
- Podman as a container engine (NetOrk/netork#818): `container_engines()` lists it with the
|
||||
API `podman-libpod`, and `open_container_engine("podman")` reaches it with `podman system
|
||||
dial-stdio` (Podman 4.0 and later). It is the host's rootful Podman, so the connection
|
||||
runs every call as root (`ContainerEngineConnection.privileged`, `ROOT_ENGINES`).
|
||||
- `apt_sources`: apt's https sources through the package cache, in the form apt-cacher-ng
|
||||
fetches over https itself and stores (`http://HTTPS///<host>/…`, with `AllowUserPorts=80
|
||||
443` on the cache). `cacheable_https_hosts(report)` names the hosts this applies to, and
|
||||
`rewrite_sources_command` / `revert_sources_command` are the root commands, for `.list`
|
||||
and deb822 `.sources` files. A host apt keeps credentials for in `auth.conf` stays on
|
||||
https, because apt finds them by the host's name and the cache is shared. The rewrite
|
||||
names such a host in the proxy file as `Package-Proxy::Not-Cached` (NetOrk/netork#2555).
|
||||
- `get_package_proxy_report()` reports those hosts as `not_cached`.
|
||||
|
||||
### Changed
|
||||
- `container_engines()` lists an engine only when its CLI names itself on `--version`:
|
||||
podman-docker's `docker` is podman, and is no longer listed as Docker.
|
||||
- `configure_package_proxy(url)` has a step `cache` before `https`. It rewrites the https
|
||||
sources it can, fetches one of them through *url*, and turns them all back to https
|
||||
where *url* cannot. The `fetch` step proves the proxy with a plain http source only.
|
||||
- `configure_package_proxy("")` turns the sources back to https (step `sources`) before it
|
||||
removes the proxy file. Without the cache, apt would look for a host called `HTTPS`.
|
||||
|
||||
## [4.39.0] - 2026-11-14
|
||||
|
||||
### Added
|
||||
|
||||
@@ -124,7 +124,11 @@ application wants made on a device runs as fixed steps the driver implements, wi
|
||||
the caller supplies: `SnmpAgentMixin.configure_snmp_agent(settings)` (install, configure,
|
||||
firewall, start), `LldpAgentMixin.configure_lldp_agent(interfaces)` (install, write the
|
||||
interfaces, enable and restart; the driver writes only the interfaces),
|
||||
`EnsurePackageMixin.ensure_package(name)`, `PackageProxyMixin.configure_package_proxy(url)`,
|
||||
`ZabbixAgentMixin.configure_zabbix_agent(settings)` (install from the host's packages or
|
||||
else Zabbix's repository, configure, firewall, enable and restart; the driver writes the
|
||||
configuration and opens the firewall; an `active_only` agent gets `StartAgents=0` and no
|
||||
firewall opening), `EnsurePackageMixin.ensure_package(name)`,
|
||||
`PackageProxyMixin.configure_package_proxy(url)`,
|
||||
`TimeSyncMixin.configure_time_sync(ntp_servers, timezone)` and
|
||||
`ContainerEngineMixin.grant_container_engine_access(user)`. A driver whose device takes the
|
||||
change in one call overrides the template method. A driver mixes in the fixes its device
|
||||
@@ -155,6 +159,34 @@ rather than by a role base: what a Linux kernel has built and loaded is read the
|
||||
everywhere, so the command and its parse are concrete here and a driver supplies only
|
||||
`_run_kernel_facts_command`. `OSDriver` does not carry it — a Windows host is an OS driver
|
||||
too, and `hasattr(driver, "get_kernel_facts")` has to stay truthful.
|
||||
The kernel facts carry the kernel's live patches too (`live_patches`, from
|
||||
`napalm_device_types.livepatch`): the patches loaded in `/sys/kernel/livepatch` with whether
|
||||
each is enabled, `kpatch list`, and Canonical Livepatch's status for the running kernel with
|
||||
the CVEs it fixes (`canonical-livepatch status --format json`, the daemon's last state; never
|
||||
`refresh`). Where Canonical's client is installed and its status does not read without root, a
|
||||
driver that can gain root supplies `_run_livepatch_status_command` and the mixin reads
|
||||
`LIVEPATCH_STATUS_COMMAND` again through it.
|
||||
|
||||
`HardeningMixin` (`get_hardening`) is mixed in the same way: how the host is hardened, as
|
||||
its kernel and its own tools say it, in one read-only command. The active security modules
|
||||
(`/sys/kernel/security/lsm`), SELinux's mode (`getenforce`) and the mode it boots in
|
||||
(`/etc/selinux/config`), AppArmor's switch and its profiles per mode (`aa-status --json`,
|
||||
the one part that needs root), the crypto policy (`update-crypto-policies --show`) and FIPS
|
||||
mode, the kernel's answer for each CPU vulnerability (`/sys/devices/system/cpu/vulnerabilities`,
|
||||
put in one word by `cpu_vulnerability_state`), `mitigations=` and `nosmt` from the kernel
|
||||
command line, and `ID`/`ID_LIKE` from `/etc/os-release`. Read as root first and, where root
|
||||
is refused, as the login user without the profile counts. A driver supplies
|
||||
`_run_hardening_command(command, privileged=)`; what was not read is `None`, never "off".
|
||||
|
||||
`LoginAccountsMixin` (`get_login_accounts`) is mixed in the same way: every account on the
|
||||
host a person can log in with -- root and UID 1000 on, with a shell that is not `nologin` or
|
||||
`false`, from `/etc/passwd` (name, UID, home and shell only; directory accounts are not read)
|
||||
-- with its last login, the newest any of `lastlog2`, `lastlog`, `wtmpdb last` and `last`
|
||||
knows, and where it came from; its lock and expiry from `passwd -S` and `chage -l`; and the
|
||||
failed attempts since that login, from `lastb` (the newest 1000 per account) or else
|
||||
`pam_faillock`'s tally. Read as root first and, where root is refused, as the login user,
|
||||
when the lock, the expiry and the failures are `None`. A driver supplies
|
||||
`_run_login_accounts_command(command, privileged=)`.
|
||||
|
||||
`ServicePackagesMixin` (`get_service_packages`) is mixed in the same way: which installed
|
||||
packages each systemd service is made of — the one shipping its unit file and the one
|
||||
@@ -172,6 +204,22 @@ wins (`get_package_proxy`, `get_package_proxy_report` with every line that sets
|
||||
different proxy, reads the result back and fetches one http source's `InRelease` through it.
|
||||
A driver supplies `_run_apt_command`, `_run_apt_root_command` and `_write_apt_file`.
|
||||
|
||||
`AptReleaseMixin` (`napalm_device_types.apt_releases`) comes with it: every source apt reads,
|
||||
with its file, line, URI and suites, and the host's release from `/etc/os-release`
|
||||
(`get_apt_source_releases`). A release upgrade leaves third-party sources on the old release,
|
||||
where they stop getting updates once the vendor stops building for it; whether a suite names
|
||||
another release than the host's is the caller's to judge (`suite_release` gives the word).
|
||||
`set_apt_source_release(path, release, codename)` moves every suite of *release* in one
|
||||
source file to *codename*, after fetching each new suite's `InRelease` with apt's downloader:
|
||||
where the vendor has none, the file stays as it is.
|
||||
|
||||
`AptHistoryMixin` (`napalm_device_types.apt_history`) implements
|
||||
`UpdateMixin.get_update_history` from apt's own log over the driver's `run_command`: every
|
||||
transaction in `/var/log/apt/history.log` and its rotations, newest first, with the same
|
||||
ids Proxmox VE 9.3's `GET /nodes/{node}/apt/history` gives (start time and the index among
|
||||
those that started in the same second of the same file). A driver whose host may run
|
||||
another package manager gates it, as napalm-linux does.
|
||||
|
||||
`HostStatusMixin` (`get_host_status`) is mixed in the same way: whether a Linux host needs
|
||||
a reboot to finish an update (`/var/run/reboot-required`, `needs-restarting -r`, or a newer
|
||||
kernel of the running flavour installed), whether it patches itself (unattended-upgrades,
|
||||
@@ -195,6 +243,17 @@ without `ss` is read with `netstat -lntup` (OpenWrt's busybox, old net-tools); o
|
||||
cgroup names the procd service (`/services/<name>/<instance>`). A host with neither raises
|
||||
`ListeningSocketsUnavailable`.
|
||||
|
||||
`ServicesRestartMixin` (`get_services_need_restart`) is mixed in the same way: the systemd
|
||||
services that still run code an update replaced on disk -- an openssl or glibc update is not
|
||||
finished until they restart. One fixed, read-only command, as root: `needs-restarting -s`
|
||||
where dnf-utils has it, else `needrestart -b -r l` (list only, whatever `needrestart.conf`
|
||||
says), else the processes whose `/proc/<pid>/maps` maps deleted code
|
||||
(`DELETED_CODE_PATTERN`), each named by the service its cgroup gives, as for the listening
|
||||
sockets. A container's processes are left out, an LXC container's as well (a Proxmox node's
|
||||
containers update themselves). A driver supplies `_run_services_restart_command(command)`; the command arrives as
|
||||
one `sh -c` argument and reads no stdin. Without root there is no reading: one that saw only
|
||||
the login user's processes would read as clean.
|
||||
|
||||
`LogSourcesMixin` (`get_log_sources`) is mixed in the same way: every log the host writes, in
|
||||
one round trip. The units journald holds entries for (`journalctl -F _SYSTEMD_UNIT`, services
|
||||
only), the log files running processes hold open (`/proc/<pid>/fd`: `*.log`, `*.log.N` and
|
||||
@@ -403,10 +462,11 @@ but not revert sets `revert_config_revision = None`.
|
||||
The mixin sits in `DeviceTypeDriver` and only declares, so `hasattr(driver, "run_command")` is true exactly where a driver implements it. For SSH drivers, `channel.run_on_transport` and `channel.open_stream_on_transport` are the implementation over a paramiko exec channel: no PTY, stderr kept apart, a real exit code. How a command gains root stays with the driver.
|
||||
|
||||
**`ContainerEngineMixin` is deliberately different from `SystemdServicesMixin`.** The systemd mixin owns its command and its parse; this one owns neither.
|
||||
- `container_engines()` says which engines the host offers (`[{"engine": "docker", "api": "docker-engine"}]`).
|
||||
- `container_engines()` says which engines the host offers (`[{"engine": "docker", "api": "docker-engine"}, {"engine": "podman", "api": "podman-libpod"}]`). An engine is listed when its CLI answers `--version` with its own name; podman-docker's `docker` says it is podman and is left out.
|
||||
- `open_container_engine(engine)` returns a `ContainerEngineConnection`:
|
||||
- `open_api()` is a stream to the engine's API (`docker system dial-stdio`);
|
||||
- `open_api()` is a stream to the engine's API (`docker system dial-stdio`, `podman system dial-stdio`);
|
||||
- `run_cli(args)` and `stream_cli(args)` run the engine's CLI with arguments the caller chooses. With `privileged=True` the driver runs it the way `run_command` gains root, for an engine that refuses the login user.
|
||||
- **Podman is reached as root** (`ROOT_ENGINES`, `connection.privileged`): the host's rootful Podman, the engine of the system's containers and of Quadlet's units, whose API `podman.socket` serves. A login user's rootless containers are that user's own and invisible to others. `podman system dial-stdio` exists from Podman 4.0 on and needs the socket listening (`systemctl enable --now podman.socket`) (NetOrk/netork#818).
|
||||
- The driver decides only *how* the engine is reached. Its hook `_container_engine_binary(engine)` returns, for QNAP, the Container Station path, and the caller never sees it.
|
||||
|
||||
**What runs on the engine, and what to do with it, is netOrk's** (NetOrk/netork#765): the container model, the Engine API requests, compose, updates. Above the connection everything is specific to the service, so this package abstracts the connection and nothing more.
|
||||
|
||||
@@ -78,8 +78,10 @@ The same shape replaces every action in today's `run_device_action`:
|
||||
|---|---|
|
||||
| `fix_snmp` | `configure_snmp_agent(settings)` |
|
||||
| `fix_apt_proxy` | `configure_package_proxy(url)` |
|
||||
| an apt source on another release than the host (NetOrk/netork#2614) | `set_apt_source_release(path, release, codename)` |
|
||||
| `fix_docker_permissions` | `grant_container_engine_access(user)` |
|
||||
| `install_lldpd`, `install_auc` | `ensure_package(name)` |
|
||||
| the Zabbix agent where no container engine runs (NetOrk/netork#2571) | `configure_zabbix_agent(settings)` |
|
||||
|
||||
The mixin is mixed in by the driver, or by the platform package, not by a role base. A
|
||||
driver that inherits a template it cannot run on its device, as a NAS driver built on the
|
||||
@@ -154,10 +156,13 @@ the driver.
|
||||
| `package_managers` | rpm, dnf and yum history, apk's and opkg's databases, `/proc/<pid>/comm` |
|
||||
| `kernel` | `/proc`, `/lib/modules`, gzip, base64 |
|
||||
| `listening` | `ss`, `netstat`, `/proc/<pid>/cgroup` |
|
||||
| `services_restart` | `needs-restarting`, `needrestart`, `/proc/<pid>/maps` and `cgroup` |
|
||||
| `systemd` | `systemctl` |
|
||||
| `virtual_ips` | vip-manager, keepalived, awk |
|
||||
| `system_identity` | SMBIOS via sysfs and `dmidecode` |
|
||||
| `package_updates` | apt and dnf output |
|
||||
| `apt_history` | apt's history log, `zcat`, `/etc/localtime` |
|
||||
| `apt_releases` | apt's source files (one-line and deb822), `/etc/os-release`, `apt-helper` |
|
||||
| `ssh_server` | OpenSSH (`sshd -T`, `sshd -t`, `sshd_config`); which algorithms to drop stays the caller's |
|
||||
| `terminal` | ANSI escape codes in shell output |
|
||||
| `channel`: `run_on_transport`, `open_stream_on_transport`, `ParamikoExecStream` | paramiko exec channels |
|
||||
|
||||
@@ -37,12 +37,15 @@ Function classes -- what a device *can do*. Shared behaviour lives here once
|
||||
instead of being restated on every role that happens to need it:
|
||||
|
||||
* :class:`~napalm_device_types.channel.CommandChannelMixin`
|
||||
* :class:`~napalm_device_types.apt_history.AptHistoryMixin`
|
||||
* :class:`~napalm_device_types.config_lifecycle.ConfigLifecycleMixin`
|
||||
* :class:`~napalm_device_types.config_revisions.ConfigRevisionsMixin`
|
||||
* :class:`~napalm_device_types.config_sync.ConfigSyncMixin`
|
||||
* :class:`~napalm_device_types.container_engine.ContainerEngineMixin`
|
||||
* :class:`~napalm_device_types.credential_expiry.CredentialExpiryMixin`
|
||||
* :class:`~napalm_device_types.dhcp.DhcpServerMixin`
|
||||
* :class:`~napalm_device_types.firewall_rules.FirewallRuleMixin`
|
||||
* :class:`~napalm_device_types.hardening.HardeningMixin`
|
||||
* :class:`~napalm_device_types.health_metrics.HealthMetricsMixin`
|
||||
* :class:`~napalm_device_types.host_status.HostStatusMixin`
|
||||
* :class:`~napalm_device_types.host_reboot.HostRebootMixin`
|
||||
@@ -51,6 +54,7 @@ instead of being restated on every role that happens to need it:
|
||||
* :class:`~napalm_device_types.kernel.KernelFactsMixin`
|
||||
* :class:`~napalm_device_types.listening.ListeningSocketsMixin`
|
||||
* :class:`~napalm_device_types.local_accounts.LocalAccountsMixin`
|
||||
* :class:`~napalm_device_types.login_accounts.LoginAccountsMixin`
|
||||
* :class:`~napalm_device_types.log_sources.LogSourcesMixin`
|
||||
* :class:`~napalm_device_types.host_firewall.HostFirewallMixin`
|
||||
* :class:`~napalm_device_types.mac_acl.MacAclMixin`
|
||||
@@ -60,6 +64,7 @@ instead of being restated on every role that happens to need it:
|
||||
* :class:`~napalm_device_types.running_backups.RunningBackupsMixin`
|
||||
* :class:`~napalm_device_types.service_clusters.ServiceClustersMixin`
|
||||
* :class:`~napalm_device_types.service_packages.ServicePackagesMixin`
|
||||
* :class:`~napalm_device_types.services_restart.ServicesRestartMixin`
|
||||
* :class:`~napalm_device_types.ssh_server_auth.SshServerAuthMixin`
|
||||
* :class:`~napalm_device_types.sudo_history.SudoHistoryMixin`
|
||||
* :class:`~napalm_device_types.scheduled_jobs.ScheduledJobsMixin`
|
||||
@@ -78,6 +83,14 @@ Introspection -- :func:`~napalm_device_types.roles.roles_of`,
|
||||
"""
|
||||
|
||||
from napalm_device_types.access_point import AccessPointDriver
|
||||
from napalm_device_types.apt_history import (
|
||||
APT_HISTORY_COMMAND,
|
||||
AptHistoryMixin,
|
||||
AptHistoryUnreadable,
|
||||
apt_history_command,
|
||||
host_zone,
|
||||
parse_apt_history,
|
||||
)
|
||||
from napalm_device_types.apt_proxy import (
|
||||
APT_PROXY_COMMAND,
|
||||
AptProxyMixin,
|
||||
@@ -86,6 +99,15 @@ from napalm_device_types.apt_proxy import (
|
||||
parse_apt_proxy,
|
||||
same_proxy_url,
|
||||
)
|
||||
from napalm_device_types.apt_releases import (
|
||||
APT_RELEASES_COMMAND,
|
||||
AptReleaseFixDict,
|
||||
AptReleaseMixin,
|
||||
AptReleasesDict,
|
||||
AptSourceDict,
|
||||
parse_apt_releases,
|
||||
suite_release,
|
||||
)
|
||||
from napalm_device_types.arp import ARP_AGE_UNKNOWN
|
||||
from napalm_device_types.backup_server import BackupServerDriver
|
||||
from napalm_device_types.backups import (
|
||||
@@ -134,18 +156,31 @@ from napalm_device_types.container_engine import (
|
||||
ContainerEngineMixin,
|
||||
ContainerEngineUnavailable,
|
||||
)
|
||||
from napalm_device_types.credential_expiry import (
|
||||
CredentialExpiryDict,
|
||||
CredentialExpiryMixin,
|
||||
CredentialKind,
|
||||
)
|
||||
from napalm_device_types.dhcp import DhcpApplyError, DhcpServerMixin, normalize_cidr, normalize_mac
|
||||
from napalm_device_types.dns_forward import DnsForwardMixin
|
||||
from napalm_device_types.firewall import FirewallDriver
|
||||
from napalm_device_types.firewall_rules import FirewallRuleMixin
|
||||
from napalm_device_types.firmware import FirmwareOfferMixin
|
||||
from napalm_device_types.firmware import FirmwareOfferDict, FirmwareOfferMixin, FirmwareUpgradeMixin
|
||||
from napalm_device_types.fixes import (
|
||||
EnsurePackageMixin,
|
||||
LldpAgentMixin,
|
||||
PackageProxyMixin,
|
||||
SnmpAgentMixin,
|
||||
ZabbixAgentMixin,
|
||||
run_fix_steps,
|
||||
)
|
||||
from napalm_device_types.hardening import (
|
||||
HARDENING_COMMAND,
|
||||
HardeningDict,
|
||||
HardeningMixin,
|
||||
cpu_vulnerability_state,
|
||||
parse_hardening,
|
||||
)
|
||||
from napalm_device_types.health_metrics import HealthMetricsMixin
|
||||
from napalm_device_types.host_firewall import (
|
||||
HostFirewallMixin,
|
||||
@@ -157,7 +192,12 @@ from napalm_device_types.host_shutdown import HostShutdownMixin
|
||||
from napalm_device_types.host_status import HOST_STATUS_COMMAND, HostStatusMixin, parse_host_status
|
||||
from napalm_device_types.hypervisor import HypervisorDriver
|
||||
from napalm_device_types.interface_filter import InterfaceFilterMixin
|
||||
from napalm_device_types.kernel import KERNEL_FACTS_COMMAND, KernelFactsMixin, parse_kernel_facts
|
||||
from napalm_device_types.kernel import (
|
||||
KERNEL_FACTS_COMMAND,
|
||||
LIVEPATCH_STATUS_COMMAND,
|
||||
KernelFactsMixin,
|
||||
parse_kernel_facts,
|
||||
)
|
||||
from napalm_device_types.lag import add_lag_interfaces
|
||||
from napalm_device_types.licenses import LicenseMixin
|
||||
from napalm_device_types.listening import (
|
||||
@@ -166,6 +206,12 @@ from napalm_device_types.listening import (
|
||||
ListeningSocketsUnavailable,
|
||||
parse_listening_sockets,
|
||||
)
|
||||
from napalm_device_types.livepatch import (
|
||||
CanonicalLivepatchDict,
|
||||
LivePatchesDict,
|
||||
canonical_release,
|
||||
parse_canonical_status,
|
||||
)
|
||||
from napalm_device_types.lldp import (
|
||||
LldpNeighborDict,
|
||||
LldpNeighborRow,
|
||||
@@ -193,6 +239,14 @@ from napalm_device_types.log_sources import (
|
||||
parse_log_forwarding,
|
||||
parse_log_sources,
|
||||
)
|
||||
from napalm_device_types.login_accounts import (
|
||||
LOGIN_ACCOUNTS_COMMAND,
|
||||
LoginAccountDict,
|
||||
LoginAccountsDict,
|
||||
LoginAccountsMixin,
|
||||
login_capable,
|
||||
parse_login_accounts,
|
||||
)
|
||||
from napalm_device_types.mac_acl import MacAclMixin
|
||||
from napalm_device_types.management_controller import ManagementControllerDriver
|
||||
from napalm_device_types.media import MediaDriver
|
||||
@@ -204,7 +258,6 @@ from napalm_device_types.models import (
|
||||
DnsForwardDict,
|
||||
EventLogEntryDict,
|
||||
FirmwareDict,
|
||||
FirmwareOfferDict,
|
||||
FixResultDict,
|
||||
FixStepDict,
|
||||
FixStepOutcomeDict,
|
||||
@@ -220,6 +273,23 @@ from napalm_device_types.models import (
|
||||
UpdateProgressDict,
|
||||
)
|
||||
from napalm_device_types.nat_vpn import NatVpnMixin
|
||||
from napalm_device_types.opened_ports import (
|
||||
OPENED_PORTS_RECORD,
|
||||
SNMP_PURPOSE,
|
||||
ZABBIX_AGENT_PURPOSE,
|
||||
OpenedPortsRecordDict,
|
||||
OpenedRuleDict,
|
||||
RevokedRulesDict,
|
||||
opened_rule_line,
|
||||
opened_rules_text,
|
||||
parse_opened_ports_record,
|
||||
read_opened_ports_command,
|
||||
record_opened_rule_command,
|
||||
revoke_recorded_rules,
|
||||
revoked_output,
|
||||
ufw_allow_recorded_command,
|
||||
ufw_delete_command,
|
||||
)
|
||||
from napalm_device_types.os import OSDriver
|
||||
from napalm_device_types.ospf import OspfMixin
|
||||
from napalm_device_types.package_updates import (
|
||||
@@ -274,6 +344,13 @@ from napalm_device_types.service_packages import (
|
||||
parse_service_packages,
|
||||
)
|
||||
from napalm_device_types.services import ServiceControlMixin
|
||||
from napalm_device_types.services_restart import (
|
||||
SERVICES_RESTART_COMMAND,
|
||||
RestartProcessDict,
|
||||
ServicesRestartDict,
|
||||
ServicesRestartMixin,
|
||||
parse_services_restart,
|
||||
)
|
||||
from napalm_device_types.snmp_health_profile import (
|
||||
SnmpHealthProfile,
|
||||
SnmpInterfacesSpec,
|
||||
@@ -335,7 +412,13 @@ from napalm_device_types.time_sync import (
|
||||
check_ntp_servers,
|
||||
)
|
||||
from napalm_device_types.time_sync_posix import PosixTimeSyncMixin, parse_time_sync
|
||||
from napalm_device_types.updates import PackageIndexMissing, UpdateMixin
|
||||
from napalm_device_types.updates import (
|
||||
PackageIndexMissing,
|
||||
UpdateHistoryAction,
|
||||
UpdateHistoryDict,
|
||||
UpdateHistoryPackageDict,
|
||||
UpdateMixin,
|
||||
)
|
||||
from napalm_device_types.virtual_ips import (
|
||||
VIRTUAL_IPS_COMMAND,
|
||||
VirtualIpsMixin,
|
||||
@@ -343,6 +426,12 @@ from napalm_device_types.virtual_ips import (
|
||||
)
|
||||
from napalm_device_types.vm_migration import MigrationPreflightDict
|
||||
from napalm_device_types.vm_stop_request import VmStopRequestMixin
|
||||
from napalm_device_types.zabbix_agent import (
|
||||
ZabbixAgentSettingsDict,
|
||||
check_zabbix_agent_settings,
|
||||
zabbix_agent_config,
|
||||
zabbix_repository_command,
|
||||
)
|
||||
|
||||
__all__ = [
|
||||
"BACKUP_JOB_KINDS",
|
||||
@@ -374,7 +463,14 @@ __all__ = [
|
||||
"OspfInterfaceDict",
|
||||
"OspfMixin",
|
||||
"UpdateProgressDict",
|
||||
"UpdateHistoryAction",
|
||||
"UpdateHistoryDict",
|
||||
"UpdateHistoryPackageDict",
|
||||
"CredentialExpiryDict",
|
||||
"CredentialExpiryMixin",
|
||||
"CredentialKind",
|
||||
"FirmwareOfferMixin",
|
||||
"FirmwareUpgradeMixin",
|
||||
"LicenseDict",
|
||||
"LicenseMixin",
|
||||
"EnsurePackageMixin",
|
||||
@@ -383,15 +479,48 @@ __all__ = [
|
||||
"FixStepOutcomeDict",
|
||||
"LldpAgentMixin",
|
||||
"PackageProxyMixin",
|
||||
"APT_HISTORY_COMMAND",
|
||||
"AptHistoryMixin",
|
||||
"AptHistoryUnreadable",
|
||||
"apt_history_command",
|
||||
"host_zone",
|
||||
"parse_apt_history",
|
||||
"APT_PROXY_COMMAND",
|
||||
"AptProxyMixin",
|
||||
"https_proxy_for",
|
||||
"parse_apt_fetch",
|
||||
"parse_apt_proxy",
|
||||
"same_proxy_url",
|
||||
"APT_RELEASES_COMMAND",
|
||||
"AptReleaseFixDict",
|
||||
"AptReleaseMixin",
|
||||
"AptReleasesDict",
|
||||
"AptSourceDict",
|
||||
"parse_apt_releases",
|
||||
"suite_release",
|
||||
"SnmpAgentMixin",
|
||||
"SnmpAgentSettingsDict",
|
||||
"run_fix_steps",
|
||||
"ZabbixAgentMixin",
|
||||
"ZabbixAgentSettingsDict",
|
||||
"check_zabbix_agent_settings",
|
||||
"zabbix_agent_config",
|
||||
"zabbix_repository_command",
|
||||
"OPENED_PORTS_RECORD",
|
||||
"SNMP_PURPOSE",
|
||||
"ZABBIX_AGENT_PURPOSE",
|
||||
"OpenedPortsRecordDict",
|
||||
"OpenedRuleDict",
|
||||
"opened_rule_line",
|
||||
"opened_rules_text",
|
||||
"parse_opened_ports_record",
|
||||
"read_opened_ports_command",
|
||||
"record_opened_rule_command",
|
||||
"RevokedRulesDict",
|
||||
"revoke_recorded_rules",
|
||||
"revoked_output",
|
||||
"ufw_allow_recorded_command",
|
||||
"ufw_delete_command",
|
||||
"SnmpHealthProfile",
|
||||
"SnmpInterfacesSpec",
|
||||
"SnmpMemorySpec",
|
||||
@@ -455,7 +584,28 @@ __all__ = [
|
||||
"KernelFactsMixin",
|
||||
"KERNEL_FACTS_COMMAND",
|
||||
"parse_kernel_facts",
|
||||
"LIVEPATCH_STATUS_COMMAND",
|
||||
"CanonicalLivepatchDict",
|
||||
"LivePatchesDict",
|
||||
"canonical_release",
|
||||
"parse_canonical_status",
|
||||
"HARDENING_COMMAND",
|
||||
"HardeningMixin",
|
||||
"HardeningDict",
|
||||
"cpu_vulnerability_state",
|
||||
"parse_hardening",
|
||||
"LOGIN_ACCOUNTS_COMMAND",
|
||||
"LoginAccountDict",
|
||||
"LoginAccountsDict",
|
||||
"LoginAccountsMixin",
|
||||
"login_capable",
|
||||
"parse_login_accounts",
|
||||
"SERVICE_PACKAGES_COMMAND",
|
||||
"SERVICES_RESTART_COMMAND",
|
||||
"ServicesRestartMixin",
|
||||
"ServicesRestartDict",
|
||||
"RestartProcessDict",
|
||||
"parse_services_restart",
|
||||
"ServicePackagesMixin",
|
||||
"parse_service_packages",
|
||||
"LISTENING_SOCKETS_COMMAND",
|
||||
|
||||
@@ -0,0 +1,115 @@
|
||||
"""The shapes an access point's getters return (models.py's Access Point part).
|
||||
|
||||
Apart from ``models.py`` for its size; ``models`` re-exports each, so
|
||||
``napalm_device_types.models.RadioStatusDict`` stays where callers import it.
|
||||
"""
|
||||
|
||||
from typing import NotRequired
|
||||
|
||||
from typing_extensions import TypedDict
|
||||
|
||||
|
||||
class WirelessClientDict(TypedDict):
|
||||
mac: str
|
||||
ssid: str
|
||||
radio: str
|
||||
signal: int
|
||||
noise: int
|
||||
tx_rate: float
|
||||
rx_rate: float
|
||||
uptime: int
|
||||
# Optional fields populated by DHCP cross-reference (e.g. from firewall)
|
||||
ip: NotRequired[str]
|
||||
hostname: NotRequired[str]
|
||||
lease_end: NotRequired[int] # Unix timestamp when DHCP lease expires
|
||||
|
||||
|
||||
class SSIDDict(TypedDict):
|
||||
enabled: bool
|
||||
radio: str
|
||||
bssid: str
|
||||
encryption: str
|
||||
hidden: bool
|
||||
clients: int
|
||||
|
||||
|
||||
class RadioStatusDict(TypedDict):
|
||||
"""One radio: ``enabled`` is the configuration, the rest what the radio does.
|
||||
|
||||
The runtime state is left out where the driver cannot read it, never guessed
|
||||
(NetOrk/netork#31): ``up`` whether the radio runs, ``pending`` whether the
|
||||
device is still bringing it up or down, ``setup_failed`` whether the device
|
||||
gave up bringing it up after its retries.
|
||||
"""
|
||||
|
||||
enabled: bool
|
||||
band: str
|
||||
channel: int
|
||||
channel_width: int
|
||||
tx_power: int
|
||||
frequency: float
|
||||
up: NotRequired[bool]
|
||||
pending: NotRequired[bool]
|
||||
setup_failed: NotRequired[bool]
|
||||
|
||||
|
||||
class ChannelScanEntryDict(TypedDict):
|
||||
"""One neighboring AP entry as returned by get_channel_scan()."""
|
||||
|
||||
bssid: str
|
||||
ssid: str
|
||||
frequency: int # centre frequency in MHz, e.g. 2437
|
||||
channel: int # channel number, e.g. 6
|
||||
signal_dbm: int # RSSI in dBm, e.g. -72
|
||||
channel_width: int # MHz: 20 / 40 / 80 / 160; 0 if unknown
|
||||
band: str # "2.4GHz" | "5GHz" | "6GHz"
|
||||
|
||||
|
||||
class WirelessConfigDict(TypedDict):
|
||||
country_code: str
|
||||
regulatory_domain: str
|
||||
beacon_interval: int
|
||||
dtim_period: int
|
||||
rts_threshold: int
|
||||
fragmentation_threshold: int
|
||||
short_preamble: bool
|
||||
wmm_enabled: bool
|
||||
|
||||
|
||||
class FastTransitionConfigDict(TypedDict):
|
||||
enabled: bool
|
||||
ssid: str
|
||||
mobility_domain: str
|
||||
reassociation_deadline: int
|
||||
r0_key_lifetime: int
|
||||
r1_key_holder: str
|
||||
pmk_r1_push: bool
|
||||
over_ds: bool
|
||||
|
||||
|
||||
class MeshPeerDict(TypedDict):
|
||||
mac: str
|
||||
radio: str
|
||||
signal: int
|
||||
tx_rate: float
|
||||
rx_rate: float
|
||||
uptime: int
|
||||
hop_count: int
|
||||
|
||||
|
||||
class MeshConfigDict(TypedDict):
|
||||
enabled: bool
|
||||
radio: str
|
||||
mesh_id: str
|
||||
path_metric: str
|
||||
gate_announcements: bool
|
||||
is_gate: bool
|
||||
encryption: str
|
||||
|
||||
|
||||
class SSIDBridgeDict(TypedDict):
|
||||
ssid: str
|
||||
bridge: str
|
||||
vlan_id: int
|
||||
tagged: bool
|
||||
client_isolation: bool
|
||||
@@ -0,0 +1,402 @@
|
||||
"""apt's history log as past transactions (``UpdateMixin.get_update_history``, NetOrk/netork#2728).
|
||||
|
||||
apt appends a block to ``/var/log/apt/history.log`` for every run that changed a
|
||||
package, also those no caller started (an operator's ``apt``, unattended-upgrades,
|
||||
PackageKit)::
|
||||
|
||||
Start-Date: 2026-11-26 10:00:00
|
||||
Commandline: apt-get -y upgrade
|
||||
Requested-By: admin (1000)
|
||||
Install: linux-image-6.12.57+deb13-amd64:amd64 (6.12.57-1, automatic)
|
||||
Upgrade: openssh-server:amd64 (1:10.0p1-7, 1:10.0p1-7+deb13u1)
|
||||
Remove: ifupdown:amd64 (0.8.44)
|
||||
Error: Sub-process /usr/bin/dpkg returned an error code (1)
|
||||
End-Date: 2026-11-26 10:01:00
|
||||
|
||||
logrotate moves it to ``history.log.1.gz`` and on, monthly, twelve deep by default.
|
||||
The file is 0644 on Debian and Ubuntu, so :data:`APT_HISTORY_COMMAND` reads it
|
||||
as the login user; :class:`AptHistoryMixin` asks for root only where a file is
|
||||
not readable that way. One round trip prints every file behind a marker line,
|
||||
the host's time zone (``/etc/localtime``'s link, ``/etc/timezone``) and its UTC
|
||||
offset (``date +%z``), which stands in where the zone has no name.
|
||||
|
||||
The dates are the host's local time. A transaction is named like Proxmox VE 9.3's
|
||||
``GET /nodes/{node}/apt/history`` names it: its start in unix seconds and the
|
||||
number of earlier transactions with the same start **in the same log file**, so
|
||||
a Proxmox VE node that moves to 9.3 keeps the ids it had. The count takes every
|
||||
block with a readable start, also one skipped below; it never depends on *since*.
|
||||
|
||||
Strict: a block whose package lines or end do not read as apt writes them is left
|
||||
out, never guessed at; a block without ``End-Date`` is one that is running or was
|
||||
interrupted (``end`` None). A report cut short, or a file that could not be read,
|
||||
raises: an empty list means no transaction, never "could not read".
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import re
|
||||
from collections.abc import Callable
|
||||
from datetime import datetime, timedelta, timezone, tzinfo
|
||||
from typing import TYPE_CHECKING
|
||||
from zoneinfo import ZoneInfo, ZoneInfoNotFoundError
|
||||
|
||||
from napalm_device_types._time_sync_reading import _zone_name
|
||||
from napalm_device_types.updates import (
|
||||
UpdateHistoryAction,
|
||||
UpdateHistoryDict,
|
||||
UpdateHistoryPackageDict,
|
||||
)
|
||||
|
||||
if TYPE_CHECKING: # pragma: no cover - for type checkers only
|
||||
from napalm_device_types.channel import CommandResult
|
||||
|
||||
#: Where apt keeps its history log.
|
||||
APT_HISTORY_DIR = "/var/log/apt"
|
||||
|
||||
_MARK = "### apt-history"
|
||||
|
||||
#: Seconds the read may take: twelve rotated months of a busy host.
|
||||
_READ_TIMEOUT = 120
|
||||
|
||||
|
||||
def apt_history_command(log_dir: str = APT_HISTORY_DIR) -> str:
|
||||
"""``sh`` that prints the time zone, the UTC offset and every history file in *log_dir*.
|
||||
|
||||
Each file follows a ``### apt-history file <path>`` line and ends with a
|
||||
``### apt-history status <exit code>`` line; one the login user may not read
|
||||
is only named (``unreadable``). ``### apt-history end`` closes the report.
|
||||
"""
|
||||
return (
|
||||
f"m='{_MARK}'; "
|
||||
"z=$( { readlink /etc/localtime || cat /etc/timezone; } 2>/dev/null | head -n 1); "
|
||||
'printf "%s zone %s\\n" "$m" "$z"; '
|
||||
'printf "%s offset %s\\n" "$m" "$(date +%z)"; '
|
||||
f"for f in {log_dir}/history.log {log_dir}/history.log.*; do "
|
||||
'[ -f "$f" ] || continue; '
|
||||
'if [ ! -r "$f" ]; then printf "%s unreadable %s\\n" "$m" "$f"; continue; fi; '
|
||||
'printf "%s file %s\\n" "$m" "$f"; '
|
||||
'case "$f" in *.gz) zcat -- "$f";; *) cat -- "$f";; esac 2>/dev/null; '
|
||||
'printf "\\n%s status %s\\n" "$m" "$?"; '
|
||||
"done; "
|
||||
'printf "%s end\\n" "$m"'
|
||||
)
|
||||
|
||||
|
||||
#: Prints apt's history log, rotated files too, with the host's time zone.
|
||||
APT_HISTORY_COMMAND = apt_history_command()
|
||||
|
||||
|
||||
class AptHistoryUnreadable(PermissionError):
|
||||
"""A history file the user that read the log may not read."""
|
||||
|
||||
|
||||
#: The package lines apt writes, and the action each stands for.
|
||||
_ACTIONS: dict[str, UpdateHistoryAction] = {
|
||||
"Install": "install",
|
||||
"Reinstall": "reinstall",
|
||||
"Upgrade": "upgrade",
|
||||
"Downgrade": "downgrade",
|
||||
"Remove": "remove",
|
||||
"Purge": "purge",
|
||||
"Disappeared": "disappear",
|
||||
}
|
||||
#: ``name[:arch] (versions)``; neither a name nor a Debian version holds ``,``, ``(`` or ``)``.
|
||||
_ENTRY = re.compile(r"([^\s,()]+) \(([^()]*)\)")
|
||||
#: ``Disappeared`` names a package without a version where apt no longer knows it.
|
||||
_DISAPPEARED = re.compile(r"([^\s,()]+)(?: \(([^\s,()]+)\))?")
|
||||
_REQUESTED_BY = re.compile(r"(.+) \(\d+\)")
|
||||
_DATE = "%Y-%m-%d %H:%M:%S"
|
||||
_OFFSET = re.compile(r"([+-])(\d\d)(\d\d)")
|
||||
#: ``history.log``, ``history.log.<n>`` and ``history.log.<n>.gz``.
|
||||
_ROTATED = re.compile(r"history\.log(?:\.(\d+)(?:\.gz)?)?")
|
||||
|
||||
|
||||
def host_zone(name: str, offset: str) -> tzinfo:
|
||||
"""The host's zone from its name, else the fixed UTC offset ``date +%z`` printed.
|
||||
|
||||
:raises ValueError: when neither says.
|
||||
"""
|
||||
zone = _zone_name(name)
|
||||
if zone:
|
||||
try:
|
||||
return ZoneInfo(zone)
|
||||
except (ZoneInfoNotFoundError, ValueError):
|
||||
pass
|
||||
match = _OFFSET.fullmatch(offset.strip())
|
||||
if match is None:
|
||||
raise ValueError(f"the host named no time zone ({name!r}) and no UTC offset ({offset!r})")
|
||||
sign = -1 if match.group(1) == "-" else 1
|
||||
return timezone(sign * timedelta(hours=int(match.group(2)), minutes=int(match.group(3))))
|
||||
|
||||
|
||||
def _local(value: str, zone: tzinfo) -> int | None:
|
||||
"""apt's ``YYYY-MM-DD HH:MM:SS`` in *zone* as unix seconds; None for anything else."""
|
||||
try:
|
||||
when = datetime.strptime(" ".join(value.split()), _DATE)
|
||||
except ValueError:
|
||||
return None
|
||||
return int(when.replace(tzinfo=zone).timestamp())
|
||||
|
||||
|
||||
_Versions = tuple[str | None, str | None] | None
|
||||
|
||||
|
||||
def _installed(v: list[str]) -> _Versions:
|
||||
return (None, v[0]) if v[1:] in ([], ["automatic"]) else None
|
||||
|
||||
|
||||
def _changed(v: list[str]) -> _Versions:
|
||||
return (v[0], v[1]) if len(v) == 2 else None
|
||||
|
||||
|
||||
def _same(v: list[str]) -> _Versions:
|
||||
return (v[0], v[0]) if len(v) == 1 else None
|
||||
|
||||
|
||||
def _removed(v: list[str]) -> _Versions:
|
||||
# A package removed earlier and purged now has no installed version: ``Purge: name ()``.
|
||||
return (v[0] or None, None) if len(v) == 1 else None
|
||||
|
||||
|
||||
def _gone(v: list[str]) -> _Versions:
|
||||
return ((v[0] if v else None), None) if len(v) <= 1 else None
|
||||
|
||||
|
||||
#: Per action: ``(old, new)`` from the versions apt wrote in a package's brackets.
|
||||
_VERSIONS: dict[UpdateHistoryAction, Callable[[list[str]], _Versions]] = {
|
||||
"install": _installed,
|
||||
"reinstall": _same,
|
||||
"upgrade": _changed,
|
||||
"downgrade": _changed,
|
||||
"remove": _removed,
|
||||
"purge": _removed,
|
||||
"disappear": _gone,
|
||||
}
|
||||
|
||||
|
||||
def _versions(action: UpdateHistoryAction, versions: list[str]) -> _Versions:
|
||||
"""``(old, new)`` of one package; None where what apt wrote does not fit *action*."""
|
||||
if action not in ("remove", "purge") and not all(versions):
|
||||
return None
|
||||
return _VERSIONS[action](versions)
|
||||
|
||||
|
||||
def _disappeared(value: str) -> list[tuple[str, list[str]]] | None:
|
||||
found = [_DISAPPEARED.fullmatch(item) for item in value.split(", ")]
|
||||
if not all(found):
|
||||
return None
|
||||
return [(m.group(1), [m.group(2)] if m.group(2) else []) for m in found if m]
|
||||
|
||||
|
||||
def _entries(action: UpdateHistoryAction, value: str) -> list[tuple[str, list[str]]] | None:
|
||||
"""``(name[:arch], versions)`` per package of a line; None unless all of it reads."""
|
||||
if action == "disappear":
|
||||
return _disappeared(value)
|
||||
matches = list(_ENTRY.finditer(value))
|
||||
if not matches or ", ".join(m.group(0) for m in matches) != value:
|
||||
return None
|
||||
return [(m.group(1), [v.strip() for v in m.group(2).split(",")]) for m in matches]
|
||||
|
||||
|
||||
def _packages(action: UpdateHistoryAction, value: str) -> list[UpdateHistoryPackageDict] | None:
|
||||
"""The packages of one ``Install:``-style line; None unless every one reads."""
|
||||
entries = _entries(action, value.strip())
|
||||
if entries is None:
|
||||
return None
|
||||
packages: list[UpdateHistoryPackageDict] = []
|
||||
for name, versions in entries:
|
||||
pair = _versions(action, versions)
|
||||
if pair is None:
|
||||
return None
|
||||
packages.append(
|
||||
{
|
||||
"name": name.split(":", 1)[0],
|
||||
"action": action,
|
||||
"old_version": pair[0],
|
||||
"new_version": pair[1],
|
||||
}
|
||||
)
|
||||
return packages
|
||||
|
||||
|
||||
def _transaction(start: int, lines: list[str], zone: tzinfo) -> UpdateHistoryDict | None:
|
||||
"""One block after its ``Start-Date``; None where a line does not read."""
|
||||
found: UpdateHistoryDict = {
|
||||
"id": "",
|
||||
"start": start,
|
||||
"end": None,
|
||||
"packages": [],
|
||||
"requested_by": None,
|
||||
"command": None,
|
||||
"error": None,
|
||||
}
|
||||
for line in lines:
|
||||
key, sep, value = line.partition(": ")
|
||||
if not sep:
|
||||
return None
|
||||
if key in _ACTIONS:
|
||||
packages = _packages(_ACTIONS[key], value)
|
||||
if packages is None:
|
||||
return None
|
||||
found["packages"].extend(packages)
|
||||
elif key == "End-Date":
|
||||
found["end"] = _local(value, zone)
|
||||
if found["end"] is None:
|
||||
return None
|
||||
elif key in ("Commandline", "Requested-By", "Error"):
|
||||
_text(found, key, value.strip())
|
||||
return found
|
||||
|
||||
|
||||
def _text(found: UpdateHistoryDict, key: str, value: str) -> None:
|
||||
if key == "Commandline":
|
||||
found["command"] = value or None
|
||||
elif key == "Requested-By":
|
||||
match = _REQUESTED_BY.fullmatch(value)
|
||||
found["requested_by"] = (match.group(1) if match else value) or None
|
||||
else:
|
||||
found["error"] = value or None
|
||||
|
||||
|
||||
def _blocks(lines: list[str]) -> list[tuple[str, list[str]]]:
|
||||
"""``(Start-Date value, the lines after it)`` per block of one file."""
|
||||
blocks: list[tuple[str, list[str]]] = []
|
||||
for line in lines:
|
||||
line = line.rstrip("\r")
|
||||
if line.startswith("Start-Date:"):
|
||||
blocks.append((line.partition(":")[2], []))
|
||||
elif blocks and line.strip():
|
||||
blocks[-1][1].append(line)
|
||||
return blocks
|
||||
|
||||
|
||||
def _file_transactions(lines: list[str], zone: tzinfo) -> list[UpdateHistoryDict]:
|
||||
"""One file's transactions in the order it holds them, each with its id."""
|
||||
seen: dict[int, int] = {}
|
||||
found: list[UpdateHistoryDict] = []
|
||||
for date, body in _blocks(lines):
|
||||
start = _local(date, zone)
|
||||
if start is None:
|
||||
continue
|
||||
index = seen.get(start, 0)
|
||||
seen[start] = index + 1
|
||||
transaction = _transaction(start, body, zone)
|
||||
if transaction is not None:
|
||||
transaction["id"] = f"{start}-{index}"
|
||||
found.append(transaction)
|
||||
return found
|
||||
|
||||
|
||||
def _rotation(path: str) -> int | None:
|
||||
"""0 for ``history.log``, *n* for its *n*-th rotation; None for another file."""
|
||||
match = _ROTATED.fullmatch(path.rpartition("/")[2])
|
||||
if match is None:
|
||||
return None
|
||||
return int(match.group(1) or 0)
|
||||
|
||||
|
||||
def _marker(
|
||||
kind: str, rest: str, values: dict[str, str], files: dict[int, list[str]]
|
||||
) -> list[str] | None:
|
||||
"""Take one marker line; the lines of the history file it opens, if it opens one.
|
||||
|
||||
:raises AptHistoryUnreadable: for a history file the user may not read.
|
||||
"""
|
||||
rotation = _rotation(rest.strip())
|
||||
if kind == "unreadable" and rotation is not None:
|
||||
raise AptHistoryUnreadable(f"{rest.strip()} is not readable")
|
||||
if kind == "file" and rotation is not None:
|
||||
return files.setdefault(rotation, [])
|
||||
if kind in ("zone", "offset"):
|
||||
values[kind] = rest
|
||||
return None
|
||||
|
||||
|
||||
def _report(text: str) -> tuple[dict[str, str], dict[int, list[str]]]:
|
||||
"""The report's ``zone`` and ``offset``, and each history file's lines by rotation.
|
||||
|
||||
:raises ValueError: for a report cut short or a file that could not be read.
|
||||
:raises AptHistoryUnreadable: for a file the user may not read.
|
||||
"""
|
||||
values: dict[str, str] = {}
|
||||
files: dict[int, list[str]] = {}
|
||||
current: list[str] | None = None
|
||||
for line in text.splitlines():
|
||||
if not line.startswith(_MARK + " "):
|
||||
if current is not None:
|
||||
current.append(line)
|
||||
continue
|
||||
kind, _, rest = line[len(_MARK) + 1 :].partition(" ")
|
||||
if kind == "end":
|
||||
return values, files
|
||||
if kind == "status" and current is not None and rest.strip() != "0":
|
||||
raise ValueError(f"apt's history log could not be read (exit {rest.strip()})")
|
||||
current = _marker(kind, rest, values, files)
|
||||
raise ValueError("apt's history log came back cut short")
|
||||
|
||||
|
||||
def parse_apt_history(text: str, since: int | None = None) -> list[UpdateHistoryDict]:
|
||||
""":data:`APT_HISTORY_COMMAND`'s report as transactions, newest first.
|
||||
|
||||
:param since: Unix seconds; only transactions that started at or after it.
|
||||
:raises ValueError: for a report cut short, a file that could not be read, or
|
||||
a host that named neither its time zone nor its UTC offset.
|
||||
:raises AptHistoryUnreadable: for a file the user may not read.
|
||||
"""
|
||||
values, files = _report(text)
|
||||
zone = host_zone(values.get("zone", ""), values.get("offset", ""))
|
||||
oldest_first: list[UpdateHistoryDict] = []
|
||||
for rotation in sorted(files, reverse=True):
|
||||
oldest_first.extend(_file_transactions(files[rotation], zone))
|
||||
newest = sorted(reversed(oldest_first), key=lambda t: t["start"], reverse=True)
|
||||
return [t for t in newest if since is None or t["start"] >= since]
|
||||
|
||||
|
||||
class AptHistoryMixin:
|
||||
"""Adds :meth:`get_update_history` from apt's log, over the driver's ``run_command``.
|
||||
|
||||
Mixed in by the drivers of Debian-family hosts, so
|
||||
``hasattr(driver, "get_update_history")`` stays a truthful answer. The log is
|
||||
read as the login user; only a file that user may not read makes it read as root.
|
||||
"""
|
||||
|
||||
if TYPE_CHECKING: # pragma: no cover - declared for type checkers only
|
||||
|
||||
def run_command(
|
||||
self,
|
||||
command: str,
|
||||
*,
|
||||
privileged: bool = False,
|
||||
timeout: float = 60,
|
||||
stdin: bytes | None = None,
|
||||
) -> CommandResult: ...
|
||||
|
||||
def get_update_history(self, since: int | None = None) -> list[UpdateHistoryDict]:
|
||||
"""apt's transactions on the host, newest first, from *since* (unix seconds) on.
|
||||
|
||||
:raises RuntimeError: when the log could not be read.
|
||||
:raises ValueError: when the report came back cut short.
|
||||
:raises AptHistoryUnreadable: when even root could not read a file.
|
||||
"""
|
||||
try:
|
||||
return parse_apt_history(self._read_apt_history(privileged=False), since)
|
||||
except AptHistoryUnreadable:
|
||||
return parse_apt_history(self._read_apt_history(privileged=True), since)
|
||||
|
||||
def _read_apt_history(self, *, privileged: bool) -> str:
|
||||
result = self.run_command(APT_HISTORY_COMMAND, privileged=privileged, timeout=_READ_TIMEOUT)
|
||||
if result.exit_code != 0:
|
||||
said = (result.stderr or result.stdout).strip()[-300:]
|
||||
raise RuntimeError(f"cannot read apt's history log: {said or result.exit_code}")
|
||||
return result.stdout
|
||||
|
||||
|
||||
__all__ = [
|
||||
"APT_HISTORY_COMMAND",
|
||||
"APT_HISTORY_DIR",
|
||||
"AptHistoryMixin",
|
||||
"AptHistoryUnreadable",
|
||||
"apt_history_command",
|
||||
"host_zone",
|
||||
"parse_apt_history",
|
||||
]
|
||||
@@ -35,8 +35,12 @@ page is the right one, the caller says (``expect``).
|
||||
out every other line that sets a different one, reads the result back from
|
||||
``apt-config``, and fetches the ``InRelease`` of one http source through it. The
|
||||
last step is what proves it: apt reached a mirror through the proxy it is now set
|
||||
to. The source chosen is one apt does not fetch ``DIRECT``. Then it fetches one
|
||||
https source the same way; where the proxy refuses it, https goes ``DIRECT``.
|
||||
to. The source chosen is one apt does not fetch ``DIRECT``. Then the https sources
|
||||
go through the proxy in the form it stores (:mod:`~napalm_device_types.apt_sources`),
|
||||
and one of them is fetched; where the proxy cannot, they go back to https. Last it
|
||||
fetches one https source left the same way; where the proxy refuses it, https goes
|
||||
``DIRECT``. Removing the proxy turns the sources back to https first: without the
|
||||
proxy apt cannot fetch the stored form.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
@@ -49,6 +53,15 @@ from urllib.parse import urlsplit
|
||||
|
||||
from typing_extensions import TypedDict
|
||||
|
||||
from napalm_device_types.apt_releases import AptReleaseMixin
|
||||
from napalm_device_types.apt_sources import (
|
||||
NOT_CACHED_KEY,
|
||||
VIA_CACHE,
|
||||
cacheable_https_hosts,
|
||||
is_host_name,
|
||||
revert_sources_command,
|
||||
rewrite_sources_command,
|
||||
)
|
||||
from napalm_device_types.fixes import PackageProxyMixin, run_fix_steps
|
||||
from napalm_device_types.models import FixResultDict, FixStepOutcomeDict
|
||||
from napalm_device_types.terminal import strip_terminal_codes
|
||||
@@ -87,6 +100,9 @@ class AptProxyReportDict(TypedDict):
|
||||
#: The base URIs of the host's sources over http and over https.
|
||||
http_sources: list[str]
|
||||
https_sources: list[str]
|
||||
#: The hosts the cache rewrite left on https, for their credentials
|
||||
#: (:data:`~napalm_device_types.apt_sources.NOT_CACHED_KEY`).
|
||||
not_cached: list[str]
|
||||
|
||||
|
||||
class ProxyFetchDict(TypedDict):
|
||||
@@ -123,7 +139,8 @@ PROXY_URL = re.compile(r"^https?://[A-Za-z0-9.\-\[\]:@%_~/]+$")
|
||||
#: them early.
|
||||
APT_PROXY_COMMAND = (
|
||||
"( export LC_ALL=C; printf '%s%s\\n' APROXY_ BEGIN; "
|
||||
"echo '[dump]'; apt-config dump 2>/dev/null | grep -i -E '^Acquire::https?::Proxy'; "
|
||||
"echo '[dump]'; apt-config dump 2>/dev/null "
|
||||
"| grep -i -E '^(Acquire::https?::Proxy|Package-Proxy::)'; "
|
||||
'eval "$(apt-config shell ap_parts Dir::Etc::parts/d ap_main Dir::Etc::main/f 2>/dev/null)"; '
|
||||
"echo '[parts]'; for f in \"${ap_parts:-/etc/apt/apt.conf.d/}\"*; do "
|
||||
'[ -f "$f" ] && grep -Hin proxy "$f"; done; '
|
||||
@@ -133,6 +150,7 @@ APT_PROXY_COMMAND = (
|
||||
"printf '%s%s\\n' APROXY_ END ) 2>/dev/null | cat"
|
||||
)
|
||||
|
||||
_NOT_CACHED = re.compile(rf'^{re.escape(NOT_CACHED_KEY)}::\s+"([^"]+)"', re.I)
|
||||
_DUMP = re.compile(r'^Acquire::(https?)::Proxy(::\S+|-Auto-Detect)?\s+"([^"]*)"', re.I)
|
||||
_GREP = re.compile(r"^(/[^:]+):(\d+):(.*)$")
|
||||
_FLAT = re.compile(r'^\s*Acquire::http::Proxy\s+"([^"]*)"\s*;', re.I)
|
||||
@@ -293,6 +311,7 @@ def parse_apt_proxy(output: str) -> AptProxyReportDict:
|
||||
"https_settings": _settings(lines, _https_setting),
|
||||
"http_sources": _of_scheme(sources, "http"),
|
||||
"https_sources": _of_scheme(sources, "https"),
|
||||
"not_cached": [m.group(1) for m in map(_NOT_CACHED.match, sections.get("dump", [])) if m],
|
||||
}
|
||||
|
||||
|
||||
@@ -409,7 +428,7 @@ def _described(s: AptProxySettingDict) -> str:
|
||||
return f"{s['file']}:{s['line']} ({s['value']}) {what}"
|
||||
|
||||
|
||||
class AptProxyMixin(PackageProxyMixin):
|
||||
class AptProxyMixin(AptReleaseMixin, PackageProxyMixin):
|
||||
""":class:`~napalm_device_types.fixes.PackageProxyMixin` for a Debian-family host.
|
||||
|
||||
The template form, like :class:`~napalm_device_types.host_status.HostStatusMixin`:
|
||||
@@ -498,16 +517,20 @@ class AptProxyMixin(PackageProxyMixin):
|
||||
def configure_package_proxy(self, url: str) -> FixResultDict:
|
||||
"""apt fetches through *url*, and is shown to; ``""`` removes :attr:`APT_PROXY_FILE`.
|
||||
|
||||
https goes through *url* too, unless *url* refuses it: then ``DIRECT``.
|
||||
The https sources go through *url* in the form it stores, where it can; the
|
||||
rest goes through *url* too, unless *url* refuses it: then ``DIRECT``.
|
||||
"""
|
||||
if not url:
|
||||
return run_fix_steps([("configure", self._remove_package_proxy)])
|
||||
return run_fix_steps(
|
||||
[("sources", self._revert_sources), ("configure", self._remove_package_proxy)]
|
||||
)
|
||||
return run_fix_steps(
|
||||
[
|
||||
("configure", lambda: self._write_package_proxy(url)),
|
||||
("conflicts", lambda: self._comment_out_other_proxies(url)),
|
||||
("verify", lambda: self._verify_package_proxy(url)),
|
||||
("fetch", lambda: self._fetch_through_package_proxy(url)),
|
||||
("cache", lambda: self._cache_https_sources(url)),
|
||||
("https", lambda: self._https_through_package_proxy(url)),
|
||||
]
|
||||
)
|
||||
@@ -515,6 +538,11 @@ class AptProxyMixin(PackageProxyMixin):
|
||||
def _not_apt(self) -> FixStepOutcomeDict:
|
||||
return {"ok": False, "output": "not an apt host"}
|
||||
|
||||
def _revert_sources(self) -> FixStepOutcomeDict:
|
||||
if not self._is_apt_host():
|
||||
return self._not_apt()
|
||||
return self._run_apt_root_command(revert_sources_command(), "sources back on https")
|
||||
|
||||
def _remove_package_proxy(self) -> FixStepOutcomeDict:
|
||||
if not self._is_apt_host():
|
||||
return self._not_apt()
|
||||
@@ -522,7 +550,9 @@ class AptProxyMixin(PackageProxyMixin):
|
||||
f"rm -f {shlex.quote(self.APT_PROXY_FILE)}", "proxy removed"
|
||||
)
|
||||
|
||||
def _write_package_proxy(self, url: str, https_direct: bool = False) -> FixStepOutcomeDict:
|
||||
def _write_package_proxy(
|
||||
self, url: str, https_direct: bool = False, not_cached: list[str] | None = None
|
||||
) -> FixStepOutcomeDict:
|
||||
if not self._is_apt_host():
|
||||
return self._not_apt()
|
||||
if not PROXY_URL.match(url):
|
||||
@@ -530,6 +560,10 @@ class AptProxyMixin(PackageProxyMixin):
|
||||
content = f'Acquire::http::Proxy "{url}";\n'
|
||||
if https_direct:
|
||||
content += 'Acquire::https::Proxy "DIRECT";\n'
|
||||
# Host names the report read from this file; one a line could not carry is left out.
|
||||
content += "".join(
|
||||
f'{NOT_CACHED_KEY}:: "{host}";\n' for host in not_cached or [] if is_host_name(host)
|
||||
)
|
||||
return self._write_apt_file(self.APT_PROXY_FILE, content)
|
||||
|
||||
def _report(self) -> AptProxyReportDict:
|
||||
@@ -566,16 +600,7 @@ class AptProxyMixin(PackageProxyMixin):
|
||||
}
|
||||
|
||||
def _fetch_through_package_proxy(self, url: str) -> FixStepOutcomeDict:
|
||||
report = self._report()
|
||||
direct = {h.lower() for h, v in report["per_host"].items() if v.lower() == "direct"}
|
||||
source = next(
|
||||
(
|
||||
s
|
||||
for s in report["http_sources"]
|
||||
if "/dists/" in s and (urlsplit(s).hostname or "").lower() not in direct
|
||||
),
|
||||
None,
|
||||
)
|
||||
source = _plain_http_source(self._report())
|
||||
if source is None:
|
||||
return {"ok": True, "output": "no http source to fetch through the proxy; not tried"}
|
||||
target = source.rstrip("/") + "/InRelease"
|
||||
@@ -584,6 +609,49 @@ class AptProxyMixin(PackageProxyMixin):
|
||||
return {"ok": True, "output": f"fetched {target} through {url}"}
|
||||
return {"ok": False, "output": f"{target}: {fetched['error']}"}
|
||||
|
||||
def _cache_https_sources(self, url: str) -> FixStepOutcomeDict:
|
||||
"""The https sources through *url* in the form it stores; back to https where it cannot."""
|
||||
hosts = cacheable_https_hosts(self._report())
|
||||
if not hosts:
|
||||
return {"ok": True, "output": "no https source to cache"}
|
||||
rewritten = self._run_apt_root_command(
|
||||
rewrite_sources_command(hosts, self.APT_PROXY_FILE), "sources rewritten"
|
||||
)
|
||||
if not rewritten["ok"]:
|
||||
return rewritten
|
||||
return self._fetch_cached(url, hosts, self._report())
|
||||
|
||||
def _fetch_cached(
|
||||
self, url: str, hosts: list[str], report: AptProxyReportDict
|
||||
) -> FixStepOutcomeDict:
|
||||
"""One rewritten source through *url*: it stays where *url* fetched it."""
|
||||
left = sorted(set(hosts) & set(report["not_cached"]))
|
||||
named = f"; left on https, apt has credentials for them: {', '.join(left)}" if left else ""
|
||||
target = next(
|
||||
(s.rstrip("/") + "/InRelease" for s in report["http_sources"] if _cached(s)), None
|
||||
)
|
||||
if target is None:
|
||||
return {"ok": True, "output": f"no https source to cache{named}"}
|
||||
fetched = parse_apt_fetch(self._run_apt_command(apt_fetch_command(target)))
|
||||
if fetched["reachable"] and not fetched["error"]:
|
||||
cached = ", ".join(h for h in hosts if h not in left)
|
||||
return {"ok": True, "output": f"https sources cached through {url}: {cached}{named}"}
|
||||
return self._back_to_https(url, f"{target}: {fetched['error']}", named)
|
||||
|
||||
def _back_to_https(self, url: str, why: str, named: str) -> FixStepOutcomeDict:
|
||||
"""*url* did not fetch the stored form: every source goes back to https."""
|
||||
back = self._run_apt_root_command(revert_sources_command(), "sources back on https")
|
||||
if not back["ok"]:
|
||||
return {
|
||||
"ok": False,
|
||||
"output": f"{why}; turning the sources back to https failed: {back['output']}",
|
||||
}
|
||||
return {
|
||||
"ok": True,
|
||||
"output": f"{url} does not fetch https sources itself ({why}); "
|
||||
f"they stay on https, not cached{named}",
|
||||
}
|
||||
|
||||
def _https_through_package_proxy(self, url: str) -> FixStepOutcomeDict:
|
||||
"""An https source through *url*; where *url* refuses it, https goes ``DIRECT``."""
|
||||
found = _https_source(self._report(), lambda proxy: same_proxy_url(proxy, url))
|
||||
@@ -609,7 +677,9 @@ class AptProxyMixin(PackageProxyMixin):
|
||||
|
||||
def _https_direct(self, url: str) -> FixStepOutcomeDict:
|
||||
"""Write https ``DIRECT`` beside *url*, and comment out the later lines to *url*."""
|
||||
written = self._write_package_proxy(url, https_direct=True)
|
||||
written = self._write_package_proxy(
|
||||
url, https_direct=True, not_cached=self._report()["not_cached"]
|
||||
)
|
||||
if not written["ok"]:
|
||||
return written
|
||||
later = self._later_https_lines(self._report(), url)
|
||||
@@ -635,6 +705,26 @@ class AptProxyMixin(PackageProxyMixin):
|
||||
]
|
||||
|
||||
|
||||
def _plain_http_source(report: AptProxyReportDict) -> str | None:
|
||||
"""A suite's http source the proxy takes, not in the cache's https form: its proof."""
|
||||
direct = {h.lower() for h, v in report["per_host"].items() if v.lower() == "direct"}
|
||||
return next(
|
||||
(
|
||||
s
|
||||
for s in report["http_sources"]
|
||||
if "/dists/" in s
|
||||
and not s.startswith(VIA_CACHE)
|
||||
and (urlsplit(s).hostname or "").lower() not in direct
|
||||
),
|
||||
None,
|
||||
)
|
||||
|
||||
|
||||
def _cached(source: str) -> bool:
|
||||
"""A source of a suite in the form the cache stores."""
|
||||
return source.startswith(VIA_CACHE) and "/dists/" in source
|
||||
|
||||
|
||||
def _https_source(
|
||||
report: AptProxyReportDict, through: Callable[[str | None], bool]
|
||||
) -> tuple[str, str] | None:
|
||||
|
||||
@@ -0,0 +1,486 @@
|
||||
"""apt's sources and the release each names, and moving one file's sources to the host's.
|
||||
|
||||
A release upgrade moves the distribution's own sources to the new release and
|
||||
leaves the third-party ones where they were -- or turns them off, and the person
|
||||
who turns them back on keeps the old name. A source on the old release still
|
||||
answers, so apt says nothing; its packages simply stop getting updates once the
|
||||
vendor stops building for that release. Docker's last build for Ubuntu 20.04
|
||||
(``focal``) is 28.1.1, and a noble host on ``focal`` never sees a newer one
|
||||
(NetOrk/netork#2614).
|
||||
|
||||
**What is read** (:meth:`AptReleaseMixin.get_apt_source_releases`): the host's
|
||||
``/etc/os-release`` (``ID``, ``ID_LIKE``, ``VERSION_CODENAME``,
|
||||
``UBUNTU_CODENAME``) and every source apt reads -- ``sources.list`` and the
|
||||
``*.list`` and ``*.sources`` files of ``sources.list.d``, wherever ``apt-config``
|
||||
says they are -- with its file, line, types, URI, suites and components.
|
||||
Commented-out lines and deb822 paragraphs with ``Enabled: no`` are not sources.
|
||||
Whether a suite names another release than the host's is not said here: which
|
||||
words are releases of which distribution is the caller's to know
|
||||
(:func:`suite_release` gives the word).
|
||||
|
||||
**Moving a file** (:meth:`AptReleaseMixin.set_apt_source_release`): every suite of
|
||||
*release* in one of apt's source files becomes the same suite of *codename*
|
||||
(``focal-security`` → ``noble-security``), on enabled lines only. Before anything is
|
||||
written, each new suite's ``InRelease`` (or ``Release``) is fetched from its URI with
|
||||
apt's own downloader and the proxy apt is set to; when one of them is not there,
|
||||
the vendor does not build for *codename* and the file stays as it is. The file is
|
||||
written whole, as root, mode 644. Loading the package index afterwards is the
|
||||
caller's (``refresh_available_updates``).
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import base64
|
||||
import re
|
||||
import shlex
|
||||
from dataclasses import dataclass, field
|
||||
from typing import TYPE_CHECKING
|
||||
|
||||
from typing_extensions import TypedDict
|
||||
|
||||
from napalm_device_types.fixes import run_fix_steps
|
||||
from napalm_device_types.models import FixResultDict, FixStepOutcomeDict
|
||||
from napalm_device_types.terminal import strip_terminal_codes
|
||||
|
||||
_BEGIN = "ARELEASE_BEGIN"
|
||||
_END = "ARELEASE_END"
|
||||
|
||||
#: A release's codename: one lower-case word (``noble``, ``bookworm``).
|
||||
_CODENAME = re.compile(r"^[a-z][a-z0-9]*$")
|
||||
#: A suite that names a release: its codename, then perhaps a suffix (``-security``).
|
||||
_SUITE = re.compile(r"^([a-z][a-z0-9]*)(-[a-z0-9-]+)?$")
|
||||
#: One source line of a ``.list`` file, its comment cut off: types, options, URI, suite.
|
||||
_LIST_LINE = re.compile(r"^(\s*(deb|deb-src)\s+(?:\[[^\]]*\]\s+)?(\S+)\s+)(\S+)(.*)$")
|
||||
#: A deb822 field's first line.
|
||||
_FIELD = re.compile(r"^([A-Za-z][A-Za-z0-9-]*):(.*)$")
|
||||
_DISABLED = frozenset({"no", "false", "0"})
|
||||
|
||||
|
||||
class AptSourceDict(TypedDict):
|
||||
"""One source apt reads (``get_apt_source_releases``)."""
|
||||
|
||||
#: The file it is in.
|
||||
file: str
|
||||
#: The line of a ``.list`` file's entry; of a deb822 paragraph's ``Suites:`` field.
|
||||
line: int
|
||||
#: ``deb``, ``deb-src``; a deb822 paragraph may name both.
|
||||
types: list[str]
|
||||
#: Its URI, as written; a deb822 paragraph with several URIs is one source per URI.
|
||||
uri: str
|
||||
#: Its suites; a flat repository's path (``./``) is one too.
|
||||
suites: list[str]
|
||||
components: list[str]
|
||||
|
||||
|
||||
class AptReleasesDict(TypedDict):
|
||||
"""The host's release and its sources (``get_apt_source_releases``)."""
|
||||
|
||||
#: ``ID`` and ``ID_LIKE`` of ``/etc/os-release``; "" and [] when it says none.
|
||||
os_id: str
|
||||
os_like: list[str]
|
||||
#: ``VERSION_CODENAME``; a derivative's own (Linux Mint's ``virginia``).
|
||||
codename: str
|
||||
#: ``UBUNTU_CODENAME``: the Ubuntu release Ubuntu and its derivatives are built on.
|
||||
ubuntu_codename: str
|
||||
sources: list[AptSourceDict]
|
||||
|
||||
|
||||
class AptReleaseFixDict(FixResultDict):
|
||||
"""The result of ``set_apt_source_release``: the fix, and how many suites moved."""
|
||||
|
||||
rewritten: int
|
||||
|
||||
|
||||
def apt_releases_command(
|
||||
apt_config: str = "apt-config", os_release: str = "/etc/os-release"
|
||||
) -> str:
|
||||
"""The read-only command that prints the host's release and apt's source files.
|
||||
|
||||
One line, POSIX ``sh``, no privileges. Every line of a file is printed behind a
|
||||
``|``, so an empty line -- which ends a deb822 paragraph -- comes through.
|
||||
*apt_config* and *os_release* let a test point it elsewhere.
|
||||
"""
|
||||
return (
|
||||
f"( export LC_ALL=C; printf '%s%s\\n' ARELEASE_ BEGIN; echo '@@os'; "
|
||||
f'o={shlex.quote(os_release)}; [ -r "$o" ] || o=/usr/lib/os-release; '
|
||||
'[ -r "$o" ] && sed \'s/^/|/\' "$o"; '
|
||||
f'eval "$({apt_config} shell sl Dir::Etc::sourcelist/f sp Dir::Etc::sourceparts/d '
|
||||
'2>/dev/null)"; sl="${sl:-/etc/apt/sources.list}"; sp="${sp:-/etc/apt/sources.list.d/}"; '
|
||||
'for f in "$sl" "$sp"*.list "$sp"*.sources; do [ -f "$f" ] || continue; '
|
||||
'if [ -r "$f" ]; then printf \'@@file %s\\n\' "$f"; sed \'s/^/|/\' "$f"; '
|
||||
"else printf '@@unreadable %s\\n' \"$f\"; fi; done; "
|
||||
"printf '%s%s\\n' ARELEASE_ END ) 2>/dev/null | cat"
|
||||
)
|
||||
|
||||
|
||||
#: The command as a driver runs it.
|
||||
APT_RELEASES_COMMAND = apt_releases_command()
|
||||
|
||||
|
||||
def suite_release(suite: str) -> str | None:
|
||||
"""The word a suite starts with, ``noble`` of ``noble-security``; None for a path.
|
||||
|
||||
Whether that word is a release, and of which distribution, the caller knows:
|
||||
``stable`` and ``nodistro`` have the form too.
|
||||
"""
|
||||
found = _SUITE.match(suite)
|
||||
return found.group(1) if found else None
|
||||
|
||||
|
||||
def _codename(name: str) -> str:
|
||||
if not _CODENAME.match(name):
|
||||
raise ValueError(f"not a release's codename: {name!r}")
|
||||
return name
|
||||
|
||||
|
||||
# ── Reading ──────────────────────────────────────────────────────────────────
|
||||
|
||||
|
||||
def _blocks(output: str) -> list[tuple[str, list[str]]]:
|
||||
"""``(header, lines)`` of each block between the frame markers, in order."""
|
||||
lines = strip_terminal_codes(output).splitlines()
|
||||
stripped = [line.strip() for line in lines]
|
||||
try:
|
||||
start = stripped.index(_BEGIN)
|
||||
end = stripped.index(_END, start)
|
||||
except ValueError:
|
||||
raise ValueError("no intact apt release report in the output") from None
|
||||
blocks: list[tuple[str, list[str]]] = []
|
||||
for line in lines[start + 1 : end]:
|
||||
if line.startswith("@@"):
|
||||
blocks.append((line[2:].strip(), []))
|
||||
elif line.startswith("|") and blocks:
|
||||
blocks[-1][1].append(line[1:].rstrip("\r"))
|
||||
return blocks
|
||||
|
||||
|
||||
def _os_release(lines: list[str]) -> dict[str, str]:
|
||||
values: dict[str, str] = {}
|
||||
for line in lines:
|
||||
key, sep, value = line.strip().partition("=")
|
||||
if sep and key:
|
||||
values[key] = value.strip().strip("'\"")
|
||||
return values
|
||||
|
||||
|
||||
def _code(line: str) -> str:
|
||||
"""*line* without its comment."""
|
||||
return line.split("#", 1)[0]
|
||||
|
||||
|
||||
def _list_sources(path: str, lines: list[str]) -> list[AptSourceDict]:
|
||||
found: list[AptSourceDict] = []
|
||||
for number, line in enumerate(lines, start=1):
|
||||
entry = _LIST_LINE.match(_code(line))
|
||||
if entry:
|
||||
_, kind, uri, suite, rest = entry.groups()
|
||||
found.append(
|
||||
{
|
||||
"file": path,
|
||||
"line": number,
|
||||
"types": [kind],
|
||||
"uri": uri,
|
||||
"suites": [suite],
|
||||
"components": rest.split(),
|
||||
}
|
||||
)
|
||||
return found
|
||||
|
||||
|
||||
@dataclass
|
||||
class _Field:
|
||||
first: int # index of its first line
|
||||
lines: list[int] = field(default_factory=list) # indices of every line it spans
|
||||
value: str = ""
|
||||
|
||||
|
||||
@dataclass
|
||||
class _Paragraph:
|
||||
fields: dict[str, _Field] = field(default_factory=dict)
|
||||
|
||||
def value(self, name: str) -> str:
|
||||
found = self.fields.get(name)
|
||||
return found.value if found else ""
|
||||
|
||||
@property
|
||||
def enabled(self) -> bool:
|
||||
return self.value("enabled").strip().lower() not in _DISABLED
|
||||
|
||||
|
||||
def _paragraphs(lines: list[str]) -> list[_Paragraph]:
|
||||
"""The deb822 paragraphs of *lines*; comments are skipped, an empty line ends one."""
|
||||
paragraphs: list[_Paragraph] = []
|
||||
current: _Paragraph | None = None
|
||||
last: _Field | None = None
|
||||
for index, line in enumerate(lines):
|
||||
if not line.strip():
|
||||
current, last = None, None
|
||||
continue
|
||||
if line.lstrip().startswith("#"):
|
||||
continue
|
||||
if line[0] in " \t":
|
||||
if last is not None:
|
||||
last.lines.append(index)
|
||||
last.value += " " + line.strip()
|
||||
continue
|
||||
found = _FIELD.match(line)
|
||||
if not found:
|
||||
continue
|
||||
if current is None:
|
||||
current = _Paragraph()
|
||||
paragraphs.append(current)
|
||||
last = _Field(first=index, lines=[index], value=found.group(2).strip())
|
||||
current.fields[found.group(1).lower()] = last
|
||||
return paragraphs
|
||||
|
||||
|
||||
def _deb822_sources(path: str, lines: list[str]) -> list[AptSourceDict]:
|
||||
found: list[AptSourceDict] = []
|
||||
for paragraph in _paragraphs(lines):
|
||||
suites = paragraph.fields.get("suites")
|
||||
if not paragraph.enabled or suites is None:
|
||||
continue
|
||||
for uri in paragraph.value("uris").split():
|
||||
found.append(
|
||||
{
|
||||
"file": path,
|
||||
"line": suites.first + 1,
|
||||
"types": paragraph.value("types").split(),
|
||||
"uri": uri,
|
||||
"suites": suites.value.split(),
|
||||
"components": paragraph.value("components").split(),
|
||||
}
|
||||
)
|
||||
return found
|
||||
|
||||
|
||||
def _is_deb822(path: str) -> bool:
|
||||
return path.endswith(".sources")
|
||||
|
||||
|
||||
def parse_apt_releases(output: str) -> AptReleasesDict:
|
||||
"""What :func:`apt_releases_command` printed, as :class:`AptReleasesDict`.
|
||||
|
||||
:raises ValueError: if the output carried no intact report.
|
||||
"""
|
||||
os_values: dict[str, str] = {}
|
||||
sources: list[AptSourceDict] = []
|
||||
for header, lines in _blocks(output):
|
||||
kind, _, path = header.partition(" ")
|
||||
if kind == "os":
|
||||
os_values = _os_release(lines)
|
||||
elif kind == "file" and path:
|
||||
read = _deb822_sources if _is_deb822(path) else _list_sources
|
||||
sources.extend(read(path, lines))
|
||||
return {
|
||||
"os_id": os_values.get("ID", "").lower(),
|
||||
"os_like": os_values.get("ID_LIKE", "").lower().split(),
|
||||
"codename": os_values.get("VERSION_CODENAME", "").lower(),
|
||||
"ubuntu_codename": os_values.get("UBUNTU_CODENAME", "").lower(),
|
||||
"sources": sources,
|
||||
}
|
||||
|
||||
|
||||
# ── Rewriting ────────────────────────────────────────────────────────────────
|
||||
|
||||
|
||||
def _moved(suite: str, release: str, codename: str) -> str:
|
||||
return codename + suite[len(release) :] if suite_release(suite) == release else suite
|
||||
|
||||
|
||||
def _rewrite_list_line(line: str, release: str, codename: str) -> tuple[str, int]:
|
||||
code = _code(line)
|
||||
entry = _LIST_LINE.match(code)
|
||||
if not entry:
|
||||
return line, 0
|
||||
suite = entry.group(4)
|
||||
new = _moved(suite, release, codename)
|
||||
if new == suite:
|
||||
return line, 0
|
||||
head = entry.group(1)
|
||||
return head + new + line[len(head) + len(suite) :], 1
|
||||
|
||||
|
||||
def _rewrite_tokens(text: str, release: str, codename: str) -> tuple[str, int]:
|
||||
changed = 0
|
||||
|
||||
def one(token: re.Match[str]) -> str:
|
||||
nonlocal changed
|
||||
new = _moved(token.group(), release, codename)
|
||||
changed += new != token.group()
|
||||
return new
|
||||
|
||||
return re.sub(r"\S+", one, text), changed
|
||||
|
||||
|
||||
def _rewrite_deb822(lines: list[str], release: str, codename: str) -> int:
|
||||
changed = 0
|
||||
for paragraph in _paragraphs(lines):
|
||||
suites = paragraph.fields.get("suites")
|
||||
if not paragraph.enabled or suites is None:
|
||||
continue
|
||||
for index in suites.lines:
|
||||
line = lines[index]
|
||||
cut = line.index(":") + 1 if index == suites.first else 0
|
||||
tail, count = _rewrite_tokens(line[cut:], release, codename)
|
||||
lines[index] = line[:cut] + tail
|
||||
changed += count
|
||||
return changed
|
||||
|
||||
|
||||
def rewrite_release(text: str, release: str, codename: str, *, deb822: bool) -> tuple[str, int]:
|
||||
"""*text*, a source file, with every suite of *release* on *codename*; and how many.
|
||||
|
||||
Only enabled sources: not a commented-out line, not a paragraph with
|
||||
``Enabled: no``. A URI or comment that names *release* stays as it is.
|
||||
|
||||
:raises ValueError: if *release* or *codename* is not a codename.
|
||||
"""
|
||||
release, codename = _codename(release), _codename(codename)
|
||||
lines = text.split("\n")
|
||||
if deb822:
|
||||
changed = _rewrite_deb822(lines, release, codename)
|
||||
else:
|
||||
changed = 0
|
||||
for index, line in enumerate(lines):
|
||||
lines[index], count = _rewrite_list_line(line, release, codename)
|
||||
changed += count
|
||||
return "\n".join(lines), changed
|
||||
|
||||
|
||||
# ── The mixin ────────────────────────────────────────────────────────────────
|
||||
|
||||
|
||||
def _release_urls(uri: str, suite: str) -> list[str]:
|
||||
base = f"{uri.rstrip('/')}/dists/{suite}/"
|
||||
return [base + "InRelease", base + "Release"]
|
||||
|
||||
|
||||
class AptReleaseMixin:
|
||||
"""Reads the release each apt source names; moves one file's sources to another.
|
||||
|
||||
The template form, like :class:`~napalm_device_types.apt_proxy.AptProxyMixin`,
|
||||
which brings it to every driver that has it: a driver supplies
|
||||
``_run_apt_command`` and ``_write_apt_file``, and ``_is_apt_host`` where it
|
||||
can be something else.
|
||||
"""
|
||||
|
||||
if TYPE_CHECKING: # pragma: no cover - declared for type checkers only
|
||||
|
||||
def _run_apt_command(self, command: str) -> str:
|
||||
"""Run *command* on the host with ``sh``, without privileges; what it printed."""
|
||||
...
|
||||
|
||||
def _write_apt_file(self, path: str, content: str) -> FixStepOutcomeDict:
|
||||
"""Replace *path* with *content*, as a new file owned by root, mode 644."""
|
||||
...
|
||||
|
||||
def _is_apt_host(self) -> bool:
|
||||
"""Whether apt is the host's package manager; a driver that can tell overrides it."""
|
||||
return True
|
||||
|
||||
def get_apt_source_releases(self) -> AptReleasesDict | None:
|
||||
"""The host's release and every source apt reads; None on a host without apt.
|
||||
|
||||
:raises ValueError: if the host's output carried no intact report.
|
||||
"""
|
||||
if not self._is_apt_host():
|
||||
return None
|
||||
return parse_apt_releases(self._run_apt_command(APT_RELEASES_COMMAND))
|
||||
|
||||
def set_apt_source_release(self, path: str, release: str, codename: str) -> AptReleaseFixDict:
|
||||
"""Every suite of *release* in *path* on *codename*, where the vendor serves it.
|
||||
|
||||
Three steps: ``read`` (*path* is one of apt's source files, and which of its
|
||||
sources name *release*), ``check`` (each new suite's ``InRelease`` or
|
||||
``Release`` is there) and ``rewrite``. Nothing is written when a step fails;
|
||||
nothing is fetched or written when no source of *path* names *release*.
|
||||
"""
|
||||
moving: list[AptSourceDict] = []
|
||||
rewritten = [0]
|
||||
result = run_fix_steps(
|
||||
[
|
||||
("read", lambda: self._sources_on(path, release, codename, moving)),
|
||||
("check", lambda: self._served(moving, release, codename)),
|
||||
("rewrite", lambda: self._rewrite(path, release, codename, moving, rewritten)),
|
||||
]
|
||||
)
|
||||
return {**result, "rewritten": rewritten[0]}
|
||||
|
||||
def _sources_on(
|
||||
self, path: str, release: str, codename: str, moving: list[AptSourceDict]
|
||||
) -> FixStepOutcomeDict:
|
||||
_codename(release)
|
||||
_codename(codename)
|
||||
found = self.get_apt_source_releases()
|
||||
if found is None:
|
||||
return {"ok": False, "output": "not an apt host"}
|
||||
in_file = [s for s in found["sources"] if s["file"] == path]
|
||||
if not in_file:
|
||||
return {"ok": False, "output": f"{path} is none of apt's source files"}
|
||||
moving.extend(s for s in in_file if any(suite_release(x) == release for x in s["suites"]))
|
||||
if not moving:
|
||||
return {"ok": True, "output": f"no source in {path} is on {release} any more"}
|
||||
named = "; ".join(f"{s['uri']} {' '.join(s['suites'])}" for s in moving)
|
||||
return {"ok": True, "output": f"on {release} in {path}: {named}"}
|
||||
|
||||
def _served(
|
||||
self, moving: list[AptSourceDict], release: str, codename: str
|
||||
) -> FixStepOutcomeDict:
|
||||
from napalm_device_types.apt_proxy import apt_fetch_command, parse_apt_fetch
|
||||
|
||||
wanted = sorted(
|
||||
{
|
||||
(s["uri"], _moved(suite, release, codename))
|
||||
for s in moving
|
||||
for suite in s["suites"]
|
||||
if suite_release(suite) == release
|
||||
}
|
||||
)
|
||||
said: list[str] = []
|
||||
for uri, suite in wanted:
|
||||
error = ""
|
||||
for url in _release_urls(uri, suite):
|
||||
fetched = parse_apt_fetch(self._run_apt_command(apt_fetch_command(url)))
|
||||
error = fetched["error"]
|
||||
if not error:
|
||||
said.append(f"{uri} serves {suite}")
|
||||
break
|
||||
else:
|
||||
return {"ok": False, "output": f"{uri} has no {suite}: {error}; nothing changed"}
|
||||
return {"ok": True, "output": "; ".join(said) or "nothing to check"}
|
||||
|
||||
def _rewrite(
|
||||
self,
|
||||
path: str,
|
||||
release: str,
|
||||
codename: str,
|
||||
moving: list[AptSourceDict],
|
||||
rewritten: list[int],
|
||||
) -> FixStepOutcomeDict:
|
||||
if not moving:
|
||||
return {"ok": True, "output": "nothing to rewrite"}
|
||||
encoded = "".join(self._run_apt_command(f"base64 {shlex.quote(path)}").split())
|
||||
text = base64.b64decode(encoded).decode()
|
||||
new, count = rewrite_release(text, release, codename, deb822=_is_deb822(path))
|
||||
if not count:
|
||||
return {"ok": True, "output": f"no source in {path} is on {release} any more"}
|
||||
written = self._write_apt_file(path, new)
|
||||
if not written["ok"]:
|
||||
return written
|
||||
rewritten[0] = count
|
||||
suites = "1 suite" if count == 1 else f"{count} suites"
|
||||
return {"ok": True, "output": f"{path}: {suites} moved from {release} to {codename}"}
|
||||
|
||||
|
||||
__all__ = [
|
||||
"APT_RELEASES_COMMAND",
|
||||
"AptReleaseFixDict",
|
||||
"AptReleaseMixin",
|
||||
"AptReleasesDict",
|
||||
"AptSourceDict",
|
||||
"apt_releases_command",
|
||||
"parse_apt_releases",
|
||||
"rewrite_release",
|
||||
"suite_release",
|
||||
]
|
||||
@@ -0,0 +1,172 @@
|
||||
"""apt's https sources through the package cache, so that the cache stores them.
|
||||
|
||||
A source fetched over https goes through apt-cacher-ng's tunnel, if at all: the
|
||||
TLS runs end to end and nothing of it is stored. The cache fetches
|
||||
``http://HTTPS///<host>/<path>`` from ``https://<host>/<path>`` itself, with the
|
||||
certificate verified, and stores it -- where it allows port 443
|
||||
(``AllowUserPorts=80 443``) (NetOrk/netork#2555). apt fetches that form through
|
||||
its http proxy, so it works only while the cache is that proxy: without one apt
|
||||
looks for a host called ``HTTPS``.
|
||||
|
||||
**Which hosts** (:func:`cacheable_https_hosts`): the hosts of the https sources,
|
||||
on port 443, while apt has an http proxy for every host and none of its own for
|
||||
that one. Not a host with a login in the URL, nor one whose credentials apt keeps
|
||||
in ``auth.conf``: apt finds those by the host's name, which the rewrite changes,
|
||||
and paid content does not belong in a cache other hosts share. Only root reads
|
||||
``auth.conf``, so the rewrite judges that, leaves such a host on https and names
|
||||
it in the proxy file as ``Package-Proxy::Not-Cached``, which apt ignores and
|
||||
``apt-config dump`` shows to the report.
|
||||
|
||||
**The rewrite** (:func:`rewrite_sources_command`) turns ``https://<host>`` into
|
||||
the cache form on the lines that name sources: ``deb`` and ``deb-src`` in a
|
||||
``.list`` file, ``URIs:`` in a deb822 ``.sources`` file. A file without the host
|
||||
is not touched. :func:`revert_sources_command` turns every source back.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import re
|
||||
import shlex
|
||||
from typing import TYPE_CHECKING
|
||||
from urllib.parse import urlsplit
|
||||
|
||||
if TYPE_CHECKING: # pragma: no cover - the report's type, without an import cycle
|
||||
from napalm_device_types.apt_proxy import AptProxyReportDict
|
||||
|
||||
#: The prefix apt-cacher-ng fetches over https.
|
||||
VIA_CACHE = "http://HTTPS///"
|
||||
|
||||
#: The key in the proxy file that names the hosts left on https for their credentials.
|
||||
NOT_CACHED_KEY = "Package-Proxy::Not-Cached"
|
||||
|
||||
_LABEL = r"[A-Za-z0-9](?:[A-Za-z0-9-]*[A-Za-z0-9])?"
|
||||
_HOST = re.compile(rf"^{_LABEL}(?:\.{_LABEL})*$")
|
||||
_NO_PROXY = frozenset({"", "direct"})
|
||||
|
||||
#: Where apt's sources and credentials are, as shell variables; apt's defaults
|
||||
#: when apt-config cannot say.
|
||||
_LOCATE = (
|
||||
'eval "$({apt_config} shell sl Dir::Etc::sourcelist/f sp Dir::Etc::sourceparts/d '
|
||||
'nr Dir::Etc::netrc/f np Dir::Etc::netrcparts/d 2>/dev/null)"; '
|
||||
'sl="${{sl:-/etc/apt/sources.list}}"; sp="${{sp:-/etc/apt/sources.list.d/}}"; '
|
||||
'nr="${{nr:-/etc/apt/auth.conf}}"; np="${{np:-/etc/apt/auth.conf.d/}}"; '
|
||||
)
|
||||
|
||||
#: The lines that name sources: ``deb``/``deb-src`` and deb822's ``URIs:``.
|
||||
_SOURCE_LINES = "/^[[:space:]]*(deb|deb-src|[Uu][Rr][Ii][Ss]:)/"
|
||||
|
||||
#: The hosts apt has credentials for: each word after ``machine``, without its
|
||||
#: scheme, port and path, in lower case.
|
||||
_CREDENTIAL_HOSTS = (
|
||||
'creds=$(cat "$nr" "$np"* 2>/dev/null | tr -s " \\t\\r" "\\n" '
|
||||
"| awk 'p {{ print; p = 0; next }} $0 == \"machine\" {{ p = 1 }}' "
|
||||
"| sed -e 's|^[A-Za-z+]*://||' -e 's|[:/].*||' | tr A-Z a-z); "
|
||||
)
|
||||
|
||||
_REWRITE = (
|
||||
"( " + _LOCATE + _CREDENTIAL_HOSTS + "for h in {hosts}; do "
|
||||
'l=$(printf "%s" "$h" | tr A-Z a-z); '
|
||||
'if printf "%s\\n" "$creds" | grep -qxF -- "$l"; then '
|
||||
'grep -qF -- "\\"$h\\"" {proxy_file} 2>/dev/null || '
|
||||
'printf \'{key}:: "%s";\\n\' "$h" >> {proxy_file} || exit 1; continue; fi; '
|
||||
"e=$(printf '%s' \"$h\" | sed 's/[.]/[.]/g'); "
|
||||
'for f in "$sl" "$sp"*.list "$sp"*.sources; do '
|
||||
'[ -f "$f" ] && grep -qF -- "https://$h" "$f" || continue; '
|
||||
'sed -i -E "{lines} s#([[:space:]:])https://$e([/[:space:]]|\\$)#\\1{via}$h\\2#g" "$f" '
|
||||
"|| exit 1; done; done )"
|
||||
)
|
||||
|
||||
_REVERT = (
|
||||
"( " + _LOCATE + 'for f in "$sl" "$sp"*.list "$sp"*.sources; do '
|
||||
'[ -f "$f" ] && grep -qF -- "{via}" "$f" || continue; '
|
||||
"sed -i -E '{lines} s#([[:space:]:]){via}#\\1https://#g' \"$f\" || exit 1; done )"
|
||||
)
|
||||
|
||||
|
||||
def cache_form(url: str) -> str:
|
||||
"""*url*, an https URL, in the form apt-cacher-ng fetches over https and stores.
|
||||
|
||||
:raises ValueError: if *url* is not an https URL.
|
||||
"""
|
||||
if not url.startswith("https://"):
|
||||
raise ValueError(f"not an https URL: {url!r}")
|
||||
return VIA_CACHE + url[len("https://") :]
|
||||
|
||||
|
||||
def _per_host_direct(report: AptProxyReportDict) -> set[str]:
|
||||
hosts = {**report["per_host"], **report["https_per_host"]}
|
||||
return {h.lower() for h, v in hosts.items() if v.lower() in _NO_PROXY}
|
||||
|
||||
|
||||
def _host_of(source: str) -> str | None:
|
||||
"""The host of an https source the cache can fetch: port 443, no login in the URL."""
|
||||
try:
|
||||
parts = urlsplit(source)
|
||||
port = parts.port
|
||||
except ValueError:
|
||||
return None
|
||||
if parts.username is not None or port not in (None, 443) or not parts.hostname:
|
||||
return None
|
||||
return parts.hostname
|
||||
|
||||
|
||||
def cacheable_https_hosts(report: AptProxyReportDict) -> list[str]:
|
||||
"""The hosts of the https sources the rewrite would send through the cache, sorted.
|
||||
|
||||
None while apt has no http proxy for every host: the cache form goes through it.
|
||||
Not a host apt fetches ``DIRECT``, nor one the rewrite left on https for its
|
||||
credentials (``not_cached``), nor one on another port or with a login in the URL.
|
||||
"""
|
||||
if not report["proxy"]:
|
||||
return []
|
||||
skip = _per_host_direct(report) | {h.lower() for h in report.get("not_cached", [])}
|
||||
hosts = {_host_of(s) for s in report["https_sources"]}
|
||||
return sorted(h for h in hosts if h and h.lower() not in skip)
|
||||
|
||||
|
||||
def is_host_name(host: str) -> bool:
|
||||
"""Whether *host* is a DNS name: letters, digits and hyphens between dots."""
|
||||
return bool(_HOST.match(host))
|
||||
|
||||
|
||||
def _checked(hosts: list[str]) -> str:
|
||||
for host in hosts:
|
||||
if not is_host_name(host):
|
||||
raise ValueError(f"not a host name: {host!r}")
|
||||
return " ".join(hosts)
|
||||
|
||||
|
||||
def rewrite_sources_command(
|
||||
hosts: list[str], proxy_file: str, apt_config: str = "apt-config"
|
||||
) -> str:
|
||||
"""The root command that sends the https sources of *hosts* through the cache.
|
||||
|
||||
A host apt has credentials for stays on https and is named in *proxy_file*.
|
||||
*apt_config* is how apt-config is called; a test points apt's paths elsewhere.
|
||||
|
||||
:raises ValueError: if one of *hosts* is not a host name.
|
||||
"""
|
||||
return _REWRITE.format(
|
||||
apt_config=apt_config,
|
||||
hosts=_checked(hosts),
|
||||
proxy_file=shlex.quote(proxy_file),
|
||||
key=NOT_CACHED_KEY,
|
||||
lines=_SOURCE_LINES,
|
||||
via=VIA_CACHE,
|
||||
)
|
||||
|
||||
|
||||
def revert_sources_command(apt_config: str = "apt-config") -> str:
|
||||
"""The root command that turns every source in the cache form back to https."""
|
||||
return _REVERT.format(apt_config=apt_config, lines=_SOURCE_LINES, via=VIA_CACHE)
|
||||
|
||||
|
||||
__all__ = [
|
||||
"NOT_CACHED_KEY",
|
||||
"VIA_CACHE",
|
||||
"cache_form",
|
||||
"cacheable_https_hosts",
|
||||
"is_host_name",
|
||||
"revert_sources_command",
|
||||
"rewrite_sources_command",
|
||||
]
|
||||
@@ -23,6 +23,22 @@ Mixed in by a driver, not by a role base: a Windows host is an
|
||||
:class:`~napalm_device_types.os.OSDriver` too, and without a shell channel it
|
||||
has no ``dial-stdio`` to offer. ``hasattr(driver, "open_container_engine")``
|
||||
stays truthful.
|
||||
|
||||
**Which engine a CLI is.** An engine is listed when its CLI answers
|
||||
``--version`` with its own name: ``Docker version 29.0.1, build …``, ``podman
|
||||
version 5.2.2``. podman-docker installs a ``docker`` that is podman; listed as
|
||||
Docker it would be read twice, the second time as the login user's rootless
|
||||
Podman (NetOrk/netork#818).
|
||||
|
||||
**Podman as root.** The Podman this reaches is the host's *rootful* one: the
|
||||
engine of the system's containers, whose units Quadlet generates from
|
||||
``/etc/containers/systemd`` and whose API ``podman.socket`` serves at
|
||||
``/run/podman/podman.sock``. Rootless containers belong to the user who runs
|
||||
them, in that user's own storage, and no other login sees them. So the
|
||||
connection to Podman runs every call as root (``privileged``), the way the
|
||||
driver gains root for any command: root itself, or sudo. ``podman system
|
||||
dial-stdio`` exists from Podman 4.0 on; it reaches the API socket, which has
|
||||
to be listening (``systemctl enable --now podman.socket``).
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
@@ -34,8 +50,11 @@ from typing import TYPE_CHECKING, Any, cast
|
||||
from napalm_device_types.channel import ByteStream, CommandResult
|
||||
from napalm_device_types.models import ContainerEngineDict, FixResultDict
|
||||
|
||||
#: Engines this package knows how to reach, and the API each speaks.
|
||||
ENGINES: dict[str, str] = {"docker": "docker-engine"}
|
||||
#: Engines this package knows how to reach, and the API each speaks. Podman's
|
||||
#: is its own service, which serves Docker's API next to libpod's.
|
||||
ENGINES: dict[str, str] = {"docker": "docker-engine", "podman": "podman-libpod"}
|
||||
#: Engines reached as root: rootful Podman's socket is root's (see above).
|
||||
ROOT_ENGINES: frozenset[str] = frozenset({"podman"})
|
||||
|
||||
_PROBE_TIMEOUT = 15
|
||||
_CLI_TIMEOUT = 120
|
||||
@@ -52,17 +71,24 @@ class ContainerEngineConnection:
|
||||
arguments; binary, quoting and the channel are the driver's.
|
||||
"""
|
||||
|
||||
def __init__(self, driver: Any, engine: str, binary: str) -> None:
|
||||
def __init__(self, driver: Any, engine: str, binary: str, *, privileged: bool = False) -> None:
|
||||
self._driver = driver
|
||||
self._binary = binary
|
||||
self.engine = engine
|
||||
#: Every call runs as root: the engine is root's (rootful Podman).
|
||||
self.privileged = privileged
|
||||
|
||||
def _command(self, args: Sequence[str]) -> str:
|
||||
return shlex.join([self._binary, *args])
|
||||
|
||||
def open_api(self) -> ByteStream:
|
||||
"""A stream to the engine's API: HTTP/1.1 over ``system dial-stdio``."""
|
||||
return cast(ByteStream, self._driver.open_stream(self._command(["system", "dial-stdio"])))
|
||||
return cast(
|
||||
ByteStream,
|
||||
self._driver.open_stream(
|
||||
self._command(["system", "dial-stdio"]), privileged=self.privileged
|
||||
),
|
||||
)
|
||||
|
||||
def run_cli(
|
||||
self,
|
||||
@@ -80,7 +106,10 @@ class ContainerEngineConnection:
|
||||
return cast(
|
||||
CommandResult,
|
||||
self._driver.run_command(
|
||||
self._command(args), privileged=privileged, timeout=timeout, stdin=stdin
|
||||
self._command(args),
|
||||
privileged=privileged or self.privileged,
|
||||
timeout=timeout,
|
||||
stdin=stdin,
|
||||
),
|
||||
)
|
||||
|
||||
@@ -96,7 +125,8 @@ class ContainerEngineConnection:
|
||||
return cast(
|
||||
ByteStream,
|
||||
self._driver.open_stream(
|
||||
f"{command} 2>&1" if merge_stderr else command, privileged=privileged
|
||||
f"{command} 2>&1" if merge_stderr else command,
|
||||
privileged=privileged or self.privileged,
|
||||
),
|
||||
)
|
||||
|
||||
@@ -134,20 +164,32 @@ class ContainerEngineMixin:
|
||||
* engine (string) - e.g. "docker"
|
||||
* api (string) - what its API is, e.g. "docker-engine"
|
||||
|
||||
An engine is listed when its CLI exists on the host. Whether the login
|
||||
user may use it is decided by the first API call, which says
|
||||
"permission denied" in the stream's stderr.
|
||||
An engine is listed when its CLI exists on the host and names itself
|
||||
when asked for its version: podman-docker's ``docker`` says it is podman,
|
||||
and is left out. Whether the login user may use the engine is decided by
|
||||
the first API call, which says "permission denied" in the stream's stderr.
|
||||
"""
|
||||
found: list[ContainerEngineDict] = []
|
||||
for engine, api in ENGINES.items():
|
||||
probe = shlex.join(["command", "-v", self._container_engine_binary(engine)])
|
||||
result = self.run_command(probe, timeout=_PROBE_TIMEOUT)
|
||||
if result.exit_code == 0 and result.stdout.strip():
|
||||
found.append({"engine": engine, "api": api})
|
||||
return found
|
||||
return [
|
||||
{"engine": engine, "api": api}
|
||||
for engine, api in ENGINES.items()
|
||||
if self._answers_as(engine)
|
||||
]
|
||||
|
||||
def _answers_as(self, engine: str) -> bool:
|
||||
"""Whether *engine*'s CLI is on the host and says it is *engine*."""
|
||||
binary = shlex.quote(self._container_engine_binary(engine))
|
||||
probe = f"command -v {binary} >/dev/null 2>&1 && {binary} --version"
|
||||
result = self.run_command(probe, timeout=_PROBE_TIMEOUT)
|
||||
words = result.stdout.split()
|
||||
return result.exit_code == 0 and bool(words) and words[0].lower() == engine
|
||||
|
||||
def open_container_engine(self, engine: str) -> ContainerEngineConnection:
|
||||
"""The connection to *engine*; :class:`ContainerEngineUnavailable` if unknown."""
|
||||
if engine not in ENGINES:
|
||||
raise ContainerEngineUnavailable(f"no way to reach container engine {engine!r}")
|
||||
return ContainerEngineConnection(self, engine, self._container_engine_binary(engine))
|
||||
return ContainerEngineConnection(
|
||||
self,
|
||||
engine,
|
||||
self._container_engine_binary(engine),
|
||||
privileged=engine in ROOT_ENGINES,
|
||||
)
|
||||
@@ -0,0 +1,58 @@
|
||||
"""When the credential a driver logs in with stops working.
|
||||
|
||||
An API token can be given an expiry, and a platform can require one (Proxmox VE
|
||||
9.3's datacenter ``token-policy``). Once it has passed, every login fails with
|
||||
an authentication error, and an application that polls the device learns of it
|
||||
only then. A driver that can read its own credential's expiry says so here, so
|
||||
the application can warn before, the way it warns of an expiring certificate.
|
||||
|
||||
Which credential is read is the driver's: the one this connection logged in
|
||||
with, never another.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from typing import TYPE_CHECKING, Literal
|
||||
|
||||
from typing_extensions import TypedDict
|
||||
|
||||
#: ``"api-token"``: a token of an account; ``"account"``: the account a password logs in to.
|
||||
CredentialKind = Literal["api-token", "account"]
|
||||
|
||||
|
||||
class CredentialExpiryDict(TypedDict):
|
||||
"""The credential this connection logged in with, and when it expires."""
|
||||
|
||||
kind: CredentialKind
|
||||
#: The credential as the platform names it, e.g. ``"netork@pve!poll"``.
|
||||
name: str
|
||||
#: Unix seconds; ``None`` when it never expires.
|
||||
expires: int | None
|
||||
|
||||
|
||||
class CredentialExpiryMixin:
|
||||
"""Reads the expiry of the credential the driver logged in with.
|
||||
|
||||
Declared under ``if TYPE_CHECKING``: a contract, not a placeholder.
|
||||
"""
|
||||
|
||||
if TYPE_CHECKING:
|
||||
|
||||
def get_credential_expiry(self) -> CredentialExpiryDict:
|
||||
"""
|
||||
The credential this connection logged in with, and when it expires.
|
||||
|
||||
``expires`` is ``None`` for one that never expires. A credential
|
||||
whose expiry has passed cannot log in, so a driver that returns at
|
||||
all reports one that still works.
|
||||
|
||||
:raises PermissionError: The platform will not tell this credential
|
||||
its own expiry (a token whose privileges do not reach it). Not a
|
||||
fault of the connection; a caller then knows nothing either way.
|
||||
:raises RuntimeError: The platform could not be read.
|
||||
|
||||
Example::
|
||||
|
||||
{"kind": "api-token", "name": "netork@pve!poll", "expires": 1767225600}
|
||||
"""
|
||||
...
|
||||
@@ -1,23 +1,39 @@
|
||||
"""The firmware a vendor offers for a device.
|
||||
"""The firmware a vendor offers for a device, and installing it.
|
||||
|
||||
A fact for the caller (docs/STRUCTURE.md): a driver may know the newer firmware
|
||||
from the vendor's download catalogue or the device's own update check; whether
|
||||
running an older one is a problem is decided above the driver. Comparing the
|
||||
vendor's version strings is vendor knowledge, so the driver says itself whether
|
||||
the offer is newer. Declared only; a driver that can tell implements it.
|
||||
|
||||
Installing it is a capability of its own (``FirmwareUpgradeMixin``): when and
|
||||
whether is the caller's call, as with package updates; how is the driver's.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
from typing import TYPE_CHECKING, NotRequired, TypedDict
|
||||
|
||||
from typing import TYPE_CHECKING
|
||||
|
||||
from napalm_device_types.models import FirmwareOfferDict
|
||||
class FirmwareOfferDict(TypedDict):
|
||||
"""The firmware a device runs and the newest its vendor offers
|
||||
(``FirmwareOfferMixin.get_firmware_offer``). A fact, not a judgement."""
|
||||
|
||||
current_version: str
|
||||
latest_version: str
|
||||
newer: bool # the offer is newer than what runs, by the vendor's versioning
|
||||
download_url: NotRequired[str]
|
||||
# The driver can install latest_version itself (FirmwareUpgradeMixin) now; False
|
||||
# while the device lacks what that takes (OpenWrt without owut). Left out where
|
||||
# the driver never installs firmware on this device.
|
||||
installable: NotRequired[bool]
|
||||
# The newest of a later release line (OpenWrt 25.12 on a 24.10 device), which
|
||||
# latest_version does not cross to: shown, never installed by the driver.
|
||||
latest_major_version: NotRequired[str]
|
||||
|
||||
|
||||
class FirmwareOfferMixin:
|
||||
if TYPE_CHECKING: # pragma: no cover - declared for type checkers only
|
||||
|
||||
def get_firmware_offer(self) -> FirmwareOfferDict | None:
|
||||
def get_firmware_offer(self) -> "FirmwareOfferDict | None":
|
||||
"""The firmware running and the newest the vendor offers.
|
||||
|
||||
None when the driver cannot tell for this device (an unknown model,
|
||||
@@ -29,3 +45,23 @@ class FirmwareOfferMixin:
|
||||
"newer": True, "download_url": "https://.../GS308E_1.0.2.12.zip"}
|
||||
"""
|
||||
...
|
||||
|
||||
|
||||
class FirmwareUpgradeMixin:
|
||||
if TYPE_CHECKING: # pragma: no cover - declared for type checkers only
|
||||
|
||||
def start_firmware_upgrade(self, version: str) -> None:
|
||||
"""Starts installing *version*, an offer's ``latest_version`` that
|
||||
:meth:`FirmwareOfferMixin.get_firmware_offer` called ``installable``.
|
||||
|
||||
The device runs the upgrade by itself and restarts at its end, which
|
||||
ends the session; the configuration is kept. Returns once it has
|
||||
started. ``UpdateMixin.get_update_progress`` follows it until then:
|
||||
``"failed"`` when it stopped before the device restarted, which leaves
|
||||
the running firmware as it was.
|
||||
|
||||
:raises ValueError: *version* is not a version string the driver takes.
|
||||
:raises RuntimeError: the device cannot start it (what it takes is
|
||||
missing, an upgrade is already running).
|
||||
"""
|
||||
...
|
||||
@@ -16,13 +16,14 @@ They replace ``run_device_action`` (docs/STRUCTURE.md):
|
||||
``fix_apt_proxy`` :meth:`PackageProxyMixin.configure_package_proxy`
|
||||
``fix_docker_permissions`` ``ContainerEngineMixin.grant_container_engine_access``
|
||||
``install_lldpd`` and co. :meth:`EnsurePackageMixin.ensure_package`
|
||||
(new) :meth:`ZabbixAgentMixin.configure_zabbix_agent`
|
||||
========================== ===================================================
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from collections.abc import Callable, Sequence
|
||||
from typing import TYPE_CHECKING, Any, ClassVar
|
||||
from typing import TYPE_CHECKING, Any, ClassVar, cast
|
||||
|
||||
from napalm_device_types.models import (
|
||||
FixResultDict,
|
||||
@@ -31,6 +32,7 @@ from napalm_device_types.models import (
|
||||
PackageDict,
|
||||
SnmpAgentSettingsDict,
|
||||
)
|
||||
from napalm_device_types.zabbix_agent import ZabbixAgentSettingsDict, check_zabbix_agent_settings
|
||||
|
||||
#: One step of a fix: its name and the call that does it.
|
||||
FixStep = tuple[str, Callable[[], FixStepOutcomeDict]]
|
||||
@@ -58,6 +60,23 @@ def run_fix_steps(steps: Sequence[FixStep]) -> FixResultDict:
|
||||
}
|
||||
|
||||
|
||||
def enable_and_restart(
|
||||
manage_service: Callable[[str, str], dict[str, Any]], service: str
|
||||
) -> FixStepOutcomeDict:
|
||||
"""Enable *service* at boot, then restart it so it reads its configuration; not
|
||||
restarted when it cannot be enabled."""
|
||||
for action in ("enable", "restart"):
|
||||
result = manage_service(service, action)
|
||||
if not result.get("success"):
|
||||
output = str(result.get("output", "")).strip()
|
||||
return {"ok": False, "output": f"{action} {service}: {output}".rstrip(": ")}
|
||||
return {"ok": True, "output": f"{service} enabled and restarted"}
|
||||
|
||||
|
||||
def _joined(*parts: object) -> str:
|
||||
return "\n".join(str(p).strip() for p in parts if p and str(p).strip())
|
||||
|
||||
|
||||
class SnmpAgentMixin:
|
||||
"""Run an SNMP agent on the device that answers the caller.
|
||||
|
||||
@@ -171,13 +190,7 @@ class LldpAgentMixin:
|
||||
return {"ok": bool(result["success"]), "output": str(result.get("output", ""))}
|
||||
|
||||
def _start_lldp_agent(self) -> FixStepOutcomeDict:
|
||||
service = self.LLDP_AGENT_SERVICE
|
||||
for action in ("enable", "restart"):
|
||||
result = self.manage_service(service, action)
|
||||
if not result.get("success"):
|
||||
output = str(result.get("output", "")).strip()
|
||||
return {"ok": False, "output": f"{action} {service}: {output}".rstrip(": ")}
|
||||
return {"ok": True, "output": f"{service} enabled and restarted"}
|
||||
return enable_and_restart(self.manage_service, self.LLDP_AGENT_SERVICE)
|
||||
|
||||
if TYPE_CHECKING: # pragma: no cover - declared for type checkers only
|
||||
|
||||
@@ -193,6 +206,141 @@ class LldpAgentMixin:
|
||||
...
|
||||
|
||||
|
||||
class ZabbixAgentMixin:
|
||||
"""Run a native Zabbix agent that answers the caller's server.
|
||||
|
||||
For a host without a container engine, where the agent cannot run as a
|
||||
container. The steps: load the package index where the driver can
|
||||
(``refresh_available_updates``), install the agent from the host's own packages -- and
|
||||
where those have none, from Zabbix's repository for ``settings["release"]``
|
||||
(:func:`~napalm_device_types.zabbix_agent.zabbix_repository_command`) --, write
|
||||
its configuration (:func:`~napalm_device_types.zabbix_agent.zabbix_agent_config`),
|
||||
let the allowed sources through the host's firewall -- for an agent that is
|
||||
``active_only``, which listens on no port, close what netOrk opened for it
|
||||
earlier instead --, enable and restart it.
|
||||
Installing and starting are generic, over ``ensure_package`` and
|
||||
``manage_service`` with ``ZABBIX_AGENT_PACKAGE`` and ``ZABBIX_AGENT_SERVICE``.
|
||||
Whether Zabbix reaches it is the caller's to ask Zabbix.
|
||||
|
||||
The settings are checked before anything changes; ``ValueError`` names the one
|
||||
that does not hold. A driver that cannot add a repository sets
|
||||
``_add_zabbix_repository`` to ``None``: its hosts then take the distribution's
|
||||
package or none.
|
||||
"""
|
||||
|
||||
#: The package that brings the agent, as ``ensure_package`` takes it.
|
||||
ZABBIX_AGENT_PACKAGE: ClassVar[str] = "zabbix-agent"
|
||||
#: The agent's service, as ``manage_service`` takes it.
|
||||
ZABBIX_AGENT_SERVICE: ClassVar[str] = "zabbix-agent"
|
||||
|
||||
def configure_zabbix_agent(self, settings: ZabbixAgentSettingsDict) -> FixResultDict:
|
||||
"""Install, configure, open, enable and restart the agent with *settings*.
|
||||
|
||||
:raises ValueError: for settings the agent's configuration cannot take,
|
||||
before anything changes.
|
||||
"""
|
||||
check_zabbix_agent_settings(settings)
|
||||
return run_fix_steps(
|
||||
[
|
||||
("install", lambda: self._install_zabbix_agent(settings)),
|
||||
("configure", lambda: self._write_zabbix_agent_config(settings)),
|
||||
("firewall", lambda: self._open_zabbix_agent_port(settings)),
|
||||
("start", self._start_zabbix_agent),
|
||||
]
|
||||
)
|
||||
|
||||
def _install_zabbix_agent(self, settings: ZabbixAgentSettingsDict) -> FixStepOutcomeDict:
|
||||
index = self._load_package_index()
|
||||
first = self.ensure_package(self.ZABBIX_AGENT_PACKAGE)
|
||||
if first["success"]:
|
||||
return {"ok": True, "output": _joined(index, first.get("output"))}
|
||||
release = settings.get("release")
|
||||
add = getattr(self, "_add_zabbix_repository", None)
|
||||
if not release or not callable(add):
|
||||
return {"ok": False, "output": _joined(index, first.get("output"))}
|
||||
added = add(release)
|
||||
if not added["ok"]:
|
||||
return {"ok": False, "output": _joined(index, added.get("output"))}
|
||||
second = self.ensure_package(self.ZABBIX_AGENT_PACKAGE)
|
||||
return {
|
||||
"ok": bool(second["success"]),
|
||||
"output": _joined(index, added.get("output"), second.get("output")),
|
||||
}
|
||||
|
||||
def _load_package_index(self) -> str:
|
||||
"""Load the package index where the driver can (OpenWrt keeps it in RAM, gone
|
||||
after a restart); what went wrong, or "". The install tries either way."""
|
||||
refresh = getattr(self, "refresh_available_updates", None)
|
||||
if not callable(refresh):
|
||||
return ""
|
||||
loaded = refresh()
|
||||
if loaded.get("success"):
|
||||
return ""
|
||||
return f"package index not loaded: {str(loaded.get('output', '')).strip()}"
|
||||
|
||||
def _open_zabbix_agent_port(self, settings: ZabbixAgentSettingsDict) -> FixStepOutcomeDict:
|
||||
"""The driver's firewall step. An agent that only connects out listens on no
|
||||
port (NetOrk/netork#2683): nothing is opened, and the driver closes what netOrk
|
||||
opened for the agent earlier (``_revoke_zabbix_agent_sources``,
|
||||
NetOrk/netork#2693). A driver without it changes nothing and says why."""
|
||||
if not settings.get("active_only"):
|
||||
return self._allow_zabbix_agent_sources(settings)
|
||||
revoke = getattr(self, "_revoke_zabbix_agent_sources", None)
|
||||
if callable(revoke):
|
||||
return cast(FixStepOutcomeDict, revoke(settings))
|
||||
return {
|
||||
"ok": True,
|
||||
"output": "active only: the agent listens on no port; this driver cannot tell"
|
||||
" a rule netOrk opened for it from the operator's, so the firewall is unchanged",
|
||||
}
|
||||
|
||||
def _start_zabbix_agent(self) -> FixStepOutcomeDict:
|
||||
return enable_and_restart(self.manage_service, self.ZABBIX_AGENT_SERVICE)
|
||||
|
||||
if TYPE_CHECKING: # pragma: no cover - declared for type checkers only
|
||||
|
||||
def ensure_package(self, name: str) -> FixResultDict: ...
|
||||
|
||||
def manage_service(self, name: str, action: str) -> dict[str, Any]: ...
|
||||
|
||||
def refresh_available_updates(self) -> dict[str, Any]: ...
|
||||
|
||||
# The steps a driver implements:
|
||||
|
||||
def _add_zabbix_repository(self, release: str) -> FixStepOutcomeDict:
|
||||
"""Add Zabbix's repository for *release* and refresh the package index
|
||||
(``zabbix_repository_command`` builds the command for most hosts)."""
|
||||
...
|
||||
|
||||
def _write_zabbix_agent_config(
|
||||
self, settings: ZabbixAgentSettingsDict
|
||||
) -> FixStepOutcomeDict:
|
||||
"""Write *settings* into the agent's configuration file, keeping the rest of
|
||||
it (``zabbix_agent_config``), and whatever else the device needs before the
|
||||
agent may start."""
|
||||
...
|
||||
|
||||
def _allow_zabbix_agent_sources(
|
||||
self, settings: ZabbixAgentSettingsDict
|
||||
) -> FixStepOutcomeDict:
|
||||
"""Let ``settings["allowed_sources"]`` reach tcp/``listen_port``; ``ok`` with
|
||||
nothing to do where the host has no firewall of its own, or for []. Not
|
||||
called for an ``active_only`` agent."""
|
||||
...
|
||||
|
||||
# Optional: a driver that can tell its own rules from the operator's.
|
||||
|
||||
def _revoke_zabbix_agent_sources(
|
||||
self, settings: ZabbixAgentSettingsDict
|
||||
) -> FixStepOutcomeDict:
|
||||
"""Close what ``_allow_zabbix_agent_sources`` opened for the agent on an
|
||||
earlier run, for an ``active_only`` agent, and nothing else: a rule the
|
||||
operator wrote stays, however alike (NetOrk/netork#2693). ``ok`` where
|
||||
nothing was opened. Where the firewall itself does not say who wrote a
|
||||
rule, the driver keeps :mod:`~napalm_device_types.opened_ports`' record."""
|
||||
...
|
||||
|
||||
|
||||
class PackageProxyMixin:
|
||||
"""Point the device's package manager at a caching proxy."""
|
||||
|
||||
@@ -215,5 +363,7 @@ __all__ = [
|
||||
"LldpAgentMixin",
|
||||
"PackageProxyMixin",
|
||||
"SnmpAgentMixin",
|
||||
"ZabbixAgentMixin",
|
||||
"enable_and_restart",
|
||||
"run_fix_steps",
|
||||
]
|
||||
@@ -0,0 +1,341 @@
|
||||
"""How a Linux host is hardened, as its kernel and its own tools say it (NetOrk/netork#2706).
|
||||
|
||||
Five things, each read where the host itself keeps it:
|
||||
|
||||
- **The security modules in force:** ``/sys/kernel/security/lsm`` lists the active
|
||||
LSMs. SELinux's mode comes from ``getenforce`` (or ``/sys/fs/selinux/enforce``), the
|
||||
mode it boots in from ``SELINUX=`` in ``/etc/selinux/config``. AppArmor's switch is
|
||||
``/sys/module/apparmor/parameters/enabled``, its profiles per mode come from
|
||||
``aa-status --json`` -- the one part that needs root.
|
||||
- **The crypto policy:** ``update-crypto-policies --show`` (the dnf family; Debian and
|
||||
Ubuntu have none) and FIPS mode from ``/proc/sys/crypto/fips_enabled``.
|
||||
- **The CPU vulnerabilities:** each file under ``/sys/devices/system/cpu/vulnerabilities``
|
||||
holds the kernel's own answer for one of them: ``Not affected``, ``Mitigation: ...``,
|
||||
``Vulnerable...``, or ``Unknown: ...`` (:func:`cpu_vulnerability_state`).
|
||||
- **The kernel command line:** ``mitigations=`` (``auto`` when not given, as in the
|
||||
kernel) and ``nosmt``.
|
||||
- **The distribution's IDs** (``ID`` and ``ID_LIKE`` from ``/etc/os-release``), so a
|
||||
consumer can tell an Enterprise Linux host, where SELinux is the distribution's own
|
||||
module, from one that merely has it installed.
|
||||
|
||||
One fixed command, read-only, the same on every Linux host, so it and its parse live
|
||||
here once and a driver only carries the command across. **Not read is None, never
|
||||
empty or off:** a section the command did not print -- a file missing, a tool not
|
||||
installed, root refused -- comes back ``None``, so a consumer never reads "not looked"
|
||||
as "clean".
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import json
|
||||
import re
|
||||
from shlex import quote
|
||||
from typing import TYPE_CHECKING, Literal, TypedDict
|
||||
|
||||
from napalm_device_types.terminal import strip_terminal_codes
|
||||
|
||||
_BEGIN = "HARDENING_BEGIN"
|
||||
_END = "HARDENING_END"
|
||||
_VULNERABILITIES = "/sys/devices/system/cpu/vulnerabilities"
|
||||
|
||||
#: One line, POSIX ``sh``, read-only. The frame markers are printed in two halves so
|
||||
#: that a transport which echoes the command does not show them early. The tools are in
|
||||
#: ``/usr/sbin`` on some systems, outside a login user's ``PATH``. ``r`` prints a file
|
||||
#: under a section header and ends it with a newline: ``/sys/kernel/security/lsm`` has
|
||||
#: none of its own.
|
||||
HARDENING_COMMAND = (
|
||||
"PATH=$PATH:/usr/sbin:/sbin; "
|
||||
'r() { if [ -r "$2" ]; then echo "[$1]"; cat "$2" 2>/dev/null; echo; fi; }; '
|
||||
"printf '%s%s\\n' HARDENING_ BEGIN; "
|
||||
"r lsm /sys/kernel/security/lsm; "
|
||||
"r cmdline /proc/cmdline; "
|
||||
"r fips /proc/sys/crypto/fips_enabled; "
|
||||
"r apparmor_enabled /sys/module/apparmor/parameters/enabled; "
|
||||
"if [ -r /etc/os-release ]; then echo '[os]'; grep -E '^(ID|ID_LIKE)=' /etc/os-release; fi; "
|
||||
"if command -v getenforce >/dev/null 2>&1; then echo '[selinux]'; getenforce 2>/dev/null; "
|
||||
"else r selinux_enforce /sys/fs/selinux/enforce; fi; "
|
||||
"if [ -r /etc/selinux/config ]; then echo '[selinux_config]'; "
|
||||
"grep -E '^SELINUX=' /etc/selinux/config; fi; "
|
||||
"if command -v update-crypto-policies >/dev/null 2>&1; then echo '[crypto_policy]'; "
|
||||
"update-crypto-policies --show 2>/dev/null; fi; "
|
||||
f"if [ -d {_VULNERABILITIES} ]; then echo '[cpu_vulnerabilities]'; "
|
||||
f"grep -H . {_VULNERABILITIES}/* 2>/dev/null; fi; "
|
||||
"if command -v aa-status >/dev/null 2>&1; then echo '[aa_status]'; "
|
||||
"aa-status --json 2>/dev/null; echo; fi; "
|
||||
"printf '%s%s\\n' HARDENING_ END"
|
||||
)
|
||||
|
||||
CpuVulnerabilityState = Literal["not_affected", "mitigated", "vulnerable", "unknown"]
|
||||
|
||||
_SELINUX_MODES = frozenset({"enforcing", "permissive", "disabled"})
|
||||
_ENFORCE_FILE = {"1": "enforcing", "0": "permissive"}
|
||||
_SECTION = re.compile(r"^\[([a-z_]+)\]$")
|
||||
|
||||
|
||||
class SelinuxDict(TypedDict):
|
||||
"""SELinux on the host. ``None`` in a field: could not be read."""
|
||||
|
||||
mode: str | None # "enforcing", "permissive" or "disabled"
|
||||
configured: str | None # SELINUX= in /etc/selinux/config: the mode it boots in
|
||||
|
||||
|
||||
class AppArmorDict(TypedDict):
|
||||
"""AppArmor on the host. ``None`` in a field: could not be read."""
|
||||
|
||||
enabled: bool | None # /sys/module/apparmor/parameters/enabled, else the LSM list
|
||||
#: Loaded profiles per mode ("enforce", "complain", ...), from ``aa-status --json``;
|
||||
#: None without root, which it needs.
|
||||
profiles: dict[str, int] | None
|
||||
|
||||
|
||||
class HardeningDict(TypedDict):
|
||||
"""What :meth:`HardeningMixin.get_hardening` read. ``None``: not read, never "off"."""
|
||||
|
||||
lsm: list[str] | None # /sys/kernel/security/lsm, in the kernel's order
|
||||
selinux: SelinuxDict | None # None: no sign of SELinux on the host
|
||||
apparmor: AppArmorDict | None # None: no sign of AppArmor on the host
|
||||
crypto_policy: str | None # update-crypto-policies --show, e.g. "DEFAULT:SHA1"
|
||||
fips: bool | None # /proc/sys/crypto/fips_enabled
|
||||
#: File name under /sys/devices/system/cpu/vulnerabilities -> the kernel's text.
|
||||
cpu_vulnerabilities: dict[str, str] | None
|
||||
cmdline: str | None # /proc/cmdline
|
||||
mitigations: str | None # mitigations= on the command line; "auto" when not given
|
||||
nosmt: bool | None # SMT switched off by the command line
|
||||
os_ids: list[str] | None # ID, then ID_LIKE, from /etc/os-release, lowercased
|
||||
|
||||
|
||||
def cpu_vulnerability_state(text: str) -> CpuVulnerabilityState:
|
||||
"""What the kernel's text for one CPU vulnerability says, in one word.
|
||||
|
||||
The kernel writes ``Not affected``, ``Mitigation: ...`` (also behind a prefix, as
|
||||
``KVM: Mitigation: VMX disabled``), ``Vulnerable...`` or ``Processor vulnerable``,
|
||||
and ``Unknown: ...`` where it cannot tell (a guest that cannot see its host's
|
||||
microcode). A mitigation that leaves SMT exposed is still the kernel's
|
||||
``Mitigation``: the text keeps the rest.
|
||||
"""
|
||||
lowered = text.strip().lower()
|
||||
if lowered.startswith("not affected"):
|
||||
return "not_affected"
|
||||
if lowered.startswith(("vulnerable", "processor vulnerable")):
|
||||
return "vulnerable"
|
||||
if lowered.startswith("mitigation") or ": mitigation" in lowered:
|
||||
return "mitigated"
|
||||
return "unknown"
|
||||
|
||||
|
||||
def _sections(output: str) -> dict[str, list[str]]:
|
||||
lines = [line.strip() for line in strip_terminal_codes(output).splitlines()]
|
||||
try:
|
||||
start = lines.index(_BEGIN)
|
||||
end = lines.index(_END, start)
|
||||
except ValueError:
|
||||
raise ValueError("no intact hardening report in the output") from None
|
||||
sections: dict[str, list[str]] = {}
|
||||
current: list[str] = []
|
||||
for line in lines[start + 1 : end]:
|
||||
header = _SECTION.match(line)
|
||||
if header:
|
||||
current = sections.setdefault(header.group(1), [])
|
||||
elif line:
|
||||
current.append(line)
|
||||
return sections
|
||||
|
||||
|
||||
def _first(sections: dict[str, list[str]], key: str) -> str | None:
|
||||
lines = sections.get(key)
|
||||
return lines[0] if lines else None
|
||||
|
||||
|
||||
def _unquote(value: str) -> str:
|
||||
value = value.strip()
|
||||
return value[1:-1] if len(value) >= 2 and value[0] == value[-1] and value[0] in "\"'" else value
|
||||
|
||||
|
||||
def _lsm(sections: dict[str, list[str]]) -> list[str] | None:
|
||||
line = _first(sections, "lsm")
|
||||
if line is None:
|
||||
return None
|
||||
return [name.strip() for name in line.split(",") if name.strip()]
|
||||
|
||||
|
||||
def _selinux_configured(sections: dict[str, list[str]]) -> str | None:
|
||||
"""The mode it boots in: ``SELINUX=`` in ``/etc/selinux/config``, the last one."""
|
||||
configured = None
|
||||
for line in sections.get("selinux_config", []):
|
||||
key, _, value = line.partition("=")
|
||||
if key.strip() == "SELINUX":
|
||||
configured = _unquote(value).lower() or None
|
||||
return configured
|
||||
|
||||
|
||||
def _selinux_running(sections: dict[str, list[str]]) -> str | None:
|
||||
"""The mode it runs in: ``getenforce``'s word, else ``/sys/fs/selinux/enforce``."""
|
||||
said = (_first(sections, "selinux") or "").lower()
|
||||
if said in _SELINUX_MODES:
|
||||
return said
|
||||
return _ENFORCE_FILE.get(_first(sections, "selinux_enforce") or "")
|
||||
|
||||
|
||||
def _selinux_seen(sections: dict[str, list[str]], lsm: list[str] | None, mode: str | None) -> bool:
|
||||
"""Whether the host shows any sign of SELinux: a mode, its configuration, the LSM list."""
|
||||
return mode is not None or "selinux_config" in sections or "selinux" in (lsm or [])
|
||||
|
||||
|
||||
def _selinux(sections: dict[str, list[str]], lsm: list[str] | None) -> SelinuxDict | None:
|
||||
mode = _selinux_running(sections)
|
||||
if not _selinux_seen(sections, lsm, mode):
|
||||
return None
|
||||
if mode is None and "selinux_config" in sections and lsm is not None:
|
||||
# Installed, but not among the modules the kernel runs: switched off at boot.
|
||||
mode = None if "selinux" in lsm else "disabled"
|
||||
return {"mode": mode, "configured": _selinux_configured(sections)}
|
||||
|
||||
|
||||
def _profiles(sections: dict[str, list[str]]) -> dict[str, int] | None:
|
||||
text = "".join(sections.get("aa_status", []))
|
||||
try:
|
||||
profiles = json.loads(text).get("profiles")
|
||||
except (ValueError, AttributeError):
|
||||
return None
|
||||
if not isinstance(profiles, dict):
|
||||
return None
|
||||
counts: dict[str, int] = {}
|
||||
for mode in profiles.values():
|
||||
counts[str(mode)] = counts.get(str(mode), 0) + 1
|
||||
return dict(sorted(counts.items()))
|
||||
|
||||
|
||||
def _apparmor(sections: dict[str, list[str]], lsm: list[str] | None) -> AppArmorDict | None:
|
||||
switch = _first(sections, "apparmor_enabled")
|
||||
profiles = _profiles(sections)
|
||||
in_lsm = "apparmor" in (lsm or [])
|
||||
if switch is None and profiles is None and not in_lsm:
|
||||
return None
|
||||
if switch is not None:
|
||||
enabled: bool | None = switch.upper().startswith("Y")
|
||||
else:
|
||||
enabled = True if in_lsm else None
|
||||
return {"enabled": enabled, "profiles": profiles}
|
||||
|
||||
|
||||
def _cpu_vulnerabilities(sections: dict[str, list[str]]) -> dict[str, str] | None:
|
||||
if "cpu_vulnerabilities" not in sections:
|
||||
return None
|
||||
found: dict[str, str] = {}
|
||||
for line in sections["cpu_vulnerabilities"]:
|
||||
path, sep, text = line.partition(":")
|
||||
if sep:
|
||||
found[path.rsplit("/", 1)[-1]] = text.strip()
|
||||
return dict(sorted(found.items()))
|
||||
|
||||
|
||||
def _command_line(cmdline: str | None) -> tuple[str | None, bool | None]:
|
||||
"""``mitigations=`` (the last one wins, as in the kernel) and whether SMT is off."""
|
||||
if cmdline is None:
|
||||
return None, None
|
||||
mitigations = "auto"
|
||||
nosmt = False
|
||||
for word in cmdline.split():
|
||||
key, _, value = word.partition("=")
|
||||
if key == "mitigations":
|
||||
mitigations = value
|
||||
elif key == "nosmt":
|
||||
nosmt = True
|
||||
return mitigations, nosmt or "nosmt" in mitigations.split(",")
|
||||
|
||||
|
||||
def _os_ids(sections: dict[str, list[str]]) -> list[str] | None:
|
||||
if "os" not in sections:
|
||||
return None
|
||||
values = {}
|
||||
for line in sections["os"]:
|
||||
key, _, value = line.partition("=")
|
||||
values[key.strip()] = _unquote(value)
|
||||
ids: list[str] = []
|
||||
for word in f"{values.get('ID', '')} {values.get('ID_LIKE', '')}".lower().split():
|
||||
if word not in ids:
|
||||
ids.append(word)
|
||||
return ids
|
||||
|
||||
|
||||
def parse_hardening(output: str) -> HardeningDict:
|
||||
"""Parse what :data:`HARDENING_COMMAND` printed.
|
||||
|
||||
:raises ValueError: when the output carries no intact report.
|
||||
"""
|
||||
sections = _sections(output)
|
||||
lsm = _lsm(sections)
|
||||
cmdline = _first(sections, "cmdline")
|
||||
mitigations, nosmt = _command_line(cmdline)
|
||||
fips = _first(sections, "fips")
|
||||
return {
|
||||
"lsm": lsm,
|
||||
"selinux": _selinux(sections, lsm),
|
||||
"apparmor": _apparmor(sections, lsm),
|
||||
"crypto_policy": _first(sections, "crypto_policy"),
|
||||
"fips": None if fips is None else fips == "1",
|
||||
"cpu_vulnerabilities": _cpu_vulnerabilities(sections),
|
||||
"cmdline": cmdline,
|
||||
"mitigations": mitigations,
|
||||
"nosmt": nosmt,
|
||||
"os_ids": _os_ids(sections),
|
||||
}
|
||||
|
||||
|
||||
class HardeningMixin:
|
||||
"""Adds :meth:`get_hardening` to a driver that can run a command on a Linux host.
|
||||
|
||||
The template form (README, "Function classes"): the command and its parse are the
|
||||
same everywhere, and a driver supplies only :meth:`_run_hardening_command` -- how a
|
||||
command reaches its host, and how it gains root there. Mixed in by the drivers that
|
||||
can, so ``hasattr(driver, "get_hardening")`` stays a truthful answer.
|
||||
"""
|
||||
|
||||
if TYPE_CHECKING: # pragma: no cover - declared for type checkers only
|
||||
|
||||
def _run_hardening_command(self, command: str, *, privileged: bool) -> str:
|
||||
"""Run *command* on the host and return what it printed; as root when
|
||||
*privileged*. The command is a single ``sh -c`` invocation; it reads no stdin."""
|
||||
...
|
||||
|
||||
def get_hardening(self) -> HardeningDict:
|
||||
"""
|
||||
Returns how the host is hardened: its security modules, crypto policy, CPU
|
||||
vulnerabilities and kernel command line.
|
||||
|
||||
* lsm (list or None) - the active security modules, in the kernel's order
|
||||
* selinux ({mode, configured} or None) - None without any sign of SELinux
|
||||
* apparmor ({enabled, profiles} or None) - profiles per mode need root
|
||||
* crypto_policy (str or None) - ``update-crypto-policies --show``
|
||||
* fips (bool or None) - FIPS mode
|
||||
* cpu_vulnerabilities (dict or None) - name -> the kernel's text
|
||||
* cmdline (str or None), mitigations (str or None), nosmt (bool or None)
|
||||
* os_ids (list or None) - ``ID`` and ``ID_LIKE`` from ``/etc/os-release``
|
||||
|
||||
``None`` means not read. Read as root first, for AppArmor's profiles; where root
|
||||
is refused, as the login user, without them.
|
||||
|
||||
Example::
|
||||
|
||||
{
|
||||
"lsm": ["lockdown", "capability", "yama", "selinux", "bpf"],
|
||||
"selinux": {"mode": "enforcing", "configured": "enforcing"},
|
||||
"apparmor": None,
|
||||
"crypto_policy": "DEFAULT",
|
||||
"fips": False,
|
||||
"cpu_vulnerabilities": {"meltdown": "Not affected",
|
||||
"spectre_v2": "Mitigation: Retpolines; ..."},
|
||||
"cmdline": "BOOT_IMAGE=... ro",
|
||||
"mitigations": "auto",
|
||||
"nosmt": False,
|
||||
"os_ids": ["almalinux", "rhel", "centos", "fedora"],
|
||||
}
|
||||
|
||||
:raises ValueError: if neither reading carried an intact report.
|
||||
"""
|
||||
command = f"sh -c {quote(HARDENING_COMMAND)}"
|
||||
try:
|
||||
return parse_hardening(self._run_hardening_command(command, privileged=True))
|
||||
except ValueError:
|
||||
pass
|
||||
return parse_hardening(self._run_hardening_command(command, privileged=False))
|
||||
@@ -41,6 +41,13 @@ class HypervisorDriver(PackageManagementMixin, HealthMetricsMixin, DeviceTypeDri
|
||||
|
||||
Inherits all standard NAPALM NetworkDriver methods and adds
|
||||
hypervisor-specific operations that concrete drivers must implement.
|
||||
|
||||
A guest is known by its ``vmid``, which a platform may give to another guest
|
||||
once the first is gone, and where it has one also by its ``uid``
|
||||
(``VMDict.uid``): an identity that survives a migration, a restore and a
|
||||
changed ``vmid`` -- Proxmox VE 9.3's ``uid``, VMware's instance UUID. A driver
|
||||
leaves it out where the platform has none or has not given the guest one yet;
|
||||
a caller then knows that guest by ``vmid`` alone.
|
||||
"""
|
||||
|
||||
#: Stable key netOrk exposes as ``device_class``. The order in which a
|
||||
@@ -69,15 +76,19 @@ class HypervisorDriver(PackageManagementMixin, HealthMetricsMixin, DeviceTypeDri
|
||||
Each entry contains:
|
||||
|
||||
* name (string) - VM display name
|
||||
* vmid (string) - hypervisor-internal ID (Proxmox: ``"100"``,
|
||||
VMware: the instance UUID)
|
||||
* status (string) - ``"running"``, ``"stopped"``, ``"paused"``, ``"suspended"``
|
||||
* vmid (string) - hypervisor-internal ID (Proxmox: ``"100"``, VMware: the instance UUID)
|
||||
* status (string) - ``"running"``, ``"stopped"``, ``"paused"``, ``"suspended"``.
|
||||
A guest that is not executing is never ``"running"``: ``"paused"``
|
||||
while its process still holds its memory (Proxmox's ``qmpstatus``
|
||||
``paused``), ``"suspended"`` once its state was saved away (VMware's
|
||||
``suspended``). :meth:`resume_vm` brings either back.
|
||||
* vcpus (int) - number of virtual CPUs assigned
|
||||
* memory (int) - configured RAM in megabytes
|
||||
* cpu_usage (float) - current CPU utilisation 0.0–1.0
|
||||
* memory_usage (int) - current RAM usage in megabytes
|
||||
* uptime (int) - uptime in seconds (0 if not running)
|
||||
* node (string) - cluster node this VM lives on (empty string for standalone)
|
||||
* uid (string, optional) - outlives the ``vmid``; absent where none (``VMDict.uid``)
|
||||
|
||||
Example::
|
||||
|
||||
@@ -248,7 +259,9 @@ class HypervisorDriver(PackageManagementMixin, HealthMetricsMixin, DeviceTypeDri
|
||||
def suspend_vm(self, name: str) -> None:
|
||||
"""
|
||||
Suspends (pauses) a running virtual machine, preserving its in-memory
|
||||
state. The VM can be resumed with :meth:`start_vm`.
|
||||
state. :meth:`get_vms` then reports it ``"paused"`` (its process
|
||||
still holds the memory) or ``"suspended"`` (its state was saved
|
||||
away), and :meth:`resume_vm` brings it back.
|
||||
|
||||
:param name: VM name or its ``vmid``.
|
||||
:raises ValueError: If no VM with the given name/ID exists.
|
||||
@@ -260,6 +273,33 @@ class HypervisorDriver(PackageManagementMixin, HealthMetricsMixin, DeviceTypeDri
|
||||
"""
|
||||
...
|
||||
|
||||
def resume_vm(self, name: str) -> None:
|
||||
"""
|
||||
Resumes a paused or suspended virtual machine where it stopped, the
|
||||
counterpart of :meth:`suspend_vm`. The method blocks until the
|
||||
hypervisor took the request.
|
||||
|
||||
The guest's clock is set to the host's time after it resumes, where the
|
||||
platform can do so (Proxmox VE: through the guest agent): a guest that
|
||||
stood still for hours would otherwise run behind. No caller wants
|
||||
otherwise, so it is the driver's to do, not a choice.
|
||||
|
||||
Optional, like every power action: a driver whose platform cannot
|
||||
resume a guest does not implement it, and a caller then offers no
|
||||
resume. A driver that can resume some guests but not others (a
|
||||
Proxmox container) refuses the others with ``RuntimeError``.
|
||||
|
||||
:param name: VM name or its ``vmid``.
|
||||
:raises ValueError: If no VM with the given name/ID exists.
|
||||
:raises RuntimeError: If the VM is neither paused nor suspended, or
|
||||
the platform cannot resume this kind of guest.
|
||||
|
||||
Example::
|
||||
|
||||
driver.resume_vm("web01")
|
||||
"""
|
||||
...
|
||||
|
||||
# ------------------------------------------------------------------
|
||||
# Snapshots
|
||||
# ------------------------------------------------------------------
|
||||
|
||||
@@ -16,6 +16,13 @@ What the four lists mean for a module, and why "not loaded" alone is never
|
||||
"absent": a module that is not loaded can still be loaded on demand -- by an
|
||||
attacker too, where autoloading reaches it. Only a module that is neither
|
||||
loaded, nor compiled in, nor shipped for this kernel is one it cannot have.
|
||||
|
||||
**The live patches** the kernel carries come with it (NetOrk/netork#2701,
|
||||
:mod:`napalm_device_types.livepatch`): the patches loaded in ``/sys/kernel/livepatch``,
|
||||
``kpatch list``, and Canonical Livepatch's status with the CVEs it fixes. That status
|
||||
may need root: where the client is installed and its status did not read without, a
|
||||
driver that supplies ``_run_livepatch_status_command`` reads it again as root, one
|
||||
fixed, read-only command (:data:`LIVEPATCH_STATUS_COMMAND`).
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
@@ -26,6 +33,7 @@ import gzip
|
||||
import zlib
|
||||
from typing import TYPE_CHECKING
|
||||
|
||||
from napalm_device_types.livepatch import live_patches, parse_canonical_status
|
||||
from napalm_device_types.models import KernelFactsDict
|
||||
|
||||
_BEGIN = "KFACTS_BEGIN"
|
||||
@@ -43,11 +51,23 @@ KERNEL_FACTS_COMMAND = (
|
||||
"if [ -r /boot/config-$r ]; then echo '[config]'; grep '^CONFIG_' /boot/config-$r; "
|
||||
"elif [ -r /proc/config.gz ]; then echo '[config]'; "
|
||||
"zcat /proc/config.gz | grep '^CONFIG_'; fi; "
|
||||
"if [ -d /sys/kernel/livepatch ]; then echo '[livepatch]'; "
|
||||
'for p in /sys/kernel/livepatch/*; do [ -d "$p" ] && '
|
||||
'echo "${p##*/} $(cat "$p/enabled") $(cat "$p/transition")"; done; fi; '
|
||||
"if command -v kpatch >/dev/null; then echo '[kpatch]'; kpatch list; fi; "
|
||||
"c=$(command -v canonical-livepatch || ls /snap/bin/canonical-livepatch); "
|
||||
"if [ -n \"$c\" ]; then echo '[canonical_livepatch]'; "
|
||||
"\"$c\" status --format json | tr -d '\\n'; echo; fi; "
|
||||
"} 2>/dev/null | gzip -c | base64; "
|
||||
"printf '%s%s\\n' KFACTS_ END"
|
||||
)
|
||||
|
||||
|
||||
#: Canonical Livepatch's status, as root: the client lives in ``/snap/bin``, outside the
|
||||
#: ``PATH`` sudo keeps. Read-only: ``status`` reads what the daemon holds.
|
||||
LIVEPATCH_STATUS_COMMAND = "/snap/bin/canonical-livepatch status --format json"
|
||||
|
||||
|
||||
def module_name(raw: str) -> str:
|
||||
"""A module as the kernel names it: no path, no ``.ko`` suffix, ``_`` for ``-``.
|
||||
|
||||
@@ -124,6 +144,7 @@ def parse_kernel_facts(output: str) -> KernelFactsDict:
|
||||
"builtin": names("builtin"),
|
||||
"available": names("available"),
|
||||
"config": _config(sections["config"]) if "config" in sections else None,
|
||||
"live_patches": live_patches(sections),
|
||||
}
|
||||
|
||||
|
||||
@@ -144,6 +165,9 @@ class KernelFactsMixin:
|
||||
"""Run *command* on the host with ``sh`` and return what it printed."""
|
||||
...
|
||||
|
||||
#: Optional: a driver that can gain root supplies
|
||||
#: ``_run_livepatch_status_command(command) -> str``, which runs *command* as root.
|
||||
|
||||
def get_kernel_facts(self) -> KernelFactsDict:
|
||||
"""
|
||||
Returns what the running kernel has built and loaded.
|
||||
@@ -166,6 +190,29 @@ class KernelFactsMixin:
|
||||
"config": {"CONFIG_TIPC": "m", "CONFIG_HZ": "250"},
|
||||
}
|
||||
|
||||
* live_patches (dict) - loaded (``/sys/kernel/livepatch``, None without live
|
||||
patching), kpatch (``kpatch list``) and canonical (Canonical Livepatch's
|
||||
status for the running kernel, with the CVEs it fixes); each None when not read
|
||||
|
||||
:raises ValueError: if the host's output carried no intact report.
|
||||
"""
|
||||
return parse_kernel_facts(self._run_kernel_facts_command(KERNEL_FACTS_COMMAND))
|
||||
facts = parse_kernel_facts(self._run_kernel_facts_command(KERNEL_FACTS_COMMAND))
|
||||
return self._with_canonical_as_root(facts)
|
||||
|
||||
def _with_canonical_as_root(self, facts: KernelFactsDict) -> KernelFactsDict:
|
||||
"""*facts* with Canonical's status read as root where it did not read without.
|
||||
|
||||
Only where the client was found (its section printed) and gave no status, and
|
||||
only by a driver that can gain root. A refusal leaves it unread.
|
||||
"""
|
||||
patches = facts.get("live_patches")
|
||||
run = getattr(self, "_run_livepatch_status_command", None)
|
||||
if patches is None or not patches["canonical_installed"] or not callable(run):
|
||||
return facts
|
||||
if patches["canonical"] is not None:
|
||||
return facts
|
||||
try:
|
||||
patches["canonical"] = parse_canonical_status(run(LIVEPATCH_STATUS_COMMAND))
|
||||
except Exception: # noqa: BLE001 - root refused or the client failed: not read
|
||||
pass
|
||||
return facts
|
||||
@@ -0,0 +1,201 @@
|
||||
"""The live patches a running Linux kernel carries, as the kernel and the vendors' tools say it.
|
||||
|
||||
A live patch replaces kernel functions while the kernel runs: it fixes a CVE without a
|
||||
new release, and without the reboot a new release needs (NetOrk/netork#2701). Three
|
||||
places say which are in, each read by the kernel facts (:mod:`napalm_device_types.kernel`):
|
||||
|
||||
- **The kernel itself:** ``/sys/kernel/livepatch/<patch>/enabled`` for every patch
|
||||
loaded, whoever built it (kpatch, Canonical, SUSE's kGraft successor), and
|
||||
``transition`` while it is still being applied. No package needed.
|
||||
- **kpatch** (the Red Hat family): ``kpatch list`` names the patch modules loaded, with
|
||||
whether each is enabled, and those installed for each kernel.
|
||||
- **Canonical Livepatch** (Ubuntu Pro): ``canonical-livepatch status --format json``,
|
||||
the daemon's last state -- the kernel it is for, whether a patch is applied, and the
|
||||
CVEs it fixes. ``status`` reads what the daemon holds; netOrk never runs ``refresh``,
|
||||
which is what calls Canonical.
|
||||
|
||||
Parsing only: what a patch means for a CVE is the consumer's call. **Not read is None**:
|
||||
a kernel built without live patching has no ``/sys/kernel/livepatch`` and ``loaded`` is
|
||||
None; a host without kpatch or Canonical's client has ``kpatch`` / ``canonical`` None.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import json
|
||||
import re
|
||||
from collections.abc import Iterable, Mapping
|
||||
from typing import Any
|
||||
|
||||
from typing_extensions import TypedDict
|
||||
|
||||
_CVE = re.compile(r"\bcve-(\d{4})-(\d{4,})\b", re.IGNORECASE)
|
||||
#: ``5.15.0-91.101-generic`` (Canonical's) is ``5.15.0-91-generic`` (``uname -r``).
|
||||
_CANONICAL_KERNEL = re.compile(r"^(\d+\.\d+\.\d+-\d+)\.[^-]+(-.+)$")
|
||||
_KPATCH_LOADED = re.compile(r"^(\S+)\s+\[(enabled|disabled)\]$")
|
||||
_KPATCH_INSTALLED = re.compile(r"^(\S+)\s+\((\S+)\)$")
|
||||
|
||||
|
||||
class LoadedLivePatchDict(TypedDict):
|
||||
"""One directory under ``/sys/kernel/livepatch``."""
|
||||
|
||||
name: str
|
||||
enabled: bool | None
|
||||
#: Still being applied to (or taken off) every task.
|
||||
transition: bool | None
|
||||
|
||||
|
||||
class KpatchModuleDict(TypedDict, total=False):
|
||||
name: str
|
||||
enabled: bool # loaded ones
|
||||
kernel: str # installed ones: the kernel they are built for
|
||||
|
||||
|
||||
class KpatchDict(TypedDict):
|
||||
loaded: list[KpatchModuleDict]
|
||||
installed: list[KpatchModuleDict]
|
||||
|
||||
|
||||
class LivepatchFixDict(TypedDict):
|
||||
cve: str # upper case, "CVE-2023-1077"
|
||||
patched: bool
|
||||
|
||||
|
||||
class CanonicalLivepatchDict(TypedDict):
|
||||
"""``canonical-livepatch status`` for the running kernel. None in a field: not said."""
|
||||
|
||||
kernel: str | None # as Canonical writes it: "5.15.0-91.101-generic"
|
||||
running: bool | None
|
||||
state: str | None # "applied", "nothing-to-apply", "unapplied", "apply-failed", ...
|
||||
check_state: str | None # "checked", "needs-check", "check-failed", ...
|
||||
version: str | None
|
||||
fixes: list[LivepatchFixDict]
|
||||
|
||||
|
||||
class LivePatchesDict(TypedDict):
|
||||
#: ``/sys/kernel/livepatch``; None: the kernel has no live patching.
|
||||
loaded: list[LoadedLivePatchDict] | None
|
||||
#: ``kpatch list``; None: kpatch is not installed.
|
||||
kpatch: KpatchDict | None
|
||||
#: ``canonical-livepatch status``; None: not installed, or its status not read.
|
||||
canonical: CanonicalLivepatchDict | None
|
||||
#: Canonical's client is on the host (``canonical`` None then: its status unread).
|
||||
canonical_installed: bool
|
||||
|
||||
|
||||
def _flag(word: str | None) -> bool | None:
|
||||
return {"1": True, "0": False}.get(word or "")
|
||||
|
||||
|
||||
def parse_sysfs_livepatches(lines: Iterable[str]) -> list[LoadedLivePatchDict]:
|
||||
"""``<name> <enabled> <transition>`` per loaded patch, as the command prints them."""
|
||||
patches: list[LoadedLivePatchDict] = []
|
||||
for line in lines:
|
||||
words = line.split()
|
||||
if not words:
|
||||
continue
|
||||
patches.append(
|
||||
{
|
||||
"name": words[0],
|
||||
"enabled": _flag(words[1] if len(words) > 1 else None),
|
||||
"transition": _flag(words[2] if len(words) > 2 else None),
|
||||
}
|
||||
)
|
||||
return patches
|
||||
|
||||
|
||||
def parse_kpatch_list(lines: Iterable[str]) -> KpatchDict:
|
||||
"""``kpatch list``: the loaded modules with their state, the installed ones by kernel."""
|
||||
found: KpatchDict = {"loaded": [], "installed": []}
|
||||
for line in (raw.strip() for raw in lines):
|
||||
loaded = _KPATCH_LOADED.match(line)
|
||||
if loaded:
|
||||
found["loaded"].append({"name": loaded[1], "enabled": loaded[2] == "enabled"})
|
||||
continue
|
||||
installed = _KPATCH_INSTALLED.match(line)
|
||||
if installed:
|
||||
found["installed"].append({"name": installed[1], "kernel": installed[2]})
|
||||
return found
|
||||
|
||||
|
||||
def canonical_release(kernel: str | None) -> str | None:
|
||||
"""Canonical's name of a kernel as ``uname -r`` names it: without the upload number."""
|
||||
if kernel is None:
|
||||
return None
|
||||
match = _CANONICAL_KERNEL.match(kernel)
|
||||
return f"{match[1]}{match[2]}" if match else kernel
|
||||
|
||||
|
||||
def _get(data: Mapping[str, Any], key: str) -> Any:
|
||||
"""*key* in either case: the client wrote ``Status``, later ``status``."""
|
||||
for name, value in data.items():
|
||||
if name.lower() == key.lower():
|
||||
return value
|
||||
return None
|
||||
|
||||
|
||||
def _text(value: object) -> str | None:
|
||||
return value if isinstance(value, str) and value else None
|
||||
|
||||
|
||||
def _cve(text: str) -> str | None:
|
||||
match = _CVE.search(text)
|
||||
return f"CVE-{match[1]}-{match[2]}" if match else None
|
||||
|
||||
|
||||
def _fixes(value: object) -> list[LivepatchFixDict]:
|
||||
"""The 10.x client's list of fixes, or the 9.x client's text of ``* cve-...`` lines."""
|
||||
if isinstance(value, str):
|
||||
return [{"cve": cve, "patched": True} for line in value.splitlines() if (cve := _cve(line))]
|
||||
fixes: list[LivepatchFixDict] = []
|
||||
for fix in value if isinstance(value, list) else []:
|
||||
if not isinstance(fix, Mapping):
|
||||
continue
|
||||
cve = _cve(str(_get(fix, "Name") or ""))
|
||||
if cve:
|
||||
fixes.append({"cve": cve, "patched": _get(fix, "Patched") is True})
|
||||
return fixes
|
||||
|
||||
|
||||
def _running_entry(entries: list[Any]) -> Mapping[str, Any] | None:
|
||||
"""The status of the running kernel: the one marked running, else the only one."""
|
||||
mappings = [e for e in entries if isinstance(e, Mapping)]
|
||||
running = [e for e in mappings if _get(e, "Running") is True]
|
||||
if running:
|
||||
return running[0]
|
||||
return mappings[0] if len(mappings) == 1 else None
|
||||
|
||||
|
||||
def parse_canonical_status(text: str) -> CanonicalLivepatchDict | None:
|
||||
"""``canonical-livepatch status --format json``; None when it carries no status."""
|
||||
try:
|
||||
data = json.loads(text)
|
||||
except ValueError:
|
||||
return None
|
||||
entries = _get(data, "Status") if isinstance(data, Mapping) else None
|
||||
entry = _running_entry(entries) if isinstance(entries, list) else None
|
||||
if entry is None:
|
||||
return None
|
||||
patch = _get(entry, "Livepatch")
|
||||
patch = patch if isinstance(patch, Mapping) else {}
|
||||
running = _get(entry, "Running")
|
||||
return {
|
||||
"kernel": _text(_get(entry, "Kernel")),
|
||||
"running": running if isinstance(running, bool) else None,
|
||||
"state": _text(_get(patch, "State")),
|
||||
"check_state": _text(_get(patch, "CheckState")),
|
||||
"version": _text(_get(patch, "Version")),
|
||||
"fixes": _fixes(_get(patch, "Fixes")),
|
||||
}
|
||||
|
||||
|
||||
def live_patches(sections: Mapping[str, list[str]]) -> LivePatchesDict:
|
||||
"""The three readings from the kernel facts' sections."""
|
||||
canonical = sections.get("canonical_livepatch")
|
||||
return {
|
||||
"loaded": parse_sysfs_livepatches(sections["livepatch"])
|
||||
if "livepatch" in sections
|
||||
else None,
|
||||
"kpatch": parse_kpatch_list(sections["kpatch"]) if "kpatch" in sections else None,
|
||||
"canonical": parse_canonical_status("".join(canonical)) if canonical else None,
|
||||
"canonical_installed": canonical is not None,
|
||||
}
|
||||
@@ -0,0 +1,442 @@
|
||||
"""Every account a person can log in with on a Linux host, and how it is used (NetOrk/netork#2707).
|
||||
|
||||
An access review asks who can get into the systems people actually log in to. On a
|
||||
host that is every account with a shell, not only the ones an application created:
|
||||
|
||||
- **The accounts:** ``/etc/passwd``, root and UID 1000 on, with a shell that lets them
|
||||
in (not ``nologin`` or ``false``; :func:`login_capable`). Only the name, UID, home and
|
||||
shell cross: the comment field is a person's name. Accounts from a directory (SSSD,
|
||||
an AD join) are not in ``/etc/passwd`` and are not read: the directory reviews them.
|
||||
- **The last login,** from every source the host has -- ``lastlog2`` (util-linux 2.40
|
||||
on), the legacy ``lastlog``, ``wtmpdb last`` and ``last`` (wtmp) -- the newest of them
|
||||
wins, with the tool that told it. A host upgraded to lastlog2 keeps an old lastlog
|
||||
file, a desktop login reaches wtmp and not lastlog: no single source is the whole story.
|
||||
- **Lock and expiry,** from ``passwd -S`` (the password set, locked or empty) and
|
||||
``chage -l`` (password change, password and account expiry), as root. An account is
|
||||
``locked`` when its password is locked or it expired -- ``usermod -L -e 1`` does both.
|
||||
- **The failed attempts since the last login,** a number per account: from ``lastb``
|
||||
(btmp; the newest :data:`FAILED_LOGINS_READ` per account) where the host keeps it,
|
||||
else from ``pam_faillock``'s tally, which a successful login resets. Root only.
|
||||
|
||||
One fixed command, read-only, the same on every Linux host; ``LC_ALL=C`` keeps the tools'
|
||||
dates in one format. **Not read is None, never "no":** read as the login user, the lock,
|
||||
the expiry and the failures are ``None``, not "unlocked" or "none failed".
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import re
|
||||
from collections.abc import Iterable
|
||||
from datetime import UTC, date, datetime
|
||||
from shlex import quote
|
||||
from typing import TYPE_CHECKING, TypedDict
|
||||
|
||||
from napalm_device_types.terminal import strip_terminal_codes
|
||||
|
||||
_BEGIN = "LOGINS_BEGIN"
|
||||
_END = "LOGINS_END"
|
||||
|
||||
#: The failed attempts ``lastb`` hands over per account, newest first: a host on the
|
||||
#: internet collects millions in btmp. A count that reaches it is "at least".
|
||||
FAILED_LOGINS_READ = 1000
|
||||
|
||||
#: Root, and people: UID 1000 on, without the overflow UID ``nobody`` has.
|
||||
_FIRST_PERSON_UID = 1000
|
||||
_NOBODY_UID = 65534
|
||||
_NO_LOGIN_SHELLS = frozenset({"nologin", "false"})
|
||||
|
||||
#: The awk filter for a login-capable ``/etc/passwd`` line; :func:`login_capable` again.
|
||||
_CAPABLE = f"($3==0||$3>={_FIRST_PERSON_UID})&&$3!={_NOBODY_UID}&&$7!~/(^|\\/)(nologin|false)$/"
|
||||
#: Keeps the lines of the accounts in ``$u``, the first *n* of each.
|
||||
_KEEP = 'awk -v u=" $u " -v n={n} \'index(u, " " $1 " ") && c[$1]++ < n\''
|
||||
|
||||
#: One line, POSIX ``sh``, read-only, no stdin (a sudo password must not reach a tool).
|
||||
#: The frame markers are printed in two halves so that a transport which echoes the
|
||||
#: command does not show them early. ``passwd``, ``chage`` and ``faillock`` live in
|
||||
#: ``/usr/sbin`` on some systems, outside a login user's ``PATH``.
|
||||
LOGIN_ACCOUNTS_COMMAND = (
|
||||
"exec </dev/null; PATH=$PATH:/usr/sbin:/sbin; LC_ALL=C; export LC_ALL; "
|
||||
f"u=$(awk -F: '{_CAPABLE}{{print $1}}' /etc/passwd 2>/dev/null | tr '\\n' ' '); "
|
||||
'h() { command -v "$1" >/dev/null 2>&1; }; '
|
||||
"printf '%s%s\\n' LOGINS_ BEGIN; "
|
||||
"echo '[uid]'; id -u; echo '[now]'; date -u +%Y-%m-%d; "
|
||||
f'echo \'[passwd]\'; awk -F: \'{_CAPABLE}{{print $1":"$3":"$6":"$7}}\' /etc/passwd; '
|
||||
f"if h lastlog2; then echo '[lastlog2]'; lastlog2 2>/dev/null | {_KEEP.format(n=1)}; fi; "
|
||||
f"if h lastlog; then echo '[lastlog]'; lastlog 2>/dev/null | {_KEEP.format(n=1)}; fi; "
|
||||
"if h wtmpdb && wtmpdb last --time-format iso -n 1 >/dev/null 2>&1; then echo '[wtmpdb]'; "
|
||||
f"wtmpdb last --time-format iso 2>/dev/null | {_KEEP.format(n=1)}; fi; "
|
||||
"if h last && last --time-format iso -n 1 >/dev/null 2>&1; then echo '[wtmp]'; "
|
||||
f"last --time-format iso -w 2>/dev/null | {_KEEP.format(n=1)}; fi; "
|
||||
"if h lastb && lastb --time-format iso -n 1 >/dev/null 2>&1; then echo '[lastb]'; "
|
||||
f"lastb --time-format iso -w 2>/dev/null | {_KEEP.format(n=FAILED_LOGINS_READ)}; fi; "
|
||||
'for n in $u; do echo "[passwd_status $n]"; passwd -S "$n" 2>/dev/null; '
|
||||
'echo "[chage $n]"; chage -l "$n" 2>/dev/null; '
|
||||
'if h faillock; then echo "[faillock $n]"; faillock --user "$n" 2>/dev/null; fi; done; '
|
||||
"printf '%s%s\\n' LOGINS_ END"
|
||||
)
|
||||
|
||||
#: The tools a last login can come from, in the order they are named.
|
||||
LOGIN_SOURCES = ("lastlog2", "lastlog", "wtmpdb", "wtmp")
|
||||
|
||||
_SECTION = re.compile(r"^\[([a-z0-9_]+)(?: (\S+))?\]$")
|
||||
#: ``%a %b %e %H:%M:%S %z %Y``, lastlog's and lastlog2's date, at the end of a line.
|
||||
_LASTLOG_DATE = re.compile(r"\s(\w{3} \w{3} +\d{1,2} \d{2}:\d{2}:\d{2}(?: [+-]\d{4})? \d{4})$")
|
||||
_ISO = re.compile(r"^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}")
|
||||
#: A row of a ``faillock`` tally starts with its date.
|
||||
_ISO_DATE = re.compile(r"^\d{4}-\d{2}-\d{2} ")
|
||||
#: ``passwd -S``'s second word: shadow's and libuser's.
|
||||
_PASSWORD_STATES = {"P": "set", "PS": "set", "L": "locked", "LK": "locked", "NP": "none"}
|
||||
_NEVER = "never"
|
||||
_MUST_CHANGE = "password must be changed"
|
||||
|
||||
_Sections = dict[tuple[str, str | None], list[str]]
|
||||
|
||||
|
||||
class LoginAccountDict(TypedDict):
|
||||
"""One login-capable account. ``None`` in a field: could not be read."""
|
||||
|
||||
name: str
|
||||
uid: int
|
||||
home: str
|
||||
shell: str
|
||||
#: The newest login any source knows, ISO 8601 in UTC; None: never, or not read
|
||||
#: (``login_sources`` empty).
|
||||
last_login: str | None
|
||||
last_login_from: str | None # the remote host; None for a console login
|
||||
last_login_port: str | None # the terminal: "pts/0", "tty1", ":0"
|
||||
last_login_source: str | None # one of LOGIN_SOURCES
|
||||
password: str | None # "set", "locked" or "none" (passwd -S)
|
||||
password_changed: str | None # ISO date; None: never set, or not read
|
||||
password_expires: str | None # ISO date, "never" or "must_change"
|
||||
account_expires: str | None # ISO date or "never"
|
||||
#: The password locked, or the account expired on the host's date.
|
||||
locked: bool | None
|
||||
#: Failed attempts since the last login (lastb), or in the tally (faillock).
|
||||
failed_logins: int | None
|
||||
#: The count reached FAILED_LOGINS_READ: there may be more.
|
||||
failed_logins_capped: bool
|
||||
|
||||
|
||||
class LoginAccountsDict(TypedDict):
|
||||
"""What :meth:`LoginAccountsMixin.get_login_accounts` read."""
|
||||
|
||||
accounts: list[LoginAccountDict]
|
||||
#: The sources of the last logins the host has, of LOGIN_SOURCES; empty: none.
|
||||
login_sources: list[str]
|
||||
#: "lastb" or "faillock"; None: neither could be read.
|
||||
failed_logins_source: str | None
|
||||
#: Read as root: the lock, the expiry and the failures are known.
|
||||
privileged: bool
|
||||
|
||||
|
||||
class _Login(TypedDict):
|
||||
at: datetime
|
||||
port: str | None
|
||||
host: str | None
|
||||
source: str
|
||||
|
||||
|
||||
def login_capable(uid: int, shell: str) -> bool:
|
||||
"""Whether an account with *uid* and *shell* is one a person logs in with: root, or
|
||||
UID 1000 on (not ``nobody``'s), and a shell that is not ``nologin`` or ``false``.
|
||||
An empty shell is ``/bin/sh``."""
|
||||
if uid != 0 and (uid < _FIRST_PERSON_UID or uid == _NOBODY_UID):
|
||||
return False
|
||||
return shell.rsplit("/", 1)[-1] not in _NO_LOGIN_SHELLS
|
||||
|
||||
|
||||
def _sections(output: str) -> _Sections:
|
||||
lines = [line.rstrip() for line in strip_terminal_codes(output).splitlines()]
|
||||
stripped = [line.strip() for line in lines]
|
||||
try:
|
||||
start = stripped.index(_BEGIN)
|
||||
end = stripped.index(_END, start)
|
||||
except ValueError:
|
||||
raise ValueError("no intact login report in the output") from None
|
||||
sections: _Sections = {}
|
||||
current: list[str] = []
|
||||
for line in lines[start + 1 : end]:
|
||||
header = _SECTION.match(line.strip())
|
||||
if header:
|
||||
current = sections.setdefault((header.group(1), header.group(2)), [])
|
||||
elif line.strip():
|
||||
current.append(line)
|
||||
return sections
|
||||
|
||||
|
||||
def _first(sections: _Sections, key: str, arg: str | None = None) -> str | None:
|
||||
lines = sections.get((key, arg))
|
||||
return lines[0].strip() if lines else None
|
||||
|
||||
|
||||
def _accounts(sections: _Sections) -> list[tuple[str, int, str, str]]:
|
||||
accounts = []
|
||||
for line in sections.get(("passwd", None), []):
|
||||
fields = line.strip().split(":")
|
||||
if len(fields) != 4 or not fields[1].isdigit():
|
||||
continue
|
||||
name, uid, home, shell = fields[0], int(fields[1]), fields[2], fields[3]
|
||||
if login_capable(uid, shell):
|
||||
accounts.append((name, uid, home, shell))
|
||||
return accounts
|
||||
|
||||
|
||||
def _where(middle: list[str]) -> tuple[str | None, str | None]:
|
||||
"""The terminal and the remote host between a line's name and its date."""
|
||||
port = middle[0] if middle else None
|
||||
host = middle[1] if len(middle) > 1 else None
|
||||
return port, host
|
||||
|
||||
|
||||
def _lastlog_line(line: str, source: str) -> tuple[str, _Login] | None:
|
||||
"""A ``lastlog``/``lastlog2`` line; None for "Never logged in" or a header."""
|
||||
found = _LASTLOG_DATE.search(line)
|
||||
if not found:
|
||||
return None
|
||||
text = " ".join(found.group(1).split())
|
||||
try:
|
||||
if re.search(r" [+-]\d{4} ", text):
|
||||
at = datetime.strptime(text, "%a %b %d %H:%M:%S %z %Y")
|
||||
else:
|
||||
at = datetime.strptime(text, "%a %b %d %H:%M:%S %Y").replace(tzinfo=UTC)
|
||||
except ValueError:
|
||||
return None
|
||||
words = line[: found.start()].split()
|
||||
port, host = _where(words[1:])
|
||||
return words[0], {"at": at, "port": port, "host": host, "source": source}
|
||||
|
||||
|
||||
def _iso_line(line: str, source: str) -> tuple[str, _Login] | None:
|
||||
"""A ``last``/``lastb``/``wtmpdb last`` line in ``--time-format iso``."""
|
||||
words = line.split()
|
||||
for index, word in enumerate(words[1:], start=1):
|
||||
if _ISO.match(word):
|
||||
try:
|
||||
at = datetime.fromisoformat(word)
|
||||
except ValueError:
|
||||
return None
|
||||
if at.tzinfo is None:
|
||||
at = at.replace(tzinfo=UTC)
|
||||
port, host = _where(words[1:index])
|
||||
return words[0], {"at": at, "port": port, "host": host, "source": source}
|
||||
return None
|
||||
|
||||
|
||||
def _source_logins(sections: _Sections, source: str) -> Iterable[tuple[str, _Login]]:
|
||||
parse = _lastlog_line if source in ("lastlog2", "lastlog") else _iso_line
|
||||
for line in sections.get((source, None), []):
|
||||
parsed = parse(line, source)
|
||||
if parsed is not None:
|
||||
yield parsed
|
||||
|
||||
|
||||
def _last_logins(sections: _Sections, sources: list[str]) -> dict[str, _Login]:
|
||||
"""Each account's newest login over every source read."""
|
||||
newest: dict[str, _Login] = {}
|
||||
for source in sources:
|
||||
for name, login in _source_logins(sections, source):
|
||||
if name not in newest or login["at"] > newest[name]["at"]:
|
||||
newest[name] = login
|
||||
return newest
|
||||
|
||||
|
||||
def _chage_date(value: str) -> str | None:
|
||||
try:
|
||||
return datetime.strptime(value, "%b %d, %Y").date().isoformat()
|
||||
except ValueError:
|
||||
return None
|
||||
|
||||
|
||||
def _chage(lines: list[str]) -> dict[str, str]:
|
||||
fields = {}
|
||||
for line in lines:
|
||||
key, sep, value = line.partition(":")
|
||||
if sep:
|
||||
fields[" ".join(key.split()).lower()] = value.strip()
|
||||
return fields
|
||||
|
||||
|
||||
def _expiry(value: str | None, *, must_change: bool = False) -> str | None:
|
||||
"""A chage date as ISO, "never", "must_change"; None when it does not read as one."""
|
||||
if value is None:
|
||||
return None
|
||||
if value == _NEVER:
|
||||
return _NEVER
|
||||
if value == _MUST_CHANGE:
|
||||
return "must_change" if must_change else None
|
||||
return _chage_date(value)
|
||||
|
||||
|
||||
def _password(sections: _Sections, name: str) -> str | None:
|
||||
words = (_first(sections, "passwd_status", name) or "").split()
|
||||
if len(words) < 2 or words[0] != name:
|
||||
return None
|
||||
return _PASSWORD_STATES.get(words[1])
|
||||
|
||||
|
||||
def _expired(account_expires: str | None, today: date | None) -> bool | None:
|
||||
"""Whether the account expired on the host's date; pam_unix refuses it from that day."""
|
||||
if account_expires is None:
|
||||
return None
|
||||
if account_expires == _NEVER:
|
||||
return False
|
||||
return None if today is None else date.fromisoformat(account_expires) <= today
|
||||
|
||||
|
||||
def _locked(password: str | None, account_expires: str | None, today: date | None) -> bool | None:
|
||||
"""Locked when either says so, open when both say not, else unknown."""
|
||||
password_locked = None if password is None else password == "locked"
|
||||
expired = _expired(account_expires, today)
|
||||
if password_locked or expired:
|
||||
return True
|
||||
if password_locked is False and expired is False:
|
||||
return False
|
||||
return None
|
||||
|
||||
|
||||
def _today(sections: _Sections) -> date | None:
|
||||
try:
|
||||
return date.fromisoformat(_first(sections, "now") or "")
|
||||
except ValueError:
|
||||
return None
|
||||
|
||||
|
||||
def _faillock(lines: list[str] | None) -> int | None:
|
||||
"""The valid failures in a ``faillock --user`` tally; None without its table."""
|
||||
if not lines or not any(line.split()[:1] == ["When"] for line in lines):
|
||||
return None
|
||||
return sum(1 for line in lines if _ISO_DATE.match(line.strip()) and line.split()[-1] == "V")
|
||||
|
||||
|
||||
def _btmp(sections: _Sections) -> dict[str, list[datetime]]:
|
||||
failures: dict[str, list[datetime]] = {}
|
||||
for name, login in _source_logins(sections, "lastb"):
|
||||
failures.setdefault(name, []).append(login["at"])
|
||||
return failures
|
||||
|
||||
|
||||
def _failures(
|
||||
sections: _Sections, name: str, last: _Login | None, btmp: dict[str, list[datetime]] | None
|
||||
) -> tuple[int | None, bool]:
|
||||
"""Failed attempts since *last* and whether the count is capped: lastb first."""
|
||||
if btmp is not None:
|
||||
seen = btmp.get(name, [])
|
||||
count = sum(1 for at in seen if last is None or at > last["at"])
|
||||
return count, count >= FAILED_LOGINS_READ
|
||||
return _faillock(sections.get(("faillock", name))), False
|
||||
|
||||
|
||||
def _failed_source(sections: _Sections, names: list[str]) -> str | None:
|
||||
if ("lastb", None) in sections:
|
||||
return "lastb"
|
||||
if any(_faillock(sections.get(("faillock", name))) is not None for name in names):
|
||||
return "faillock"
|
||||
return None
|
||||
|
||||
|
||||
def _account(
|
||||
sections: _Sections,
|
||||
entry: tuple[str, int, str, str],
|
||||
last: _Login | None,
|
||||
btmp: dict[str, list[datetime]] | None,
|
||||
) -> LoginAccountDict:
|
||||
name, uid, home, shell = entry
|
||||
chage = _chage(sections.get(("chage", name), []))
|
||||
password = _password(sections, name)
|
||||
account_expires = _expiry(chage.get("account expires"))
|
||||
failed, capped = _failures(sections, name, last, btmp)
|
||||
return {
|
||||
"name": name,
|
||||
"uid": uid,
|
||||
"home": home,
|
||||
"shell": shell,
|
||||
"last_login": None if last is None else last["at"].astimezone(UTC).isoformat(),
|
||||
"last_login_from": None if last is None else last["host"],
|
||||
"last_login_port": None if last is None else last["port"],
|
||||
"last_login_source": None if last is None else last["source"],
|
||||
"password": password,
|
||||
"password_changed": _chage_date(chage.get("last password change", "")),
|
||||
"password_expires": _expiry(chage.get("password expires"), must_change=True),
|
||||
"account_expires": account_expires,
|
||||
"locked": _locked(password, account_expires, _today(sections)),
|
||||
"failed_logins": failed,
|
||||
"failed_logins_capped": capped,
|
||||
}
|
||||
|
||||
|
||||
def parse_login_accounts(output: str) -> LoginAccountsDict:
|
||||
"""Parse what :data:`LOGIN_ACCOUNTS_COMMAND` printed.
|
||||
|
||||
:raises ValueError: when the output carries no intact report.
|
||||
"""
|
||||
sections = _sections(output)
|
||||
entries = _accounts(sections)
|
||||
sources = [source for source in LOGIN_SOURCES if (source, None) in sections]
|
||||
logins = _last_logins(sections, sources)
|
||||
btmp = _btmp(sections) if ("lastb", None) in sections else None
|
||||
return {
|
||||
"accounts": [_account(sections, e, logins.get(e[0]), btmp) for e in entries],
|
||||
"login_sources": sources,
|
||||
"failed_logins_source": _failed_source(sections, [e[0] for e in entries]),
|
||||
"privileged": _first(sections, "uid") == "0",
|
||||
}
|
||||
|
||||
|
||||
class LoginAccountsMixin:
|
||||
"""Adds :meth:`get_login_accounts` to a driver that can run a command on a Linux host.
|
||||
|
||||
The template form (README, "Function classes"): the command and its parse are the
|
||||
same everywhere, and a driver supplies only :meth:`_run_login_accounts_command` --
|
||||
how a command reaches its host, and how it gains root there. Mixed in by the drivers
|
||||
that can, so ``hasattr(driver, "get_login_accounts")`` stays a truthful answer.
|
||||
"""
|
||||
|
||||
if TYPE_CHECKING: # pragma: no cover - declared for type checkers only
|
||||
|
||||
def _run_login_accounts_command(self, command: str, *, privileged: bool) -> str:
|
||||
"""Run *command* on the host and return what it printed; as root when
|
||||
*privileged*. The command is a single ``sh -c`` invocation; it reads no stdin."""
|
||||
...
|
||||
|
||||
def get_login_accounts(self) -> LoginAccountsDict:
|
||||
"""
|
||||
Returns every account on the host a person can log in with, and how it is used.
|
||||
|
||||
* accounts (list) - root and UID 1000 on with a login shell, in ``/etc/passwd``'s
|
||||
order: name, uid, home, shell; last_login (ISO, UTC), last_login_from,
|
||||
last_login_port and last_login_source; password ("set", "locked", "none"),
|
||||
password_changed, password_expires and account_expires (ISO date, "never",
|
||||
"must_change"), locked; failed_logins since the last login and
|
||||
failed_logins_capped
|
||||
* login_sources (list) - which of lastlog2, lastlog, wtmpdb, wtmp the host has
|
||||
* failed_logins_source (str or None) - "lastb" or "faillock"
|
||||
* privileged (bool) - read as root
|
||||
|
||||
``None`` in a field means not read. Read as root first; where root is refused, as
|
||||
the login user: the last logins only.
|
||||
|
||||
Example::
|
||||
|
||||
{
|
||||
"accounts": [{"name": "alice", "uid": 1000, "home": "/home/alice",
|
||||
"shell": "/bin/bash",
|
||||
"last_login": "2026-11-27T21:01:02+00:00",
|
||||
"last_login_from": "192.0.2.10", "last_login_port": "pts/0",
|
||||
"last_login_source": "lastlog", "password": "set",
|
||||
"password_changed": "2026-11-01",
|
||||
"password_expires": "never", "account_expires": "never",
|
||||
"locked": False, "failed_logins": 2,
|
||||
"failed_logins_capped": False}],
|
||||
"login_sources": ["lastlog", "wtmp"],
|
||||
"failed_logins_source": "lastb",
|
||||
"privileged": True,
|
||||
}
|
||||
|
||||
:raises ValueError: if neither reading carried an intact report.
|
||||
"""
|
||||
command = f"sh -c {quote(LOGIN_ACCOUNTS_COMMAND)}"
|
||||
try:
|
||||
return parse_login_accounts(self._run_login_accounts_command(command, privileged=True))
|
||||
except ValueError:
|
||||
pass
|
||||
return parse_login_accounts(self._run_login_accounts_command(command, privileged=False))
|
||||
+22
-108
@@ -1,5 +1,4 @@
|
||||
"""
|
||||
TypedDicts for NAPALM device-type-specific return values.
|
||||
"""TypedDicts for NAPALM device-type-specific return values.
|
||||
|
||||
These supplement the types defined in napalm.base.models and are used by the
|
||||
abstract device-type driver classes in this package.
|
||||
@@ -9,7 +8,20 @@ from typing import Literal, NotRequired, get_args
|
||||
|
||||
from typing_extensions import TypedDict
|
||||
|
||||
# The SNMP health profile shapes live in snmp_health_profile.py; re-exported here, where they were.
|
||||
# The SNMP health profile shapes live in snmp_health_profile.py, those of the access
|
||||
# point getters in access_point_models.py; re-exported here, where they were.
|
||||
from napalm_device_types.access_point_models import ChannelScanEntryDict as ChannelScanEntryDict
|
||||
from napalm_device_types.access_point_models import (
|
||||
FastTransitionConfigDict as FastTransitionConfigDict,
|
||||
)
|
||||
from napalm_device_types.access_point_models import MeshConfigDict as MeshConfigDict
|
||||
from napalm_device_types.access_point_models import MeshPeerDict as MeshPeerDict
|
||||
from napalm_device_types.access_point_models import RadioStatusDict as RadioStatusDict
|
||||
from napalm_device_types.access_point_models import SSIDBridgeDict as SSIDBridgeDict
|
||||
from napalm_device_types.access_point_models import SSIDDict as SSIDDict
|
||||
from napalm_device_types.access_point_models import WirelessClientDict as WirelessClientDict
|
||||
from napalm_device_types.access_point_models import WirelessConfigDict as WirelessConfigDict
|
||||
from napalm_device_types.livepatch import LivePatchesDict
|
||||
from napalm_device_types.snmp_health_profile import SnmpHealthProfile as SnmpHealthProfile
|
||||
from napalm_device_types.snmp_health_profile import SnmpInterfacesSpec as SnmpInterfacesSpec
|
||||
from napalm_device_types.snmp_health_profile import SnmpMemorySpec as SnmpMemorySpec
|
||||
@@ -131,101 +143,6 @@ class HostStatusDict(TypedDict):
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
|
||||
class WirelessClientDict(TypedDict):
|
||||
mac: str
|
||||
ssid: str
|
||||
radio: str
|
||||
signal: int
|
||||
noise: int
|
||||
tx_rate: float
|
||||
rx_rate: float
|
||||
uptime: int
|
||||
# Optional fields populated by DHCP cross-reference (e.g. from firewall)
|
||||
ip: NotRequired[str]
|
||||
hostname: NotRequired[str]
|
||||
lease_end: NotRequired[int] # Unix timestamp when DHCP lease expires
|
||||
|
||||
|
||||
class SSIDDict(TypedDict):
|
||||
enabled: bool
|
||||
radio: str
|
||||
bssid: str
|
||||
encryption: str
|
||||
hidden: bool
|
||||
clients: int
|
||||
|
||||
|
||||
class RadioStatusDict(TypedDict):
|
||||
enabled: bool
|
||||
band: str
|
||||
channel: int
|
||||
channel_width: int
|
||||
tx_power: int
|
||||
frequency: float
|
||||
|
||||
|
||||
class ChannelScanEntryDict(TypedDict):
|
||||
"""One neighboring AP entry as returned by get_channel_scan()."""
|
||||
|
||||
bssid: str
|
||||
ssid: str
|
||||
frequency: int # centre frequency in MHz, e.g. 2437
|
||||
channel: int # channel number, e.g. 6
|
||||
signal_dbm: int # RSSI in dBm, e.g. -72
|
||||
channel_width: int # MHz: 20 / 40 / 80 / 160; 0 if unknown
|
||||
band: str # "2.4GHz" | "5GHz" | "6GHz"
|
||||
|
||||
|
||||
class WirelessConfigDict(TypedDict):
|
||||
country_code: str
|
||||
regulatory_domain: str
|
||||
beacon_interval: int
|
||||
dtim_period: int
|
||||
rts_threshold: int
|
||||
fragmentation_threshold: int
|
||||
short_preamble: bool
|
||||
wmm_enabled: bool
|
||||
|
||||
|
||||
class FastTransitionConfigDict(TypedDict):
|
||||
enabled: bool
|
||||
ssid: str
|
||||
mobility_domain: str
|
||||
reassociation_deadline: int
|
||||
r0_key_lifetime: int
|
||||
r1_key_holder: str
|
||||
pmk_r1_push: bool
|
||||
over_ds: bool
|
||||
|
||||
|
||||
class MeshPeerDict(TypedDict):
|
||||
mac: str
|
||||
radio: str
|
||||
signal: int
|
||||
tx_rate: float
|
||||
rx_rate: float
|
||||
uptime: int
|
||||
hop_count: int
|
||||
|
||||
|
||||
class MeshConfigDict(TypedDict):
|
||||
enabled: bool
|
||||
radio: str
|
||||
mesh_id: str
|
||||
path_metric: str
|
||||
gate_announcements: bool
|
||||
is_gate: bool
|
||||
encryption: str
|
||||
|
||||
|
||||
class SSIDBridgeDict(TypedDict):
|
||||
ssid: str
|
||||
bridge: str
|
||||
vlan_id: int
|
||||
tagged: bool
|
||||
client_isolation: bool
|
||||
|
||||
|
||||
class Dot1XConfigDict(TypedDict):
|
||||
"""802.1X / WPA-Enterprise config for an access-point SSID."""
|
||||
|
||||
@@ -373,6 +290,8 @@ class KernelFactsDict(TypedDict):
|
||||
builtin: list[str] | None # modules.builtin -- compiled into the kernel image
|
||||
available: list[str] | None # modules.dep -- shipped as loadable modules
|
||||
config: dict[str, str] | None # build configuration, set options only; quotes stripped
|
||||
#: The live patches the kernel carries (NetOrk/netork#2701, ``livepatch``).
|
||||
live_patches: NotRequired[LivePatchesDict]
|
||||
|
||||
|
||||
class ListeningSocketDict(TypedDict):
|
||||
@@ -835,6 +754,7 @@ class VMDict(TypedDict):
|
||||
memory_usage: int
|
||||
uptime: int
|
||||
node: str
|
||||
uid: NotRequired[str] # outlives a migration, a restore, a changed vmid (get_vms)
|
||||
|
||||
|
||||
class VMPassthroughDict(TypedDict):
|
||||
@@ -1172,16 +1092,6 @@ class OspfDict(TypedDict):
|
||||
interfaces: dict[str, OspfInterfaceDict] # by interface name
|
||||
|
||||
|
||||
class FirmwareOfferDict(TypedDict):
|
||||
"""The firmware a device runs and the newest its vendor offers
|
||||
(``FirmwareOfferMixin.get_firmware_offer``). A fact, not a judgement."""
|
||||
|
||||
current_version: str
|
||||
latest_version: str
|
||||
newer: bool # the offer is newer than what runs, by the vendor's versioning
|
||||
download_url: NotRequired[str]
|
||||
|
||||
|
||||
class HypervisorHostDict(TypedDict):
|
||||
"""One host of a hypervisor or cluster (``HypervisorDriver.get_hypervisor_hosts``)."""
|
||||
|
||||
@@ -1440,3 +1350,7 @@ class ManagementProtocolsDict(TypedDict):
|
||||
snmp: ProtocolStateDict
|
||||
kvm: ProtocolStateDict
|
||||
virtual_media: ProtocolStateDict
|
||||
|
||||
|
||||
# Importable from here as before 4.41; it lives with its contract now.
|
||||
from napalm_device_types.firmware import FirmwareOfferDict as FirmwareOfferDict # noqa: E402
|
||||
@@ -0,0 +1,341 @@
|
||||
"""The record of the firewall rules netOrk opened on a host (NetOrk/netork#2693).
|
||||
|
||||
ufw, iptables and firewalld do not say who wrote a rule: a rule netOrk added to let an
|
||||
agent's server through looks exactly like one the operator wrote. To close it again --
|
||||
when a Zabbix agent becomes active only, say, and listens on no port any more -- a
|
||||
driver needs to know which rules are netOrk's. So a driver that opens a port in one of
|
||||
them records the rule in :data:`OPENED_PORTS_RECORD`, a file only root may write, and
|
||||
**only when the firewall did not have the rule before**: an identical rule the operator
|
||||
wrote earlier is never recorded, and so never removed. Closing removes exactly the
|
||||
recorded rules and leaves every other one in place; what it left for the same port is
|
||||
reported (:func:`revoked_output`). Rules opened before a driver recorded them have no
|
||||
line here and stay, reported.
|
||||
|
||||
**The line.** One rule per line, whitespace-separated, read strictly::
|
||||
|
||||
v1 <purpose> <backend> <proto> <port> <source> # ufw, iptables
|
||||
v1 <purpose> firewalld <proto> <port> <source> <zone> <runtime|permanent>
|
||||
|
||||
``purpose`` says which agent opened it (``zabbix-agent``, ``snmp``), ``source`` is a
|
||||
network in its normal form (``10.0.0.1/32``). A line that is not exactly that is
|
||||
reported and never acted on; it stays in the file.
|
||||
|
||||
**The file.** It is read only when the directory and the file are root's, are not
|
||||
writable by anyone else and are what they claim to be (no symbolic link): a record
|
||||
someone else could have written could name the operator's rules.
|
||||
|
||||
What is the same on every host and needs no I/O lives here: the line, reading it,
|
||||
the shell that records a rule, and ufw's commands, which napalm-linux and
|
||||
napalm-proxmox share. A driver runs them as root.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import ipaddress
|
||||
import re
|
||||
from collections.abc import Callable
|
||||
from typing import Literal, TypedDict, cast
|
||||
|
||||
from napalm_device_types.models import FixStepOutcomeDict
|
||||
|
||||
#: Where a host keeps the rules netOrk opened, root's and outside every account's home.
|
||||
OPENED_PORTS_DIRECTORY = "/var/lib/netork"
|
||||
OPENED_PORTS_RECORD = f"{OPENED_PORTS_DIRECTORY}/opened-ports"
|
||||
|
||||
#: The purposes the drivers record their rules under.
|
||||
ZABBIX_AGENT_PURPOSE = "zabbix-agent"
|
||||
SNMP_PURPOSE = "snmp"
|
||||
|
||||
Backend = Literal["ufw", "iptables", "firewalld"]
|
||||
_BACKENDS = ("ufw", "iptables", "firewalld")
|
||||
|
||||
_PURPOSE = re.compile(r"^[a-z][a-z0-9-]{0,31}$")
|
||||
_ZONE = re.compile(r"^[A-Za-z0-9_-]{1,32}$")
|
||||
#: What :func:`record_opened_rule_command` puts between double quotes: the line's own
|
||||
#: characters, and ``$z`` for a zone the shell loops over.
|
||||
_RECORDABLE = re.compile(r"^v1( (\$z|[A-Za-z0-9./:_-]+))+$")
|
||||
|
||||
|
||||
class OpenedRuleDict(TypedDict):
|
||||
"""One rule netOrk opened, as its record line says."""
|
||||
|
||||
purpose: str
|
||||
backend: Backend
|
||||
proto: Literal["tcp", "udp"]
|
||||
port: int
|
||||
#: The network in its normal form, ``10.0.0.1/32``.
|
||||
source: str
|
||||
#: firewalld's zone; "" for ufw and iptables.
|
||||
zone: str
|
||||
#: firewalld: the permanent configuration, not the runtime one. True for the others.
|
||||
permanent: bool
|
||||
|
||||
|
||||
class OpenedPortsRecordDict(TypedDict):
|
||||
"""What :func:`parse_opened_ports_record` read."""
|
||||
|
||||
rules: list[OpenedRuleDict]
|
||||
#: Lines that are not exactly a rule: reported, never acted on.
|
||||
unknown: list[str]
|
||||
#: Why the record was not read at all; "" when it was, or when there is none.
|
||||
problem: str
|
||||
|
||||
|
||||
def opened_rule_line(rule: OpenedRuleDict) -> str:
|
||||
"""The record's line for *rule*."""
|
||||
fields = ["v1", rule["purpose"], rule["backend"], rule["proto"], str(rule["port"])]
|
||||
fields.append(rule["source"])
|
||||
if rule["backend"] == "firewalld":
|
||||
fields += [rule["zone"], "permanent" if rule["permanent"] else "runtime"]
|
||||
return " ".join(fields)
|
||||
|
||||
|
||||
def _network(value: str) -> bool:
|
||||
"""Whether *value* is a network in its normal form, with its prefix."""
|
||||
try:
|
||||
return "/" in value and str(ipaddress.ip_network(value)) == value
|
||||
except ValueError:
|
||||
return False
|
||||
|
||||
|
||||
def _port(value: str) -> bool:
|
||||
return value.isdigit() and value == str(int(value)) and 0 < int(value) < 65536
|
||||
|
||||
|
||||
def _firewalld_place(fields: list[str]) -> tuple[str, bool] | None:
|
||||
"""firewalld's zone and whether the configuration is the permanent one, or None."""
|
||||
zone, scope = fields
|
||||
if not _ZONE.match(zone) or scope not in ("runtime", "permanent"):
|
||||
return None
|
||||
return zone, scope == "permanent"
|
||||
|
||||
|
||||
def _well_formed(fields: list[str]) -> bool:
|
||||
"""Whether *fields* are a rule line's: version, backend and as many as it takes,
|
||||
a purpose, a protocol, a port and a network."""
|
||||
backend = fields[2] if len(fields) > 2 else ""
|
||||
if fields[0] != "v1" or backend not in _BACKENDS:
|
||||
return False
|
||||
if len(fields) != (8 if backend == "firewalld" else 6):
|
||||
return False
|
||||
purpose, proto, port, source = fields[1], fields[3], fields[4], fields[5]
|
||||
return (
|
||||
bool(_PURPOSE.match(purpose))
|
||||
and proto in ("tcp", "udp")
|
||||
and _port(port)
|
||||
and _network(source)
|
||||
)
|
||||
|
||||
|
||||
def _rule(line: str) -> OpenedRuleDict | None:
|
||||
"""The rule *line* says, or None where it is not exactly one."""
|
||||
fields = line.split(" ")
|
||||
if not _well_formed(fields):
|
||||
return None
|
||||
purpose, backend, proto, port, source = fields[1:6]
|
||||
place = _firewalld_place(fields[6:]) if backend == "firewalld" else ("", True)
|
||||
if place is None:
|
||||
return None
|
||||
return {
|
||||
"purpose": purpose,
|
||||
"backend": cast(Backend, backend),
|
||||
"proto": cast(Literal["tcp", "udp"], proto),
|
||||
"port": int(port),
|
||||
"source": source,
|
||||
"zone": place[0],
|
||||
"permanent": place[1],
|
||||
}
|
||||
|
||||
|
||||
def read_opened_ports_command() -> str:
|
||||
"""The shell, as root, that prints owner, mode and kind of the directory and the
|
||||
record, then the record; nothing where there is no record."""
|
||||
return (
|
||||
f"if [ -e {OPENED_PORTS_RECORD} ] || [ -L {OPENED_PORTS_RECORD} ]; then"
|
||||
f" stat -c '%u %a %F' {OPENED_PORTS_DIRECTORY} {OPENED_PORTS_RECORD}"
|
||||
f" && cat {OPENED_PORTS_RECORD}; fi"
|
||||
)
|
||||
|
||||
|
||||
def _untrusted(stat_line: str, kind: str) -> str:
|
||||
"""Why the path *stat_line* describes may not be trusted; "" where it may."""
|
||||
parts = stat_line.split(" ", 2)
|
||||
if len(parts) != 3 or not parts[1].isdigit():
|
||||
return "owner and mode unknown"
|
||||
owner, mode, actual = parts
|
||||
if actual != kind:
|
||||
return f"not a {kind}"
|
||||
if owner != "0":
|
||||
return "not root's"
|
||||
if int(mode, 8) & 0o022:
|
||||
return "writable by others than root"
|
||||
return ""
|
||||
|
||||
|
||||
def parse_opened_ports_record(output: str) -> OpenedPortsRecordDict:
|
||||
"""The rules the output of :func:`read_opened_ports_command` names.
|
||||
|
||||
Nothing at all where the directory or the record is not root's alone; lines that
|
||||
are not exactly a rule go to ``unknown``.
|
||||
"""
|
||||
if not output.strip():
|
||||
return {"rules": [], "unknown": [], "problem": ""}
|
||||
lines = output.split("\n")
|
||||
for path, stat_line, kind in (
|
||||
(OPENED_PORTS_DIRECTORY, lines[0], "directory"),
|
||||
(OPENED_PORTS_RECORD, lines[1] if len(lines) > 1 else "", "regular file"),
|
||||
):
|
||||
why = _untrusted(stat_line.strip(), kind)
|
||||
if why:
|
||||
return {"rules": [], "unknown": [], "problem": f"{path}: {why}; not read"}
|
||||
rules: list[OpenedRuleDict] = []
|
||||
unknown: list[str] = []
|
||||
for line in lines[2:]:
|
||||
if not line.strip():
|
||||
continue
|
||||
rule = _rule(line)
|
||||
if rule is None:
|
||||
unknown.append(line)
|
||||
else:
|
||||
rules.append(rule)
|
||||
return {"rules": rules, "unknown": unknown, "problem": ""}
|
||||
|
||||
|
||||
class RevokedRulesDict(TypedDict):
|
||||
"""What :func:`revoke_recorded_rules` did."""
|
||||
|
||||
removed: list[OpenedRuleDict]
|
||||
#: The record after it: every other line, in order, as the driver writes it back.
|
||||
record: str
|
||||
#: A rule it could not remove, with why; it stays in ``record``.
|
||||
failed: list[str]
|
||||
|
||||
|
||||
def revoke_recorded_rules(
|
||||
record: OpenedPortsRecordDict,
|
||||
purpose: str,
|
||||
remove: Callable[[OpenedRuleDict], FixStepOutcomeDict],
|
||||
) -> RevokedRulesDict:
|
||||
"""Remove each rule of *record* recorded under *purpose*, whatever port it opened,
|
||||
with the driver's *remove*; keep every other line, the unknown ones too."""
|
||||
removed: list[OpenedRuleDict] = []
|
||||
kept: list[str] = []
|
||||
failed: list[str] = []
|
||||
for rule in record["rules"]:
|
||||
if rule["purpose"] == purpose:
|
||||
outcome = remove(rule)
|
||||
if outcome["ok"]:
|
||||
removed.append(rule)
|
||||
continue
|
||||
failed.append(f"{opened_rule_line(rule)}: {outcome.get('output', '')}")
|
||||
kept.append(opened_rule_line(rule))
|
||||
return {
|
||||
"removed": removed,
|
||||
"record": opened_rules_text(kept + record["unknown"]),
|
||||
"failed": failed,
|
||||
}
|
||||
|
||||
|
||||
def opened_rules_text(lines: list[str]) -> str:
|
||||
"""The record holding *lines*, as a driver writes it back after closing rules."""
|
||||
return "".join(f"{line}\n" for line in lines)
|
||||
|
||||
|
||||
def record_opened_rule_command(line: str) -> str:
|
||||
"""The shell, as root, that appends *line* to the record, creating root's
|
||||
directory and file where they are missing.
|
||||
|
||||
*line* is :func:`opened_rule_line`'s, where firewalld's zone may be ``$z``, the
|
||||
variable of a shell loop over the zones.
|
||||
|
||||
:raises ValueError: for anything else.
|
||||
"""
|
||||
if not _RECORDABLE.match(line):
|
||||
raise ValueError(f"not a record line: {line!r}")
|
||||
return (
|
||||
f"install -d -m 755 -o root -g root {OPENED_PORTS_DIRECTORY}"
|
||||
f" && printf '%s\\n' \"{line}\" >> {OPENED_PORTS_RECORD}"
|
||||
f" && chmod 644 {OPENED_PORTS_RECORD}"
|
||||
)
|
||||
|
||||
|
||||
def _ufw_rule(source: str, port: int, proto: str) -> str:
|
||||
return f"from {source} to any port {port} proto {proto}"
|
||||
|
||||
|
||||
def ufw_allow_recorded_command(source: str, port: int, proto: str, purpose: str) -> str:
|
||||
"""The shell, as root, that lets *source* reach *proto*/*port* in ufw and records
|
||||
the rule when ufw added it.
|
||||
|
||||
ufw answers "Skipping adding existing rule" for a rule it had -- someone else's,
|
||||
which is not recorded -- and "Rule added" (active) or "Rules updated" (inactive)
|
||||
for a new one. ``LC_ALL=C`` keeps those words English.
|
||||
"""
|
||||
line = opened_rule_line(
|
||||
{
|
||||
"purpose": purpose,
|
||||
"backend": "ufw",
|
||||
"proto": cast(Literal["tcp", "udp"], proto),
|
||||
"port": port,
|
||||
"source": source,
|
||||
"zone": "",
|
||||
"permanent": True,
|
||||
}
|
||||
)
|
||||
return (
|
||||
f"{{ o=$(LC_ALL=C ufw allow {_ufw_rule(source, port, proto)} 2>&1);"
|
||||
f' s=$?; echo "$o"; [ "$s" -eq 0 ] && case "$o" in *Skipping*) ;;'
|
||||
f" *'Rule added'*|*'Rules updated'*) {record_opened_rule_command(line)};; esac; }}"
|
||||
)
|
||||
|
||||
|
||||
def ufw_delete_command(rule: OpenedRuleDict) -> str:
|
||||
"""The shell, as root, that deletes *rule* from ufw; done too where ufw no longer
|
||||
has it ("Could not delete non-existent rule")."""
|
||||
return (
|
||||
"{ o=$(LC_ALL=C ufw delete allow"
|
||||
f" {_ufw_rule(rule['source'], rule['port'], rule['proto'])} 2>&1)"
|
||||
' || case "$o" in *non-existent*) ;; *) echo "$o"; false ;; esac; }'
|
||||
)
|
||||
|
||||
|
||||
def revoked_output(
|
||||
removed: list[OpenedRuleDict], *, unknown: list[str], left: int, proto: str, port: int
|
||||
) -> str:
|
||||
"""What closing said: the rules it *removed*, the record lines it could not read,
|
||||
and the *left* rules for *proto*/*port* that netOrk did not record."""
|
||||
parts = []
|
||||
if removed:
|
||||
sources = ", ".join(sorted({r["source"] for r in removed}))
|
||||
ports = ", ".join(sorted({f"{r['proto']}/{r['port']}" for r in removed}))
|
||||
parts.append(f"removed the rules netOrk opened for {ports} from {sources}")
|
||||
else:
|
||||
parts.append("netOrk recorded no rule it opened; nothing removed")
|
||||
if unknown:
|
||||
parts.append(f"record lines not understood, left alone: {'; '.join(unknown)}")
|
||||
if left:
|
||||
parts.append(
|
||||
f"{left} rule(s) for {proto}/{port} that netOrk did not record are left in place"
|
||||
" -- the operator's, or opened before netOrk recorded its rules"
|
||||
)
|
||||
return "; ".join(parts)
|
||||
|
||||
|
||||
__all__ = [
|
||||
"OPENED_PORTS_DIRECTORY",
|
||||
"OPENED_PORTS_RECORD",
|
||||
"SNMP_PURPOSE",
|
||||
"ZABBIX_AGENT_PURPOSE",
|
||||
"OpenedPortsRecordDict",
|
||||
"OpenedRuleDict",
|
||||
"opened_rule_line",
|
||||
"opened_rules_text",
|
||||
"parse_opened_ports_record",
|
||||
"read_opened_ports_command",
|
||||
"record_opened_rule_command",
|
||||
"RevokedRulesDict",
|
||||
"revoke_recorded_rules",
|
||||
"revoked_output",
|
||||
"ufw_allow_recorded_command",
|
||||
"ufw_delete_command",
|
||||
]
|
||||
@@ -0,0 +1,223 @@
|
||||
"""Services that still run replaced code: what an update did not finish without a restart.
|
||||
|
||||
An upgrade of openssl or glibc replaces the files on disk. Every daemon that had
|
||||
them loaded keeps running the old code, vulnerable or not, until it restarts
|
||||
(NetOrk/netork#2700). Whether the *host* needs a reboot is
|
||||
:mod:`napalm_device_types.host_status`'s; this asks which *services* need a restart.
|
||||
It is read the same way on every Linux host, so the command and its parse live
|
||||
here once, and a driver only carries the command across.
|
||||
|
||||
**Three sources, in this order:**
|
||||
|
||||
- ``needs-restarting -s`` (dnf-utils, the dnf family): the services it names.
|
||||
- ``needrestart -b -r l`` (Debian, Ubuntu): batch mode, list only. ``-r l`` and
|
||||
``NEEDRESTART_MODE=l`` both say so, so whatever the host's ``needrestart.conf``
|
||||
asks for, this never restarts anything.
|
||||
- Neither there, or both failed: every process whose ``/proc/<pid>/maps`` maps
|
||||
deleted code (:data:`DELETED_CODE_PATTERN`) -- an executable mapping of a file
|
||||
under ``/usr``, ``/lib*``, ``/bin``, ``/sbin`` or ``/opt`` that is gone from
|
||||
disk. Shared memory, memfd and temporary files are deleted on purpose and do not
|
||||
count, nor data such as the locale archive.
|
||||
|
||||
**Units from cgroups.** For the ``/proc`` scan, ``/proc/<pid>/cgroup`` names the
|
||||
systemd service a process runs in, as for the listening sockets: a process of a
|
||||
user's own systemd is that user's manager (``user@1000``), one of a container --
|
||||
Docker, Podman, or LXC as on a Proxmox node -- is left out (the container runs its
|
||||
own libraries, which no host update replaces, and its own systemd's units are none
|
||||
of the host's services), and one in no service -- a login session, systemd itself --
|
||||
is listed as a process. The host's tools name services only, so ``processes`` stays empty
|
||||
for them.
|
||||
|
||||
**Root, or nothing.** Only root sees every process's memory. The script goes to
|
||||
the host as one ``sh -c`` argument, so a ``sudo`` prefix covers all of it. A
|
||||
reading without root would miss every other user's process and read as clean, so
|
||||
there is none: when root is refused, no report comes back and the parse raises.
|
||||
It is one fixed command, read-only, so it fits a sudoers allowlist.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import re
|
||||
from shlex import quote
|
||||
from typing import TYPE_CHECKING, TypedDict
|
||||
|
||||
from napalm_device_types.listening import _cgroup_paths, _container, _unit
|
||||
from napalm_device_types.terminal import strip_terminal_codes
|
||||
|
||||
|
||||
class RestartProcessDict(TypedDict):
|
||||
"""A process that runs replaced code and belongs to no systemd service."""
|
||||
|
||||
pid: int
|
||||
name: str # /proc/<pid>/comm
|
||||
|
||||
|
||||
class ServicesRestartDict(TypedDict):
|
||||
"""What :meth:`ServicesRestartMixin.get_services_need_restart` read.
|
||||
|
||||
``units`` are the systemd services, without ".service", that still run code
|
||||
an update replaced on disk; empty when none does. ``processes`` are the ones
|
||||
that belong to no service (a login session, systemd itself), read only by the
|
||||
``/proc`` scan; the host's own tools name services only.
|
||||
"""
|
||||
|
||||
source: str # "needs-restarting", "needrestart" or "maps"
|
||||
units: list[str]
|
||||
processes: list[RestartProcessDict]
|
||||
|
||||
|
||||
_BEGIN = "RST_BEGIN"
|
||||
_END = "RST_END"
|
||||
NEEDS_RESTARTING = "needs-restarting"
|
||||
NEEDRESTART = "needrestart"
|
||||
MAPS = "maps"
|
||||
_SOURCES = (NEEDS_RESTARTING, NEEDRESTART, MAPS)
|
||||
|
||||
#: A line of ``/proc/<pid>/maps`` that maps deleted code: executable, from a
|
||||
#: directory packages install into, and gone from disk. POSIX ERE, for ``grep -E``.
|
||||
DELETED_CODE_PATTERN = (
|
||||
r"^[0-9a-f]+-[0-9a-f]+ ..x. .* /(usr|lib|lib32|lib64|bin|sbin|opt)/.* \(deleted\)$"
|
||||
)
|
||||
|
||||
#: One line, POSIX ``sh``, read-only. The frame markers are printed in two halves
|
||||
#: so that a transport which echoes the command does not show them early. The
|
||||
#: tools are in ``/usr/sbin`` on some systems, outside a login user's ``PATH``.
|
||||
SERVICES_RESTART_COMMAND = (
|
||||
"PATH=$PATH:/usr/sbin:/sbin; "
|
||||
"printf '%s%s\\n' RST_ BEGIN; s=; "
|
||||
"if command -v needs-restarting >/dev/null 2>&1 "
|
||||
"&& o=$(needs-restarting -s 2>/dev/null); then s=needs-restarting; "
|
||||
"elif command -v needrestart >/dev/null 2>&1 "
|
||||
"&& o=$(NEEDRESTART_MODE=l needrestart -b -r l 2>/dev/null); then s=needrestart; fi; "
|
||||
'if [ -n "$s" ]; then echo "[$s]"; printf \'%s\\n\' "$o"; else p=; '
|
||||
"for d in /proc/[0-9]*; do "
|
||||
f'grep -qE \'{DELETED_CODE_PATTERN}\' "$d/maps" 2>/dev/null && p="$p ${{d#/proc/}}"; '
|
||||
"done; "
|
||||
"echo '[maps]'; for i in $p; do "
|
||||
'printf \'%s %s\\n\' "$i" "$(cat /proc/$i/comm 2>/dev/null)"; done; '
|
||||
"echo '[cgroups]'; for i in $p; do "
|
||||
'sed "s|^|$i |" /proc/$i/cgroup 2>/dev/null; done; fi; '
|
||||
"printf '%s%s\\n' RST_ END"
|
||||
)
|
||||
|
||||
#: A service as ``needs-restarting -s`` names it; anything else it prints is noise
|
||||
#: ("Updating Subscription Management repositories.").
|
||||
_SERVICE_LINE = re.compile(r"^([\w:.@\\-]+)\.service$")
|
||||
_NEEDRESTART_SVC = re.compile(r"^NEEDRESTART-SVC:\s*(.+?)\s*$")
|
||||
#: A process of a user's own systemd: that user's manager is what restarts it.
|
||||
_USER_MANAGER = re.compile(r"/(user@\d+)\.service(?=/|$)")
|
||||
#: A process inside an LXC container: ``/lxc/<name>/`` (Proxmox VE, which nests the
|
||||
#: container's own cgroups under ``ns``; cgroup v1) or ``/lxc.payload.<name>/`` (LXC 4
|
||||
#: and later). Not ``/lxc.monitor/<name>``: ``lxc-start`` runs the host's binary.
|
||||
_LXC = re.compile(r"^/lxc(?:/|\.payload\.)[^/]+(?:/|$)")
|
||||
_SERVICE_SUFFIX = ".service"
|
||||
|
||||
|
||||
def _sections(output: str) -> dict[str, list[str]]:
|
||||
lines = [line.strip() for line in strip_terminal_codes(output).splitlines()]
|
||||
try:
|
||||
start = lines.index(_BEGIN)
|
||||
end = lines.index(_END, start)
|
||||
except ValueError:
|
||||
raise ValueError("no intact services restart report in the output") from None
|
||||
sections: dict[str, list[str]] = {}
|
||||
current: list[str] = []
|
||||
for line in lines[start + 1 : end]:
|
||||
if line.startswith("[") and line.endswith("]") and " " not in line:
|
||||
current = sections.setdefault(line[1:-1], [])
|
||||
elif line:
|
||||
current.append(line)
|
||||
return sections
|
||||
|
||||
|
||||
def _without_suffix(unit: str) -> str:
|
||||
return unit[: -len(_SERVICE_SUFFIX)] if unit.endswith(_SERVICE_SUFFIX) else unit
|
||||
|
||||
|
||||
def _needs_restarting(lines: list[str]) -> list[str]:
|
||||
return [m.group(1) for m in map(_SERVICE_LINE.match, lines) if m]
|
||||
|
||||
|
||||
def _needrestart(lines: list[str]) -> list[str]:
|
||||
return [_without_suffix(m.group(1)) for m in map(_NEEDRESTART_SVC.match, lines) if m]
|
||||
|
||||
|
||||
def _process_unit(path: str | None) -> str | None:
|
||||
manager = _USER_MANAGER.search(path or "")
|
||||
return manager.group(1) if manager else _unit(path)
|
||||
|
||||
|
||||
def _maps(sections: dict[str, list[str]]) -> tuple[list[str], list[RestartProcessDict]]:
|
||||
paths = _cgroup_paths(sections.get("cgroups", []))
|
||||
units: list[str] = []
|
||||
processes: list[RestartProcessDict] = []
|
||||
for line in sections.get(MAPS, []):
|
||||
pid, _, name = line.partition(" ")
|
||||
if not pid.isdigit():
|
||||
continue
|
||||
path = paths.get(int(pid))
|
||||
if _container(path) or _LXC.match(path or ""):
|
||||
continue
|
||||
unit = _process_unit(path)
|
||||
if unit:
|
||||
units.append(unit)
|
||||
else:
|
||||
processes.append({"pid": int(pid), "name": name.strip()})
|
||||
return units, sorted(processes, key=lambda p: p["pid"])
|
||||
|
||||
|
||||
def parse_services_restart(output: str) -> ServicesRestartDict:
|
||||
"""Parse what :data:`SERVICES_RESTART_COMMAND` printed.
|
||||
|
||||
:raises ValueError: when the output carries no intact report, or one without a source.
|
||||
"""
|
||||
sections = _sections(output)
|
||||
source = next((s for s in _SOURCES if s in sections), None)
|
||||
if source is None:
|
||||
raise ValueError("the services restart report names no source")
|
||||
processes: list[RestartProcessDict] = []
|
||||
if source == NEEDS_RESTARTING:
|
||||
units = _needs_restarting(sections[source])
|
||||
elif source == NEEDRESTART:
|
||||
units = _needrestart(sections[source])
|
||||
else:
|
||||
units, processes = _maps(sections)
|
||||
return {"source": source, "units": sorted(set(units)), "processes": processes}
|
||||
|
||||
|
||||
class ServicesRestartMixin:
|
||||
"""Adds :meth:`get_services_need_restart` to a driver that can run a command on a
|
||||
Linux host as root.
|
||||
|
||||
The template form (README, "Function classes"): the command and its parse are
|
||||
the same everywhere, and a driver supplies only
|
||||
:meth:`_run_services_restart_command` -- how a command reaches its host as
|
||||
root. Mixed in by the drivers that can, so
|
||||
``hasattr(driver, "get_services_need_restart")`` stays a truthful answer.
|
||||
"""
|
||||
|
||||
if TYPE_CHECKING: # pragma: no cover - declared for type checkers only
|
||||
|
||||
def _run_services_restart_command(self, command: str) -> str:
|
||||
"""Run *command* on the host as root and return what it printed. The
|
||||
command is a single ``sh -c`` invocation; it reads nothing from stdin."""
|
||||
...
|
||||
|
||||
def get_services_need_restart(self) -> ServicesRestartDict:
|
||||
"""
|
||||
Returns the systemd services that still run code an update replaced.
|
||||
|
||||
* source (string) - ``needs-restarting``, ``needrestart`` or ``maps``
|
||||
* units (list of strings) - the services, without ``.service``; empty when none
|
||||
* processes (list of {pid, name}) - replaced code outside any service
|
||||
(``maps`` only)
|
||||
|
||||
Example::
|
||||
|
||||
{"source": "needrestart", "units": ["nginx", "ssh"], "processes": []}
|
||||
|
||||
:raises ValueError: if the host's output carried no intact report -- root
|
||||
refused, or the command cut short.
|
||||
"""
|
||||
command = f"sh -c {quote(SERVICES_RESTART_COMMAND)}"
|
||||
return parse_services_restart(self._run_services_restart_command(command))
|
||||
@@ -12,9 +12,47 @@ this class in can never shadow a working implementation from a sibling base.
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from typing import TYPE_CHECKING, Any
|
||||
from typing import TYPE_CHECKING, Any, Literal
|
||||
|
||||
from napalm_device_types.models import ApplyUpdatesResultDict, UpdateDict, UpdateProgressDict
|
||||
from typing_extensions import TypedDict
|
||||
|
||||
from napalm_device_types.models import (
|
||||
ApplyUpdatesResultDict,
|
||||
UpdateDict,
|
||||
UpdateProgressDict,
|
||||
)
|
||||
|
||||
UpdateHistoryAction = Literal[
|
||||
"install", "reinstall", "upgrade", "downgrade", "remove", "purge", "disappear"
|
||||
]
|
||||
|
||||
|
||||
class UpdateHistoryPackageDict(TypedDict):
|
||||
"""One package a past transaction changed (``UpdateHistoryDict.packages``)."""
|
||||
|
||||
name: str
|
||||
action: UpdateHistoryAction # "disappear": dpkg dropped it, its files taken by another
|
||||
old_version: str | None # None where nothing was installed before
|
||||
new_version: str | None # None where nothing is installed after
|
||||
|
||||
|
||||
class UpdateHistoryDict(TypedDict):
|
||||
"""A past run of the host's package manager (``UpdateMixin.get_update_history``).
|
||||
|
||||
A fact of the host's own log: what it changed, when, and who asked, also for
|
||||
a run that no application of the caller started.
|
||||
"""
|
||||
|
||||
#: Stable for the same transaction across reads, unique on the host: apt's
|
||||
#: start time with its index among those starting in the same second, dnf's
|
||||
#: transaction ID.
|
||||
id: str
|
||||
start: int # unix seconds
|
||||
end: int | None # None: still running, or interrupted
|
||||
packages: list[UpdateHistoryPackageDict]
|
||||
requested_by: str | None # the user behind sudo, pkexec or PackageKit; None when unknown
|
||||
command: str | None # the command line, where the log keeps it
|
||||
error: str | None # the error the run ended with; None for none
|
||||
|
||||
|
||||
class PackageIndexMissing(RuntimeError):
|
||||
@@ -83,6 +121,44 @@ class UpdateMixin:
|
||||
"""
|
||||
...
|
||||
|
||||
def get_update_history(self, since: int | None = None) -> list[UpdateHistoryDict]:
|
||||
"""
|
||||
The transactions the host's package manager ran, newest first: what
|
||||
each changed, when, and who asked for it -- also those no caller of
|
||||
this driver started (an operator's ``apt upgrade``, unattended-upgrades).
|
||||
|
||||
:param since: Unix seconds; only transactions that started at or after
|
||||
it. ``None`` for as far back as the host's log reaches.
|
||||
|
||||
**An empty list means no transaction since.** A reader that cannot
|
||||
read raises, as :meth:`get_available_updates` does: a caller keeps what
|
||||
it read before, and an empty list for "don't know" would read as a
|
||||
host that never changed. ``NotImplementedError`` where the package
|
||||
manager keeps no history.
|
||||
|
||||
Example::
|
||||
|
||||
[
|
||||
{
|
||||
"id": "1764158400-0",
|
||||
"start": 1764158400,
|
||||
"end": 1764158460,
|
||||
"packages": [
|
||||
{
|
||||
"name": "openssh-server",
|
||||
"action": "upgrade",
|
||||
"old_version": "1:9.2p1-2+deb12u1",
|
||||
"new_version": "1:9.2p1-2+deb12u2",
|
||||
},
|
||||
],
|
||||
"requested_by": "admin",
|
||||
"command": "apt-get -y upgrade",
|
||||
"error": None,
|
||||
},
|
||||
]
|
||||
"""
|
||||
...
|
||||
|
||||
def refresh_available_updates(self) -> dict[str, Any]:
|
||||
"""
|
||||
Refreshes the host's package index, so that :meth:`get_available_updates`
|
||||
@@ -97,7 +173,8 @@ class UpdateMixin:
|
||||
"""
|
||||
Where an update the device runs by itself stands, for a caller that
|
||||
follows it: a firewall's firmware upgrade, which :meth:`apply_updates`
|
||||
only starts. ``state`` is ``"running"`` until it ends in ``"done"``
|
||||
only starts, or one that ``FirmwareUpgradeMixin.start_firmware_upgrade``
|
||||
started. ``state`` is ``"running"`` until it ends in ``"done"``
|
||||
or ``"failed"``; ``log`` is the device's whole log of it.
|
||||
|
||||
Declared only: a driver whose :meth:`apply_updates` returns when the
|
||||
|
||||
@@ -0,0 +1,238 @@
|
||||
"""A native Zabbix agent: its configuration and Zabbix's package repository.
|
||||
|
||||
What :class:`~napalm_device_types.fixes.ZabbixAgentMixin` needs that is the same on
|
||||
every host, without I/O: which settings an agent may be given
|
||||
(:func:`check_zabbix_agent_settings`), the agent's configuration file with them
|
||||
(:func:`zabbix_agent_config`), and the command that adds Zabbix's repository where
|
||||
the host's own packages have no agent (:func:`zabbix_repository_command`). A driver
|
||||
reads and writes the file and runs the command.
|
||||
|
||||
**Which lines.** ``Server`` (who may ask, for passive checks), ``ServerActive``
|
||||
(where active checks go), ``ListenPort`` and, when the caller names one,
|
||||
``Hostname`` -- the host's technical name in Zabbix, which an active agent sends.
|
||||
Every other line stays as it was; a key the file does not set is added at its end.
|
||||
|
||||
**Active only** (NetOrk/netork#2683). An agent whose site only lets it connect out
|
||||
gets ``StartAgents=0``: Zabbix's agent then runs no passive checks and listens on no
|
||||
port. ``Server`` is mandatory only while ``StartAgents`` is not 0, so it is commented
|
||||
out -- nobody may ask -- and ``ServerActive`` is required instead. An agent that is not
|
||||
active only gets a ``StartAgents=0`` line commented out, since it would keep the agent
|
||||
from listening; another count of listeners stays.
|
||||
|
||||
**The repository.** Zabbix publishes a ``zabbix-release`` package per release line
|
||||
and distribution that adds its repository and key. Since 7.2 it lives under
|
||||
``<release>/release/<distribution>/``; up to 7.0 under ``<release>/<distribution>/``,
|
||||
with the rpm in an ``x86_64`` directory. The release line is the server's: an agent
|
||||
may be older than its server, not newer.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import re
|
||||
import shlex
|
||||
from typing import NotRequired, TypedDict
|
||||
|
||||
|
||||
class ZabbixAgentSettingsDict(TypedDict):
|
||||
"""What the caller wants a native Zabbix agent to be (``ZabbixAgentMixin``)."""
|
||||
|
||||
server: str # Server: the addresses that may ask (passive checks), comma-separated
|
||||
server_active: str # ServerActive: where active checks go, comma-separated; "" for none
|
||||
listen_port: int # ListenPort
|
||||
# addresses or CIDRs let through to the port; [] changes no firewall
|
||||
allowed_sources: list[str]
|
||||
# Hostname: the host's technical name in Zabbix; absent keeps the agent's
|
||||
hostname: NotRequired[str]
|
||||
# the server's release line ("7.4"): Zabbix's repository to fall back to where the
|
||||
# host's own packages have no agent; absent: no fallback
|
||||
release: NotRequired[str]
|
||||
# the agent only connects out: StartAgents=0, Server commented out (``server`` may be
|
||||
# ""), ServerActive required, and the firewall step opens nothing; absent: False
|
||||
active_only: NotRequired[bool]
|
||||
|
||||
|
||||
#: Addresses, comma-separated, as ``Server`` and ``ServerActive`` take them: names,
|
||||
#: IPv4, ``[IPv6]`` and ports. Nothing a config line or a shell word breaks out of.
|
||||
_ADDRESSES = re.compile(r"^[A-Za-z0-9.:\[\]-]+(,[A-Za-z0-9.:\[\]-]+)*$")
|
||||
#: What Zabbix allows in a technical host name.
|
||||
_HOSTNAME = re.compile(r"^[A-Za-z0-9._ -]+$")
|
||||
#: A release line, as Zabbix's repository names it.
|
||||
_RELEASE = re.compile(r"^(\d+)\.(\d+)$")
|
||||
|
||||
_KEYS = ("Server", "ServerActive", "ListenPort", "Hostname", "StartAgents")
|
||||
_LINE = re.compile(r"^(\s*)(" + "|".join(_KEYS) + r")\s*=\s*(.*?)\s*$")
|
||||
|
||||
REPOSITORY = "https://repo.zabbix.com/zabbix"
|
||||
#: The distributions Zabbix publishes packages for, by ``/etc/os-release``'s ``ID``:
|
||||
#: the name in the repository's path, and whether they take a deb.
|
||||
_DISTRIBUTIONS: dict[str, tuple[str, bool]] = {
|
||||
"ubuntu": ("ubuntu", True),
|
||||
"debian": ("debian", True),
|
||||
"raspbian": ("raspbian", True),
|
||||
"rhel": ("rhel", False),
|
||||
"centos": ("rhel", False),
|
||||
"ol": ("oracle", False),
|
||||
"almalinux": ("alma", False),
|
||||
"rocky": ("rocky", False),
|
||||
}
|
||||
|
||||
|
||||
def check_zabbix_agent_settings(settings: ZabbixAgentSettingsDict) -> None:
|
||||
"""Refuse what an agent's configuration or a shell line cannot take.
|
||||
|
||||
:raises ValueError: naming the setting.
|
||||
"""
|
||||
active_only = settings.get("active_only", False)
|
||||
if not isinstance(active_only, bool):
|
||||
raise ValueError(f"active_only is True or False, not {active_only!r}")
|
||||
_check_addresses("Server", str(settings.get("server", "")), required=not active_only)
|
||||
_check_addresses("ServerActive", str(settings.get("server_active", "")), required=active_only)
|
||||
hostname = settings.get("hostname")
|
||||
if hostname is not None and not _HOSTNAME.match(hostname):
|
||||
raise ValueError(f"not a Zabbix host name: {hostname!r}")
|
||||
port = settings.get("listen_port")
|
||||
if not isinstance(port, int) or isinstance(port, bool) or not 1 <= port <= 65535:
|
||||
raise ValueError(f"not a port: {port!r}")
|
||||
release = settings.get("release")
|
||||
if release is not None and not _RELEASE.match(release):
|
||||
raise ValueError(f"not a Zabbix release line (major.minor): {release!r}")
|
||||
|
||||
|
||||
def _check_addresses(key: str, value: str, *, required: bool) -> None:
|
||||
if (value or required) and not _ADDRESSES.match(value):
|
||||
raise ValueError(f"not addresses an agent's {key} takes: {value!r}")
|
||||
|
||||
|
||||
def _wanted(settings: ZabbixAgentSettingsDict) -> dict[str, str]:
|
||||
"""The value of each key the caller sets; "" comments the key out."""
|
||||
active_only = bool(settings.get("active_only"))
|
||||
wanted = {
|
||||
"Server": "" if active_only else settings["server"],
|
||||
"ServerActive": settings.get("server_active", ""),
|
||||
"ListenPort": str(settings["listen_port"]),
|
||||
}
|
||||
if settings.get("hostname"):
|
||||
wanted["Hostname"] = str(settings["hostname"])
|
||||
if active_only:
|
||||
wanted["StartAgents"] = "0"
|
||||
return wanted
|
||||
|
||||
|
||||
def _unwanted(settings: ZabbixAgentSettingsDict) -> dict[str, str]:
|
||||
"""Lines commented out where they hold this value, though the caller sets no value
|
||||
for their key: ``StartAgents=0`` would keep an agent that is not active only from
|
||||
listening."""
|
||||
return {} if settings.get("active_only") else {"StartAgents": "0"}
|
||||
|
||||
|
||||
def zabbix_agent_config(text: str, settings: ZabbixAgentSettingsDict) -> tuple[str, list[str]]:
|
||||
"""*text*, an agent's configuration file, with *settings*; and what changed, one
|
||||
``"Key: old → new"`` each.
|
||||
|
||||
An empty ``server_active`` comments ``ServerActive`` out: the agent then runs
|
||||
passive checks only. ``active_only`` is the other way round: ``StartAgents=0``
|
||||
and ``Server`` commented out.
|
||||
"""
|
||||
wanted, unwanted = _wanted(settings), _unwanted(settings)
|
||||
lines: list[str] = []
|
||||
changes: list[str] = []
|
||||
seen: set[str] = set()
|
||||
for line in text.splitlines(keepends=True):
|
||||
match = _LINE.match(line.rstrip("\r\n"))
|
||||
key = match.group(2) if match else ""
|
||||
if match and key in wanted:
|
||||
seen.add(key)
|
||||
lines.append(_set_line(line, match, wanted, changes))
|
||||
elif match and unwanted.get(key) == match.group(3):
|
||||
lines.append(_set_line(line, match, {key: ""}, changes))
|
||||
else:
|
||||
lines.append(line)
|
||||
_add_missing(
|
||||
lines, [key for key in _KEYS if wanted.get(key) and key not in seen], wanted, changes
|
||||
)
|
||||
return "".join(lines), changes
|
||||
|
||||
|
||||
def _add_missing(
|
||||
lines: list[str], keys: list[str], wanted: dict[str, str], changes: list[str]
|
||||
) -> None:
|
||||
"""*keys*, which the file does not set, at its end."""
|
||||
if keys and lines and not lines[-1].endswith("\n"):
|
||||
lines[-1] += "\n"
|
||||
for key in keys:
|
||||
lines.append(f"{key}={wanted[key]}\n")
|
||||
changes.append(f"{key}: (not set) → {wanted[key]}")
|
||||
|
||||
|
||||
def _set_line(line: str, match: re.Match[str], wanted: dict[str, str], changes: list[str]) -> str:
|
||||
"""*line*, which sets a key the caller wants, as the caller wants it."""
|
||||
indent, key, old = match.groups()
|
||||
end = "\n" if line.endswith("\n") else ""
|
||||
new = wanted[key]
|
||||
if not new:
|
||||
changes.append(f"{key}: {old} → (not set)")
|
||||
return f"{indent}# {key}={old}{end}"
|
||||
if old == new:
|
||||
return line
|
||||
changes.append(f"{key}: {old} → {new}")
|
||||
return f"{indent}{key}={new}{end}"
|
||||
|
||||
|
||||
def _os_release(text: str) -> dict[str, str]:
|
||||
fields = {}
|
||||
for line in text.splitlines():
|
||||
key, sep, value = line.partition("=")
|
||||
if sep:
|
||||
fields[key.strip()] = value.strip().strip("'\"")
|
||||
return fields
|
||||
|
||||
|
||||
def _distribution(fields: dict[str, str]) -> tuple[str, bool]:
|
||||
for candidate in [fields.get("ID", ""), *fields.get("ID_LIKE", "").split()]:
|
||||
if candidate in _DISTRIBUTIONS:
|
||||
return _DISTRIBUTIONS[candidate]
|
||||
raise ValueError(f"Zabbix publishes no repository for {fields.get('ID') or 'this system'}")
|
||||
|
||||
|
||||
def zabbix_repository_command(os_release: str, release: str) -> str:
|
||||
"""The root command that adds Zabbix's *release* repository to the host whose
|
||||
``/etc/os-release`` is *os_release*, and refreshes the package index.
|
||||
|
||||
:raises ValueError: for a release line that is not ``major.minor``, or a
|
||||
distribution Zabbix publishes nothing for.
|
||||
"""
|
||||
match = _RELEASE.match(release)
|
||||
if not match:
|
||||
raise ValueError(f"not a Zabbix release line (major.minor): {release!r}")
|
||||
fields = _os_release(os_release)
|
||||
name, deb = _distribution(fields)
|
||||
version = fields.get("VERSION_ID", "")
|
||||
new_layout = (int(match.group(1)), int(match.group(2))) >= (7, 2)
|
||||
base = f"{REPOSITORY}/{release}/" + ("release/" if new_layout else "") + name
|
||||
if deb:
|
||||
# Raspberry Pi OS's packages are named after the Debian release they follow.
|
||||
label = "debian" if name == "raspbian" else name
|
||||
filename = f"zabbix-release_latest_{release}+{label}{version}_all.deb"
|
||||
url = f"{base}/pool/main/z/zabbix-release/{filename}"
|
||||
package = shlex.quote(url)
|
||||
return (
|
||||
"t=$(mktemp -d) && "
|
||||
f'{{ curl -fsSL -o "$t/zabbix-release.deb" {package} '
|
||||
f'|| wget -qO "$t/zabbix-release.deb" {package}; }} && '
|
||||
'dpkg -i "$t/zabbix-release.deb" && apt-get update; '
|
||||
# The download's directory goes either way; the status is the install's.
|
||||
's=$?; rm -rf "$t"; [ "$s" -eq 0 ]'
|
||||
)
|
||||
major = version.split(".")[0]
|
||||
arch = "noarch" if new_layout else "x86_64"
|
||||
url = f"{base}/{major}/{arch}/zabbix-release-latest-{release}.el{major}.noarch.rpm"
|
||||
return f"dnf -y install {shlex.quote(url)}"
|
||||
|
||||
|
||||
__all__ = [
|
||||
"REPOSITORY",
|
||||
"ZabbixAgentSettingsDict",
|
||||
"check_zabbix_agent_settings",
|
||||
"zabbix_agent_config",
|
||||
"zabbix_repository_command",
|
||||
]
|
||||
+1
-1
@@ -4,7 +4,7 @@ build-backend = "setuptools.build_meta"
|
||||
|
||||
[project]
|
||||
name = "napalm-device-types"
|
||||
version = "4.39.0"
|
||||
version = "4.51.0"
|
||||
description = "Abstract device-type base classes for NAPALM drivers"
|
||||
readme = "README.md"
|
||||
requires-python = ">=3.12"
|
||||
|
||||
@@ -31,7 +31,7 @@
|
||||
},
|
||||
"mypy_relaxed": [],
|
||||
"python_file_lines": {
|
||||
"napalm_device_types/models.py": 1442
|
||||
"napalm_device_types/models.py": 1353
|
||||
},
|
||||
"untyped_public": []
|
||||
}
|
||||
@@ -0,0 +1,402 @@
|
||||
"""apt's history log as past transactions (NetOrk/netork#2728).
|
||||
|
||||
The blocks below are written as apt writes them (``apt-pkg/deb/dpkgpm.cc``): two
|
||||
spaces between date and time, ``name:arch (version[, ...])`` entries joined by
|
||||
``, ``, ``Install``'s ``automatic``, ``Upgrade``/``Downgrade`` with old and new,
|
||||
``Remove``/``Purge`` with the version that was installed, ``Error`` before
|
||||
``End-Date``. The ids follow Proxmox VE 9.3's ``GET /nodes/{node}/apt/history``:
|
||||
start time, and the count of earlier transactions with that start in the same file.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import gzip
|
||||
import os
|
||||
import subprocess
|
||||
from datetime import UTC, datetime, timedelta, timezone
|
||||
from pathlib import Path
|
||||
|
||||
import pytest
|
||||
|
||||
from napalm_device_types import (
|
||||
APT_HISTORY_COMMAND,
|
||||
AptHistoryMixin,
|
||||
AptHistoryUnreadable,
|
||||
apt_history_command,
|
||||
host_zone,
|
||||
parse_apt_history,
|
||||
)
|
||||
from napalm_device_types.channel import CommandResult
|
||||
|
||||
|
||||
def _utc(text: str) -> int:
|
||||
return int(datetime.strptime(text, "%Y-%m-%d %H:%M:%S").replace(tzinfo=UTC).timestamp())
|
||||
|
||||
|
||||
CURRENT = """
|
||||
Start-Date: 2026-11-26 10:00:00
|
||||
Commandline: apt-get -y upgrade
|
||||
Requested-By: admin (1000)
|
||||
Install: linux-image-6.12.57+deb13-amd64:amd64 (6.12.57-1, automatic), linux-headers-6.12.57+deb13-common:all (6.12.57-1, automatic), htop:amd64 (3.4.1-5)
|
||||
Upgrade: openssh-server:amd64 (1:10.0p1-7, 1:10.0p1-7+deb13u1), libssl3t64:amd64 (3.5.1-1, 3.5.1-1+deb13u1), libssl3t64:i386 (3.5.1-1, 3.5.1-1+deb13u1)
|
||||
End-Date: 2026-11-26 10:01:00
|
||||
|
||||
Start-Date: 2026-11-26 10:01:00
|
||||
Commandline: /usr/bin/apt remove wazuh-agent
|
||||
Remove: wazuh-agent:amd64 (4.14.8-1)
|
||||
Error: Sub-process /usr/bin/dpkg returned an error code (1)
|
||||
End-Date: 2026-11-26 10:01:00
|
||||
|
||||
Start-Date: 2026-11-26 10:01:00
|
||||
Commandline: /usr/bin/apt purge wazuh-agent
|
||||
Purge: wazuh-agent:amd64 (4.14.8-1), linux-image-6.12.48+deb13-amd64:amd64 ()
|
||||
End-Date: 2026-11-26 10:01:00
|
||||
|
||||
Start-Date: 2026-11-26 10:05:13
|
||||
Commandline: /usr/bin/unattended-upgrade
|
||||
Upgrade: tzdata:all (2025b-4, 2025b-4+deb13u1)
|
||||
"""
|
||||
|
||||
ROTATED = """
|
||||
Start-Date: 2026-07-14 03:12:40
|
||||
Commandline: apt-get install --reinstall libvulkan1
|
||||
Requested-By: admin (1000)
|
||||
Reinstall: libvulkan1:amd64 (1.4.309.0-1), libvulkan1:i386 (1.4.309.0-1)
|
||||
End-Date: 2026-07-14 03:12:41
|
||||
|
||||
Start-Date: 2026-07-14 03:13:05
|
||||
Commandline: apt-get install pve-manager=9.0.10
|
||||
Downgrade: pve-manager:amd64 (9.0.11, 9.0.10)
|
||||
Disappeared: libfoo1 (1.2-3), libbar0
|
||||
End-Date: 2026-07-14 03:13:20
|
||||
"""
|
||||
|
||||
OLDEST = """
|
||||
Start-Date: 2026-01-12 06:25:01
|
||||
Commandline: apt-get dist-upgrade
|
||||
Remove: caribou (0.4.21-9)
|
||||
End-Date: 2026-01-12 06:25:30
|
||||
"""
|
||||
|
||||
|
||||
def _report(files: dict[str, str], zone: str = "/usr/share/zoneinfo/Europe/Berlin") -> str:
|
||||
"""What :data:`APT_HISTORY_COMMAND` prints for *files* (path -> content)."""
|
||||
lines = [f"### apt-history zone {zone}", "### apt-history offset +0100"]
|
||||
for path, content in files.items():
|
||||
lines += [f"### apt-history file {path}", content, "", "### apt-history status 0"]
|
||||
return "\n".join([*lines, "### apt-history end", ""])
|
||||
|
||||
|
||||
LOGS = {
|
||||
"/var/log/apt/history.log": CURRENT,
|
||||
"/var/log/apt/history.log.1.gz": ROTATED,
|
||||
"/var/log/apt/history.log.10.gz": OLDEST,
|
||||
}
|
||||
|
||||
|
||||
class TestParse:
|
||||
def test_newest_first_over_every_file(self):
|
||||
ids = [t["id"] for t in parse_apt_history(_report(LOGS))]
|
||||
assert ids == [
|
||||
f"{_utc('2026-11-26 09:05:13')}-0",
|
||||
f"{_utc('2026-11-26 09:01:00')}-1",
|
||||
f"{_utc('2026-11-26 09:01:00')}-0",
|
||||
f"{_utc('2026-11-26 09:00:00')}-0",
|
||||
f"{_utc('2026-07-14 01:13:05')}-0",
|
||||
f"{_utc('2026-07-14 01:12:40')}-0",
|
||||
f"{_utc('2026-01-12 05:25:01')}-0",
|
||||
]
|
||||
|
||||
def test_a_transaction_with_its_packages(self):
|
||||
upgrade = parse_apt_history(_report(LOGS))[3]
|
||||
assert upgrade == {
|
||||
"id": f"{_utc('2026-11-26 09:00:00')}-0",
|
||||
"start": _utc("2026-11-26 09:00:00"),
|
||||
"end": _utc("2026-11-26 09:01:00"),
|
||||
"packages": [
|
||||
{
|
||||
"name": "linux-image-6.12.57+deb13-amd64",
|
||||
"action": "install",
|
||||
"old_version": None,
|
||||
"new_version": "6.12.57-1",
|
||||
},
|
||||
{
|
||||
"name": "linux-headers-6.12.57+deb13-common",
|
||||
"action": "install",
|
||||
"old_version": None,
|
||||
"new_version": "6.12.57-1",
|
||||
},
|
||||
{
|
||||
"name": "htop",
|
||||
"action": "install",
|
||||
"old_version": None,
|
||||
"new_version": "3.4.1-5",
|
||||
},
|
||||
{
|
||||
"name": "openssh-server",
|
||||
"action": "upgrade",
|
||||
"old_version": "1:10.0p1-7",
|
||||
"new_version": "1:10.0p1-7+deb13u1",
|
||||
},
|
||||
{
|
||||
"name": "libssl3t64",
|
||||
"action": "upgrade",
|
||||
"old_version": "3.5.1-1",
|
||||
"new_version": "3.5.1-1+deb13u1",
|
||||
},
|
||||
{
|
||||
"name": "libssl3t64",
|
||||
"action": "upgrade",
|
||||
"old_version": "3.5.1-1",
|
||||
"new_version": "3.5.1-1+deb13u1",
|
||||
},
|
||||
],
|
||||
"requested_by": "admin",
|
||||
"command": "apt-get -y upgrade",
|
||||
"error": None,
|
||||
}
|
||||
|
||||
def test_the_error_a_run_ended_with(self):
|
||||
failed = parse_apt_history(_report(LOGS))[2]
|
||||
assert failed["error"] == "Sub-process /usr/bin/dpkg returned an error code (1)"
|
||||
assert failed["requested_by"] is None
|
||||
assert failed["packages"] == [
|
||||
{
|
||||
"name": "wazuh-agent",
|
||||
"action": "remove",
|
||||
"old_version": "4.14.8-1",
|
||||
"new_version": None,
|
||||
}
|
||||
]
|
||||
|
||||
def test_a_purge_of_what_was_removed_before_had_no_version(self):
|
||||
purge = parse_apt_history(_report(LOGS))[1]
|
||||
assert [(p["name"], p["action"], p["old_version"]) for p in purge["packages"]] == [
|
||||
("wazuh-agent", "purge", "4.14.8-1"),
|
||||
("linux-image-6.12.48+deb13-amd64", "purge", None),
|
||||
]
|
||||
|
||||
def test_a_run_without_end_is_running_or_interrupted(self):
|
||||
newest = parse_apt_history(_report(LOGS))[0]
|
||||
assert newest["end"] is None
|
||||
assert newest["command"] == "/usr/bin/unattended-upgrade"
|
||||
|
||||
def test_reinstall_downgrade_disappeared_and_arch_less_names(self):
|
||||
history = parse_apt_history(_report(LOGS))
|
||||
downgrade, reinstall, oldest = history[4], history[5], history[6]
|
||||
assert [(p["name"], p["old_version"], p["new_version"]) for p in reinstall["packages"]] == [
|
||||
("libvulkan1", "1.4.309.0-1", "1.4.309.0-1"),
|
||||
("libvulkan1", "1.4.309.0-1", "1.4.309.0-1"),
|
||||
]
|
||||
assert [
|
||||
(p["action"], p["name"], p["old_version"], p["new_version"])
|
||||
for p in downgrade["packages"]
|
||||
] == [
|
||||
("downgrade", "pve-manager", "9.0.11", "9.0.10"),
|
||||
("disappear", "libfoo1", "1.2-3", None),
|
||||
("disappear", "libbar0", None, None),
|
||||
]
|
||||
assert oldest["packages"] == [
|
||||
{"name": "caribou", "action": "remove", "old_version": "0.4.21-9", "new_version": None}
|
||||
]
|
||||
|
||||
def test_summer_time_is_the_zones(self):
|
||||
reinstall = parse_apt_history(_report(LOGS))[5]
|
||||
assert reinstall["start"] == _utc("2026-07-14 01:12:40") # CEST, UTC+2
|
||||
|
||||
def test_since_filters_by_start_and_keeps_the_ids(self):
|
||||
since = _utc("2026-11-26 09:01:00")
|
||||
ids = [t["id"] for t in parse_apt_history(_report(LOGS), since=since)]
|
||||
assert ids == [f"{_utc('2026-11-26 09:05:13')}-0", f"{since}-1", f"{since}-0"]
|
||||
|
||||
def test_nothing_logged_is_an_empty_list(self):
|
||||
assert parse_apt_history(_report({})) == []
|
||||
assert parse_apt_history(_report({"/var/log/apt/history.log": ""})) == []
|
||||
|
||||
def test_the_index_is_counted_per_file(self):
|
||||
same = "\nStart-Date: 2026-11-26 10:00:00\nInstall: htop:amd64 (3.4.1-5)\nEnd-Date: 2026-11-26 10:00:00\n"
|
||||
history = parse_apt_history(
|
||||
_report({"/var/log/apt/history.log": same * 2, "/var/log/apt/history.log.1.gz": same})
|
||||
)
|
||||
start = _utc("2026-11-26 09:00:00")
|
||||
assert [t["id"] for t in history] == [f"{start}-1", f"{start}-0", f"{start}-0"]
|
||||
|
||||
|
||||
class TestStrict:
|
||||
@pytest.mark.parametrize(
|
||||
"line",
|
||||
[
|
||||
"Upgrade: openssh-server:amd64 (1:10.0p1-7)", # an upgrade names old and new
|
||||
"Install: htop:amd64 (3.4.1-5, manual)",
|
||||
"Remove: htop:amd64 (3.4.1-5), ",
|
||||
"Install: htop:amd64 (3.4.1-5", # cut short
|
||||
"Upgrade: htop:amd64 (, 3.4.1-5)",
|
||||
"Disappeared: libfoo1 (1.2-3) (1.2-4)",
|
||||
"a line apt never writes",
|
||||
],
|
||||
)
|
||||
def test_a_malformed_block_is_left_out_but_counted(self, line):
|
||||
log = (
|
||||
f"Start-Date: 2026-11-26 10:00:00\n{line}\nEnd-Date: 2026-11-26 10:00:01\n\n"
|
||||
"Start-Date: 2026-11-26 10:00:00\nInstall: htop:amd64 (3.4.1-5)\n"
|
||||
"End-Date: 2026-11-26 10:00:02\n"
|
||||
)
|
||||
history = parse_apt_history(_report({"/var/log/apt/history.log": log}))
|
||||
assert [t["id"] for t in history] == [f"{_utc('2026-11-26 09:00:00')}-1"]
|
||||
|
||||
def test_an_unreadable_date_is_no_transaction(self):
|
||||
log = (
|
||||
"Start-Date: yesterday\nInstall: htop:amd64 (3.4.1-5)\n\n"
|
||||
"Start-Date: 2026-11-26 10:00:00\nInstall: htop:amd64 (3.4.1-5)\n"
|
||||
"End-Date: soon\n"
|
||||
)
|
||||
assert parse_apt_history(_report({"/var/log/apt/history.log": log})) == []
|
||||
|
||||
def test_lines_before_the_first_block_are_ignored(self):
|
||||
log = "Install: htop:amd64 (3.4.1-5)\n" + OLDEST
|
||||
assert len(parse_apt_history(_report({"/var/log/apt/history.log": log}))) == 1
|
||||
|
||||
def test_a_report_cut_short_raises(self):
|
||||
with pytest.raises(ValueError, match="cut short"):
|
||||
parse_apt_history(_report(LOGS).replace("### apt-history end\n", ""))
|
||||
|
||||
def test_a_file_that_could_not_be_read_raises(self):
|
||||
report = _report(LOGS).replace("status 0", "status 1", 1)
|
||||
with pytest.raises(ValueError, match="exit 1"):
|
||||
parse_apt_history(report)
|
||||
|
||||
def test_a_file_the_user_may_not_read_raises(self):
|
||||
report = _report(LOGS).replace(
|
||||
"### apt-history end",
|
||||
"### apt-history unreadable /var/log/apt/history.log.2.gz\n### apt-history end",
|
||||
)
|
||||
with pytest.raises(AptHistoryUnreadable, match="history.log.2.gz"):
|
||||
parse_apt_history(report)
|
||||
|
||||
def test_other_files_in_the_directory_are_not_read(self):
|
||||
report = _report({**LOGS, "/var/log/apt/history.log.dpkg-old": OLDEST}).replace(
|
||||
"### apt-history end",
|
||||
"### apt-history unreadable /var/log/apt/history.log.bak\n### apt-history end",
|
||||
)
|
||||
assert len(parse_apt_history(report)) == 7
|
||||
|
||||
|
||||
class TestZone:
|
||||
def test_a_named_zone(self):
|
||||
assert str(host_zone("Europe/Berlin\n", "+0100")) == "Europe/Berlin"
|
||||
assert str(host_zone("/usr/share/zoneinfo/America/New_York", "-0500")) == "America/New_York"
|
||||
|
||||
@pytest.mark.parametrize("name", ["", "Mars/Olympus_Mons", "../../etc/passwd"])
|
||||
def test_without_a_known_name_the_offset(self, name):
|
||||
assert host_zone(name, "+0530") == timezone(timedelta(hours=5, minutes=30))
|
||||
assert host_zone(name, "-0300\n") == timezone(-timedelta(hours=3))
|
||||
|
||||
def test_neither_raises(self):
|
||||
with pytest.raises(ValueError, match="no time zone"):
|
||||
host_zone("", "")
|
||||
|
||||
def test_a_host_on_its_offset_alone(self):
|
||||
history = parse_apt_history(_report({"/var/log/apt/history.log": OLDEST}, zone=""))
|
||||
assert history[0]["start"] == _utc("2026-01-12 05:25:01") # +0100
|
||||
|
||||
|
||||
class TestCommand:
|
||||
"""The command run for real with ``sh`` against a log directory in a temp directory."""
|
||||
|
||||
@staticmethod
|
||||
def _run(log_dir: Path) -> str:
|
||||
done = subprocess.run(
|
||||
["sh", "-c", apt_history_command(str(log_dir))],
|
||||
capture_output=True,
|
||||
text=True,
|
||||
check=True,
|
||||
)
|
||||
return done.stdout
|
||||
|
||||
@staticmethod
|
||||
def _logs(log_dir: Path) -> None:
|
||||
(log_dir / "history.log").write_text(CURRENT)
|
||||
(log_dir / "history.log.1.gz").write_bytes(gzip.compress(ROTATED.encode()))
|
||||
(log_dir / "history.log.10.gz").write_bytes(gzip.compress(OLDEST.encode()))
|
||||
(log_dir / "term.log").write_text("Log started: 2026-11-26 10:00:00\n")
|
||||
|
||||
def test_every_file_rotated_or_not(self, tmp_path):
|
||||
self._logs(tmp_path)
|
||||
history = parse_apt_history(self._run(tmp_path))
|
||||
# Dated in this machine's zone: the order and the fields, not the seconds.
|
||||
assert len(history) == 7
|
||||
assert history[0]["command"] == "/usr/bin/unattended-upgrade"
|
||||
assert history[-1]["command"] == "apt-get dist-upgrade"
|
||||
|
||||
def test_the_zone_and_offset_are_printed(self, tmp_path):
|
||||
out = self._run(tmp_path)
|
||||
assert "### apt-history zone " in out
|
||||
assert "### apt-history offset " in out
|
||||
assert out.endswith("### apt-history end\n")
|
||||
|
||||
def test_no_log_is_no_transaction(self, tmp_path):
|
||||
assert parse_apt_history(self._run(tmp_path / "missing")) == []
|
||||
|
||||
@pytest.mark.skipif(os.geteuid() == 0, reason="root reads every file")
|
||||
def test_an_unreadable_file_is_named(self, tmp_path):
|
||||
self._logs(tmp_path)
|
||||
(tmp_path / "history.log.1.gz").chmod(0)
|
||||
with pytest.raises(AptHistoryUnreadable):
|
||||
parse_apt_history(self._run(tmp_path))
|
||||
|
||||
def test_the_constant_reads_apts_own_directory(self):
|
||||
assert APT_HISTORY_COMMAND == apt_history_command("/var/log/apt")
|
||||
|
||||
|
||||
class _Host(AptHistoryMixin):
|
||||
def __init__(self, *answers: CommandResult) -> None:
|
||||
self.answers = list(answers)
|
||||
self.ran: list[bool] = []
|
||||
|
||||
def run_command(
|
||||
self,
|
||||
command: str,
|
||||
*,
|
||||
privileged: bool = False,
|
||||
timeout: float = 60,
|
||||
stdin: bytes | None = None,
|
||||
) -> CommandResult:
|
||||
assert command == APT_HISTORY_COMMAND
|
||||
assert stdin is None
|
||||
self.ran.append(privileged)
|
||||
return self.answers.pop(0)
|
||||
|
||||
|
||||
UNREADABLE = _report(LOGS).replace(
|
||||
"### apt-history end",
|
||||
"### apt-history unreadable /var/log/apt/history.log.2.gz\n### apt-history end",
|
||||
)
|
||||
|
||||
|
||||
class TestMixin:
|
||||
def test_read_as_the_login_user(self):
|
||||
host = _Host(CommandResult(_report(LOGS), "", 0))
|
||||
assert len(host.get_update_history()) == 7
|
||||
assert host.ran == [False]
|
||||
|
||||
def test_since_is_applied(self):
|
||||
host = _Host(CommandResult(_report(LOGS), "", 0))
|
||||
assert len(host.get_update_history(since=_utc("2026-11-26 09:01:00"))) == 3
|
||||
|
||||
def test_a_file_only_root_may_read_is_read_as_root(self):
|
||||
host = _Host(CommandResult(UNREADABLE, "", 0), CommandResult(_report(LOGS), "", 0))
|
||||
assert len(host.get_update_history()) == 7
|
||||
assert host.ran == [False, True]
|
||||
|
||||
def test_unreadable_even_as_root_raises(self):
|
||||
host = _Host(CommandResult(UNREADABLE, "", 0), CommandResult(UNREADABLE, "", 0))
|
||||
with pytest.raises(AptHistoryUnreadable):
|
||||
host.get_update_history()
|
||||
|
||||
def test_a_failed_run_raises(self):
|
||||
host = _Host(
|
||||
CommandResult(UNREADABLE, "", 0),
|
||||
CommandResult("", "sudo: a password is required", 1),
|
||||
)
|
||||
with pytest.raises(RuntimeError, match="password is required"):
|
||||
host.get_update_history()
|
||||
+195
-1
@@ -25,6 +25,7 @@ from napalm_device_types.apt_proxy import (
|
||||
parse_apt_proxy,
|
||||
same_proxy_url,
|
||||
)
|
||||
from napalm_device_types.apt_sources import NOT_CACHED_KEY, VIA_CACHE
|
||||
from napalm_device_types.fixes import PackageProxyMixin
|
||||
|
||||
|
||||
@@ -302,6 +303,13 @@ _CONNECT_DENIED = """Err:1 https://download.docker.com/linux/ubuntu/dists/noble/
|
||||
E: Failed to fetch https://download.docker.com/linux/ubuntu/dists/noble/InRelease Invalid response from proxy: HTTP/1.0 403 CONNECT denied (ask the admin to allow HTTPS tunnels) [IP: 10.40.100.10 3142]
|
||||
E: Download Failed"""
|
||||
|
||||
#: A cache that does not fetch the cache form itself: ``AllowUserPorts`` is 80 alone
|
||||
#: (apt-cacher-ng 3.7.5, NetOrk/netork#2555).
|
||||
_PROHIBITED_PORT = """Err:1 http://HTTPS///download.docker.com/linux/ubuntu/dists/noble/InRelease
|
||||
403 Configuration error (confusing proxy mode) or prohibited port (see AllowUserPorts) [IP: 127.0.0.1 39143]
|
||||
E: Failed to fetch http://HTTPS///download.docker.com/linux/ubuntu/dists/noble/InRelease 403 Configuration error (confusing proxy mode) or prohibited port (see AllowUserPorts) [IP: 127.0.0.1 39143]
|
||||
E: Download Failed"""
|
||||
|
||||
|
||||
def _fetch(output, rc, match=None):
|
||||
lines = ["APROXY_BEGIN", "[fetch]", *output.splitlines(), "[rc]", str(rc)]
|
||||
@@ -422,9 +430,21 @@ class _Host(AptProxyMixin):
|
||||
"""
|
||||
|
||||
def __init__(
|
||||
self, files=None, fetch_rc=0, apt=True, https_sources=(), tunnel=True, direct_rc=0
|
||||
self,
|
||||
files=None,
|
||||
fetch_rc=0,
|
||||
apt=True,
|
||||
https_sources=(),
|
||||
tunnel=True,
|
||||
direct_rc=0,
|
||||
cache_https=False,
|
||||
credentials=(),
|
||||
):
|
||||
self.files = dict(files or {})
|
||||
#: Whether the proxy fetches the cache form itself (AllowUserPorts 443), and
|
||||
#: the hosts apt keeps credentials for.
|
||||
self.cache_https = cache_https
|
||||
self.credentials = set(credentials)
|
||||
self.fetch_rc = fetch_rc
|
||||
self.apt = apt
|
||||
self.https_sources = list(https_sources)
|
||||
@@ -459,6 +479,12 @@ class _Host(AptProxyMixin):
|
||||
value, https = self._effective(), self._effective("https")
|
||||
dump = [f'Acquire::http::Proxy "{value}";'] if value else []
|
||||
dump += [f'Acquire::https::Proxy "{https}";'] if https else []
|
||||
dump += [
|
||||
line
|
||||
for path, text in self.files.items()
|
||||
for line in text.splitlines()
|
||||
if line.startswith(NOT_CACHED_KEY)
|
||||
]
|
||||
return _report(
|
||||
dump=dump,
|
||||
parts=[f"{p}:{n}:{t}" for p, n, t in self._settings() if p.startswith(_D)],
|
||||
@@ -466,6 +492,8 @@ class _Host(AptProxyMixin):
|
||||
sources=["http://deb.debian.org/debian/dists/trixie/", *self.https_sources],
|
||||
)
|
||||
self.fetched.append(command)
|
||||
if re.search(r"download-file '?http://HTTPS///", command):
|
||||
return _fetch(_FETCHED, 0) if self.cache_https else _fetch(_PROHIBITED_PORT, 100)
|
||||
if re.search(r"download-file '?https://", command):
|
||||
return self._fetch_https(command)
|
||||
return _fetch(_FETCHED if self.fetch_rc == 0 else _REFUSED, self.fetch_rc, match=1)
|
||||
@@ -482,6 +510,11 @@ class _Host(AptProxyMixin):
|
||||
|
||||
def _run_apt_root_command(self, command, done):
|
||||
self.root.append(command)
|
||||
if NOT_CACHED_KEY in command:
|
||||
return self._rewrite(re.search(r"for h in ([^;]+); do", command).group(1).split(), done)
|
||||
if "#\\1https://#g" in command:
|
||||
self.https_sources = [s.replace(VIA_CACHE, "https://") for s in self.https_sources]
|
||||
return {"ok": True, "output": done}
|
||||
path = command.rsplit(" ", 1)[-1].strip("'")
|
||||
for m in re.finditer(r"(\d+)\{/[^}]*\}", command):
|
||||
n = int(m.group(1))
|
||||
@@ -492,6 +525,19 @@ class _Host(AptProxyMixin):
|
||||
self.files.pop(command.split()[-1].strip("'"), None)
|
||||
return {"ok": True, "output": done}
|
||||
|
||||
def _rewrite(self, hosts, done):
|
||||
for host in hosts:
|
||||
if host in self.credentials:
|
||||
proxy = self.files.get(f"{_D}00proxy", "")
|
||||
self.files[f"{_D}00proxy"] = proxy + f'{NOT_CACHED_KEY}:: "{host}";\n'
|
||||
continue
|
||||
prefix = f"https://{host}/"
|
||||
self.https_sources = [
|
||||
VIA_CACHE + s[len("https://") :] if s.startswith(prefix) else s
|
||||
for s in self.https_sources
|
||||
]
|
||||
return {"ok": True, "output": done}
|
||||
|
||||
|
||||
class TestCheckHttpsSource:
|
||||
def test_one_source_the_way_apt_fetches_it(self):
|
||||
@@ -569,8 +615,10 @@ class TestConfigurePackageProxy:
|
||||
"conflicts",
|
||||
"verify",
|
||||
"fetch",
|
||||
"cache",
|
||||
"https",
|
||||
]
|
||||
assert "no https source" in _step(result, "cache")["output"]
|
||||
assert "no https source" in result["steps"][-1]["output"]
|
||||
assert host.files[f"{_D}00proxy"] == 'Acquire::http::Proxy "http://c:3142";\n'
|
||||
assert "InRelease" in host.fetched[0] and "DIRECT" not in host.fetched[0]
|
||||
@@ -766,6 +814,144 @@ class TestConfigurePackageProxy:
|
||||
assert host.files == {}
|
||||
|
||||
|
||||
class TestCacheHttpsSources:
|
||||
"""NetOrk/netork#2555: the cache stores an https source only in its own form."""
|
||||
|
||||
def test_a_cache_that_fetches_https_gets_them(self):
|
||||
host = _Host(https_sources=[_DOCKER], cache_https=True)
|
||||
|
||||
result = host.configure_package_proxy("http://c:3142")
|
||||
|
||||
assert result["success"] is True
|
||||
assert host.https_sources == [f"{VIA_CACHE}download.docker.com/linux/ubuntu/dists/noble/"]
|
||||
assert _step(result, "cache")["output"] == (
|
||||
"https sources cached through http://c:3142: download.docker.com"
|
||||
)
|
||||
assert any(VIA_CACHE in c for c in host.fetched)
|
||||
assert "no https source goes through" in _step(result, "https")["output"]
|
||||
|
||||
def test_a_cache_that_does_not_turns_them_back(self):
|
||||
host = _Host(https_sources=[_DOCKER])
|
||||
|
||||
result = host.configure_package_proxy("http://c:3142")
|
||||
|
||||
assert result["success"] is True
|
||||
assert host.https_sources == [_DOCKER]
|
||||
output = _step(result, "cache")["output"]
|
||||
assert "http://c:3142 does not fetch https sources itself" in output
|
||||
assert "prohibited port (see AllowUserPorts)" in output
|
||||
assert "they stay on https, not cached" in output
|
||||
assert _step(result, "https")["output"] == (
|
||||
f"fetched {_DOCKER}InRelease through http://c:3142"
|
||||
)
|
||||
|
||||
def test_a_host_with_credentials_stays_on_https_and_is_named(self):
|
||||
pve = "https://enterprise.proxmox.com/debian/pve/dists/trixie/"
|
||||
host = _Host(
|
||||
https_sources=[pve, _DOCKER],
|
||||
cache_https=True,
|
||||
credentials={"enterprise.proxmox.com"},
|
||||
)
|
||||
|
||||
result = host.configure_package_proxy("http://c:3142")
|
||||
|
||||
assert result["success"] is True
|
||||
assert pve in host.https_sources
|
||||
output = _step(result, "cache")["output"]
|
||||
assert "cached through http://c:3142: download.docker.com" in output
|
||||
assert "left on https, apt has credentials for them: enterprise.proxmox.com" in output
|
||||
assert host.get_package_proxy_report()["not_cached"] == ["enterprise.proxmox.com"]
|
||||
|
||||
def test_only_hosts_with_credentials(self):
|
||||
pve = "https://enterprise.proxmox.com/debian/pve/dists/trixie/"
|
||||
host = _Host(https_sources=[pve], cache_https=True, credentials={"enterprise.proxmox.com"})
|
||||
|
||||
result = host.configure_package_proxy("http://c:3142")
|
||||
|
||||
assert _step(result, "cache")["output"] == (
|
||||
"no https source to cache; "
|
||||
"left on https, apt has credentials for them: enterprise.proxmox.com"
|
||||
)
|
||||
|
||||
def test_the_https_direct_fallback_keeps_the_hosts_left_on_https(self):
|
||||
pve = "https://enterprise.proxmox.com/debian/pve/dists/trixie/"
|
||||
host = _Host(https_sources=[pve], tunnel=False, credentials={"enterprise.proxmox.com"})
|
||||
|
||||
result = host.configure_package_proxy("http://c:3142")
|
||||
|
||||
assert result["success"] is True
|
||||
assert host.files[f"{_D}00proxy"] == (
|
||||
'Acquire::http::Proxy "http://c:3142";\n'
|
||||
'Acquire::https::Proxy "DIRECT";\n'
|
||||
f'{NOT_CACHED_KEY}:: "enterprise.proxmox.com";\n'
|
||||
)
|
||||
|
||||
def test_a_rewrite_that_fails_stops_the_fix(self):
|
||||
host = _Host(https_sources=[_DOCKER], cache_https=True)
|
||||
real = host._run_apt_root_command
|
||||
|
||||
def denied(command, done):
|
||||
if NOT_CACHED_KEY in command:
|
||||
return {"ok": False, "output": "sed: denied"}
|
||||
return real(command, done)
|
||||
|
||||
host._run_apt_root_command = denied
|
||||
|
||||
result = host.configure_package_proxy("http://c:3142")
|
||||
|
||||
assert result["success"] is False
|
||||
assert result["steps"][-1] == {"step": "cache", "ok": False, "output": "sed: denied"}
|
||||
|
||||
def test_a_turn_back_that_fails_says_so(self):
|
||||
host = _Host(https_sources=[_DOCKER])
|
||||
real = host._run_apt_root_command
|
||||
|
||||
def denied(command, done):
|
||||
if "#\\1https://#g" in command:
|
||||
return {"ok": False, "output": "sed: denied"}
|
||||
return real(command, done)
|
||||
|
||||
host._run_apt_root_command = denied
|
||||
|
||||
result = host.configure_package_proxy("http://c:3142")
|
||||
|
||||
assert result["success"] is False
|
||||
output = result["steps"][-1]["output"]
|
||||
assert "turning the sources back to https failed: sed: denied" in output
|
||||
|
||||
def test_the_proof_of_the_proxy_is_a_plain_http_source(self):
|
||||
"""A source already in the cache form says nothing about plain http."""
|
||||
host = _Host(https_sources=[f"{VIA_CACHE}download.docker.com/linux/ubuntu/dists/noble/"])
|
||||
|
||||
host.configure_package_proxy("http://c:3142")
|
||||
|
||||
fetch = next(c for c in host.fetched if "InRelease" in c)
|
||||
assert "deb.debian.org" in fetch
|
||||
|
||||
def test_removing_the_proxy_turns_the_sources_back_first(self):
|
||||
host = _Host(
|
||||
{f"{_D}00proxy": 'Acquire::http::Proxy "http://c:3142";\n'},
|
||||
https_sources=[f"{VIA_CACHE}download.docker.com/linux/ubuntu/dists/noble/"],
|
||||
)
|
||||
|
||||
result = host.configure_package_proxy("")
|
||||
|
||||
assert result["success"] is True
|
||||
assert [s["step"] for s in result["steps"]] == ["sources", "configure"]
|
||||
assert host.https_sources == [_DOCKER]
|
||||
assert host.files == {}
|
||||
|
||||
def test_a_turn_back_that_fails_keeps_the_proxy(self):
|
||||
"""Without the cache apt looks for a host called HTTPS: the proxy stays."""
|
||||
host = _Host({f"{_D}00proxy": 'Acquire::http::Proxy "http://c:3142";\n'})
|
||||
host._run_apt_root_command = lambda command, done: {"ok": False, "output": "denied"}
|
||||
|
||||
result = host.configure_package_proxy("")
|
||||
|
||||
assert result["success"] is False
|
||||
assert f"{_D}00proxy" in host.files
|
||||
|
||||
|
||||
class TestWhatTheParserSkips:
|
||||
def test_a_line_that_is_no_grep_output(self):
|
||||
assert (
|
||||
@@ -824,3 +1010,11 @@ def test_the_comment_out_command_for_https():
|
||||
assert comment_out_command("/etc/apt/apt.conf", [3], scheme="https") == (
|
||||
"sed -i -e '3{/^[[:space:]]*Acquire::https::Proxy[[:space:]]/Is|^|// |}' /etc/apt/apt.conf"
|
||||
)
|
||||
|
||||
|
||||
def test_a_line_left_on_https_that_is_no_host_name_is_not_written_back():
|
||||
host = _Host()
|
||||
host._write_package_proxy("http://c:3142", not_cached=["ok.example", 'x"; Foo "1'])
|
||||
assert host.files[f"{_D}00proxy"] == (
|
||||
f'Acquire::http::Proxy "http://c:3142";\n{NOT_CACHED_KEY}:: "ok.example";\n'
|
||||
)
|
||||
@@ -0,0 +1,393 @@
|
||||
"""apt's sources and the release they name, and moving one file's sources to the host's.
|
||||
|
||||
A release upgrade keeps third-party sources on the old release: z2m-house, Ubuntu
|
||||
24.04 (noble), kept Docker's source on ``focal`` and never saw a Docker newer than
|
||||
the last focal build (NetOrk/netork#2614). The read command runs here for real, on
|
||||
files in a temporary directory that ``apt-config -o`` points apt's settings at.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import base64
|
||||
import shutil
|
||||
import subprocess
|
||||
|
||||
import pytest
|
||||
|
||||
from napalm_device_types.apt_proxy import AptProxyMixin
|
||||
from napalm_device_types.apt_releases import (
|
||||
AptReleaseMixin,
|
||||
apt_releases_command,
|
||||
parse_apt_releases,
|
||||
rewrite_release,
|
||||
suite_release,
|
||||
)
|
||||
|
||||
_APT_CONFIG = shutil.which("apt-config")
|
||||
needs_apt = pytest.mark.skipif(_APT_CONFIG is None, reason="apt-config is not on this host")
|
||||
|
||||
_NOBLE = (
|
||||
'PRETTY_NAME="Ubuntu 24.04.3 LTS"\nNAME="Ubuntu"\nVERSION_ID="24.04"\n'
|
||||
"VERSION_CODENAME=noble\nID=ubuntu\nID_LIKE=debian\nUBUNTU_CODENAME=noble\n"
|
||||
)
|
||||
_TRIXIE = 'PRETTY_NAME="Debian GNU/Linux 13 (trixie)"\nVERSION_CODENAME=trixie\nID=debian\n'
|
||||
_MINT = (
|
||||
'NAME="Linux Mint"\nVERSION_CODENAME=virginia\nID=linuxmint\nID_LIKE="ubuntu debian"\n'
|
||||
"UBUNTU_CODENAME=jammy\n"
|
||||
)
|
||||
|
||||
#: z2m-house's Docker source, as found: through the cache, on focal (#2614).
|
||||
_Z2M_DOCKER = "deb http://HTTPS///download.docker.com/linux/ubuntu focal stable\n"
|
||||
_Z2M_DOCKER_FILE = "archive_uri-https_download_docker_com_linux_ubuntu-noble.list"
|
||||
_UBUNTU_SOURCES = (
|
||||
"Types: deb\n"
|
||||
"URIs: http://archive.ubuntu.com/ubuntu/\n"
|
||||
"Suites: noble noble-updates noble-backports\n"
|
||||
"Components: main restricted universe multiverse\n"
|
||||
"Signed-By: /usr/share/keyrings/ubuntu-archive-keyring.gpg\n"
|
||||
"\n"
|
||||
"Types: deb\n"
|
||||
"URIs: http://security.ubuntu.com/ubuntu/\n"
|
||||
"Suites: noble-security\n"
|
||||
"Components: main restricted universe multiverse\n"
|
||||
)
|
||||
|
||||
|
||||
def _framed(os_release: str, files: dict[str, str]) -> str:
|
||||
"""What :func:`apt_releases_command` prints for *os_release* and *files*."""
|
||||
lines = ["ARELEASE_BEGIN", "@@os"]
|
||||
lines += [f"|{line}" for line in os_release.splitlines()]
|
||||
for path, text in files.items():
|
||||
lines.append(f"@@file {path}")
|
||||
lines += [f"|{line}" for line in text.splitlines()]
|
||||
lines.append("ARELEASE_END")
|
||||
return "\n".join(lines) + "\n"
|
||||
|
||||
|
||||
class TestSuiteRelease:
|
||||
@pytest.mark.parametrize(
|
||||
("suite", "release"),
|
||||
[
|
||||
("noble", "noble"),
|
||||
("noble-security", "noble"),
|
||||
("noble-updates", "noble"),
|
||||
("focal-backports", "focal"),
|
||||
("bookworm-proposed-updates", "bookworm"),
|
||||
("trixie-security", "trixie"),
|
||||
],
|
||||
)
|
||||
def test_the_release_a_suite_names(self, suite, release):
|
||||
assert suite_release(suite) == release
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
("suite", "word"),
|
||||
[("stable", "stable"), ("nodistro", "nodistro"), ("pve-no-subscription", "pve")],
|
||||
)
|
||||
def test_a_word_the_caller_judges(self, suite, word):
|
||||
# Which words are releases is the caller's to know: "stable" has the form too.
|
||||
assert suite_release(suite) == word
|
||||
|
||||
@pytest.mark.parametrize("suite", ["/", "./", "focal/", "Focal", "$(ARCH)", ""])
|
||||
def test_a_suite_of_another_form(self, suite):
|
||||
# A flat repository's path, or anything not a lower-case word, names none.
|
||||
assert suite_release(suite) is None
|
||||
|
||||
|
||||
class TestParse:
|
||||
def test_the_host_and_a_list_source(self):
|
||||
found = parse_apt_releases(
|
||||
_framed(_NOBLE, {f"/etc/apt/sources.list.d/{_Z2M_DOCKER_FILE}": _Z2M_DOCKER})
|
||||
)
|
||||
assert found["os_id"] == "ubuntu"
|
||||
assert found["os_like"] == ["debian"]
|
||||
assert found["codename"] == "noble"
|
||||
assert found["ubuntu_codename"] == "noble"
|
||||
assert found["sources"] == [
|
||||
{
|
||||
"file": f"/etc/apt/sources.list.d/{_Z2M_DOCKER_FILE}",
|
||||
"line": 1,
|
||||
"types": ["deb"],
|
||||
"uri": "http://HTTPS///download.docker.com/linux/ubuntu",
|
||||
"suites": ["focal"],
|
||||
"components": ["stable"],
|
||||
}
|
||||
]
|
||||
|
||||
def test_options_comments_and_disabled_lines(self):
|
||||
text = (
|
||||
"# deb http://old.example/ubuntu bionic main\n"
|
||||
"\n"
|
||||
"deb [arch=amd64 signed-by=/etc/apt/keyrings/docker.asc] "
|
||||
"https://download.docker.com/linux/ubuntu jammy stable # moved by hand\n"
|
||||
"deb-src [ arch=amd64 ] http://archive.ubuntu.com/ubuntu noble main\n"
|
||||
"deb https://repo.example/flat ./\n"
|
||||
)
|
||||
found = parse_apt_releases(_framed(_NOBLE, {"/etc/apt/sources.list": text}))
|
||||
assert [
|
||||
(s["line"], s["types"], s["uri"], s["suites"], s["components"])
|
||||
for s in found["sources"]
|
||||
] == [
|
||||
(3, ["deb"], "https://download.docker.com/linux/ubuntu", ["jammy"], ["stable"]),
|
||||
(4, ["deb-src"], "http://archive.ubuntu.com/ubuntu", ["noble"], ["main"]),
|
||||
(5, ["deb"], "https://repo.example/flat", ["./"], []),
|
||||
]
|
||||
|
||||
def test_deb822_paragraphs_one_per_uri(self):
|
||||
text = (
|
||||
"Types: deb deb-src\n"
|
||||
"URIs: http://a.example/ubuntu http://b.example/ubuntu\n"
|
||||
"Suites: focal\n"
|
||||
" focal-updates\n"
|
||||
"Components: main\n"
|
||||
"\n"
|
||||
"# a comment between paragraphs\n"
|
||||
"Enabled: no\n"
|
||||
"Types: deb\n"
|
||||
"URIs: http://c.example/ubuntu\n"
|
||||
"Suites: bionic\n"
|
||||
"Components: main\n"
|
||||
)
|
||||
found = parse_apt_releases(_framed(_NOBLE, {"/etc/apt/sources.list.d/x.sources": text}))
|
||||
assert [(s["line"], s["types"], s["uri"], s["suites"]) for s in found["sources"]] == [
|
||||
(3, ["deb", "deb-src"], "http://a.example/ubuntu", ["focal", "focal-updates"]),
|
||||
(3, ["deb", "deb-src"], "http://b.example/ubuntu", ["focal", "focal-updates"]),
|
||||
]
|
||||
|
||||
def test_debian_and_a_derivative(self):
|
||||
assert parse_apt_releases(_framed(_TRIXIE, {}))["codename"] == "trixie"
|
||||
mint = parse_apt_releases(_framed(_MINT, {}))
|
||||
assert (mint["os_id"], mint["os_like"], mint["codename"], mint["ubuntu_codename"]) == (
|
||||
"linuxmint",
|
||||
["ubuntu", "debian"],
|
||||
"virginia",
|
||||
"jammy",
|
||||
)
|
||||
|
||||
def test_without_os_release(self):
|
||||
found = parse_apt_releases("ARELEASE_BEGIN\n@@os\nARELEASE_END\n")
|
||||
assert (found["os_id"], found["codename"], found["ubuntu_codename"]) == ("", "", "")
|
||||
|
||||
def test_an_unreadable_file_is_left_out(self):
|
||||
out = _framed(_NOBLE, {}).replace(
|
||||
"ARELEASE_END", "@@unreadable /etc/apt/sources.list\nARELEASE_END"
|
||||
)
|
||||
assert parse_apt_releases(out)["sources"] == []
|
||||
|
||||
def test_no_intact_report(self):
|
||||
with pytest.raises(ValueError):
|
||||
parse_apt_releases("ARELEASE_BEGIN\n@@os\n")
|
||||
|
||||
|
||||
@needs_apt
|
||||
class TestTheCommand:
|
||||
def test_reads_list_and_sources_files_as_apt_names_them(self, tmp_path):
|
||||
(tmp_path / "sources.list.d").mkdir()
|
||||
(tmp_path / "sources.list").write_text("")
|
||||
(tmp_path / "sources.list.d" / _Z2M_DOCKER_FILE).write_text(_Z2M_DOCKER)
|
||||
(tmp_path / "sources.list.d" / "ubuntu.sources").write_text(_UBUNTU_SOURCES)
|
||||
(tmp_path / "sources.list.d" / "old.list.distUpgrade").write_text(_Z2M_DOCKER)
|
||||
(tmp_path / "os-release").write_text(_NOBLE)
|
||||
command = apt_releases_command(
|
||||
apt_config=(
|
||||
f"apt-config -o Dir::Etc::sourcelist={tmp_path}/sources.list "
|
||||
f"-o Dir::Etc::sourceparts={tmp_path}/sources.list.d/"
|
||||
),
|
||||
os_release=str(tmp_path / "os-release"),
|
||||
)
|
||||
done = subprocess.run(["sh", "-c", command], capture_output=True, text=True, check=False)
|
||||
found = parse_apt_releases(done.stdout)
|
||||
assert found["codename"] == "noble"
|
||||
assert [(s["file"].rsplit("/", 1)[-1], s["suites"]) for s in found["sources"]] == [
|
||||
(_Z2M_DOCKER_FILE, ["focal"]),
|
||||
("ubuntu.sources", ["noble", "noble-updates", "noble-backports"]),
|
||||
("ubuntu.sources", ["noble-security"]),
|
||||
]
|
||||
|
||||
|
||||
class TestRewriteRelease:
|
||||
def test_a_list_line(self):
|
||||
assert rewrite_release(_Z2M_DOCKER, "focal", "noble", deb822=False) == (
|
||||
"deb http://HTTPS///download.docker.com/linux/ubuntu noble stable\n",
|
||||
1,
|
||||
)
|
||||
|
||||
def test_suffixes_options_and_a_uri_that_names_the_release(self):
|
||||
text = (
|
||||
"deb [signed-by=/k.asc] http://repo.example/focal/ focal-security main # focal\n"
|
||||
"# deb http://repo.example/focal/ focal main\n"
|
||||
"deb http://repo.example/other noble main\n"
|
||||
"deb http://repo.example/flat ./\n"
|
||||
)
|
||||
assert rewrite_release(text, "focal", "noble", deb822=False) == (
|
||||
"deb [signed-by=/k.asc] http://repo.example/focal/ noble-security main # focal\n"
|
||||
"# deb http://repo.example/focal/ focal main\n"
|
||||
"deb http://repo.example/other noble main\n"
|
||||
"deb http://repo.example/flat ./\n",
|
||||
1,
|
||||
)
|
||||
|
||||
def test_a_release_that_is_only_a_prefix_is_not_it(self):
|
||||
text = "deb http://repo.example/x focalfossa main\n"
|
||||
assert rewrite_release(text, "focal", "noble", deb822=False) == (text, 0)
|
||||
|
||||
def test_deb822_suites_and_continuations_of_enabled_paragraphs(self):
|
||||
text = (
|
||||
"Types: deb\n"
|
||||
"URIs: http://a.example/focal\n"
|
||||
"Suites: focal focal-updates\n"
|
||||
" focal-backports\n"
|
||||
"Components: main\n"
|
||||
"\n"
|
||||
"Enabled: no\n"
|
||||
"Types: deb\n"
|
||||
"URIs: http://b.example/ubuntu\n"
|
||||
"Suites: focal\n"
|
||||
"Components: main\n"
|
||||
)
|
||||
new, changed = rewrite_release(text, "focal", "noble", deb822=True)
|
||||
assert changed == 3
|
||||
assert new == (
|
||||
"Types: deb\n"
|
||||
"URIs: http://a.example/focal\n"
|
||||
"Suites: noble noble-updates\n"
|
||||
" noble-backports\n"
|
||||
"Components: main\n"
|
||||
"\n"
|
||||
"Enabled: no\n"
|
||||
"Types: deb\n"
|
||||
"URIs: http://b.example/ubuntu\n"
|
||||
"Suites: focal\n"
|
||||
"Components: main\n"
|
||||
)
|
||||
|
||||
def test_the_text_without_a_final_newline_stays_so(self):
|
||||
assert rewrite_release("deb http://a/ focal main", "focal", "noble", deb822=False) == (
|
||||
"deb http://a/ noble main",
|
||||
1,
|
||||
)
|
||||
|
||||
@pytest.mark.parametrize("bad", ["", "Noble", "no ble", "noble;", "../x"])
|
||||
def test_a_name_that_is_no_codename(self, bad):
|
||||
with pytest.raises(ValueError):
|
||||
rewrite_release(_Z2M_DOCKER, bad, "noble", deb822=False)
|
||||
with pytest.raises(ValueError):
|
||||
rewrite_release(_Z2M_DOCKER, "focal", bad, deb822=False)
|
||||
|
||||
|
||||
_OK = "[fetch]\nGet:1 x\n[rc]\n0\n"
|
||||
_NOT_FOUND = "[fetch]\nE: Failed to fetch {url} 404 Not Found [IP: 1.2.3.4 80]\n[rc]\n100\n"
|
||||
|
||||
|
||||
class _Host(AptReleaseMixin):
|
||||
"""An apt host whose files are a dict and whose fetches answer from a set."""
|
||||
|
||||
def __init__(self, files, os_release=_NOBLE, served=(), apt=True):
|
||||
self.files = dict(files)
|
||||
self.os_release = os_release
|
||||
self.served = set(served)
|
||||
self.apt = apt
|
||||
self.fetched: list[str] = []
|
||||
self.written: list[str] = []
|
||||
|
||||
def _is_apt_host(self):
|
||||
return self.apt
|
||||
|
||||
def _run_apt_command(self, command):
|
||||
if "ARELEASE_" in command:
|
||||
return _framed(self.os_release, self.files)
|
||||
if command.startswith("base64 "):
|
||||
path = command.split(" ", 1)[1].strip("'")
|
||||
return base64.b64encode(self.files[path].encode()).decode() + "\n"
|
||||
url = command.split("download-file ", 1)[1].split()[0].strip("'")
|
||||
self.fetched.append(url)
|
||||
body = _OK if url in self.served else _NOT_FOUND.format(url=url)
|
||||
return f"APROXY_BEGIN\n{body}APROXY_END\n"
|
||||
|
||||
def _write_apt_file(self, path, content):
|
||||
self.written.append(path)
|
||||
self.files[path] = content
|
||||
return {"ok": True, "output": f"wrote {path}"}
|
||||
|
||||
|
||||
_DOCKER_PATH = f"/etc/apt/sources.list.d/{_Z2M_DOCKER_FILE}"
|
||||
_DOCKER_NOBLE = "http://HTTPS///download.docker.com/linux/ubuntu/dists/noble/InRelease"
|
||||
|
||||
|
||||
class TestTheMixin:
|
||||
def test_reads_the_host(self):
|
||||
found = _Host({_DOCKER_PATH: _Z2M_DOCKER}).get_apt_source_releases()
|
||||
assert found is not None
|
||||
assert found["codename"] == "noble"
|
||||
assert found["sources"][0]["suites"] == ["focal"]
|
||||
|
||||
def test_none_without_apt(self):
|
||||
assert _Host({}, apt=False).get_apt_source_releases() is None
|
||||
|
||||
def test_moves_the_file_once_the_vendor_serves_the_release(self):
|
||||
host = _Host({_DOCKER_PATH: _Z2M_DOCKER}, served={_DOCKER_NOBLE})
|
||||
result = host.set_apt_source_release(_DOCKER_PATH, "focal", "noble")
|
||||
assert result["success"], result["output"]
|
||||
assert host.files[_DOCKER_PATH] == (
|
||||
"deb http://HTTPS///download.docker.com/linux/ubuntu noble stable\n"
|
||||
)
|
||||
assert host.fetched == [_DOCKER_NOBLE]
|
||||
assert result["rewritten"] == 1
|
||||
assert [s["step"] for s in result["steps"]] == ["read", "check", "rewrite"]
|
||||
|
||||
def test_the_release_file_when_there_is_no_inrelease(self):
|
||||
release = _DOCKER_NOBLE.replace("InRelease", "Release")
|
||||
host = _Host({_DOCKER_PATH: _Z2M_DOCKER}, served={release})
|
||||
assert host.set_apt_source_release(_DOCKER_PATH, "focal", "noble")["success"]
|
||||
assert host.fetched == [_DOCKER_NOBLE, release]
|
||||
|
||||
def test_refuses_where_the_vendor_has_no_such_release(self):
|
||||
host = _Host({_DOCKER_PATH: _Z2M_DOCKER})
|
||||
result = host.set_apt_source_release(_DOCKER_PATH, "focal", "noble")
|
||||
assert not result["success"]
|
||||
assert host.written == []
|
||||
assert "noble" in result["output"] and "404" in result["output"]
|
||||
assert result["rewritten"] == 0
|
||||
|
||||
def test_one_suite_missing_leaves_the_whole_file(self):
|
||||
text = "deb http://a.example/u focal main\ndeb http://a.example/u focal-security main\n"
|
||||
served = {"http://a.example/u/dists/noble/InRelease"}
|
||||
host = _Host({"/etc/apt/sources.list": text}, served=served)
|
||||
result = host.set_apt_source_release("/etc/apt/sources.list", "focal", "noble")
|
||||
assert not result["success"]
|
||||
assert host.files["/etc/apt/sources.list"] == text
|
||||
|
||||
def test_a_file_apt_does_not_read_is_never_written(self):
|
||||
host = _Host({_DOCKER_PATH: _Z2M_DOCKER}, served={_DOCKER_NOBLE})
|
||||
result = host.set_apt_source_release("/etc/shadow", "focal", "noble")
|
||||
assert not result["success"]
|
||||
assert host.written == []
|
||||
|
||||
def test_nothing_left_on_that_release(self):
|
||||
host = _Host({_DOCKER_PATH: _Z2M_DOCKER.replace("focal", "noble")})
|
||||
result = host.set_apt_source_release(_DOCKER_PATH, "focal", "noble")
|
||||
assert result["success"]
|
||||
assert result["rewritten"] == 0
|
||||
assert host.written == [] and host.fetched == []
|
||||
|
||||
def test_a_deb822_file(self):
|
||||
path = "/etc/apt/sources.list.d/docker.sources"
|
||||
text = "Types: deb\nURIs: https://download.docker.com/linux/ubuntu\nSuites: focal\nComponents: stable\n"
|
||||
served = {"https://download.docker.com/linux/ubuntu/dists/noble/InRelease"}
|
||||
host = _Host({path: text}, served=served)
|
||||
assert host.set_apt_source_release(path, "focal", "noble")["success"]
|
||||
assert "Suites: noble\n" in host.files[path]
|
||||
|
||||
def test_not_an_apt_host(self):
|
||||
result = _Host({}, apt=False).set_apt_source_release(_DOCKER_PATH, "focal", "noble")
|
||||
assert not result["success"]
|
||||
|
||||
def test_a_name_that_is_no_codename_changes_nothing(self):
|
||||
host = _Host({_DOCKER_PATH: _Z2M_DOCKER}, served={_DOCKER_NOBLE})
|
||||
result = host.set_apt_source_release(_DOCKER_PATH, "focal", "noble; rm -rf /")
|
||||
assert not result["success"]
|
||||
assert host.written == [] and host.fetched == []
|
||||
|
||||
|
||||
def test_every_apt_proxy_host_reads_its_releases():
|
||||
# Every driver with apt's proxy is an apt host: it reads its sources' releases too.
|
||||
assert issubclass(AptProxyMixin, AptReleaseMixin)
|
||||
@@ -0,0 +1,318 @@
|
||||
"""https sources through the cache: which can be, and the root commands that turn them.
|
||||
|
||||
apt-cacher-ng fetches ``http://HTTPS///<host>/<path>`` from ``https://<host>/<path>``
|
||||
and stores it, where it allows port 443 (``AllowUserPorts=80 443``); a source
|
||||
fetched over https itself goes through the cache's tunnel and is never stored
|
||||
(NetOrk/netork#2555). The commands run here for real, on files in a temporary
|
||||
directory that ``apt-config -o`` points apt's own settings at.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import shutil
|
||||
import subprocess
|
||||
|
||||
import pytest
|
||||
|
||||
from napalm_device_types.apt_proxy import parse_apt_proxy
|
||||
from napalm_device_types.apt_sources import (
|
||||
VIA_CACHE,
|
||||
cache_form,
|
||||
cacheable_https_hosts,
|
||||
is_host_name,
|
||||
revert_sources_command,
|
||||
rewrite_sources_command,
|
||||
)
|
||||
|
||||
|
||||
def _report(**over):
|
||||
report = {
|
||||
"proxy": "http://c:3142",
|
||||
"per_host": {},
|
||||
"auto_detect": None,
|
||||
"settings": [],
|
||||
"https_proxy": "http://c:3142",
|
||||
"https_per_host": {},
|
||||
"https_settings": [],
|
||||
"http_sources": ["http://deb.debian.org/debian/dists/trixie/"],
|
||||
"https_sources": [],
|
||||
"not_cached": [],
|
||||
}
|
||||
report.update(over)
|
||||
return report
|
||||
|
||||
|
||||
class TestCacheForm:
|
||||
def test_an_https_url(self):
|
||||
assert cache_form("https://download.docker.com/linux/ubuntu/dists/noble/") == (
|
||||
"http://HTTPS///download.docker.com/linux/ubuntu/dists/noble/"
|
||||
)
|
||||
|
||||
def test_the_prefix(self):
|
||||
assert VIA_CACHE == "http://HTTPS///"
|
||||
|
||||
def test_not_an_https_url(self):
|
||||
with pytest.raises(ValueError):
|
||||
cache_form("http://deb.debian.org/debian/")
|
||||
|
||||
|
||||
class TestCacheableHttpsHosts:
|
||||
def test_each_host_once_sorted(self):
|
||||
report = _report(
|
||||
https_sources=[
|
||||
"https://packages.wazuh.com/4.x/apt/dists/stable/",
|
||||
"https://download.docker.com/linux/ubuntu/dists/noble/",
|
||||
"https://download.docker.com/linux/ubuntu/dists/noble-test/",
|
||||
]
|
||||
)
|
||||
assert cacheable_https_hosts(report) == ["download.docker.com", "packages.wazuh.com"]
|
||||
|
||||
def test_none_without_an_http_proxy(self):
|
||||
# The cache form goes through the http proxy: without one it goes nowhere.
|
||||
report = _report(proxy=None, https_sources=["https://h.example/dists/x/"])
|
||||
assert cacheable_https_hosts(report) == []
|
||||
|
||||
def test_a_host_apt_fetches_direct_stays(self):
|
||||
report = _report(
|
||||
per_host={"a.example": "DIRECT"},
|
||||
https_per_host={"B.example": "direct"},
|
||||
https_sources=[
|
||||
"https://a.example/dists/x/",
|
||||
"https://b.example/dists/x/",
|
||||
"https://c.example/dists/x/",
|
||||
],
|
||||
)
|
||||
assert cacheable_https_hosts(report) == ["c.example"]
|
||||
|
||||
def test_a_host_with_credentials_stays(self):
|
||||
report = _report(
|
||||
https_sources=["https://enterprise.proxmox.com/debian/pve/dists/trixie/"],
|
||||
not_cached=["enterprise.proxmox.com"],
|
||||
)
|
||||
assert cacheable_https_hosts(report) == []
|
||||
|
||||
def test_another_port_or_a_login_in_the_url_stays(self):
|
||||
# The cache allows port 443 alone, and a login in the URL is a credential too.
|
||||
report = _report(
|
||||
https_sources=[
|
||||
"https://h.example:8443/dists/x/",
|
||||
"https://u:p@i.example/dists/x/",
|
||||
"https://j.example:443/dists/x/",
|
||||
]
|
||||
)
|
||||
assert cacheable_https_hosts(report) == ["j.example"]
|
||||
|
||||
def test_a_report_from_before_not_cached(self):
|
||||
report = _report(https_sources=["https://h.example/dists/x/"])
|
||||
del report["not_cached"]
|
||||
assert cacheable_https_hosts(report) == ["h.example"]
|
||||
|
||||
|
||||
class TestNotCachedInTheReport:
|
||||
def test_the_dump_names_them(self):
|
||||
output = "\n".join(
|
||||
[
|
||||
"APROXY_BEGIN",
|
||||
"[dump]",
|
||||
'Acquire::http::Proxy "http://c:3142";',
|
||||
'Package-Proxy::Not-Cached "";',
|
||||
'Package-Proxy::Not-Cached:: "enterprise.proxmox.com";',
|
||||
'Package-Proxy::Not-Cached:: "esm.ubuntu.com";',
|
||||
"[sources]",
|
||||
"APROXY_END",
|
||||
]
|
||||
)
|
||||
assert parse_apt_proxy(output)["not_cached"] == [
|
||||
"enterprise.proxmox.com",
|
||||
"esm.ubuntu.com",
|
||||
]
|
||||
|
||||
def test_none(self):
|
||||
assert parse_apt_proxy("APROXY_BEGIN\n[dump]\nAPROXY_END")["not_cached"] == []
|
||||
|
||||
|
||||
def test_the_hosts_are_checked():
|
||||
with pytest.raises(ValueError):
|
||||
rewrite_sources_command(["h.example; rm -rf /"], "/etc/apt/apt.conf.d/00proxy")
|
||||
|
||||
|
||||
_APT_CONFIG = shutil.which("apt-config")
|
||||
needs_apt = pytest.mark.skipif(_APT_CONFIG is None, reason="apt-config is not on this host")
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def etc(tmp_path):
|
||||
"""apt's sources, its credentials and the proxy file, under *tmp_path*."""
|
||||
(tmp_path / "sources.list.d").mkdir()
|
||||
(tmp_path / "auth.conf.d").mkdir()
|
||||
(tmp_path / "00proxy").write_text('Acquire::http::Proxy "http://c:3142";\n')
|
||||
return tmp_path
|
||||
|
||||
|
||||
def _apt_config(etc):
|
||||
return (
|
||||
f"apt-config -o Dir::Etc::sourcelist={etc}/sources.list "
|
||||
f"-o Dir::Etc::sourceparts={etc}/sources.list.d/ "
|
||||
f"-o Dir::Etc::netrc={etc}/auth.conf -o Dir::Etc::netrcparts={etc}/auth.conf.d/"
|
||||
)
|
||||
|
||||
|
||||
def _run(command):
|
||||
done = subprocess.run(["sh", "-c", command], capture_output=True, text=True, check=False)
|
||||
assert done.returncode == 0, done.stderr
|
||||
return done.stdout
|
||||
|
||||
|
||||
_DOCKER_LIST = (
|
||||
"deb [arch=amd64 signed-by=/etc/apt/keyrings/docker.asc] "
|
||||
"https://download.docker.com/linux/ubuntu noble stable\n"
|
||||
)
|
||||
_DOCKER_SOURCES = (
|
||||
"Types: deb\n"
|
||||
"URIs: https://download.docker.com/linux/ubuntu\n"
|
||||
"Suites: noble\n"
|
||||
"Components: stable\n"
|
||||
"Signed-By: /etc/apt/keyrings/docker.asc\n"
|
||||
)
|
||||
|
||||
|
||||
@needs_apt
|
||||
class TestRewrite:
|
||||
def test_a_one_line_source(self, etc):
|
||||
(etc / "sources.list.d" / "docker.list").write_text(_DOCKER_LIST)
|
||||
|
||||
_run(rewrite_sources_command(["download.docker.com"], f"{etc}/00proxy", _apt_config(etc)))
|
||||
|
||||
assert (etc / "sources.list.d" / "docker.list").read_text() == (
|
||||
"deb [arch=amd64 signed-by=/etc/apt/keyrings/docker.asc] "
|
||||
"http://HTTPS///download.docker.com/linux/ubuntu noble stable\n"
|
||||
)
|
||||
|
||||
def test_a_deb822_source(self, etc):
|
||||
(etc / "sources.list.d" / "docker.sources").write_text(_DOCKER_SOURCES)
|
||||
|
||||
_run(rewrite_sources_command(["download.docker.com"], f"{etc}/00proxy", _apt_config(etc)))
|
||||
|
||||
assert (etc / "sources.list.d" / "docker.sources").read_text() == (
|
||||
_DOCKER_SOURCES.replace("https://", "http://HTTPS///")
|
||||
)
|
||||
|
||||
def test_sources_list_itself_and_only_the_hosts_named(self, etc):
|
||||
(etc / "sources.list").write_text(
|
||||
"deb http://deb.debian.org/debian trixie main\n"
|
||||
"deb https://a.example/debian trixie main\n"
|
||||
"deb-src https://a.example/debian trixie main\n"
|
||||
"deb https://b.example/debian trixie main\n"
|
||||
"# deb https://a.example/old trixie main\n"
|
||||
)
|
||||
|
||||
_run(rewrite_sources_command(["a.example"], f"{etc}/00proxy", _apt_config(etc)))
|
||||
|
||||
assert (etc / "sources.list").read_text() == (
|
||||
"deb http://deb.debian.org/debian trixie main\n"
|
||||
"deb http://HTTPS///a.example/debian trixie main\n"
|
||||
"deb-src http://HTTPS///a.example/debian trixie main\n"
|
||||
"deb https://b.example/debian trixie main\n"
|
||||
"# deb https://a.example/old trixie main\n"
|
||||
)
|
||||
|
||||
def test_a_longer_name_or_another_port_stays(self, etc):
|
||||
text = (
|
||||
"deb https://a.example.org/debian trixie main\n"
|
||||
"deb https://a.example:8443/debian trixie main\n"
|
||||
)
|
||||
(etc / "sources.list").write_text(text)
|
||||
|
||||
_run(rewrite_sources_command(["a.example"], f"{etc}/00proxy", _apt_config(etc)))
|
||||
|
||||
assert (etc / "sources.list").read_text() == text
|
||||
|
||||
def test_a_host_with_credentials_stays_and_is_named(self, etc):
|
||||
(etc / "sources.list.d" / "pve.sources").write_text(
|
||||
"Types: deb\nURIs: https://enterprise.proxmox.com/debian/pve\nSuites: trixie\n"
|
||||
)
|
||||
(etc / "sources.list.d" / "docker.list").write_text(_DOCKER_LIST)
|
||||
(etc / "auth.conf.d" / "pve.conf").write_text(
|
||||
"machine https://Enterprise.Proxmox.com/debian/pve\nlogin key\npassword secret\n"
|
||||
)
|
||||
|
||||
_run(
|
||||
rewrite_sources_command(
|
||||
["enterprise.proxmox.com", "download.docker.com"],
|
||||
f"{etc}/00proxy",
|
||||
_apt_config(etc),
|
||||
)
|
||||
)
|
||||
|
||||
assert "https://enterprise.proxmox.com" in (etc / "sources.list.d/pve.sources").read_text()
|
||||
assert "HTTPS///download.docker.com" in (etc / "sources.list.d/docker.list").read_text()
|
||||
assert (etc / "00proxy").read_text() == (
|
||||
'Acquire::http::Proxy "http://c:3142";\n'
|
||||
'Package-Proxy::Not-Cached:: "enterprise.proxmox.com";\n'
|
||||
)
|
||||
assert "secret" not in (etc / "00proxy").read_text()
|
||||
|
||||
def test_credentials_in_auth_conf_on_one_line(self, etc):
|
||||
(etc / "sources.list").write_text("deb https://esm.ubuntu.com/apps/ubuntu noble main\n")
|
||||
(etc / "auth.conf").write_text("machine esm.ubuntu.com/apps/ubuntu/ login a password b\n")
|
||||
|
||||
_run(rewrite_sources_command(["esm.ubuntu.com"], f"{etc}/00proxy", _apt_config(etc)))
|
||||
|
||||
assert "https://esm.ubuntu.com" in (etc / "sources.list").read_text()
|
||||
assert "esm.ubuntu.com" in (etc / "00proxy").read_text()
|
||||
|
||||
def test_a_file_without_the_host_is_left_untouched(self, etc):
|
||||
other = etc / "sources.list.d" / "other.list"
|
||||
other.write_text("deb http://deb.debian.org/debian trixie main\n")
|
||||
before = other.stat().st_ino # sed -i writes a new file; grep first leaves it be
|
||||
|
||||
_run(rewrite_sources_command(["a.example"], f"{etc}/00proxy", _apt_config(etc)))
|
||||
|
||||
assert other.stat().st_ino == before
|
||||
|
||||
def test_twice_is_once(self, etc):
|
||||
(etc / "sources.list.d" / "docker.list").write_text(_DOCKER_LIST)
|
||||
command = rewrite_sources_command(
|
||||
["download.docker.com"], f"{etc}/00proxy", _apt_config(etc)
|
||||
)
|
||||
|
||||
_run(command)
|
||||
_run(command)
|
||||
|
||||
assert (etc / "sources.list.d" / "docker.list").read_text().count("HTTPS///") == 1
|
||||
|
||||
|
||||
@needs_apt
|
||||
class TestRevert:
|
||||
def test_every_source_goes_back_to_https(self, etc):
|
||||
(etc / "sources.list.d" / "docker.list").write_text(_DOCKER_LIST)
|
||||
(etc / "sources.list.d" / "docker.sources").write_text(_DOCKER_SOURCES)
|
||||
_run(rewrite_sources_command(["download.docker.com"], f"{etc}/00proxy", _apt_config(etc)))
|
||||
|
||||
_run(revert_sources_command(_apt_config(etc)))
|
||||
|
||||
assert (etc / "sources.list.d" / "docker.list").read_text() == _DOCKER_LIST
|
||||
assert (etc / "sources.list.d" / "docker.sources").read_text() == _DOCKER_SOURCES
|
||||
|
||||
def test_nothing_to_revert(self, etc):
|
||||
(etc / "sources.list").write_text("deb http://deb.debian.org/debian trixie main\n")
|
||||
|
||||
_run(revert_sources_command(_apt_config(etc)))
|
||||
|
||||
assert (
|
||||
etc / "sources.list"
|
||||
).read_text() == "deb http://deb.debian.org/debian trixie main\n"
|
||||
|
||||
|
||||
def test_the_commands_are_valid_posix_sh():
|
||||
for command in (
|
||||
rewrite_sources_command(["a.example"], "/etc/apt/apt.conf.d/00proxy"),
|
||||
revert_sources_command(),
|
||||
):
|
||||
assert subprocess.run(["sh", "-n", "-c", command], check=False).returncode == 0
|
||||
|
||||
|
||||
def test_a_host_name():
|
||||
assert is_host_name("download.docker.com")
|
||||
assert not is_host_name('h"; Acquire::x "y')
|
||||
assert not is_host_name("-h.example")
|
||||
@@ -19,30 +19,40 @@ from napalm_device_types.container_engine import (
|
||||
ContainerEngineUnavailable,
|
||||
)
|
||||
|
||||
#: What each engine's CLI says to ``--version``.
|
||||
VERSIONS = {
|
||||
"docker": "Docker version 29.0.1, build 1a2b3c4",
|
||||
"podman": "podman version 5.2.2",
|
||||
}
|
||||
|
||||
|
||||
class FakeDriver(ContainerEngineMixin):
|
||||
"""A driver with a channel: records what it is asked to run."""
|
||||
"""A driver with a channel: records what it is asked to run.
|
||||
|
||||
def __init__(self, present=("docker",), binary=None):
|
||||
*present* are the engines whose CLI is installed; *says* overrides what an
|
||||
engine's CLI answers to ``--version`` (podman-docker's ``docker`` is podman).
|
||||
"""
|
||||
|
||||
def __init__(self, present=("docker",), binary=None, says=None):
|
||||
self.present = set(present)
|
||||
self.binary = binary
|
||||
self.says = dict(says or {})
|
||||
self.commands = []
|
||||
self.streams = []
|
||||
|
||||
def run_command(self, command, *, privileged=False, timeout=60, stdin=None):
|
||||
self.commands.append((command, privileged, timeout, stdin))
|
||||
found = any(command == f"command -v {b}" for b in self._binaries())
|
||||
return CommandResult(
|
||||
stdout="/usr/bin/x\n" if found else "", stderr="", exit_code=0 if found else 1
|
||||
)
|
||||
for engine in self.present:
|
||||
b = self._container_engine_binary(engine)
|
||||
if command == f"command -v {b} >/dev/null 2>&1 && {b} --version":
|
||||
answer = self.says.get(engine, VERSIONS[engine])
|
||||
return CommandResult(stdout=answer + "\n", stderr="", exit_code=0)
|
||||
return CommandResult(stdout="", stderr="", exit_code=1)
|
||||
|
||||
def open_stream(self, command, *, privileged=False):
|
||||
self.streams.append((command, privileged))
|
||||
return object()
|
||||
|
||||
def _binaries(self):
|
||||
return {self._container_engine_binary(e) for e in self.present}
|
||||
|
||||
def _container_engine_binary(self, engine):
|
||||
return self.binary or super()._container_engine_binary(engine)
|
||||
|
||||
@@ -123,6 +133,60 @@ def test_an_unknown_engine_is_refused():
|
||||
FakeDriver().open_container_engine("rkt")
|
||||
|
||||
|
||||
class TestPodman:
|
||||
"""Podman, reached the way Docker is (NetOrk/netork#818).
|
||||
|
||||
Its API is Podman's own service, which also speaks Docker's: netOrk reads the
|
||||
host's *rootful* Podman, the engine of the system's containers (Quadlet units
|
||||
in ``/etc/containers/systemd``, ``podman.socket``). A login user's rootless
|
||||
containers are that user's own and invisible to anybody else, so the
|
||||
connection to Podman runs as root, the way the driver gains root for any command.
|
||||
"""
|
||||
|
||||
def test_a_host_with_podman_lists_it_with_its_api(self):
|
||||
driver = FakeDriver(present=("podman",))
|
||||
|
||||
assert driver.container_engines() == [{"engine": "podman", "api": "podman-libpod"}]
|
||||
|
||||
def test_a_host_with_both_lists_both(self):
|
||||
driver = FakeDriver(present=("docker", "podman"))
|
||||
|
||||
assert driver.container_engines() == [
|
||||
{"engine": "docker", "api": "docker-engine"},
|
||||
{"engine": "podman", "api": "podman-libpod"},
|
||||
]
|
||||
|
||||
def test_podman_docker_is_not_docker(self):
|
||||
"""podman-docker installs a ``docker`` that runs podman: listing it as
|
||||
Docker would read the login user's rootless Podman a second time."""
|
||||
driver = FakeDriver(present=("docker", "podman"), says={"docker": VERSIONS["podman"]})
|
||||
|
||||
assert driver.container_engines() == [{"engine": "podman", "api": "podman-libpod"}]
|
||||
|
||||
def test_the_api_stream_runs_as_root(self):
|
||||
driver = FakeDriver(present=("podman",))
|
||||
|
||||
driver.open_container_engine("podman").open_api()
|
||||
|
||||
assert driver.streams == [("podman system dial-stdio", True)]
|
||||
|
||||
def test_the_cli_runs_as_root_too(self):
|
||||
driver = FakeDriver(present=("podman",))
|
||||
conn = driver.open_container_engine("podman")
|
||||
|
||||
conn.run_cli(["pull", "nginx"])
|
||||
conn.stream_cli(["pull", "nginx"])
|
||||
|
||||
assert driver.commands[-1][:2] == ("podman pull nginx", True)
|
||||
assert driver.streams == [("podman pull nginx", True)]
|
||||
|
||||
def test_the_connection_says_it_runs_as_root(self):
|
||||
driver = FakeDriver(present=("docker", "podman"))
|
||||
|
||||
assert driver.open_container_engine("podman").privileged is True
|
||||
assert driver.open_container_engine("docker").privileged is False
|
||||
|
||||
|
||||
def test_the_connection_names_its_engine():
|
||||
conn = FakeDriver().open_container_engine("docker")
|
||||
|
||||
|
||||
@@ -56,8 +56,26 @@ def test_a_firmware_offer_says_what_runs_and_what_is_offered():
|
||||
from napalm_device_types import FirmwareOfferDict, FirmwareOfferMixin
|
||||
|
||||
hints = get_type_hints(FirmwareOfferDict)
|
||||
assert set(hints) == {"current_version", "latest_version", "newer", "download_url"}
|
||||
assert set(hints) == {
|
||||
"current_version",
|
||||
"latest_version",
|
||||
"newer",
|
||||
"download_url",
|
||||
"installable",
|
||||
"latest_major_version",
|
||||
}
|
||||
assert FirmwareOfferDict.__required_keys__ == frozenset(
|
||||
{"current_version", "latest_version", "newer"}
|
||||
)
|
||||
assert not hasattr(FirmwareOfferMixin, "get_firmware_offer")
|
||||
|
||||
|
||||
def test_a_firmware_upgrade_is_started_and_followed_like_a_device_run_update():
|
||||
"""A driver that can install the firmware it offers starts it and the device
|
||||
runs it by itself, restarting at its end (OpenWrt's sysupgrade, NetOrk/netork#2615);
|
||||
the caller follows it through ``get_update_progress``. Declared only, so
|
||||
``hasattr`` tells a caller whether the driver offers it."""
|
||||
from napalm_device_types import FirmwareUpgradeMixin, UpdateMixin
|
||||
|
||||
assert not hasattr(FirmwareUpgradeMixin, "start_firmware_upgrade")
|
||||
assert not hasattr(UpdateMixin, "get_update_progress")
|
||||
@@ -259,6 +259,7 @@ class TestLldpAgent:
|
||||
"ensure_package",
|
||||
"configure_package_proxy",
|
||||
"grant_container_engine_access",
|
||||
"configure_zabbix_agent",
|
||||
],
|
||||
)
|
||||
def test_no_role_base_offers_a_fix(base, method):
|
||||
|
||||
@@ -0,0 +1,391 @@
|
||||
"""get_hardening: how a Linux host is hardened, as the kernel and the host's tools say it.
|
||||
|
||||
The security modules in force (``/sys/kernel/security/lsm``, SELinux's mode, AppArmor's
|
||||
profiles), the system-wide crypto policy and FIPS mode, what the kernel reports for each
|
||||
known CPU vulnerability, and the command line it booted with (NetOrk/netork#2706). One
|
||||
read-only command, the same on every Linux host, so it lives here once and a driver only
|
||||
carries it across. Root only adds AppArmor's profile counts.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import json
|
||||
import os
|
||||
import subprocess
|
||||
|
||||
import pytest
|
||||
|
||||
from napalm_device_types import OSDriver
|
||||
from napalm_device_types.hardening import (
|
||||
HARDENING_COMMAND,
|
||||
HardeningMixin,
|
||||
cpu_vulnerability_state,
|
||||
parse_hardening,
|
||||
)
|
||||
|
||||
#: AlmaLinux 9 on a KVM guest: SELinux enforcing, the DEFAULT policy, no FIPS.
|
||||
ALMA_9 = [
|
||||
("lsm", "lockdown,capability,yama,selinux,bpf"),
|
||||
("cmdline", "BOOT_IMAGE=(hd0,gpt2)/vmlinuz-5.14.0-503.el9.x86_64 root=/dev/vda4 ro"),
|
||||
("fips", "0"),
|
||||
("os", 'ID="almalinux"\nID_LIKE="rhel centos fedora"'),
|
||||
("selinux", "Enforcing"),
|
||||
("selinux_config", "SELINUX=enforcing"),
|
||||
("crypto_policy", "DEFAULT"),
|
||||
(
|
||||
"cpu_vulnerabilities",
|
||||
"/sys/devices/system/cpu/vulnerabilities/meltdown:Not affected\n"
|
||||
"/sys/devices/system/cpu/vulnerabilities/spec_rstack_overflow:Mitigation: Safe RET\n"
|
||||
"/sys/devices/system/cpu/vulnerabilities/spectre_v1:Mitigation: usercopy/swapgs "
|
||||
"barriers and __user pointer sanitization\n"
|
||||
"/sys/devices/system/cpu/vulnerabilities/spectre_v2:Mitigation: Retpolines; IBPB: "
|
||||
"conditional; IBRS_FW; STIBP: always-on; RSB filling; PBRSB-eIBRS: Not affected; "
|
||||
"BHI: Not affected\n"
|
||||
"/sys/devices/system/cpu/vulnerabilities/mmio_stale_data:Unknown: No mitigations",
|
||||
),
|
||||
]
|
||||
|
||||
AA_STATUS = {
|
||||
"version": "2",
|
||||
"profiles": {
|
||||
"/snap/snapd/21759/usr/lib/snapd/snap-confine": "enforce",
|
||||
"lsb_release": "enforce",
|
||||
"rsyslogd": "enforce",
|
||||
"unprivileged_userns": "enforce",
|
||||
"ubuntu_pro_apt_news": "complain",
|
||||
"Discord": "unconfined",
|
||||
},
|
||||
"processes": {
|
||||
"/usr/sbin/rsyslogd": [{"profile": "rsyslogd", "pid": "812", "status": "enforce"}]
|
||||
},
|
||||
}
|
||||
|
||||
#: Ubuntu 24.04, read as root: AppArmor with its profiles, no crypto-policies, no SELinux.
|
||||
UBUNTU_2404 = [
|
||||
("lsm", "lockdown,capability,landlock,yama,apparmor,ima,evm"),
|
||||
("cmdline", "BOOT_IMAGE=/vmlinuz-6.8.0-49-generic root=/dev/mapper/vg-root ro quiet splash"),
|
||||
("fips", "0"),
|
||||
("apparmor_enabled", "Y"),
|
||||
("os", "ID=ubuntu\nID_LIKE=debian"),
|
||||
(
|
||||
"cpu_vulnerabilities",
|
||||
"/sys/devices/system/cpu/vulnerabilities/meltdown:Not affected\n"
|
||||
"/sys/devices/system/cpu/vulnerabilities/spectre_v2:Mitigation: Enhanced / Automatic "
|
||||
"IBRS; IBPB: conditional; RSB filling; PBRSB-eIBRS: SW sequence; BHI: BHI_DIS_S",
|
||||
),
|
||||
("aa_status", json.dumps(AA_STATUS)),
|
||||
]
|
||||
|
||||
#: Debian 12 booted with mitigations=off.
|
||||
MITIGATIONS_OFF = [
|
||||
("lsm", "lockdown,capability,landlock,yama,apparmor,tomoyo"),
|
||||
("cmdline", "BOOT_IMAGE=/boot/vmlinuz-6.1.0-25-amd64 root=UUID=1b2c ro quiet mitigations=off"),
|
||||
("apparmor_enabled", "Y"),
|
||||
("os", "ID=debian"),
|
||||
(
|
||||
"cpu_vulnerabilities",
|
||||
"/sys/devices/system/cpu/vulnerabilities/meltdown:Vulnerable\n"
|
||||
"/sys/devices/system/cpu/vulnerabilities/mds:Vulnerable; SMT vulnerable\n"
|
||||
"/sys/devices/system/cpu/vulnerabilities/spectre_v1:Vulnerable: __user pointer "
|
||||
"sanitization and usercopy barriers only; no swapgs barriers\n"
|
||||
"/sys/devices/system/cpu/vulnerabilities/spectre_v2:Vulnerable; IBPB: disabled; "
|
||||
"STIBP: disabled; PBRSB-eIBRS: Vulnerable; BHI: Vulnerable",
|
||||
),
|
||||
("aa_status", ""),
|
||||
]
|
||||
|
||||
|
||||
def _wire(sections: list[tuple[str, str]], *, noise: str = "") -> str:
|
||||
"""The report as the command prints it, framed."""
|
||||
body = "".join(f"[{name}]\n{text}\n" for name, text in sections)
|
||||
return f"{noise}HARDENING_BEGIN\n{body}HARDENING_END\n"
|
||||
|
||||
|
||||
class TestTheFixtures:
|
||||
def test_alma_9_selinux_enforcing_default_policy(self):
|
||||
reading = parse_hardening(_wire(ALMA_9))
|
||||
|
||||
assert reading == {
|
||||
"lsm": ["lockdown", "capability", "yama", "selinux", "bpf"],
|
||||
"selinux": {"mode": "enforcing", "configured": "enforcing"},
|
||||
"apparmor": None,
|
||||
"crypto_policy": "DEFAULT",
|
||||
"fips": False,
|
||||
"cpu_vulnerabilities": {
|
||||
"meltdown": "Not affected",
|
||||
"mmio_stale_data": "Unknown: No mitigations",
|
||||
"spec_rstack_overflow": "Mitigation: Safe RET",
|
||||
"spectre_v1": "Mitigation: usercopy/swapgs barriers and __user pointer "
|
||||
"sanitization",
|
||||
"spectre_v2": "Mitigation: Retpolines; IBPB: conditional; IBRS_FW; STIBP: "
|
||||
"always-on; RSB filling; PBRSB-eIBRS: Not affected; BHI: Not affected",
|
||||
},
|
||||
"cmdline": "BOOT_IMAGE=(hd0,gpt2)/vmlinuz-5.14.0-503.el9.x86_64 root=/dev/vda4 ro",
|
||||
"mitigations": "auto",
|
||||
"nosmt": False,
|
||||
"os_ids": ["almalinux", "rhel", "centos", "fedora"],
|
||||
}
|
||||
|
||||
def test_ubuntu_24_04_apparmor_with_its_profiles(self):
|
||||
reading = parse_hardening(_wire(UBUNTU_2404))
|
||||
|
||||
assert reading["selinux"] is None
|
||||
assert reading["apparmor"] == {
|
||||
"enabled": True,
|
||||
"profiles": {"complain": 1, "enforce": 4, "unconfined": 1},
|
||||
}
|
||||
assert reading["crypto_policy"] is None
|
||||
assert reading["os_ids"] == ["ubuntu", "debian"]
|
||||
|
||||
def test_mitigations_off(self):
|
||||
reading = parse_hardening(_wire(MITIGATIONS_OFF))
|
||||
|
||||
assert reading["mitigations"] == "off"
|
||||
assert reading["nosmt"] is False
|
||||
assert {cpu_vulnerability_state(v) for v in reading["cpu_vulnerabilities"].values()} == {
|
||||
"vulnerable"
|
||||
}
|
||||
|
||||
def test_apparmor_without_root_has_no_profile_counts(self):
|
||||
"""``aa-status`` needs root: without it the profiles are unread, never zero."""
|
||||
reading = parse_hardening(_wire(MITIGATIONS_OFF))
|
||||
|
||||
assert reading["apparmor"] == {"enabled": True, "profiles": None}
|
||||
|
||||
|
||||
class TestNotReadIsNone:
|
||||
def test_a_section_never_printed_is_none(self):
|
||||
"""``None`` is "could not read": an old kernel without the ``lsm`` file, a
|
||||
host without ``update-crypto-policies``."""
|
||||
reading = parse_hardening(_wire([]))
|
||||
|
||||
assert reading == {
|
||||
"lsm": None,
|
||||
"selinux": None,
|
||||
"apparmor": None,
|
||||
"crypto_policy": None,
|
||||
"fips": None,
|
||||
"cpu_vulnerabilities": None,
|
||||
"cmdline": None,
|
||||
"mitigations": None,
|
||||
"nosmt": None,
|
||||
"os_ids": None,
|
||||
}
|
||||
|
||||
def test_an_empty_vulnerabilities_directory_is_read_and_empty(self):
|
||||
reading = parse_hardening(_wire([("cpu_vulnerabilities", "")]))
|
||||
|
||||
assert reading["cpu_vulnerabilities"] == {}
|
||||
|
||||
def test_output_without_the_frame_raises(self):
|
||||
with pytest.raises(ValueError):
|
||||
parse_hardening("sudo: a password is required\n")
|
||||
|
||||
def test_whatever_surrounds_the_frame_is_ignored(self):
|
||||
noise = "Last login: today\nprintf '%s%s\\n' HARDENING_ BEGIN; ...\n"
|
||||
|
||||
assert parse_hardening(_wire(ALMA_9, noise=noise))["crypto_policy"] == "DEFAULT"
|
||||
|
||||
def test_aa_status_output_that_is_not_json_is_unread(self):
|
||||
reading = parse_hardening(
|
||||
_wire([("apparmor_enabled", "Y"), ("aa_status", "apparmor not present.")])
|
||||
)
|
||||
|
||||
assert reading["apparmor"] == {"enabled": True, "profiles": None}
|
||||
|
||||
|
||||
class TestSelinux:
|
||||
def test_getenforce_permissive(self):
|
||||
reading = parse_hardening(_wire([("selinux", "Permissive")]))
|
||||
|
||||
assert reading["selinux"] == {"mode": "permissive", "configured": None}
|
||||
|
||||
def test_disabled_by_getenforce(self):
|
||||
reading = parse_hardening(
|
||||
_wire([("selinux", "Disabled"), ("selinux_config", "SELINUX=disabled")])
|
||||
)
|
||||
|
||||
assert reading["selinux"] == {"mode": "disabled", "configured": "disabled"}
|
||||
|
||||
@pytest.mark.parametrize("value, mode", [("1", "enforcing"), ("0", "permissive")])
|
||||
def test_without_getenforce_the_enforce_file_answers(self, value, mode):
|
||||
reading = parse_hardening(_wire([("selinux_enforce", value)]))
|
||||
|
||||
assert reading["selinux"]["mode"] == mode
|
||||
|
||||
def test_configured_but_not_among_the_active_modules_is_disabled(self):
|
||||
"""The policy is installed (``/etc/selinux/config``), the kernel runs without it."""
|
||||
reading = parse_hardening(
|
||||
_wire([("lsm", "capability,yama"), ("selinux_config", 'SELINUX="enforcing"')])
|
||||
)
|
||||
|
||||
assert reading["selinux"] == {"mode": "disabled", "configured": "enforcing"}
|
||||
|
||||
def test_configured_without_a_list_of_modules_is_unknown(self):
|
||||
reading = parse_hardening(_wire([("selinux_config", "SELINUX=enforcing")]))
|
||||
|
||||
assert reading["selinux"] == {"mode": None, "configured": "enforcing"}
|
||||
|
||||
|
||||
class TestSelinuxParts:
|
||||
"""The three questions the SELinux part answers, each on its own (napalm-standard's
|
||||
complexity limit): the mode it boots in, the mode it runs in, and whether the
|
||||
host has SELinux at all."""
|
||||
|
||||
def test_the_configured_mode_is_the_last_selinux_line(self):
|
||||
from napalm_device_types.hardening import _selinux_configured
|
||||
|
||||
lines = ["SELINUXTYPE=targeted", 'SELINUX="Permissive"']
|
||||
assert _selinux_configured({"selinux_config": lines}) == "permissive"
|
||||
assert _selinux_configured({"selinux_config": ["SELINUX="]}) is None
|
||||
assert _selinux_configured({}) is None
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
"sections, mode",
|
||||
[
|
||||
({"selinux": ["Enforcing"]}, "enforcing"),
|
||||
({"selinux": ["something else"], "selinux_enforce": ["0"]}, "permissive"),
|
||||
({"selinux_enforce": ["1"]}, "enforcing"),
|
||||
({"selinux_enforce": ["2"]}, None),
|
||||
({}, None),
|
||||
],
|
||||
)
|
||||
def test_the_running_mode_getenforce_first(self, sections, mode):
|
||||
from napalm_device_types.hardening import _selinux_running
|
||||
|
||||
assert _selinux_running(sections) == mode
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
"sections, lsm, seen",
|
||||
[
|
||||
({}, ["capability", "selinux"], True),
|
||||
({"selinux_config": []}, None, True),
|
||||
({}, ["capability", "apparmor"], False),
|
||||
({}, None, False),
|
||||
],
|
||||
)
|
||||
def test_whether_the_host_has_it(self, sections, lsm, seen):
|
||||
from napalm_device_types.hardening import _selinux_seen
|
||||
|
||||
assert _selinux_seen(sections, lsm, None) is seen
|
||||
assert _selinux_seen(sections, lsm, "enforcing") is True
|
||||
|
||||
|
||||
class TestAppArmor:
|
||||
def test_in_the_list_of_modules_without_the_parameter_file(self):
|
||||
reading = parse_hardening(_wire([("lsm", "capability,apparmor")]))
|
||||
|
||||
assert reading["apparmor"] == {"enabled": True, "profiles": None}
|
||||
|
||||
def test_switched_off(self):
|
||||
reading = parse_hardening(_wire([("lsm", "capability"), ("apparmor_enabled", "N")]))
|
||||
|
||||
assert reading["apparmor"] == {"enabled": False, "profiles": None}
|
||||
|
||||
|
||||
class TestCommandLine:
|
||||
@pytest.mark.parametrize(
|
||||
"cmdline, mitigations, nosmt",
|
||||
[
|
||||
("ro quiet", "auto", False),
|
||||
("ro mitigations=off", "off", False),
|
||||
("ro mitigations=auto,nosmt", "auto,nosmt", True),
|
||||
("ro nosmt", "auto", True),
|
||||
("ro nosmt=force", "auto", True),
|
||||
("ro mitigations=auto mitigations=off", "off", False),
|
||||
],
|
||||
)
|
||||
def test_mitigations_and_smt(self, cmdline, mitigations, nosmt):
|
||||
"""The last ``mitigations=`` wins, as in the kernel; ``nosmt`` comes alone or
|
||||
with ``mitigations=auto,nosmt``."""
|
||||
reading = parse_hardening(_wire([("cmdline", cmdline)]))
|
||||
|
||||
assert (reading["mitigations"], reading["nosmt"]) == (mitigations, nosmt)
|
||||
|
||||
|
||||
class TestCryptoPolicy:
|
||||
def test_a_subpolicy_is_kept(self):
|
||||
reading = parse_hardening(_wire([("crypto_policy", "LEGACY:AD-SUPPORT"), ("fips", "1")]))
|
||||
|
||||
assert (reading["crypto_policy"], reading["fips"]) == ("LEGACY:AD-SUPPORT", True)
|
||||
|
||||
def test_no_output_is_unread(self):
|
||||
assert parse_hardening(_wire([("crypto_policy", "")]))["crypto_policy"] is None
|
||||
|
||||
|
||||
class TestCpuVulnerabilityState:
|
||||
@pytest.mark.parametrize(
|
||||
"text, state",
|
||||
[
|
||||
("Not affected", "not_affected"),
|
||||
("Mitigation: Retpolines; IBPB: conditional", "mitigated"),
|
||||
("KVM: Mitigation: VMX disabled", "mitigated"),
|
||||
(
|
||||
"Mitigation: PTE Inversion; VMX: conditional cache flushes, SMT vulnerable",
|
||||
"mitigated",
|
||||
),
|
||||
("Vulnerable", "vulnerable"),
|
||||
("Vulnerable: Clear CPU buffers attempted, no microcode; SMT vulnerable", "vulnerable"),
|
||||
("Processor vulnerable", "vulnerable"),
|
||||
("Unknown: Dependent on hypervisor status", "unknown"),
|
||||
("", "unknown"),
|
||||
],
|
||||
)
|
||||
def test_the_kernels_words(self, text, state):
|
||||
assert cpu_vulnerability_state(text) == state
|
||||
|
||||
|
||||
class _Driver(OSDriver, HardeningMixin):
|
||||
def __init__(self, outputs):
|
||||
self.outputs = list(outputs)
|
||||
self.calls: list[tuple[str, bool]] = []
|
||||
|
||||
def _run_hardening_command(self, command: str, *, privileged: bool) -> str:
|
||||
self.calls.append((command, privileged))
|
||||
return self.outputs.pop(0)
|
||||
|
||||
|
||||
class TestTheMixin:
|
||||
def test_read_as_root_first(self):
|
||||
driver = _Driver([_wire(UBUNTU_2404)])
|
||||
|
||||
reading = driver.get_hardening()
|
||||
|
||||
assert driver.calls[0][1] is True
|
||||
assert reading["apparmor"]["profiles"]["enforce"] == 4
|
||||
|
||||
def test_root_refused_reads_as_the_login_user(self):
|
||||
driver = _Driver(["sudo: a password is required\n", _wire(MITIGATIONS_OFF)])
|
||||
|
||||
reading = driver.get_hardening()
|
||||
|
||||
assert [privileged for _, privileged in driver.calls] == [True, False]
|
||||
assert reading["mitigations"] == "off"
|
||||
|
||||
def test_the_command_goes_to_sh(self):
|
||||
driver = _Driver([_wire(ALMA_9)])
|
||||
|
||||
driver.get_hardening()
|
||||
|
||||
assert driver.calls[0][0].startswith("sh -c ")
|
||||
|
||||
|
||||
class TestTheCommand:
|
||||
def test_the_frame_is_not_in_the_command_itself(self):
|
||||
assert "HARDENING_BEGIN" not in HARDENING_COMMAND
|
||||
assert "HARDENING_END" not in HARDENING_COMMAND
|
||||
|
||||
def test_it_changes_nothing(self):
|
||||
for verb in ("setenforce", "--set", "aa-enforce", "aa-complain", " > ", ">>", "sudo"):
|
||||
assert verb not in HARDENING_COMMAND
|
||||
|
||||
@pytest.mark.skipif(os.uname().sysname != "Linux", reason="reads a Linux host")
|
||||
def test_it_runs_and_parses_on_this_host(self):
|
||||
out = subprocess.run(
|
||||
["sh", "-c", HARDENING_COMMAND], capture_output=True, text=True, timeout=60
|
||||
).stdout
|
||||
|
||||
reading = parse_hardening(out)
|
||||
|
||||
assert reading["cmdline"] is not None
|
||||
assert reading["mitigations"] is not None
|
||||
@@ -0,0 +1,321 @@
|
||||
"""get_kernel_facts' live patches: what the running kernel has patched in while it runs.
|
||||
|
||||
A live patch fixes a kernel CVE without a new release, so a consumer that judges the
|
||||
running release alone reports the CVE open and a reboot as worth it (NetOrk/netork#2701).
|
||||
The kernel facts read three things, each where it is kept: the loaded patches in
|
||||
``/sys/kernel/livepatch`` (every distribution), ``kpatch list`` where kpatch is
|
||||
installed, and ``canonical-livepatch status --format json`` -- the daemon's last state,
|
||||
which names the CVEs each patch fixes. Canonical's status may need root: a driver that
|
||||
can gain it supplies ``_run_livepatch_status_command``.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import base64
|
||||
import gzip
|
||||
import json
|
||||
|
||||
import pytest
|
||||
|
||||
from napalm_device_types.kernel import (
|
||||
KERNEL_FACTS_COMMAND,
|
||||
LIVEPATCH_STATUS_COMMAND,
|
||||
KernelFactsMixin,
|
||||
parse_kernel_facts,
|
||||
)
|
||||
from napalm_device_types.livepatch import (
|
||||
canonical_release,
|
||||
parse_canonical_status,
|
||||
parse_kpatch_list,
|
||||
parse_sysfs_livepatches,
|
||||
)
|
||||
|
||||
#: Ubuntu 22.04 with Livepatch applied: the client of the 10.x series, as the Ubuntu
|
||||
#: Pro client reads it (``Status`` -> ``Livepatch`` -> ``Fixes``).
|
||||
CANONICAL = {
|
||||
"client-version": "10.8.3",
|
||||
"architecture": "x86_64",
|
||||
"cpu-model": "Intel(R) Xeon(R) CPU",
|
||||
"last-check": "2026-11-28T09:12:44Z",
|
||||
"boot-time": "2026-11-01T07:00:00Z",
|
||||
"uptime": "2312h12m44s",
|
||||
"Status": [
|
||||
{
|
||||
"Kernel": "5.15.0-91.101-generic",
|
||||
"Running": True,
|
||||
"Livepatch": {
|
||||
"CheckState": "checked",
|
||||
"State": "applied",
|
||||
"Version": "101.1",
|
||||
"Fixes": [
|
||||
{
|
||||
"Name": "cve-2023-1077",
|
||||
"Description": "sched: ...",
|
||||
"Bug": "",
|
||||
"Patched": True,
|
||||
},
|
||||
{
|
||||
"Name": "cve-2023-3090",
|
||||
"Description": "ipvlan: ...",
|
||||
"Bug": "",
|
||||
"Patched": True,
|
||||
},
|
||||
{
|
||||
"Name": "cve-2023-3389",
|
||||
"Description": "io_uring: ...",
|
||||
"Bug": "",
|
||||
"Patched": False,
|
||||
},
|
||||
{"Name": "lp-2023-1", "Description": "not a CVE", "Bug": "", "Patched": True},
|
||||
],
|
||||
},
|
||||
"Supported": "supported",
|
||||
}
|
||||
],
|
||||
"tier": "updates",
|
||||
}
|
||||
|
||||
#: The 9.x client wrote its fixes as one text, a ``* cve-...`` line each.
|
||||
CANONICAL_9 = {
|
||||
"Status": [
|
||||
{
|
||||
"Kernel": "5.4.0-42.46-generic",
|
||||
"Running": True,
|
||||
"Livepatch": {
|
||||
"CheckState": "checked",
|
||||
"State": "applied",
|
||||
"Version": "70.1",
|
||||
"Fixes": "* cve-2020-11935\n* cve-2020-15780 (bug 1883337)\n",
|
||||
},
|
||||
}
|
||||
]
|
||||
}
|
||||
|
||||
REPORT = """[release]
|
||||
5.15.0-91-generic
|
||||
[loaded]
|
||||
lkp_Ubuntu_5_15_0_91_101_generic_101
|
||||
[livepatch]
|
||||
lkp_Ubuntu_5_15_0_91_101_generic_101 1 0
|
||||
[canonical_livepatch]
|
||||
{json}
|
||||
"""
|
||||
|
||||
|
||||
def _wire(report: str) -> str:
|
||||
payload = base64.encodebytes(gzip.compress(report.encode())).decode()
|
||||
return f"KFACTS_BEGIN\n{payload}KFACTS_END\n"
|
||||
|
||||
|
||||
class TestSysfs:
|
||||
def test_each_loaded_patch_enabled_or_not(self):
|
||||
lines = ["livepatch_cve_2024_1 1 0", "kpatch_5_14_0_427 0 1", ""]
|
||||
|
||||
assert parse_sysfs_livepatches(lines) == [
|
||||
{"name": "livepatch_cve_2024_1", "enabled": True, "transition": False},
|
||||
{"name": "kpatch_5_14_0_427", "enabled": False, "transition": True},
|
||||
]
|
||||
|
||||
def test_an_unreadable_flag_is_none(self):
|
||||
assert parse_sysfs_livepatches(["lkp_x"]) == [
|
||||
{"name": "lkp_x", "enabled": None, "transition": None}
|
||||
]
|
||||
|
||||
|
||||
class TestKpatch:
|
||||
def test_loaded_and_installed_modules(self):
|
||||
text = [
|
||||
"Loaded patch modules:",
|
||||
"kpatch_5_14_0_427_13_1 [enabled]",
|
||||
"kpatch_cumulative_old [disabled]",
|
||||
"",
|
||||
"Installed patch modules:",
|
||||
"kpatch_5_14_0_427_13_1 (5.14.0-427.13.1.el9_4.x86_64)",
|
||||
"kpatch_5_14_0_362 (5.14.0-362.8.1.el9_3.x86_64)",
|
||||
]
|
||||
|
||||
assert parse_kpatch_list(text) == {
|
||||
"loaded": [
|
||||
{"name": "kpatch_5_14_0_427_13_1", "enabled": True},
|
||||
{"name": "kpatch_cumulative_old", "enabled": False},
|
||||
],
|
||||
"installed": [
|
||||
{"name": "kpatch_5_14_0_427_13_1", "kernel": "5.14.0-427.13.1.el9_4.x86_64"},
|
||||
{"name": "kpatch_5_14_0_362", "kernel": "5.14.0-362.8.1.el9_3.x86_64"},
|
||||
],
|
||||
}
|
||||
|
||||
def test_nothing_loaded(self):
|
||||
assert parse_kpatch_list(["Loaded patch modules:", "", "Installed patch modules:"]) == {
|
||||
"loaded": [],
|
||||
"installed": [],
|
||||
}
|
||||
|
||||
|
||||
class TestCanonical:
|
||||
def test_the_running_kernels_status_and_its_cves(self):
|
||||
status = parse_canonical_status(json.dumps(CANONICAL))
|
||||
|
||||
assert status == {
|
||||
"kernel": "5.15.0-91.101-generic",
|
||||
"running": True,
|
||||
"state": "applied",
|
||||
"check_state": "checked",
|
||||
"version": "101.1",
|
||||
"fixes": [
|
||||
{"cve": "CVE-2023-1077", "patched": True},
|
||||
{"cve": "CVE-2023-3090", "patched": True},
|
||||
{"cve": "CVE-2023-3389", "patched": False},
|
||||
],
|
||||
}
|
||||
|
||||
def test_the_9_x_clients_text_of_fixes(self):
|
||||
status = parse_canonical_status(json.dumps(CANONICAL_9))
|
||||
|
||||
assert status is not None
|
||||
assert status["fixes"] == [
|
||||
{"cve": "CVE-2020-11935", "patched": True},
|
||||
{"cve": "CVE-2020-15780", "patched": True},
|
||||
]
|
||||
|
||||
def test_keys_in_either_case(self):
|
||||
lowered = json.loads(
|
||||
json.dumps(CANONICAL).replace('"Status"', '"status"').replace('"State"', '"state"')
|
||||
)
|
||||
|
||||
assert parse_canonical_status(json.dumps(lowered))["state"] == "applied"
|
||||
|
||||
def test_the_entry_of_the_running_kernel(self):
|
||||
other = {
|
||||
"Kernel": "5.15.0-88.98-generic",
|
||||
"Running": False,
|
||||
"Livepatch": {"State": "applied", "Fixes": []},
|
||||
}
|
||||
data = {"Status": [other, CANONICAL["Status"][0]]}
|
||||
|
||||
assert parse_canonical_status(json.dumps(data))["kernel"] == "5.15.0-91.101-generic"
|
||||
|
||||
@pytest.mark.parametrize("text", ["", "error: must be root", "{}", '{"Status": []}', "[1, 2]"])
|
||||
def test_no_status_is_none(self, text):
|
||||
assert parse_canonical_status(text) is None
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
"kernel, release",
|
||||
[
|
||||
("5.15.0-91.101-generic", "5.15.0-91-generic"),
|
||||
("6.8.0-49.49~22.04.1-generic", "6.8.0-49-generic"),
|
||||
("5.4.0-1045.47-aws", "5.4.0-1045-aws"),
|
||||
("6.8.0-49-generic", "6.8.0-49-generic"),
|
||||
(None, None),
|
||||
],
|
||||
)
|
||||
def test_its_kernel_as_uname_names_it(self, kernel, release):
|
||||
assert canonical_release(kernel) == release
|
||||
|
||||
|
||||
class TestInTheKernelFacts:
|
||||
def test_read_with_the_kernel_facts(self):
|
||||
facts = parse_kernel_facts(_wire(REPORT.format(json=json.dumps(CANONICAL))))
|
||||
patches = facts["live_patches"]
|
||||
|
||||
assert patches["loaded"] == [
|
||||
{"name": "lkp_Ubuntu_5_15_0_91_101_generic_101", "enabled": True, "transition": False}
|
||||
]
|
||||
assert patches["kpatch"] is None
|
||||
assert patches["canonical"]["state"] == "applied"
|
||||
|
||||
def test_a_kernel_without_live_patching_has_none_loaded(self):
|
||||
"""No ``/sys/kernel/livepatch``: the kernel was built without it, nothing is loaded."""
|
||||
facts = parse_kernel_facts(_wire("[release]\n6.1.0-25-amd64\n"))
|
||||
|
||||
assert facts["live_patches"] == {
|
||||
"loaded": None,
|
||||
"kpatch": None,
|
||||
"canonical": None,
|
||||
"canonical_installed": False,
|
||||
}
|
||||
|
||||
def test_an_empty_directory_is_none_loaded(self):
|
||||
facts = parse_kernel_facts(_wire("[release]\n6.1.0-25-amd64\n[livepatch]\n"))
|
||||
|
||||
assert facts["live_patches"]["loaded"] == []
|
||||
|
||||
|
||||
class _Driver(KernelFactsMixin):
|
||||
def __init__(self, report: str, status: str | None = None):
|
||||
self.report = report
|
||||
self.status = status
|
||||
self.asked: list[str] = []
|
||||
|
||||
def _run_kernel_facts_command(self, command: str) -> str:
|
||||
return _wire(self.report)
|
||||
|
||||
|
||||
class _RootDriver(_Driver):
|
||||
def _run_livepatch_status_command(self, command: str) -> str:
|
||||
self.asked.append(command)
|
||||
return self.status or ""
|
||||
|
||||
|
||||
class TestCanonicalAsRoot:
|
||||
"""``canonical-livepatch status`` may refuse a user who is not root: where the
|
||||
kernel facts found the client but no status, a driver that can gain root asks again."""
|
||||
|
||||
UNREAD = "[release]\n5.15.0-91-generic\n[livepatch]\n[canonical_livepatch]\n"
|
||||
|
||||
def test_asked_again_as_root(self):
|
||||
driver = _RootDriver(self.UNREAD, json.dumps(CANONICAL))
|
||||
|
||||
facts = driver.get_kernel_facts()
|
||||
|
||||
assert driver.asked == [LIVEPATCH_STATUS_COMMAND]
|
||||
assert facts["live_patches"]["canonical"]["version"] == "101.1"
|
||||
|
||||
def test_not_asked_when_read_already(self):
|
||||
driver = _RootDriver(REPORT.format(json=json.dumps(CANONICAL)))
|
||||
|
||||
driver.get_kernel_facts()
|
||||
|
||||
assert driver.asked == []
|
||||
|
||||
def test_not_asked_without_the_client(self):
|
||||
driver = _RootDriver("[release]\n6.1.0\n")
|
||||
|
||||
driver.get_kernel_facts()
|
||||
|
||||
assert driver.asked == []
|
||||
|
||||
def test_a_driver_without_root_leaves_it_unread(self):
|
||||
facts = _Driver(self.UNREAD).get_kernel_facts()
|
||||
|
||||
assert facts["live_patches"]["canonical"] is None
|
||||
assert facts["live_patches"]["canonical_installed"] is True
|
||||
|
||||
def test_a_failed_root_read_leaves_it_unread(self):
|
||||
class Failing(_RootDriver):
|
||||
def _run_livepatch_status_command(self, command: str) -> str:
|
||||
raise RuntimeError("sudo: a password is required")
|
||||
|
||||
assert Failing(self.UNREAD).get_kernel_facts()["live_patches"]["canonical"] is None
|
||||
|
||||
|
||||
class TestTheCommands:
|
||||
def test_the_kernel_facts_read_the_live_patches(self):
|
||||
assert "/sys/kernel/livepatch" in KERNEL_FACTS_COMMAND
|
||||
assert "kpatch list" in KERNEL_FACTS_COMMAND
|
||||
assert "status --format json" in KERNEL_FACTS_COMMAND
|
||||
|
||||
def test_they_ask_canonical_nothing(self):
|
||||
"""``status`` reads the daemon's last state; ``refresh`` would call Canonical."""
|
||||
for command in (KERNEL_FACTS_COMMAND, LIVEPATCH_STATUS_COMMAND):
|
||||
for verb in (
|
||||
"refresh",
|
||||
"livepatch enable",
|
||||
"livepatch disable",
|
||||
"kpatch load",
|
||||
"kpatch unload",
|
||||
"kpatch install",
|
||||
"kpatch uninstall",
|
||||
):
|
||||
assert verb not in command
|
||||
assert LIVEPATCH_STATUS_COMMAND.endswith("status --format json")
|
||||
@@ -0,0 +1,483 @@
|
||||
"""get_login_accounts: every account on a Linux host a person can log in with (NetOrk/netork#2707).
|
||||
|
||||
The accounts come from ``/etc/passwd`` (root and UID 1000 on, with a shell that lets
|
||||
them in), their last login from whichever of ``lastlog2``, ``lastlog``, ``wtmpdb last``
|
||||
and ``last`` the host has, their lock and expiry from ``passwd -S`` and ``chage -l``,
|
||||
and the failed attempts since their last login from ``lastb`` or ``faillock``. The
|
||||
last three need root; read as the login user they are ``None``, never "unlocked" or
|
||||
"no failures".
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import os
|
||||
import subprocess
|
||||
|
||||
import pytest
|
||||
|
||||
from napalm_device_types import OSDriver
|
||||
from napalm_device_types.login_accounts import (
|
||||
FAILED_LOGINS_READ,
|
||||
LOGIN_ACCOUNTS_COMMAND,
|
||||
LoginAccountsMixin,
|
||||
login_capable,
|
||||
parse_login_accounts,
|
||||
)
|
||||
|
||||
PASSWD = (
|
||||
"root:0:/root:/bin/bash\n"
|
||||
"alice:1000:/home/alice:/bin/bash\n"
|
||||
"bob:1001:/home/bob:/usr/bin/zsh\n"
|
||||
"deploy:1002:/srv/deploy:/bin/sh"
|
||||
)
|
||||
|
||||
#: Debian 12 as root: the legacy lastlog, wtmp through ``last``, btmp through ``lastb``,
|
||||
#: Debian's ``passwd -S``. alice logs in over SSH, bob never did, deploy is locked by
|
||||
#: netOrk (``usermod -L -e 1``).
|
||||
DEBIAN_12 = [
|
||||
("uid", "0"),
|
||||
("now", "2026-11-28"),
|
||||
("passwd", PASSWD),
|
||||
(
|
||||
"lastlog",
|
||||
"Username Port From Latest\n"
|
||||
"root tty1 Mon Oct 5 09:12:44 +0200 2026\n"
|
||||
"alice pts/0 192.0.2.10 Fri Nov 27 22:01:02 +0100 2026\n"
|
||||
"bob **Never logged in**\n"
|
||||
"deploy pts/1 198.51.100.7 Sat Aug 1 10:00:00 +0200 2026",
|
||||
),
|
||||
(
|
||||
"wtmp",
|
||||
"alice pts/0 192.0.2.10 2026-11-27T22:01:02+01:00 - 2026-11-27T23:00:00+01:00 (00:59)\n"
|
||||
"root tty1 2026-10-05T09:12:44+02:00 - 2026-10-05T09:20:00+02:00 (00:07)",
|
||||
),
|
||||
(
|
||||
"lastb",
|
||||
"alice ssh:notty 203.0.113.5 2026-11-28T01:02:03+01:00 - 2026-11-28T01:02:03+01:00 (00:00)\n"
|
||||
"alice ssh:notty 203.0.113.5 2026-11-28T01:02:01+01:00 - 2026-11-28T01:02:01+01:00 (00:00)\n"
|
||||
"alice ssh:notty 203.0.113.5 2026-11-26T08:00:00+01:00 - 2026-11-26T08:00:00+01:00 (00:00)\n"
|
||||
"root ssh:notty 203.0.113.9 2026-11-20T03:00:00+01:00 - 2026-11-20T03:00:00+01:00 (00:00)\n"
|
||||
"root ssh:notty 203.0.113.9 2026-11-19T03:00:00+01:00 - 2026-11-19T03:00:00+01:00 (00:00)",
|
||||
),
|
||||
("passwd_status root", "root P 2026-01-15 0 99999 7 -1"),
|
||||
(
|
||||
"chage root",
|
||||
"Last password change\t\t\t\t\t: Jan 15, 2026\n"
|
||||
"Password expires\t\t\t\t\t: never\n"
|
||||
"Password inactive\t\t\t\t\t: never\n"
|
||||
"Account expires\t\t\t\t\t\t: never\n"
|
||||
"Minimum number of days between password change\t\t: 0\n"
|
||||
"Maximum number of days between password change\t\t: 99999\n"
|
||||
"Number of days of warning before password expires\t: 7",
|
||||
),
|
||||
("passwd_status alice", "alice P 11/01/2026 0 90 7 -1"),
|
||||
(
|
||||
"chage alice",
|
||||
"Last password change\t\t\t\t\t: Nov 01, 2026\n"
|
||||
"Password expires\t\t\t\t\t: Jan 30, 2027\n"
|
||||
"Password inactive\t\t\t\t\t: never\n"
|
||||
"Account expires\t\t\t\t\t\t: Dec 31, 2026",
|
||||
),
|
||||
("passwd_status bob", "bob NP 2026-11-01 0 99999 7 -1"),
|
||||
(
|
||||
"chage bob",
|
||||
"Last password change\t\t\t\t\t: password must be changed\n"
|
||||
"Password expires\t\t\t\t\t: password must be changed\n"
|
||||
"Password inactive\t\t\t\t\t: password must be changed\n"
|
||||
"Account expires\t\t\t\t\t\t: never",
|
||||
),
|
||||
("passwd_status deploy", "deploy L 2026-08-01 0 99999 7 -1"),
|
||||
(
|
||||
"chage deploy",
|
||||
"Last password change\t\t\t\t\t: Aug 01, 2026\n"
|
||||
"Password expires\t\t\t\t\t: never\n"
|
||||
"Password inactive\t\t\t\t\t: never\n"
|
||||
"Account expires\t\t\t\t\t\t: Jan 02, 1970",
|
||||
),
|
||||
]
|
||||
|
||||
#: Debian 13 as root: lastlog2 and wtmpdb, no btmp; pam_faillock counts failures.
|
||||
DEBIAN_13 = [
|
||||
("uid", "0"),
|
||||
("now", "2026-11-28"),
|
||||
("passwd", "root:0:/root:/bin/bash\nalice:1000:/home/alice:/bin/bash"),
|
||||
(
|
||||
"lastlog2",
|
||||
"Username Port From Latest\n"
|
||||
"alice pts/2 2001:db8::5 Thu Nov 26 18:30:00 +0100 2026\n"
|
||||
"root **Never logged in**",
|
||||
),
|
||||
(
|
||||
"wtmpdb",
|
||||
"alice pts/3 2001:db8::6 2026-11-27T07:15:00+01:00 - 2026-11-27T07:20:00+01:00 (00:05)",
|
||||
),
|
||||
("passwd_status root", "root L 2026-11-01 0 99999 7 -1"),
|
||||
("chage root", "Account expires\t\t\t\t\t\t: never"),
|
||||
(
|
||||
"faillock root",
|
||||
"root:\nWhen Type Source Valid",
|
||||
),
|
||||
("passwd_status alice", "alice P 2026-11-01 0 99999 7 -1"),
|
||||
("chage alice", "Account expires\t\t\t\t\t\t: never"),
|
||||
(
|
||||
"faillock alice",
|
||||
"alice:\n"
|
||||
"When Type Source Valid\n"
|
||||
"2026-11-28 01:02:03 RHOST 203.0.113.5 V\n"
|
||||
"2026-11-28 01:02:09 RHOST 203.0.113.5 V\n"
|
||||
"2026-11-27 23:00:00 TTY tty2 I",
|
||||
),
|
||||
]
|
||||
|
||||
#: AlmaLinux 9 as root: libuser's ``passwd -S`` with its comment.
|
||||
ALMA_9 = [
|
||||
("uid", "0"),
|
||||
("now", "2026-11-28"),
|
||||
("passwd", "alice:1000:/home/alice:/bin/bash"),
|
||||
(
|
||||
"lastlog",
|
||||
"Username Port From Latest\n"
|
||||
"alice pts/0 192.0.2.10 Fri Nov 27 22:01:02 +0100 2026",
|
||||
),
|
||||
("passwd_status alice", "alice LK 2026-11-01 0 99999 7 -1 (Password locked.)"),
|
||||
("chage alice", "Account expires\t\t\t\t\t\t: never"),
|
||||
]
|
||||
|
||||
#: The same Debian host read as the login user: no root, so no lock, expiry or failures.
|
||||
AS_LOGIN_USER = [
|
||||
("uid", "1000"),
|
||||
("now", "2026-11-28"),
|
||||
("passwd", PASSWD),
|
||||
(
|
||||
"lastlog",
|
||||
"Username Port From Latest\n"
|
||||
"alice pts/0 192.0.2.10 Fri Nov 27 22:01:02 +0100 2026",
|
||||
),
|
||||
("passwd_status root", ""),
|
||||
("chage root", ""),
|
||||
("faillock root", ""),
|
||||
("passwd_status alice", ""),
|
||||
("chage alice", "Account expires\t\t\t\t\t\t: never"),
|
||||
("faillock alice", ""),
|
||||
]
|
||||
|
||||
|
||||
def _wire(sections: list[tuple[str, str]], *, noise: str = "") -> str:
|
||||
"""The report as the command prints it, framed."""
|
||||
body = "".join(f"[{name}]\n{text}\n" for name, text in sections)
|
||||
return f"{noise}LOGINS_BEGIN\n{body}LOGINS_END\n"
|
||||
|
||||
|
||||
def _by_name(reading):
|
||||
return {account["name"]: account for account in reading["accounts"]}
|
||||
|
||||
|
||||
class TestDebian12:
|
||||
def test_every_login_capable_account_in_passwd_order(self):
|
||||
reading = parse_login_accounts(_wire(DEBIAN_12))
|
||||
|
||||
assert [a["name"] for a in reading["accounts"]] == ["root", "alice", "bob", "deploy"]
|
||||
assert reading["privileged"] is True
|
||||
assert reading["login_sources"] == ["lastlog", "wtmp"]
|
||||
assert reading["failed_logins_source"] == "lastb"
|
||||
|
||||
def test_the_last_login_with_where_it_came_from(self):
|
||||
alice = _by_name(parse_login_accounts(_wire(DEBIAN_12)))["alice"]
|
||||
|
||||
assert alice["uid"] == 1000
|
||||
assert alice["home"] == "/home/alice"
|
||||
assert alice["shell"] == "/bin/bash"
|
||||
assert alice["last_login"] == "2026-11-27T21:01:02+00:00"
|
||||
assert alice["last_login_from"] == "192.0.2.10"
|
||||
assert alice["last_login_port"] == "pts/0"
|
||||
assert alice["last_login_source"] == "lastlog"
|
||||
|
||||
def test_never_logged_in(self):
|
||||
bob = _by_name(parse_login_accounts(_wire(DEBIAN_12)))["bob"]
|
||||
|
||||
assert bob["last_login"] is None
|
||||
assert bob["last_login_source"] is None
|
||||
|
||||
def test_a_console_login_has_a_port_and_no_host(self):
|
||||
root = _by_name(parse_login_accounts(_wire(DEBIAN_12)))["root"]
|
||||
|
||||
assert root["last_login"] == "2026-10-05T07:12:44+00:00"
|
||||
assert (root["last_login_port"], root["last_login_from"]) == ("tty1", None)
|
||||
|
||||
def test_password_and_expiry(self):
|
||||
accounts = _by_name(parse_login_accounts(_wire(DEBIAN_12)))
|
||||
|
||||
assert accounts["alice"]["password"] == "set"
|
||||
assert accounts["alice"]["password_changed"] == "2026-11-01"
|
||||
assert accounts["alice"]["password_expires"] == "2027-01-30"
|
||||
assert accounts["alice"]["account_expires"] == "2026-12-31"
|
||||
assert accounts["alice"]["locked"] is False
|
||||
assert accounts["root"]["password_expires"] == "never"
|
||||
assert accounts["root"]["account_expires"] == "never"
|
||||
|
||||
def test_no_password_that_must_be_changed(self):
|
||||
bob = _by_name(parse_login_accounts(_wire(DEBIAN_12)))["bob"]
|
||||
|
||||
assert bob["password"] == "none"
|
||||
assert bob["password_changed"] is None
|
||||
assert bob["password_expires"] == "must_change"
|
||||
assert bob["locked"] is False
|
||||
|
||||
def test_locked_as_netork_locks_an_account(self):
|
||||
"""``usermod -L -e 1``: the password locked and the account expired in 1970."""
|
||||
deploy = _by_name(parse_login_accounts(_wire(DEBIAN_12)))["deploy"]
|
||||
|
||||
assert deploy["password"] == "locked"
|
||||
assert deploy["account_expires"] == "1970-01-02"
|
||||
assert deploy["locked"] is True
|
||||
|
||||
def test_failed_logins_since_the_last_one_that_worked(self):
|
||||
accounts = _by_name(parse_login_accounts(_wire(DEBIAN_12)))
|
||||
|
||||
# alice's last login was 2026-11-27 22:01; two failures came after it.
|
||||
assert accounts["alice"]["failed_logins"] == 2
|
||||
# root last logged in on 2026-10-05: both failures are later.
|
||||
assert accounts["root"]["failed_logins"] == 2
|
||||
# No line in btmp: none, and btmp was read.
|
||||
assert accounts["bob"]["failed_logins"] == 0
|
||||
assert accounts["alice"]["failed_logins_capped"] is False
|
||||
|
||||
|
||||
class TestDebian13:
|
||||
def test_the_newest_login_over_every_source(self):
|
||||
"""lastlog2 saw alice on the 26th, wtmpdb on the 27th: the 27th is her last login."""
|
||||
reading = parse_login_accounts(_wire(DEBIAN_13))
|
||||
alice = _by_name(reading)["alice"]
|
||||
|
||||
assert reading["login_sources"] == ["lastlog2", "wtmpdb"]
|
||||
assert alice["last_login"] == "2026-11-27T06:15:00+00:00"
|
||||
assert alice["last_login_source"] == "wtmpdb"
|
||||
assert alice["last_login_from"] == "2001:db8::6"
|
||||
|
||||
def test_faillock_counts_its_valid_failures(self):
|
||||
reading = parse_login_accounts(_wire(DEBIAN_13))
|
||||
accounts = _by_name(reading)
|
||||
|
||||
assert reading["failed_logins_source"] == "faillock"
|
||||
assert accounts["alice"]["failed_logins"] == 2
|
||||
assert accounts["root"]["failed_logins"] == 0
|
||||
|
||||
def test_a_locked_password_locks_the_account(self):
|
||||
root = _by_name(parse_login_accounts(_wire(DEBIAN_13)))["root"]
|
||||
|
||||
assert (root["password"], root["locked"]) == ("locked", True)
|
||||
|
||||
|
||||
class TestAlma9:
|
||||
def test_libusers_status_words(self):
|
||||
alice = _by_name(parse_login_accounts(_wire(ALMA_9)))["alice"]
|
||||
|
||||
assert alice["password"] == "locked"
|
||||
assert alice["locked"] is True
|
||||
|
||||
def test_without_lastb_or_faillock_failures_are_unread(self):
|
||||
reading = parse_login_accounts(_wire(ALMA_9))
|
||||
|
||||
assert reading["failed_logins_source"] is None
|
||||
assert _by_name(reading)["alice"]["failed_logins"] is None
|
||||
|
||||
|
||||
class TestAsTheLoginUser:
|
||||
def test_what_needs_root_is_none(self):
|
||||
reading = parse_login_accounts(_wire(AS_LOGIN_USER))
|
||||
root = _by_name(reading)["root"]
|
||||
|
||||
assert reading["privileged"] is False
|
||||
assert reading["failed_logins_source"] is None
|
||||
assert root["password"] is None
|
||||
assert root["password_expires"] is None
|
||||
assert root["account_expires"] is None
|
||||
assert root["locked"] is None
|
||||
assert root["failed_logins"] is None
|
||||
|
||||
def test_the_last_login_is_still_read(self):
|
||||
alice = _by_name(parse_login_accounts(_wire(AS_LOGIN_USER)))["alice"]
|
||||
|
||||
assert alice["last_login"] == "2026-11-27T21:01:02+00:00"
|
||||
# Its own chage is readable without root.
|
||||
assert alice["account_expires"] == "never"
|
||||
|
||||
|
||||
class TestNotReadIsNone:
|
||||
def test_no_login_source_is_not_never(self):
|
||||
"""A host without any of the tools: the last login is unread, not "never"."""
|
||||
reading = parse_login_accounts(
|
||||
_wire([("uid", "0"), ("now", "2026-11-28"), ("passwd", PASSWD)])
|
||||
)
|
||||
|
||||
assert reading["login_sources"] == []
|
||||
assert all(a["last_login"] is None for a in reading["accounts"])
|
||||
|
||||
def test_output_without_the_frame_raises(self):
|
||||
with pytest.raises(ValueError):
|
||||
parse_login_accounts("sudo: a password is required\n")
|
||||
|
||||
def test_whatever_surrounds_the_frame_is_ignored(self):
|
||||
noise = "Last login: today\nprintf '%s%s\\n' LOGINS_ BEGIN; ...\n"
|
||||
|
||||
assert len(parse_login_accounts(_wire(DEBIAN_12, noise=noise))["accounts"]) == 4
|
||||
|
||||
def test_a_line_none_of_the_formats_knows_is_left_out(self):
|
||||
reading = parse_login_accounts(
|
||||
_wire(
|
||||
[
|
||||
("uid", "0"),
|
||||
("passwd", "alice:1000:/home/alice:/bin/bash\nbroken line"),
|
||||
("lastlog", "alice pts/0 somewhere yesterday"),
|
||||
("wtmp", "alice pts/0 nowhere\nwtmp begins 2026-01-01T00:00:00+00:00"),
|
||||
("passwd_status alice", "alice"),
|
||||
("chage alice", "Account expires : sometime"),
|
||||
]
|
||||
)
|
||||
)
|
||||
alice = _by_name(reading)["alice"]
|
||||
|
||||
assert [a["name"] for a in reading["accounts"]] == ["alice"]
|
||||
assert alice["last_login"] is None
|
||||
assert alice["password"] is None
|
||||
assert alice["account_expires"] is None
|
||||
assert alice["locked"] is None
|
||||
|
||||
|
||||
class TestFailedLogins:
|
||||
def test_without_a_last_login_every_failure_counts(self):
|
||||
reading = parse_login_accounts(
|
||||
_wire(
|
||||
[
|
||||
("uid", "0"),
|
||||
("passwd", "bob:1001:/home/bob:/bin/bash"),
|
||||
(
|
||||
"lastb",
|
||||
"bob ssh:notty 203.0.113.5 2026-11-28T01:02:03+01:00 - 2026-11-28T01:02:03+01:00 (00:00)",
|
||||
),
|
||||
]
|
||||
)
|
||||
)
|
||||
|
||||
assert _by_name(reading)["bob"]["failed_logins"] == 1
|
||||
|
||||
def test_a_full_read_is_capped(self):
|
||||
"""The command keeps the newest :data:`FAILED_LOGINS_READ` per account: a count
|
||||
that reaches it is "at least"."""
|
||||
line = "alice ssh:notty 203.0.113.5 2026-11-28T01:02:03+01:00 - 2026-11-28T01:02:03+01:00 (00:00)"
|
||||
reading = parse_login_accounts(
|
||||
_wire(
|
||||
[
|
||||
("uid", "0"),
|
||||
("passwd", "alice:1000:/home/alice:/bin/bash"),
|
||||
("lastb", "\n".join([line] * FAILED_LOGINS_READ)),
|
||||
]
|
||||
)
|
||||
)
|
||||
alice = _by_name(reading)["alice"]
|
||||
|
||||
assert alice["failed_logins"] == FAILED_LOGINS_READ
|
||||
assert alice["failed_logins_capped"] is True
|
||||
|
||||
|
||||
class TestLoginCapable:
|
||||
@pytest.mark.parametrize(
|
||||
"uid, shell, capable",
|
||||
[
|
||||
(0, "/bin/bash", True),
|
||||
(1000, "/bin/sh", True),
|
||||
(1000, "", True),
|
||||
(999, "/bin/bash", False),
|
||||
(65534, "/bin/sh", False),
|
||||
(1000, "/usr/sbin/nologin", False),
|
||||
(1000, "/sbin/nologin", False),
|
||||
(1000, "/bin/false", False),
|
||||
(1000, "/usr/bin/false", False),
|
||||
],
|
||||
)
|
||||
def test_root_and_people_with_a_shell(self, uid, shell, capable):
|
||||
assert login_capable(uid, shell) is capable
|
||||
|
||||
def test_a_service_account_in_passwd_is_left_out(self):
|
||||
reading = parse_login_accounts(
|
||||
_wire(
|
||||
[
|
||||
("uid", "0"),
|
||||
(
|
||||
"passwd",
|
||||
"root:0:/root:/bin/bash\n"
|
||||
"netork:900:/var/lib/netork:/bin/bash\n"
|
||||
"nobody:65534:/nonexistent:/usr/sbin/nologin\n"
|
||||
"svc:1003:/srv/svc:/usr/sbin/nologin",
|
||||
),
|
||||
]
|
||||
)
|
||||
)
|
||||
|
||||
assert [a["name"] for a in reading["accounts"]] == ["root"]
|
||||
|
||||
|
||||
class _Driver(OSDriver, LoginAccountsMixin):
|
||||
def __init__(self, outputs):
|
||||
self.outputs = list(outputs)
|
||||
self.calls: list[tuple[str, bool]] = []
|
||||
|
||||
def _run_login_accounts_command(self, command: str, *, privileged: bool) -> str:
|
||||
self.calls.append((command, privileged))
|
||||
return self.outputs.pop(0)
|
||||
|
||||
|
||||
class TestTheMixin:
|
||||
def test_read_as_root_first(self):
|
||||
driver = _Driver([_wire(DEBIAN_12)])
|
||||
|
||||
reading = driver.get_login_accounts()
|
||||
|
||||
assert driver.calls[0][1] is True
|
||||
assert reading["privileged"] is True
|
||||
|
||||
def test_root_refused_reads_as_the_login_user(self):
|
||||
driver = _Driver(["sudo: a password is required\n", _wire(AS_LOGIN_USER)])
|
||||
|
||||
reading = driver.get_login_accounts()
|
||||
|
||||
assert [privileged for _, privileged in driver.calls] == [True, False]
|
||||
assert reading["privileged"] is False
|
||||
|
||||
def test_the_command_goes_to_sh(self):
|
||||
driver = _Driver([_wire(ALMA_9)])
|
||||
|
||||
driver.get_login_accounts()
|
||||
|
||||
assert driver.calls[0][0].startswith("sh -c ")
|
||||
|
||||
|
||||
class TestTheCommand:
|
||||
def test_the_frame_is_not_in_the_command_itself(self):
|
||||
assert "LOGINS_BEGIN" not in LOGIN_ACCOUNTS_COMMAND
|
||||
assert "LOGINS_END" not in LOGIN_ACCOUNTS_COMMAND
|
||||
|
||||
def test_it_changes_nothing(self):
|
||||
for verb in ("usermod", "passwd -l", "chage -E", "--reset", "lastlog2 -C", " > ", ">>"):
|
||||
assert verb not in LOGIN_ACCOUNTS_COMMAND
|
||||
|
||||
def test_it_reads_no_stdin_and_sends_no_password_hash(self):
|
||||
"""A sudo password on stdin must not reach a tool; the hashes in ``/etc/shadow``
|
||||
are never read: ``passwd -S`` and ``chage -l`` say what is needed."""
|
||||
assert LOGIN_ACCOUNTS_COMMAND.startswith("exec </dev/null; ")
|
||||
assert "shadow" not in LOGIN_ACCOUNTS_COMMAND
|
||||
|
||||
def test_no_gecos_field_leaves_the_host(self):
|
||||
"""The fifth field of ``/etc/passwd`` is a person's name; only name, uid, home and
|
||||
shell are printed."""
|
||||
assert '{print $1":"$3":"$6":"$7}' in LOGIN_ACCOUNTS_COMMAND
|
||||
|
||||
@pytest.mark.skipif(os.uname().sysname != "Linux", reason="reads a Linux host")
|
||||
def test_it_runs_and_parses_on_this_host(self):
|
||||
out = subprocess.run(
|
||||
["sh", "-c", LOGIN_ACCOUNTS_COMMAND], capture_output=True, text=True, timeout=60
|
||||
).stdout
|
||||
|
||||
reading = parse_login_accounts(out)
|
||||
|
||||
assert isinstance(reading["accounts"], list)
|
||||
@@ -0,0 +1,286 @@
|
||||
"""The record of the firewall rules netOrk opened on a host (NetOrk/netork#2693)."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import os
|
||||
import subprocess
|
||||
|
||||
import pytest
|
||||
|
||||
from napalm_device_types.opened_ports import (
|
||||
OPENED_PORTS_RECORD,
|
||||
OpenedRuleDict,
|
||||
opened_rule_line,
|
||||
opened_rules_text,
|
||||
parse_opened_ports_record,
|
||||
read_opened_ports_command,
|
||||
record_opened_rule_command,
|
||||
revoke_recorded_rules,
|
||||
revoked_output,
|
||||
ufw_allow_recorded_command,
|
||||
ufw_delete_command,
|
||||
)
|
||||
|
||||
UFW: OpenedRuleDict = {
|
||||
"purpose": "zabbix-agent",
|
||||
"backend": "ufw",
|
||||
"proto": "tcp",
|
||||
"port": 10050,
|
||||
"source": "10.40.100.254/32",
|
||||
"zone": "",
|
||||
"permanent": True,
|
||||
}
|
||||
FIREWALLD: OpenedRuleDict = {**UFW, "backend": "firewalld", "zone": "public", "permanent": False}
|
||||
|
||||
ROOT_DIR = "0 755 directory"
|
||||
ROOT_FILE = "0 644 regular file"
|
||||
|
||||
|
||||
def _read(*lines: str, directory: str = ROOT_DIR, record: str = ROOT_FILE) -> str:
|
||||
return "\n".join([directory, record, *lines]) + "\n"
|
||||
|
||||
|
||||
class TestTheLine:
|
||||
def test_ufw(self):
|
||||
assert opened_rule_line(UFW) == "v1 zabbix-agent ufw tcp 10050 10.40.100.254/32"
|
||||
|
||||
def test_firewalld_names_zone_and_configuration(self):
|
||||
assert opened_rule_line(FIREWALLD) == (
|
||||
"v1 zabbix-agent firewalld tcp 10050 10.40.100.254/32 public runtime"
|
||||
)
|
||||
|
||||
def test_a_line_reads_back_as_the_rule(self):
|
||||
for rule in (UFW, FIREWALLD, {**UFW, "backend": "iptables", "source": "2001:db8::/64"}):
|
||||
record = parse_opened_ports_record(_read(opened_rule_line(rule)))
|
||||
assert record["rules"] == [rule]
|
||||
assert record["unknown"] == []
|
||||
assert record["problem"] == ""
|
||||
|
||||
|
||||
class TestStrictReading:
|
||||
@pytest.mark.parametrize(
|
||||
"line",
|
||||
[
|
||||
"v2 zabbix-agent ufw tcp 10050 10.0.0.1/32",
|
||||
"v1 zabbix-agent nft tcp 10050 10.0.0.1/32",
|
||||
"v1 zabbix-agent ufw icmp 10050 10.0.0.1/32",
|
||||
"v1 zabbix-agent ufw tcp 0 10.0.0.1/32",
|
||||
"v1 zabbix-agent ufw tcp 70000 10.0.0.1/32",
|
||||
"v1 zabbix-agent ufw tcp 10050 10.0.0.1",
|
||||
"v1 zabbix-agent ufw tcp 10050 10.0.0.0/8;reboot",
|
||||
"v1 zabbix-agent ufw tcp 10050 any",
|
||||
"v1 Zabbix_Agent ufw tcp 10050 10.0.0.1/32",
|
||||
"v1 zabbix-agent ufw tcp 10050 10.0.0.1/32 public runtime",
|
||||
"v1 zabbix-agent firewalld tcp 10050 10.0.0.1/32",
|
||||
"v1 zabbix-agent firewalld tcp 10050 10.0.0.1/32 $(id) runtime",
|
||||
"v1 zabbix-agent firewalld tcp 10050 10.0.0.1/32 public sometimes",
|
||||
"v1 zabbix-agent ufw tcp 10050 10.0.0.1/32",
|
||||
],
|
||||
)
|
||||
def test_a_line_that_is_not_exactly_a_rule_is_not_acted_on(self, line):
|
||||
record = parse_opened_ports_record(_read(line))
|
||||
|
||||
assert record["rules"] == []
|
||||
assert record["unknown"] == [line]
|
||||
|
||||
def test_blank_lines_are_neither(self):
|
||||
record = parse_opened_ports_record(_read("", opened_rule_line(UFW), " "))
|
||||
|
||||
assert record["rules"] == [UFW]
|
||||
assert record["unknown"] == []
|
||||
|
||||
def test_no_record_is_no_rules(self):
|
||||
record = parse_opened_ports_record("")
|
||||
|
||||
assert record == {"rules": [], "unknown": [], "problem": ""}
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
("directory", "record", "why"),
|
||||
[
|
||||
("1000 755 directory", ROOT_FILE, "not root's"),
|
||||
("0 775 directory", ROOT_FILE, "writable"),
|
||||
(ROOT_DIR, "1000 644 regular file", "not root's"),
|
||||
(ROOT_DIR, "0 666 regular file", "writable"),
|
||||
(ROOT_DIR, "0 777 symbolic link", "not a regular file"),
|
||||
("0 755 symbolic link", ROOT_FILE, "not a directory"),
|
||||
],
|
||||
)
|
||||
def test_a_record_others_could_have_written_is_not_read(self, directory, record, why):
|
||||
read = parse_opened_ports_record(
|
||||
_read(opened_rule_line(UFW), directory=directory, record=record)
|
||||
)
|
||||
|
||||
assert read["rules"] == []
|
||||
assert why in read["problem"]
|
||||
|
||||
def test_a_read_that_says_nothing_about_owner_and_mode_is_not_trusted(self):
|
||||
read = parse_opened_ports_record("v1 zabbix-agent ufw tcp 10050 10.0.0.1/32\n")
|
||||
|
||||
assert read["rules"] == []
|
||||
assert read["problem"]
|
||||
|
||||
|
||||
class TestCommands:
|
||||
def test_reading_says_owner_mode_and_kind_of_the_directory_and_the_file(self):
|
||||
command = read_opened_ports_command()
|
||||
|
||||
assert "stat -c '%u %a %F' /var/lib/netork " + OPENED_PORTS_RECORD in command
|
||||
assert f"cat {OPENED_PORTS_RECORD}" in command
|
||||
assert "exit" not in command
|
||||
|
||||
def test_recording_creates_root_s_directory_and_appends_the_line(self):
|
||||
command = record_opened_rule_command(opened_rule_line(UFW))
|
||||
|
||||
assert command.startswith("install -d -m 755 -o root -g root /var/lib/netork")
|
||||
assert f"printf '%s\\n' \"{opened_rule_line(UFW)}\" >> {OPENED_PORTS_RECORD}" in command
|
||||
assert f"chmod 644 {OPENED_PORTS_RECORD}" in command
|
||||
|
||||
def test_recording_takes_a_firewalld_zone_from_the_shell(self):
|
||||
line = opened_rule_line({**FIREWALLD, "zone": "$z"})
|
||||
|
||||
assert '"v1 zabbix-agent firewalld tcp 10050 10.40.100.254/32 $z runtime"' in (
|
||||
record_opened_rule_command(line)
|
||||
)
|
||||
|
||||
@pytest.mark.parametrize("line", ['v1 "; rm -rf /', "v1 `id`", "v1 a\nb", "v1 $(id)"])
|
||||
def test_recording_refuses_what_is_not_a_line(self, line):
|
||||
with pytest.raises(ValueError):
|
||||
record_opened_rule_command(line)
|
||||
|
||||
def test_ufw_records_a_rule_only_when_ufw_added_it(self):
|
||||
command = ufw_allow_recorded_command("10.40.100.254/32", 10050, "tcp", "zabbix-agent")
|
||||
|
||||
assert "LC_ALL=C ufw allow from 10.40.100.254/32 to any port 10050 proto tcp" in command
|
||||
# ufw says "Skipping adding existing rule" for a rule it had: someone else's.
|
||||
assert "*Skipping*) ;;" in command
|
||||
assert "*'Rule added'*|*'Rules updated'*)" in command
|
||||
assert opened_rule_line(UFW) in command
|
||||
assert "exit" not in command
|
||||
|
||||
def test_ufw_delete(self):
|
||||
assert (
|
||||
"LC_ALL=C ufw delete allow from 10.40.100.254/32 to any port 10050 proto tcp"
|
||||
in ufw_delete_command(UFW)
|
||||
)
|
||||
assert "exit" not in ufw_delete_command(UFW)
|
||||
|
||||
|
||||
def _shell(tmp_path, command: str, ufw_says: str, ufw_status: int = 0):
|
||||
"""Run *command* with a fake ufw that answers *ufw_says*, the record under *tmp_path*."""
|
||||
fake = tmp_path / "bin" / "ufw"
|
||||
fake.parent.mkdir(exist_ok=True)
|
||||
fake.write_text(f"#!/bin/sh\necho '{ufw_says}'\nexit {ufw_status}\n")
|
||||
fake.chmod(0o755)
|
||||
record = tmp_path / "netork" / "opened-ports"
|
||||
command = command.replace(
|
||||
"install -d -m 755 -o root -g root /var/lib/netork", f"mkdir -p {record.parent}"
|
||||
).replace(OPENED_PORTS_RECORD, str(record))
|
||||
done = subprocess.run(
|
||||
["sh", "-c", command],
|
||||
env={**os.environ, "PATH": f"{fake.parent}:{os.environ['PATH']}"},
|
||||
capture_output=True,
|
||||
text=True,
|
||||
)
|
||||
return done, (record.read_text() if record.exists() else "")
|
||||
|
||||
|
||||
class TestUfwOnAShell:
|
||||
COMMAND = ufw_allow_recorded_command("10.40.100.254/32", 10050, "tcp", "zabbix-agent")
|
||||
|
||||
@pytest.mark.parametrize("says", ["Rule added", "Rules updated"])
|
||||
def test_a_rule_ufw_added_is_recorded(self, tmp_path, says):
|
||||
done, record = _shell(tmp_path, self.COMMAND, says)
|
||||
|
||||
assert done.returncode == 0, done.stderr
|
||||
assert record == opened_rule_line(UFW) + "\n"
|
||||
|
||||
def test_a_rule_ufw_had_is_not_recorded(self, tmp_path):
|
||||
done, record = _shell(tmp_path, self.COMMAND, "Skipping adding existing rule")
|
||||
|
||||
assert done.returncode == 0, done.stderr
|
||||
assert record == ""
|
||||
|
||||
def test_a_refused_rule_fails_and_is_not_recorded(self, tmp_path):
|
||||
done, record = _shell(tmp_path, self.COMMAND, "ERROR: Bad port", ufw_status=1)
|
||||
|
||||
assert done.returncode != 0
|
||||
assert "Bad port" in done.stdout
|
||||
assert record == ""
|
||||
|
||||
def test_deleting_a_rule_ufw_no_longer_has_is_done(self, tmp_path):
|
||||
done, _ = _shell(
|
||||
tmp_path, ufw_delete_command(UFW), "Could not delete non-existent rule", ufw_status=1
|
||||
)
|
||||
|
||||
assert done.returncode == 0
|
||||
|
||||
def test_a_delete_ufw_refuses_fails(self, tmp_path):
|
||||
done, _ = _shell(tmp_path, ufw_delete_command(UFW), "ERROR: problem", ufw_status=1)
|
||||
|
||||
assert done.returncode != 0
|
||||
assert "problem" in done.stdout
|
||||
|
||||
def test_rules_text_keeps_what_it_is_given_one_per_line(self):
|
||||
assert opened_rules_text([]) == ""
|
||||
assert opened_rules_text(["a", "b"]) == "a\nb\n"
|
||||
|
||||
|
||||
class TestReport:
|
||||
def test_removed_rules_are_named(self):
|
||||
output = revoked_output([UFW], unknown=[], left=0, proto="tcp", port=10050)
|
||||
|
||||
assert "removed" in output
|
||||
assert "10.40.100.254/32" in output
|
||||
|
||||
def test_without_a_recorded_rule_it_says_so(self):
|
||||
assert "netOrk recorded no rule" in revoked_output(
|
||||
[], unknown=[], left=0, proto="tcp", port=10050
|
||||
)
|
||||
|
||||
def test_rules_netork_did_not_record_are_reported_not_removed(self):
|
||||
output = revoked_output([], unknown=[], left=2, proto="tcp", port=10050)
|
||||
|
||||
assert "2 rule(s) for tcp/10050" in output
|
||||
assert "left in place" in output
|
||||
|
||||
def test_lines_it_could_not_read_are_reported(self):
|
||||
output = revoked_output([], unknown=["v9 x"], left=0, proto="tcp", port=10050)
|
||||
|
||||
assert "v9 x" in output
|
||||
|
||||
|
||||
class TestRevoking:
|
||||
SNMP: OpenedRuleDict = {**UFW, "purpose": "snmp", "proto": "udp", "port": 161}
|
||||
EARLIER_PORT: OpenedRuleDict = {**UFW, "port": 10051}
|
||||
|
||||
def _record(self, *lines):
|
||||
return parse_opened_ports_record(_read(*lines))
|
||||
|
||||
def test_only_the_purpose_s_rules_go_whatever_their_port(self):
|
||||
record = self._record(
|
||||
opened_rule_line(UFW),
|
||||
opened_rule_line(self.SNMP),
|
||||
"v9 not a rule",
|
||||
opened_rule_line(self.EARLIER_PORT),
|
||||
)
|
||||
asked: list[OpenedRuleDict] = []
|
||||
|
||||
done = revoke_recorded_rules(
|
||||
record, "zabbix-agent", lambda r: asked.append(r) or {"ok": True, "output": ""}
|
||||
)
|
||||
|
||||
assert asked == [UFW, self.EARLIER_PORT]
|
||||
assert done["removed"] == [UFW, self.EARLIER_PORT]
|
||||
assert done["record"] == f"{opened_rule_line(self.SNMP)}\nv9 not a rule\n"
|
||||
assert done["failed"] == []
|
||||
|
||||
def test_a_rule_that_will_not_go_stays_and_says_why(self):
|
||||
record = self._record(opened_rule_line(UFW))
|
||||
|
||||
done = revoke_recorded_rules(
|
||||
record, "zabbix-agent", lambda r: {"ok": False, "output": "ufw: locked"}
|
||||
)
|
||||
|
||||
assert done["removed"] == []
|
||||
assert done["record"] == f"{opened_rule_line(UFW)}\n"
|
||||
assert done["failed"] == [f"{opened_rule_line(UFW)}: ufw: locked"]
|
||||
@@ -0,0 +1,68 @@
|
||||
"""Contracts Proxmox VE 9.3 made worth having, kept neutral (NetOrk/netork#2728).
|
||||
|
||||
A guest identity that survives a changed ID, the expiry of the credential a
|
||||
driver logs in with, and what a host's package manager did in the past: each a
|
||||
shape every driver of its kind can fill, with the platform's own calls left to
|
||||
the driver.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import typing
|
||||
from typing import get_type_hints
|
||||
|
||||
from napalm_device_types import (
|
||||
CredentialExpiryDict,
|
||||
CredentialExpiryMixin,
|
||||
UpdateHistoryDict,
|
||||
UpdateHistoryPackageDict,
|
||||
UpdateMixin,
|
||||
)
|
||||
from napalm_device_types.models import VMDict
|
||||
|
||||
|
||||
def test_a_vm_may_carry_an_identity_that_outlives_its_vmid():
|
||||
assert "uid" in get_type_hints(VMDict)
|
||||
assert "uid" in VMDict.__optional_keys__
|
||||
|
||||
|
||||
def test_a_credential_expiry_names_the_credential_and_when_it_ends():
|
||||
assert set(get_type_hints(CredentialExpiryDict)) == {"kind", "name", "expires"}
|
||||
kinds = typing.get_args(get_type_hints(CredentialExpiryDict)["kind"])
|
||||
assert set(kinds) == {"api-token", "account"}
|
||||
|
||||
|
||||
def test_credential_expiry_is_a_contract_not_a_placeholder():
|
||||
assert not hasattr(CredentialExpiryMixin, "get_credential_expiry")
|
||||
|
||||
|
||||
def test_an_update_transaction_is_its_packages_and_who_asked_for_it():
|
||||
assert set(get_type_hints(UpdateHistoryDict)) == {
|
||||
"id",
|
||||
"start",
|
||||
"end",
|
||||
"packages",
|
||||
"requested_by",
|
||||
"command",
|
||||
"error",
|
||||
}
|
||||
assert set(get_type_hints(UpdateHistoryPackageDict)) == {
|
||||
"name",
|
||||
"action",
|
||||
"old_version",
|
||||
"new_version",
|
||||
}
|
||||
actions = typing.get_args(get_type_hints(UpdateHistoryPackageDict)["action"])
|
||||
assert set(actions) == {
|
||||
"install",
|
||||
"reinstall",
|
||||
"upgrade",
|
||||
"downgrade",
|
||||
"remove",
|
||||
"purge",
|
||||
"disappear",
|
||||
}
|
||||
|
||||
|
||||
def test_update_history_is_declared_next_to_pending_updates():
|
||||
assert not hasattr(UpdateMixin, "get_update_history")
|
||||
@@ -0,0 +1,29 @@
|
||||
"""A radio's runtime state beside its configuration (NetOrk/netork#31).
|
||||
|
||||
A radio can be enabled in the configuration and still not run: the 2026-07-16
|
||||
incident put every radio of a fleet into a restart loop that the configuration
|
||||
never showed. The state the device reports is three facts, each optional,
|
||||
because a driver that cannot read it leaves it out rather than guessing.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from typing import get_type_hints
|
||||
|
||||
from napalm_device_types.models import RadioStatusDict
|
||||
|
||||
RUNTIME = {"up", "pending", "setup_failed"}
|
||||
|
||||
|
||||
def test_a_radio_may_say_whether_it_runs():
|
||||
hints = get_type_hints(RadioStatusDict)
|
||||
assert RUNTIME <= set(hints)
|
||||
assert all(hints[key] is bool for key in RUNTIME)
|
||||
|
||||
|
||||
def test_the_runtime_state_is_optional():
|
||||
assert RUNTIME <= RadioStatusDict.__optional_keys__
|
||||
|
||||
|
||||
def test_the_configured_fields_stay_required():
|
||||
assert {"enabled", "band", "channel"} <= RadioStatusDict.__required_keys__
|
||||
@@ -12,6 +12,7 @@ These tests pin the property that prevents a fourth.
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import ast
|
||||
import inspect
|
||||
|
||||
import pytest
|
||||
@@ -82,6 +83,7 @@ class TestDeclaredMethodsDoNotExistAtRuntime:
|
||||
(StorageDriver, "get_disks"),
|
||||
(StorageDriver, "get_volumes"),
|
||||
(HypervisorDriver, "get_vms"),
|
||||
(HypervisorDriver, "resume_vm"),
|
||||
(FirewallDriver, "send_wake_on_lan"),
|
||||
(SwitchDriver, "set_vlan"),
|
||||
(AccessPointDriver, "get_wireless_config"),
|
||||
@@ -101,6 +103,27 @@ class TestDeclaredMethodsDoNotExistAtRuntime:
|
||||
assert not hasattr(base, method)
|
||||
|
||||
|
||||
class TestHypervisorPowerContract:
|
||||
"""The power actions a hypervisor driver may implement, as declared."""
|
||||
|
||||
@staticmethod
|
||||
def _declared(module) -> dict[str, list[str]]:
|
||||
tree = ast.parse(inspect.getsource(module))
|
||||
methods: dict[str, list[str]] = {}
|
||||
for node in ast.walk(tree):
|
||||
if isinstance(node, ast.FunctionDef):
|
||||
methods[node.name] = [a.arg for a in node.args.args]
|
||||
return methods
|
||||
|
||||
def test_resume_vm_is_declared_beside_suspend_vm(self):
|
||||
"""A VM netOrk paused must be one it can bring back (NetOrk/netork#2658)."""
|
||||
from napalm_device_types import hypervisor
|
||||
|
||||
declared = self._declared(hypervisor)
|
||||
assert declared.get("suspend_vm") == ["self", "name"]
|
||||
assert declared.get("resume_vm") == ["self", "name"]
|
||||
|
||||
|
||||
class TestNoShadowingAcrossRoles:
|
||||
"""The regression test for the bug class."""
|
||||
|
||||
|
||||
@@ -0,0 +1,334 @@
|
||||
"""get_services_need_restart: which services still run the code an update replaced.
|
||||
|
||||
An upgrade of openssl or glibc replaces the files on disk; every daemon that had
|
||||
them loaded keeps running the old code until it restarts (NetOrk/netork#2700).
|
||||
The host's own tools say which: ``needs-restarting -s`` on the dnf family,
|
||||
``needrestart -b`` on Debian and Ubuntu, and on a host with neither the
|
||||
processes that map a deleted library (``/proc/<pid>/maps``). Each process is
|
||||
then the systemd unit its cgroup names, as for the listening sockets.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import shutil
|
||||
import subprocess
|
||||
|
||||
import pytest
|
||||
|
||||
from napalm_device_types import OSDriver
|
||||
from napalm_device_types.services_restart import (
|
||||
DELETED_CODE_PATTERN,
|
||||
SERVICES_RESTART_COMMAND,
|
||||
ServicesRestartMixin,
|
||||
parse_services_restart,
|
||||
)
|
||||
|
||||
CID = "4f1c" + "0" * 60
|
||||
|
||||
#: One host after an openssl update: sshd, nginx (two workers), postgres and a
|
||||
#: user's systemd manager still map the old library.
|
||||
NEEDS_RESTARTING = """Updating Subscription Management repositories.
|
||||
sshd.service
|
||||
nginx.service
|
||||
postgresql@16-main.service
|
||||
user@1000.service
|
||||
"""
|
||||
NEEDRESTART = """NEEDRESTART-VER: 3.6
|
||||
NEEDRESTART-KCUR: 6.8.0-87-generic
|
||||
NEEDRESTART-KEXP: 6.8.0-87-generic
|
||||
NEEDRESTART-KSTA: 1
|
||||
NEEDRESTART-SVC: sshd.service
|
||||
NEEDRESTART-SVC: nginx.service
|
||||
NEEDRESTART-SVC: postgresql@16-main.service
|
||||
NEEDRESTART-SVC: user@1000.service
|
||||
NEEDRESTART-SESS: alice @ session #3
|
||||
"""
|
||||
MAPS = """700 sshd
|
||||
900 nginx
|
||||
901 nginx
|
||||
812 postgres
|
||||
1500 systemd
|
||||
1501 tmux: server
|
||||
1300 node_exporter
|
||||
"""
|
||||
CGROUPS = f"""700 0::/system.slice/sshd.service
|
||||
900 0::/system.slice/nginx.service
|
||||
901 0::/system.slice/nginx.service
|
||||
812 0::/system.slice/system-postgresql.slice/postgresql@16-main.service
|
||||
1500 0::/user.slice/user-1000.slice/user@1000.service/init.scope
|
||||
1501 0::/user.slice/user-1000.slice/session-3.scope
|
||||
1300 0::/system.slice/docker-{CID}.scope
|
||||
"""
|
||||
UNITS = ["nginx", "postgresql@16-main", "sshd", "user@1000"]
|
||||
|
||||
|
||||
def _wire(*sections: tuple[str, str], noise: str = "") -> str:
|
||||
"""The report as the command prints it, framed."""
|
||||
body = "".join(f"[{name}]\n{text}" for name, text in sections)
|
||||
return f"{noise}RST_BEGIN\n{body}RST_END\n"
|
||||
|
||||
|
||||
class TestTheThreeSourcesAgree:
|
||||
def test_needs_restarting(self):
|
||||
reading = parse_services_restart(_wire(("needs-restarting", NEEDS_RESTARTING)))
|
||||
|
||||
assert reading == {"source": "needs-restarting", "units": UNITS, "processes": []}
|
||||
|
||||
def test_needrestart(self):
|
||||
reading = parse_services_restart(_wire(("needrestart", NEEDRESTART)))
|
||||
|
||||
assert reading == {"source": "needrestart", "units": UNITS, "processes": []}
|
||||
|
||||
def test_the_maps_scan(self):
|
||||
reading = parse_services_restart(_wire(("maps", MAPS), ("cgroups", CGROUPS)))
|
||||
|
||||
assert reading["source"] == "maps"
|
||||
assert reading["units"] == UNITS
|
||||
|
||||
def test_the_maps_scan_names_the_processes_without_a_unit(self):
|
||||
reading = parse_services_restart(_wire(("maps", MAPS), ("cgroups", CGROUPS)))
|
||||
|
||||
assert reading["processes"] == [{"pid": 1501, "name": "tmux: server"}]
|
||||
|
||||
|
||||
class TestNothingToRestart:
|
||||
@pytest.mark.parametrize(
|
||||
"sections",
|
||||
[
|
||||
(("needs-restarting", ""),),
|
||||
(("needrestart", "NEEDRESTART-VER: 3.6\nNEEDRESTART-KSTA: 1\n"),),
|
||||
(("maps", ""), ("cgroups", "")),
|
||||
],
|
||||
)
|
||||
def test_a_clean_reading_is_an_empty_list(self, sections):
|
||||
reading = parse_services_restart(_wire(*sections))
|
||||
|
||||
assert reading["units"] == [] and reading["processes"] == []
|
||||
|
||||
|
||||
class TestTheMapsScan:
|
||||
def test_a_container_is_left_out(self):
|
||||
"""A container runs its image's libraries, which no host update replaces."""
|
||||
reading = parse_services_restart(
|
||||
_wire(("maps", "1300 node_exporter\n"), ("cgroups", CGROUPS))
|
||||
)
|
||||
|
||||
assert reading == {"source": "maps", "units": [], "processes": []}
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
"cgroup",
|
||||
[
|
||||
# Proxmox VE: the container's own systemd, under lxc/<vmid>/ns.
|
||||
"0::/lxc/101/ns/system.slice/nginx.service",
|
||||
"0::/lxc/101/ns/init.scope",
|
||||
# LXC 4 and later by default.
|
||||
"0::/lxc.payload.web/system.slice/nginx.service",
|
||||
# cgroup v1, systemd's hierarchy.
|
||||
"12:name=systemd:/lxc/web/system.slice/nginx.service",
|
||||
],
|
||||
)
|
||||
def test_an_lxc_container_is_left_out(self, cgroup):
|
||||
"""A Proxmox node's containers update themselves: the host sees their processes'
|
||||
mappings, and their own systemd's units, which are no services of the host's."""
|
||||
cgroups = f"2100 {cgroup}\n"
|
||||
|
||||
reading = parse_services_restart(_wire(("maps", "2100 nginx\n"), ("cgroups", cgroups)))
|
||||
|
||||
assert reading == {"source": "maps", "units": [], "processes": []}
|
||||
|
||||
def test_an_lxc_monitor_is_the_hosts(self):
|
||||
"""``lxc-start`` runs the host's own binary, outside the container."""
|
||||
reading = parse_services_restart(
|
||||
_wire(("maps", "2090 lxc-start\n"), ("cgroups", "2090 0::/lxc.monitor/101\n"))
|
||||
)
|
||||
|
||||
assert reading["processes"] == [{"pid": 2090, "name": "lxc-start"}]
|
||||
|
||||
def test_a_process_gone_before_its_cgroup_was_read_has_no_unit(self):
|
||||
reading = parse_services_restart(_wire(("maps", "4242 cron\n"), ("cgroups", "")))
|
||||
|
||||
assert reading["processes"] == [{"pid": 4242, "name": "cron"}]
|
||||
|
||||
def test_cgroup_v1_reads_the_systemd_hierarchy(self):
|
||||
cgroups = "700 12:name=systemd:/system.slice/sshd.service\n700 3:cpu:/\n"
|
||||
|
||||
reading = parse_services_restart(_wire(("maps", "700 sshd\n"), ("cgroups", cgroups)))
|
||||
|
||||
assert reading["units"] == ["sshd"]
|
||||
|
||||
def test_pid_1_is_a_process_without_a_unit(self):
|
||||
"""systemd itself needs ``daemon-reexec``, not a unit restart."""
|
||||
reading = parse_services_restart(
|
||||
_wire(("maps", "1 systemd\n"), ("cgroups", "1 0::/init.scope\n"))
|
||||
)
|
||||
|
||||
assert reading["processes"] == [{"pid": 1, "name": "systemd"}]
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
"line",
|
||||
[
|
||||
"7f2a1c000000-7f2a1c1a0000 r-xp 00028000 fd:00 131 /usr/lib/x86_64-linux-gnu/libc.so.6 (deleted)",
|
||||
"55d0c0000000-55d0c0100000 r-xp 00000000 fd:00 99 /usr/sbin/sshd (deleted)",
|
||||
"7f00-7f10 r-xp 00000000 fd:00 7 /lib64/libssl.so.3 (deleted)",
|
||||
"7f00-7f10 r-xp 00000000 fd:00 7 /opt/app/lib/libfoo.so (deleted)",
|
||||
],
|
||||
)
|
||||
def test_replaced_code_counts(self, line):
|
||||
assert (
|
||||
subprocess.run(["grep", "-qE", DELETED_CODE_PATTERN], input=line, text=True).returncode
|
||||
== 0
|
||||
)
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
"line",
|
||||
[
|
||||
# Code still on disk.
|
||||
"7f2a1c000000-7f2a1c1a0000 r-xp 00028000 fd:00 131 /usr/lib/x86_64-linux-gnu/libc.so.6",
|
||||
# Data, not code: the locale archive an update replaced.
|
||||
"7f00-7f10 r--p 00000000 fd:00 7 /usr/lib/locale/locale-archive (deleted)",
|
||||
# Deleted on purpose: shared memory, memfd, a temporary file.
|
||||
"7f00-7f10 rw-s 00000000 00:01 7 /SYSV00000000 (deleted)",
|
||||
"7f00-7f10 r-xp 00000000 00:01 7 /memfd:jit (deleted)",
|
||||
"7f00-7f10 r-xp 00000000 00:01 7 /tmp/ffiXyz (deleted)",
|
||||
"7f00-7f10 r-xp 00000000 00:01 7 /dev/shm/pulse-shm-1 (deleted)",
|
||||
],
|
||||
)
|
||||
def test_what_is_not_replaced_code(self, line):
|
||||
assert (
|
||||
subprocess.run(["grep", "-qE", DELETED_CODE_PATTERN], input=line, text=True).returncode
|
||||
== 1
|
||||
)
|
||||
|
||||
|
||||
class TestFailures:
|
||||
def test_whatever_surrounds_the_frame_is_ignored(self):
|
||||
reading = parse_services_restart(
|
||||
_wire(("needs-restarting", "sshd.service\n"), noise="[sudo] password for netork:\n")
|
||||
)
|
||||
|
||||
assert reading["units"] == ["sshd"]
|
||||
|
||||
def test_output_without_the_frame_raises(self):
|
||||
"""sudo refused: the script never ran, and that is no clean reading."""
|
||||
with pytest.raises(ValueError):
|
||||
parse_services_restart("sudo: a password is required\n")
|
||||
|
||||
def test_a_report_cut_short_raises(self):
|
||||
with pytest.raises(ValueError):
|
||||
parse_services_restart("RST_BEGIN\n[needs-restarting]\nsshd.service\n")
|
||||
|
||||
def test_a_report_without_a_source_raises(self):
|
||||
with pytest.raises(ValueError):
|
||||
parse_services_restart("RST_BEGIN\nRST_END\n")
|
||||
|
||||
|
||||
def _stub(tmp_path, name: str, script: str) -> None:
|
||||
stub = tmp_path / name
|
||||
stub.write_text(f"#!/bin/sh\n{script}\n")
|
||||
stub.chmod(0o755)
|
||||
|
||||
|
||||
def _run(tmp_path) -> str:
|
||||
for tool in ("cat", "grep", "sed", "printf"):
|
||||
if shutil.which(tool):
|
||||
(tmp_path / tool).symlink_to(shutil.which(tool))
|
||||
return subprocess.run(
|
||||
["/bin/sh", "-c", SERVICES_RESTART_COMMAND],
|
||||
capture_output=True,
|
||||
text=True,
|
||||
env={"PATH": str(tmp_path)},
|
||||
timeout=60,
|
||||
).stdout
|
||||
|
||||
|
||||
class TestTheOrderOfPreference:
|
||||
def test_needs_restarting_first(self, tmp_path):
|
||||
_stub(tmp_path, "needs-restarting", f"cat <<'EOF'\n{NEEDS_RESTARTING}EOF")
|
||||
_stub(tmp_path, "needrestart", "echo NEEDRESTART-SVC: other.service")
|
||||
|
||||
assert parse_services_restart(_run(tmp_path))["source"] == "needs-restarting"
|
||||
|
||||
def test_needrestart_when_needs_restarting_fails(self, tmp_path):
|
||||
_stub(tmp_path, "needs-restarting", "exit 1")
|
||||
_stub(tmp_path, "needrestart", f"cat <<'EOF'\n{NEEDRESTART}EOF")
|
||||
|
||||
reading = parse_services_restart(_run(tmp_path))
|
||||
|
||||
assert reading == {"source": "needrestart", "units": UNITS, "processes": []}
|
||||
|
||||
def test_needrestart_only_lists(self, tmp_path):
|
||||
"""Batch mode, list only, by its option and by its environment: whatever the
|
||||
host's needrestart.conf says, it restarts nothing."""
|
||||
_stub(tmp_path, "needrestart", 'echo "NEEDRESTART-SVC: $NEEDRESTART_MODE $*.service"')
|
||||
|
||||
reading = parse_services_restart(_run(tmp_path))
|
||||
|
||||
assert reading["units"] == ["l -b -r l"]
|
||||
|
||||
def test_the_maps_scan_when_both_fail(self, tmp_path):
|
||||
"""Stubs that fail stand in for the host's own tools, which ``/usr/sbin``
|
||||
on this host may hold."""
|
||||
_stub(tmp_path, "needs-restarting", "exit 1")
|
||||
_stub(tmp_path, "needrestart", "exit 1")
|
||||
|
||||
assert parse_services_restart(_run(tmp_path))["source"] == "maps"
|
||||
|
||||
|
||||
class TestTheCommand:
|
||||
def test_the_frame_is_not_in_the_command_itself(self):
|
||||
assert "RST_BEGIN" not in SERVICES_RESTART_COMMAND
|
||||
assert "RST_END" not in SERVICES_RESTART_COMMAND
|
||||
|
||||
def test_it_writes_and_changes_nothing(self):
|
||||
for verb in ("sudo", " > ", ">>", "kill", "rm ", "systemctl ", "-r a", "-r i"):
|
||||
assert verb not in SERVICES_RESTART_COMMAND
|
||||
|
||||
def test_it_is_posix_sh(self):
|
||||
result = subprocess.run(
|
||||
["sh", "-n", "-c", SERVICES_RESTART_COMMAND], capture_output=True, text=True
|
||||
)
|
||||
assert result.returncode == 0, result.stderr
|
||||
|
||||
def test_it_runs_and_parses_on_this_host(self):
|
||||
out = subprocess.run(
|
||||
["sh", "-c", SERVICES_RESTART_COMMAND], capture_output=True, text=True, timeout=120
|
||||
).stdout
|
||||
|
||||
reading = parse_services_restart(out)
|
||||
|
||||
assert reading["source"] in ("needs-restarting", "needrestart", "maps")
|
||||
|
||||
|
||||
class _Driver(ServicesRestartMixin):
|
||||
def __init__(self, output: str):
|
||||
self.output = output
|
||||
self.commands: list[str] = []
|
||||
|
||||
def _run_services_restart_command(self, command: str) -> str:
|
||||
self.commands.append(command)
|
||||
return self.output
|
||||
|
||||
|
||||
class TestTheTemplate:
|
||||
def test_a_driver_supplies_only_the_transport(self):
|
||||
driver = _Driver(_wire(("needs-restarting", "sshd.service\n")))
|
||||
|
||||
assert driver.get_services_need_restart()["units"] == ["sshd"]
|
||||
|
||||
def test_the_command_reaches_root_as_one_shell(self):
|
||||
driver = _Driver(_wire(("needs-restarting", "")))
|
||||
|
||||
driver.get_services_need_restart()
|
||||
|
||||
(command,) = driver.commands
|
||||
assert command.startswith("sh -c '")
|
||||
assert subprocess.run(["sh", "-n", "-c", command]).returncode == 0
|
||||
|
||||
def test_a_refused_root_raises_rather_than_reads_clean(self):
|
||||
driver = _Driver("sudo: a password is required\n")
|
||||
|
||||
with pytest.raises(ValueError):
|
||||
driver.get_services_need_restart()
|
||||
|
||||
def test_not_every_os_driver_has_it(self):
|
||||
assert not hasattr(OSDriver, "get_services_need_restart")
|
||||
@@ -0,0 +1,475 @@
|
||||
"""A native Zabbix agent: its configuration, its repository and the fix template
|
||||
(``ZabbixAgentMixin``, NetOrk/netork#2571).
|
||||
|
||||
Where a host has no container engine the application installs the agent from the
|
||||
host's own packages, and from Zabbix's repository only where those have none.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import pytest
|
||||
|
||||
from napalm_device_types import (
|
||||
ZabbixAgentMixin,
|
||||
check_zabbix_agent_settings,
|
||||
zabbix_agent_config,
|
||||
zabbix_repository_command,
|
||||
)
|
||||
|
||||
SETTINGS = {
|
||||
"server": "zabbix.example.com",
|
||||
"server_active": "zabbix.example.com",
|
||||
"listen_port": 10050,
|
||||
"allowed_sources": ["10.40.100.254"],
|
||||
"hostname": "ap-1og",
|
||||
"release": "7.4",
|
||||
}
|
||||
|
||||
SAMPLE = """# This is a configuration file for Zabbix agent daemon (Unix)
|
||||
LogFile=/tmp/zabbix_agentd.log
|
||||
|
||||
### Option: Server
|
||||
# Server=
|
||||
|
||||
Server=127.0.0.1
|
||||
ServerActive=127.0.0.1
|
||||
Hostname=Zabbix server
|
||||
# Include=/etc/zabbix_agentd.conf.d/*.conf
|
||||
"""
|
||||
|
||||
|
||||
class TestConfig:
|
||||
def test_the_lines_that_say_who_may_ask_get_the_caller_s_values(self):
|
||||
text, changes = zabbix_agent_config(SAMPLE, SETTINGS)
|
||||
|
||||
assert "\nServer=zabbix.example.com\n" in text
|
||||
assert "\nServerActive=zabbix.example.com\n" in text
|
||||
assert "\nHostname=ap-1og\n" in text
|
||||
assert "Server: 127.0.0.1 → zabbix.example.com" in changes
|
||||
assert "Hostname: Zabbix server → ap-1og" in changes
|
||||
|
||||
def test_comments_and_other_lines_stay_as_they_were(self):
|
||||
text, _ = zabbix_agent_config(SAMPLE, SETTINGS)
|
||||
|
||||
assert text.startswith("# This is a configuration file")
|
||||
assert "LogFile=/tmp/zabbix_agentd.log\n" in text
|
||||
assert "# Server=\n" in text
|
||||
assert text.endswith("# Include=/etc/zabbix_agentd.conf.d/*.conf\n" + "ListenPort=10050\n")
|
||||
|
||||
def test_a_key_the_file_does_not_set_is_added_at_the_end(self):
|
||||
text, changes = zabbix_agent_config(SAMPLE, SETTINGS)
|
||||
|
||||
assert text.endswith("ListenPort=10050\n")
|
||||
assert "ListenPort: (not set) → 10050" in changes
|
||||
|
||||
def test_a_file_that_already_says_it_changes_nothing(self):
|
||||
text, _ = zabbix_agent_config(SAMPLE, SETTINGS)
|
||||
|
||||
again, changes = zabbix_agent_config(text, SETTINGS)
|
||||
|
||||
assert again == text
|
||||
assert changes == []
|
||||
|
||||
def test_without_a_hostname_the_agent_keeps_its_own(self):
|
||||
settings = {k: v for k, v in SETTINGS.items() if k != "hostname"}
|
||||
|
||||
text, changes = zabbix_agent_config(SAMPLE, settings)
|
||||
|
||||
assert "\nHostname=Zabbix server\n" in text
|
||||
assert not any(c.startswith("Hostname") for c in changes)
|
||||
|
||||
def test_no_active_server_comments_the_line_out(self):
|
||||
text, changes = zabbix_agent_config(SAMPLE, {**SETTINGS, "server_active": ""})
|
||||
|
||||
assert "\n# ServerActive=127.0.0.1\n" in text
|
||||
assert "\nServerActive=" not in text
|
||||
assert "ServerActive: 127.0.0.1 → (not set)" in changes
|
||||
|
||||
def test_a_file_without_a_final_newline_gets_one_before_what_is_added(self):
|
||||
text, _ = zabbix_agent_config("Server=127.0.0.1", SETTINGS)
|
||||
|
||||
assert text.startswith("Server=zabbix.example.com\n")
|
||||
assert text.endswith("\n")
|
||||
|
||||
def test_every_line_of_a_key_set_twice_says_the_same(self):
|
||||
text, _ = zabbix_agent_config("Server=a\nServer=b\n", SETTINGS)
|
||||
|
||||
assert text.count("Server=zabbix.example.com\n") == 2
|
||||
|
||||
|
||||
ACTIVE_ONLY = {**SETTINGS, "active_only": True, "allowed_sources": []}
|
||||
|
||||
|
||||
class TestActiveOnly:
|
||||
"""A site whose agents only connect out (NetOrk/netork#2683): no passive listener.
|
||||
|
||||
Zabbix's ``StartAgents=0`` disables passive checks and the agent listens on no
|
||||
port; ``Server`` is mandatory only while ``StartAgents`` is not 0, so nothing is
|
||||
left that may ask.
|
||||
"""
|
||||
|
||||
def test_it_starts_no_listener_and_lets_nobody_ask(self):
|
||||
text, changes = zabbix_agent_config(SAMPLE, ACTIVE_ONLY)
|
||||
|
||||
assert text.endswith("StartAgents=0\n")
|
||||
assert "\n# Server=127.0.0.1\n" in text
|
||||
assert "\nServer=" not in text
|
||||
assert "\nServerActive=zabbix.example.com\n" in text
|
||||
assert "\nHostname=ap-1og\n" in text
|
||||
assert "StartAgents: (not set) → 0" in changes
|
||||
assert "Server: 127.0.0.1 → (not set)" in changes
|
||||
|
||||
def test_a_listener_count_of_its_own_becomes_none(self):
|
||||
text, changes = zabbix_agent_config("StartAgents=5\n", ACTIVE_ONLY)
|
||||
|
||||
assert text.startswith("StartAgents=0\n")
|
||||
assert "StartAgents: 5 → 0" in changes
|
||||
|
||||
def test_a_file_that_already_says_it_changes_nothing(self):
|
||||
text, _ = zabbix_agent_config(SAMPLE, ACTIVE_ONLY)
|
||||
|
||||
again, changes = zabbix_agent_config(text, ACTIVE_ONLY)
|
||||
|
||||
assert again == text
|
||||
assert changes == []
|
||||
|
||||
def test_a_passive_agent_listens_again(self):
|
||||
"""An agent that was active only before: ``StartAgents=0`` would keep it deaf."""
|
||||
text, _ = zabbix_agent_config(SAMPLE, ACTIVE_ONLY)
|
||||
|
||||
again, changes = zabbix_agent_config(text, SETTINGS)
|
||||
|
||||
assert "\n# StartAgents=0\n" in again
|
||||
assert "\nServer=zabbix.example.com\n" in again
|
||||
assert "StartAgents: 0 → (not set)" in changes
|
||||
|
||||
def test_a_passive_agent_keeps_its_own_listener_count(self):
|
||||
text, changes = zabbix_agent_config("StartAgents=5\n", SETTINGS)
|
||||
|
||||
assert text.startswith("StartAgents=5\n")
|
||||
assert not any(c.startswith("StartAgents") for c in changes)
|
||||
|
||||
def test_it_needs_somewhere_to_send_its_checks(self):
|
||||
with pytest.raises(ValueError):
|
||||
check_zabbix_agent_settings({**ACTIVE_ONLY, "server_active": ""})
|
||||
|
||||
def test_it_needs_no_server_that_may_ask(self):
|
||||
check_zabbix_agent_settings({**ACTIVE_ONLY, "server": ""})
|
||||
|
||||
def test_a_server_that_is_not_addresses_is_still_refused(self):
|
||||
with pytest.raises(ValueError):
|
||||
check_zabbix_agent_settings({**ACTIVE_ONLY, "server": "a\nb"})
|
||||
|
||||
@pytest.mark.parametrize("value", ["yes", 1, None])
|
||||
def test_active_only_is_a_bool(self, value):
|
||||
with pytest.raises(ValueError):
|
||||
check_zabbix_agent_settings({**SETTINGS, "active_only": value})
|
||||
|
||||
|
||||
class TestSettings:
|
||||
@pytest.mark.parametrize(
|
||||
"server",
|
||||
["", "zabbix.example.com\nUserParameter=x,id", "a b", "a;rm -rf /", "'a'"],
|
||||
)
|
||||
def test_a_server_that_is_not_addresses_is_refused(self, server):
|
||||
with pytest.raises(ValueError):
|
||||
check_zabbix_agent_settings({**SETTINGS, "server": server})
|
||||
|
||||
def test_several_servers_and_ports_pass(self):
|
||||
check_zabbix_agent_settings(
|
||||
{**SETTINGS, "server": "10.0.0.1,zabbix.example.com", "server_active": "[::1]:10051"}
|
||||
)
|
||||
|
||||
def test_a_hostname_with_a_newline_is_refused(self):
|
||||
with pytest.raises(ValueError):
|
||||
check_zabbix_agent_settings({**SETTINGS, "hostname": "ap\nServer=evil"})
|
||||
|
||||
@pytest.mark.parametrize("port", [0, 65536, "10050"])
|
||||
def test_a_listen_port_out_of_range_is_refused(self, port):
|
||||
with pytest.raises(ValueError):
|
||||
check_zabbix_agent_settings({**SETTINGS, "listen_port": port})
|
||||
|
||||
@pytest.mark.parametrize("release", ["7", "7.4.1", "latest", "7.4; id"])
|
||||
def test_a_release_that_is_not_major_dot_minor_is_refused(self, release):
|
||||
with pytest.raises(ValueError):
|
||||
check_zabbix_agent_settings({**SETTINGS, "release": release})
|
||||
|
||||
|
||||
def _os_release(**fields: str) -> str:
|
||||
return "".join(f'{key}="{value}"\n' for key, value in fields.items())
|
||||
|
||||
|
||||
class TestRepository:
|
||||
BASE = "https://repo.zabbix.com/zabbix"
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
("os_release", "url"),
|
||||
[
|
||||
(
|
||||
_os_release(ID="ubuntu", VERSION_ID="24.04", ID_LIKE="debian"),
|
||||
"7.4/release/ubuntu/pool/main/z/zabbix-release/"
|
||||
"zabbix-release_latest_7.4+ubuntu24.04_all.deb",
|
||||
),
|
||||
(
|
||||
_os_release(ID="debian", VERSION_ID="12"),
|
||||
"7.4/release/debian/pool/main/z/zabbix-release/"
|
||||
"zabbix-release_latest_7.4+debian12_all.deb",
|
||||
),
|
||||
(
|
||||
_os_release(ID="ol", VERSION_ID="9.4", ID_LIKE="fedora"),
|
||||
"7.4/release/oracle/9/noarch/zabbix-release-latest-7.4.el9.noarch.rpm",
|
||||
),
|
||||
(
|
||||
_os_release(ID="rhel", VERSION_ID="10.0", ID_LIKE="fedora"),
|
||||
"7.4/release/rhel/10/noarch/zabbix-release-latest-7.4.el10.noarch.rpm",
|
||||
),
|
||||
(
|
||||
_os_release(ID="almalinux", VERSION_ID="9.5", ID_LIKE="rhel centos fedora"),
|
||||
"7.4/release/alma/9/noarch/zabbix-release-latest-7.4.el9.noarch.rpm",
|
||||
),
|
||||
(
|
||||
_os_release(ID="rocky", VERSION_ID="9.5", ID_LIKE="rhel centos fedora"),
|
||||
"7.4/release/rocky/9/noarch/zabbix-release-latest-7.4.el9.noarch.rpm",
|
||||
),
|
||||
],
|
||||
)
|
||||
def test_the_release_package_of_the_host_s_distribution(self, os_release, url):
|
||||
command = zabbix_repository_command(os_release, "7.4")
|
||||
|
||||
assert f"{self.BASE}/{url}" in command
|
||||
|
||||
def test_a_release_before_7_2_lives_in_the_old_layout(self):
|
||||
deb = zabbix_repository_command(_os_release(ID="ubuntu", VERSION_ID="24.04"), "7.0")
|
||||
rpm = zabbix_repository_command(_os_release(ID="ol", VERSION_ID="9.4"), "7.0")
|
||||
|
||||
assert f"{self.BASE}/7.0/ubuntu/pool/main/z/zabbix-release/" in deb
|
||||
assert f"{self.BASE}/7.0/oracle/9/x86_64/zabbix-release-latest-7.0.el9.noarch.rpm" in rpm
|
||||
|
||||
def test_a_deb_is_installed_with_dpkg_and_the_index_refreshed(self):
|
||||
command = zabbix_repository_command(_os_release(ID="debian", VERSION_ID="12"), "7.4")
|
||||
|
||||
assert "dpkg -i" in command
|
||||
assert "apt-get update" in command
|
||||
|
||||
def test_an_rpm_is_installed_with_the_package_manager(self):
|
||||
command = zabbix_repository_command(_os_release(ID="rocky", VERSION_ID="9.5"), "7.4")
|
||||
|
||||
assert "dnf -y install" in command
|
||||
|
||||
def test_a_derivative_falls_back_to_what_it_is_like(self):
|
||||
command = zabbix_repository_command(
|
||||
_os_release(ID="centos", VERSION_ID="9", ID_LIKE="rhel fedora"), "7.4"
|
||||
)
|
||||
|
||||
assert "/7.4/release/rhel/9/noarch/" in command
|
||||
|
||||
def test_a_distribution_zabbix_has_no_repository_for_is_refused(self):
|
||||
with pytest.raises(ValueError, match="openwrt"):
|
||||
zabbix_repository_command(_os_release(ID="openwrt", VERSION_ID="25.12.2"), "7.4")
|
||||
|
||||
def test_a_release_that_is_not_major_dot_minor_is_refused(self):
|
||||
with pytest.raises(ValueError):
|
||||
zabbix_repository_command(_os_release(ID="debian", VERSION_ID="12"), "7.4;id")
|
||||
|
||||
|
||||
class _Agent(ZabbixAgentMixin):
|
||||
"""The generic steps over ensure_package and manage_service; the driver's others."""
|
||||
|
||||
def __init__(self, refuse: frozenset[str] = frozenset(), repository: bool = True):
|
||||
self.calls: list = []
|
||||
self.refuse = refuse
|
||||
self.installs = 0
|
||||
if not repository:
|
||||
self._add_zabbix_repository = None # type: ignore[assignment]
|
||||
|
||||
def refresh_available_updates(self):
|
||||
self.calls.append(("refresh",))
|
||||
ok = "refresh" not in self.refuse
|
||||
return {"success": ok, "output": "" if ok else "Temporary failure resolving"}
|
||||
|
||||
def ensure_package(self, name):
|
||||
self.calls.append(("ensure_package", name))
|
||||
self.installs += 1
|
||||
# The distribution has no package; after the repository is added it has.
|
||||
ok = "distribution" not in self.refuse or self.installs > 1
|
||||
return {"success": ok, "steps": [], "output": "installed" if ok else "E: no candidate"}
|
||||
|
||||
def _add_zabbix_repository(self, release):
|
||||
self.calls.append(("repository", release))
|
||||
ok = "repository" not in self.refuse
|
||||
return {"ok": ok, "output": f"Zabbix {release} repository added" if ok else "404"}
|
||||
|
||||
def _write_zabbix_agent_config(self, settings):
|
||||
self.calls.append(("configure", settings["server"]))
|
||||
return {"ok": "configure" not in self.refuse, "output": "written"}
|
||||
|
||||
def _allow_zabbix_agent_sources(self, settings):
|
||||
self.calls.append(("firewall", settings["allowed_sources"]))
|
||||
return {"ok": "firewall" not in self.refuse, "output": "open"}
|
||||
|
||||
def manage_service(self, name, action):
|
||||
self.calls.append((action, name))
|
||||
ok = action not in self.refuse
|
||||
return {"success": ok, "output": "" if ok else f"cannot {action}"}
|
||||
|
||||
|
||||
class TestZabbixAgentMixin:
|
||||
def test_install_configure_open_enable_and_restart(self):
|
||||
agent = _Agent()
|
||||
|
||||
result = agent.configure_zabbix_agent(SETTINGS)
|
||||
|
||||
assert result["success"] is True
|
||||
assert agent.calls == [
|
||||
("refresh",),
|
||||
("ensure_package", "zabbix-agent"),
|
||||
("configure", "zabbix.example.com"),
|
||||
("firewall", ["10.40.100.254"]),
|
||||
("enable", "zabbix-agent"),
|
||||
("restart", "zabbix-agent"),
|
||||
]
|
||||
assert [s["step"] for s in result["steps"]] == ["install", "configure", "firewall", "start"]
|
||||
|
||||
def test_without_a_package_in_the_distribution_zabbix_s_repository_is_added(self):
|
||||
agent = _Agent(refuse=frozenset({"distribution"}))
|
||||
|
||||
result = agent.configure_zabbix_agent(SETTINGS)
|
||||
|
||||
assert result["success"] is True
|
||||
assert agent.calls[:4] == [
|
||||
("refresh",),
|
||||
("ensure_package", "zabbix-agent"),
|
||||
("repository", "7.4"),
|
||||
("ensure_package", "zabbix-agent"),
|
||||
]
|
||||
assert "Zabbix 7.4 repository added" in result["output"]
|
||||
|
||||
def test_without_a_release_there_is_no_fallback(self):
|
||||
settings = {k: v for k, v in SETTINGS.items() if k != "release"}
|
||||
agent = _Agent(refuse=frozenset({"distribution"}))
|
||||
|
||||
result = agent.configure_zabbix_agent(settings)
|
||||
|
||||
assert result["success"] is False
|
||||
assert ("repository", "7.4") not in agent.calls
|
||||
assert "no candidate" in result["output"]
|
||||
|
||||
def test_a_driver_that_cannot_add_the_repository_fails_with_the_distribution_s_answer(self):
|
||||
agent = _Agent(refuse=frozenset({"distribution"}), repository=False)
|
||||
|
||||
result = agent.configure_zabbix_agent(SETTINGS)
|
||||
|
||||
assert result["success"] is False
|
||||
assert "no candidate" in result["output"]
|
||||
|
||||
def test_a_repository_that_cannot_be_added_configures_nothing(self):
|
||||
agent = _Agent(refuse=frozenset({"distribution", "repository"}))
|
||||
|
||||
result = agent.configure_zabbix_agent(SETTINGS)
|
||||
|
||||
assert result["success"] is False
|
||||
assert [c[0] for c in agent.calls] == ["refresh", "ensure_package", "repository"]
|
||||
assert "404" in result["output"]
|
||||
|
||||
def test_the_package_index_is_loaded_first(self):
|
||||
agent = _Agent()
|
||||
|
||||
agent.configure_zabbix_agent(SETTINGS)
|
||||
|
||||
assert agent.calls[0] == ("refresh",)
|
||||
|
||||
def test_an_index_that_will_not_load_still_lets_the_install_try(self):
|
||||
agent = _Agent(refuse=frozenset({"refresh"}))
|
||||
|
||||
result = agent.configure_zabbix_agent(SETTINGS)
|
||||
|
||||
assert result["success"] is True
|
||||
assert ("ensure_package", "zabbix-agent") in agent.calls
|
||||
assert "Temporary failure resolving" in result["steps"][0]["output"]
|
||||
|
||||
def test_a_driver_without_an_index_to_load_installs_straight_away(self):
|
||||
agent = _Agent()
|
||||
agent.refresh_available_updates = None # type: ignore[assignment]
|
||||
|
||||
result = agent.configure_zabbix_agent(SETTINGS)
|
||||
|
||||
assert result["success"] is True
|
||||
assert agent.calls[0] == ("ensure_package", "zabbix-agent")
|
||||
|
||||
def test_an_active_only_agent_opens_no_port(self):
|
||||
"""NetOrk/netork#2683: nothing listens, so nothing is let through."""
|
||||
agent = _Agent()
|
||||
|
||||
result = agent.configure_zabbix_agent({**ACTIVE_ONLY, "allowed_sources": ["10.0.0.1"]})
|
||||
|
||||
assert result["success"] is True
|
||||
assert not [c for c in agent.calls if c[0] == "firewall"]
|
||||
assert [s["step"] for s in result["steps"]] == ["install", "configure", "firewall", "start"]
|
||||
assert "active only" in result["steps"][2]["output"]
|
||||
|
||||
def test_an_active_only_agent_has_the_driver_revoke_what_netork_opened(self):
|
||||
"""NetOrk/netork#2693: a rule an earlier passive install opened is closed."""
|
||||
agent = _Agent()
|
||||
agent._revoke_zabbix_agent_sources = lambda settings: ( # type: ignore[attr-defined]
|
||||
agent.calls.append(("revoke", settings["listen_port"]))
|
||||
or {"ok": True, "output": "removed tcp/10050"}
|
||||
)
|
||||
|
||||
result = agent.configure_zabbix_agent(ACTIVE_ONLY)
|
||||
|
||||
assert result["success"] is True
|
||||
assert ("revoke", ACTIVE_ONLY["listen_port"]) in agent.calls
|
||||
assert not [c for c in agent.calls if c[0] == "firewall"]
|
||||
assert result["steps"][2]["output"] == "removed tcp/10050"
|
||||
|
||||
def test_a_driver_that_cannot_tell_its_rules_apart_changes_nothing_and_says_so(self):
|
||||
agent = _Agent()
|
||||
|
||||
result = agent.configure_zabbix_agent(ACTIVE_ONLY)
|
||||
|
||||
assert result["success"] is True
|
||||
assert "cannot tell" in result["steps"][2]["output"]
|
||||
|
||||
def test_a_revoke_that_fails_starts_nothing(self):
|
||||
agent = _Agent()
|
||||
agent._revoke_zabbix_agent_sources = lambda settings: { # type: ignore[attr-defined]
|
||||
"ok": False,
|
||||
"output": "ufw: permission denied",
|
||||
}
|
||||
|
||||
result = agent.configure_zabbix_agent(ACTIVE_ONLY)
|
||||
|
||||
assert result["success"] is False
|
||||
assert ("restart", "zabbix-agent") not in agent.calls
|
||||
|
||||
def test_a_closed_firewall_starts_nothing(self):
|
||||
agent = _Agent(refuse=frozenset({"firewall"}))
|
||||
|
||||
assert agent.configure_zabbix_agent(SETTINGS)["success"] is False
|
||||
assert ("restart", "zabbix-agent") not in agent.calls
|
||||
|
||||
def test_an_agent_that_will_not_start_at_boot_is_not_restarted(self):
|
||||
agent = _Agent(refuse=frozenset({"enable"}))
|
||||
|
||||
result = agent.configure_zabbix_agent(SETTINGS)
|
||||
|
||||
assert result["success"] is False
|
||||
assert ("restart", "zabbix-agent") not in agent.calls
|
||||
assert "cannot enable" in result["output"]
|
||||
|
||||
def test_the_package_and_service_names_are_the_driver_s(self):
|
||||
agent = _Agent()
|
||||
agent.ZABBIX_AGENT_PACKAGE = "zabbix-agentd"
|
||||
agent.ZABBIX_AGENT_SERVICE = "zabbix_agentd"
|
||||
|
||||
agent.configure_zabbix_agent(SETTINGS)
|
||||
|
||||
assert ("ensure_package", "zabbix-agentd") in agent.calls
|
||||
assert ("restart", "zabbix_agentd") in agent.calls
|
||||
|
||||
def test_settings_that_do_not_hold_are_refused_before_anything_changes(self):
|
||||
agent = _Agent()
|
||||
|
||||
with pytest.raises(ValueError):
|
||||
agent.configure_zabbix_agent({**SETTINGS, "server": "a\nb"})
|
||||
assert agent.calls == []
|
||||
Reference in new issue
Block a user