Compare commits
134
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
0e1c4e7927 | ||
|
|
98157f3673 | ||
|
|
69c43d3288 | ||
|
|
553b4d5153 | ||
|
|
647a5cc857 | ||
|
|
94badd0e23 | ||
|
|
4db8b05ab4 | ||
|
|
de91b1a918 | ||
|
|
c9a9d532aa | ||
|
|
5f6595d160 | ||
|
|
4ba81cc90e | ||
|
|
92ca800026 | ||
|
|
655d115324 | ||
|
|
6e5b0ea2ec | ||
|
|
bc7162affd | ||
|
|
3683c85f21 | ||
|
|
aab25fb049 | ||
|
|
1d377acc5f | ||
|
|
257efdef8e | ||
|
|
235c1e9a91 | ||
|
|
c2e7ea5789 | ||
|
|
10240c20bb | ||
|
|
78374cfb42 | ||
|
|
ea82d43bd4 | ||
|
|
c532a66260 | ||
|
|
2b153cd61c | ||
|
|
249046512d | ||
|
|
60ccea9a98 | ||
|
|
5c13ce1a8b | ||
|
|
1c8b1b1c60 | ||
|
|
bd17fbd84d | ||
|
|
d03fe2a2ba | ||
|
|
650379680f | ||
|
|
04a34ca6f5 | ||
|
|
d5870d9813 | ||
|
|
a30d1f6fe5 | ||
|
|
ca32b89686 | ||
|
|
cb0e308a78 | ||
|
|
c7317925ed | ||
|
|
9ac6c7cf04 | ||
|
|
d3189806d3 | ||
|
|
a3d95d72b9 | ||
|
|
ca65f007c1 | ||
|
|
9089429c2d | ||
|
|
a1e8ec78c3 | ||
|
|
3d2de27988 | ||
|
|
e4c65945b9 | ||
|
|
d3134c83b8 | ||
|
|
c2d7c4d1b4 | ||
|
|
5687f5d9a1 | ||
|
|
b891acd29c | ||
|
|
d226ebf764 | ||
|
|
60ff9d9700 | ||
|
|
897892b923 | ||
|
|
69f1701ea6 | ||
|
|
024f68c543 | ||
|
|
54f6844d84 | ||
|
|
df4f4b0e4d | ||
|
|
eaa08ae7e3 | ||
|
|
a729b35d8b | ||
|
|
e9a1fc7ff9 | ||
|
|
f49d1ca7f5 | ||
|
|
dd351f1077 | ||
|
|
b702fa5125 | ||
|
|
448eeec0fa | ||
|
|
9ce915a8b9 | ||
|
|
812a162eef | ||
|
|
bff275402e | ||
|
|
49b7d7fef7 | ||
|
|
c5be71adac | ||
|
|
7550b884b0 | ||
|
|
fbaded5913 | ||
|
|
4cd1710e19 | ||
|
|
05cef25e9b | ||
|
|
2ffad23bf0 | ||
|
|
4108eb83dd | ||
|
|
b6677c9fc5 | ||
|
|
2afdf33d4d | ||
|
|
661f6da3f7 | ||
|
|
42e93f02dd | ||
|
|
4159612a33 | ||
|
|
3aa1955382 | ||
|
|
9a4bc76dbf | ||
|
|
cc0e0358f2 | ||
|
|
e0960085c7 | ||
|
|
91b2025074 | ||
|
|
04f071afd0 | ||
|
|
9b3ac3f3eb | ||
|
|
933f81bd44 | ||
|
|
38391891ec | ||
|
|
0ba5081824 | ||
|
|
19b86d103d | ||
|
|
facc081123 | ||
|
|
a2bfa709f9 | ||
|
|
c725f4882c | ||
|
|
4b17e2f3f8 | ||
|
|
5951a6100e | ||
|
|
127e3150b4 | ||
|
|
72f0daa995 | ||
|
|
427a9ac8af | ||
|
|
c8e2b328d7 | ||
|
|
decd64b876 | ||
|
|
40f6ecd583 | ||
|
|
fc968fab44 | ||
|
|
ec8668476a | ||
|
|
1bc54b66e8 | ||
|
|
8af7c52d82 | ||
|
|
272bf21f8e | ||
|
|
c98dd928e6 | ||
|
|
350e3a6d6e | ||
|
|
81b2df9d71 | ||
|
|
108f6fb3ca | ||
|
|
cf8ee38a90 | ||
|
|
7b37366a44 | ||
|
|
647e058b8a | ||
|
|
7bd005eb29 | ||
|
|
eb7432ea5a | ||
|
|
0268019743 | ||
|
|
a78daccb56 | ||
|
|
3a76b6d47f | ||
|
|
3333d8e8f5 | ||
|
|
fe29b507b0 | ||
|
|
51ee33eebe | ||
|
|
0f5e2a1d37 | ||
|
|
b7a13d5153 | ||
|
|
007590b9bf | ||
|
|
79e52f060e | ||
|
|
3571149639 | ||
|
|
60b56c37e0 | ||
|
|
e82f99df7b | ||
|
|
2fed2f73e2 | ||
|
|
b49acb8ed7 | ||
|
|
a6f9a17858 | ||
|
|
e31bc2a3bf |
No files matched your search
@@ -0,0 +1,17 @@
|
||||
name: CI
|
||||
|
||||
on:
|
||||
push:
|
||||
branches: [main, master]
|
||||
tags: ["v*"]
|
||||
pull_request:
|
||||
|
||||
jobs:
|
||||
driver:
|
||||
uses: NAPALM/driver-standard/.gitea/workflows/driver.yml@main
|
||||
with:
|
||||
standard-ref: main
|
||||
# Until napalm-device-types 4.22.0 (AptProxyMixin, #53) is on PyPI.
|
||||
pre-install: "git+https://git.netork.io/NAPALM/napalm-device-types.git"
|
||||
secrets:
|
||||
PYPI_TOKEN: ${{ secrets.PYPI_TOKEN }}
|
||||
+362
@@ -7,6 +7,368 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
|
||||
|
||||
## [Unreleased]
|
||||
|
||||
### Added
|
||||
- On an rpm host each package names the source rpm it was built from, as `source_rpm`
|
||||
(`perf` → `kernel`); absent where rpm names none (`gpg-pubkey`). Red Hat lists `perf`,
|
||||
`python3-perf` and `bpftool` in every kernel CVE, and the source is what tells them apart
|
||||
from user space (NetOrk/netork#2394). Not dpkg's `source_package`: netOrk reads that as
|
||||
the name a distribution files its verdicts under, and Oracle's and Red Hat's name the
|
||||
binary.
|
||||
- `get_installed_advisory_cves()` through napalm-device-types' `UpdateMixin` (4.37.0): the
|
||||
CVEs a dnf host's installed security advisories close, per package, read as root from
|
||||
the cache. netOrk reads it where its knowledge base holds no records of the host's
|
||||
release (NetOrk/netork#2394). dnf only; other package managers raise
|
||||
`NotImplementedError`.
|
||||
|
||||
### Changed
|
||||
- `load_replace_candidate` is `None` instead of a method that raises
|
||||
`NotImplementedError`, so a caller that asks whether the driver can replace a
|
||||
configuration gets no. netOrk offered a config restore for these devices that
|
||||
could only fail (NetOrk/netork#2503).
|
||||
- On an rpm host a package's version carries its epoch where it has one
|
||||
(`1:6.2.0-13.el9`), as on a dpkg host. Oracle's and Red Hat's fixes name it, and without
|
||||
it an epoch-1 fix read as newer than every installed build (NetOrk/netork#2394).
|
||||
|
||||
### Fixed
|
||||
- `open_stream(privileged=True)` with a sudo password asks sudo first whether it wants it
|
||||
(`sudo -n sh -c true`). A sudo that does not prompt (NOPASSWD, a cached timestamp) used to
|
||||
get the password on stdin anyway, where it went to the command as the first bytes of the
|
||||
stream: into the Podman API, over `sudo podman system dial-stdio` (NetOrk/netork#818).
|
||||
Such a sudo now gets the command through `sudo -n`, and only one that asks gets the
|
||||
password.
|
||||
|
||||
### Added
|
||||
- `get_time_sync()` and `configure_time_sync()` through napalm-device-types'
|
||||
`PosixTimeSyncMixin` (4.35.0): the host's NTP servers in its client's order, its time zone,
|
||||
whether the clock is synchronised and which client keeps it (chrony, systemd-timesyncd,
|
||||
ntpd, OpenNTPD), read in one round trip as the login user. The zone is set with
|
||||
`timedatectl set-timezone`; chrony's servers go to `/etc/chrony/sources.d/netork.sources`
|
||||
(else a `confdir` or an included file) with every other source commented out,
|
||||
systemd-timesyncd's to `/etc/systemd/timesyncd.conf.d/netork.conf`. The host ends up with
|
||||
exactly the servers given (NetOrk/netork#2361). OpenMediaVault and QNAP inherit it.
|
||||
- `get_running_backups()` through napalm-device-types' `RunningBackupsMixin` (4.34.0): the
|
||||
host's own backups a restart would abort -- a process of restic, resticprofile, autorestic,
|
||||
borg, borgmatic, duplicity, duply, rsnapshot, rdiff-backup, proxmox-backup-client, kopia or
|
||||
btrbk doing a backup, prune, check or copy (not a mount, a restore or a listing), with the
|
||||
systemd service it runs in as its job (a timer's service; none for a cron or a login
|
||||
session), its process id and when it started. One round trip as the login user; a `ps`
|
||||
without `etimes` fails the reading (NetOrk/netork#2318). OpenMediaVault and QNAP inherit it.
|
||||
- `get_log_sources()` through napalm-device-types' `LogSourcesMixin` (4.30.0): the units
|
||||
journald holds entries for and the log files running processes hold open, with the service
|
||||
or container writing each, as root, and without root what the login user may see
|
||||
(NetOrk/netork#2049). OpenMediaVault and QNAP inherit it.
|
||||
- A deleted key can take the password with it (NetOrk/netork#2033): through
|
||||
napalm-device-types' `remove_local_account_keys(..., clear_password=True)` the keys go
|
||||
as the person, the password goes (`usermod -p '*'`), and so do the sudo rule and the
|
||||
admin groups. The account stays open and logs in with its other keys only.
|
||||
|
||||
### Changed
|
||||
- Needs napalm-device-types 4.35.0.
|
||||
|
||||
### Fixed
|
||||
- `configure_snmp_agent()` opens udp/161 on a host running firewalld (Oracle Linux, RHEL,
|
||||
Fedora): a rich rule per allowed source in the default zone and every active zone, at
|
||||
runtime and permanently, without a reload. It used to insert an iptables rule there,
|
||||
which firewalld's own reject overrides, so the fix reported the port open while SNMP
|
||||
stayed blocked (#77).
|
||||
|
||||
## [0.17.0] - 2026-11-04
|
||||
|
||||
### Added
|
||||
- Personal accounts follow what the person changes (NetOrk/netork#2013):
|
||||
`add_local_account(..., replaces=[...])` takes the old keys out of the account's key
|
||||
files as the new one goes in, `remove_local_account_keys` takes deleted keys out and
|
||||
leaves the account open, and `add_local_account(..., clear_password=True)` removes the
|
||||
password (`usermod -p '*'`): the account logs in with its key only and has no sudo.
|
||||
Keys the person added on the host stay.
|
||||
|
||||
### Changed
|
||||
- Needs napalm-device-types 4.28.0.
|
||||
|
||||
## [0.16.0] - 2026-11-03
|
||||
|
||||
### Added
|
||||
- Scheduled jobs (NetOrk/netork#1933, #67), through napalm-device-types' `PosixScheduledJobsMixin`:
|
||||
`get_scheduled_jobs()` reads `/etc/crontab`, `/etc/cron.d`, the user crontabs (Debian,
|
||||
RHEL, Alpine), the run-parts directories, `/etc/anacrontab` and every systemd timer in one
|
||||
round trip as root; `manage_scheduled_job()` enables, disables or runs one now;
|
||||
`put_scheduled_job()` and `delete_scheduled_job()` write and remove an application's own.
|
||||
OpenMediaVault and QNAP QTS inherit it and decide per verb in their own packages.
|
||||
- netOrk's own account with a fixed uid (NetOrk/netork#1817): `_account_create_with_uid`
|
||||
makes it with `useradd -m -u <uid>`. Below `UID_MIN` useradd warns and goes on, as a
|
||||
system's account.
|
||||
- Personal accounts (NetOrk/netork#1793), through napalm-device-types' `LocalAccountsMixin`:
|
||||
`get_local_accounts()`, `add_local_account()` and `lock_local_account()` with
|
||||
shadow-utils' commands (`useradd -m -s /bin/bash`, `usermod`, `gpasswd -d`). A locked
|
||||
account is an expired one (`usermod -L -e 1`): PAM refuses it a key login too, where a
|
||||
`!` in front of the password stops only the password. Opening it again lifts the expiry
|
||||
and gives the old password back. Checked on Debian 13 and Rocky Linux 9 with sshd and
|
||||
sudo. OpenMediaVault (Debian) inherits it; QNAP QTS opts out in napalm-qnap-qts.
|
||||
Requires the napalm-device-types release with `LocalAccountsMixin`.
|
||||
- `open()` tries the connection again after 1, 3, 7 and 15 s when sshd closes it before
|
||||
its banner -- what OpenSSH 9.8+ does to a source it has just penalised
|
||||
(`PerSourcePenalties`), e.g. after a security scanner's probes. Needs
|
||||
napalm-device-types' `retry_refused` (NAPALM/napalm-device-types#63,
|
||||
NetOrk/netork#1800).
|
||||
- The sudo password the old `_sudo` left in shell histories (NetOrk/netork#1090), through
|
||||
napalm-device-types' `SudoHistoryMixin`. Until NetOrk/netork#1039 every privileged command
|
||||
was typed into the interactive shell as `echo '<password>' | sudo -S -p "" …`, so the
|
||||
login user's history kept the password once per command. `get_history_sudo_lines()`
|
||||
counts those lines with `grep -c`, without reading them; `remove_history_sudo_lines()`
|
||||
deletes exactly them and gives `/etc/snmp/snmpd.conf` and `/etc/apt/apt.conf.d/00proxy`
|
||||
back to `root:root` where the old partial sudo left them to the login user (a regular
|
||||
file, never a symbolic link). OpenMediaVault and QNAP inherit both. Requires the
|
||||
napalm-device-types release with `SudoHistoryMixin`.
|
||||
- `set_hostname()` (#45): netOrk could save a Linux host's new name but not apply it
|
||||
("The driver linux does not support set_hostname()"). The host now takes the short
|
||||
name through `hostnamectl`, or `/etc/hostname` and `hostname(1)` without systemd;
|
||||
`/etc/hosts` follows (the lines naming the old name, else the `127.0.1.1` line), and a
|
||||
cloud-init host gets `preserve_hostname: true` so its next boot keeps the name. Names
|
||||
that are not valid hostnames are refused before anything runs on the host.
|
||||
|
||||
### Changed
|
||||
- Python 3.12 is the floor (`requires-python = ">=3.12"`): netOrk runs every driver
|
||||
on 3.12, so 3.10 and 3.11 are no longer tested (NAPALM/driver-standard#6).
|
||||
- The floor on napalm-device-types is 4.24.0, for its shared `lldpctl` parser.
|
||||
|
||||
### Fixed
|
||||
- `get_lldp_neighbors()` raises when lldpd runs but lldpctl fails (its socket out of
|
||||
the login's reach, a daemon restarting), with lldpctl's message, instead of reporting
|
||||
no neighbours (#66). A stopped lldpd is recognised as stopped: systemd's `inactive`
|
||||
used to pass the running check, as it contains the word "active". A host without
|
||||
lldpd, or with lldpd stopped, still reports no neighbours.
|
||||
- `get_lldp_neighbors()` lists every neighbour of a port (#58): a phone and the PC
|
||||
behind it, or the devices behind an unmanaged switch, used to merge into one entry
|
||||
and only the last one was left. A neighbour whose chassis id is a MAC address now
|
||||
carries it as `mac` (it never did), a port given as a MAC address or local id is
|
||||
reported instead of coming back empty, and an interface with a dot in its name
|
||||
(`eth0.100`) keeps its whole name.
|
||||
- `get_route_to()` reads unreachable, blackhole, prohibit and throw routes and
|
||||
multipath routes (#57). Their destinations came back as `unreachable/32`,
|
||||
`blackhole/32` or `nexthop/32`, and a multipath route as one entry without a next
|
||||
hop. A typed route now has its real prefix and its type in
|
||||
`protocol_attributes` (`{"type": "blackhole"}`), with no next hop and no outgoing
|
||||
interface, since it sends nothing out. A multipath route has one entry per next hop,
|
||||
each with its gateway and interface. A host route that FRR reports without a prefix
|
||||
length is a `/128` for IPv6 instead of a `/32` (#64), so it meets the kernel's route
|
||||
for the same host and gets FRR's protocol.
|
||||
- `get_route_to()` reads the next hop of an IPv4 route through an IPv6 gateway (RFC
|
||||
8950, as BGP unnumbered sets up), which `ip route` prints as `via inet6 fe80::1`
|
||||
(#65). The next hop came back as `inet6`; it is now the address, for multipath
|
||||
routes too. Such a route stays `family: ipv4`: the family is the destination's,
|
||||
never the next hop's.
|
||||
- `get_available_updates()` works on dnf and yum hosts whose login user has
|
||||
passwordless sudo (NOPASSWD), as netOrk's own account does, and marks the security
|
||||
fixes there (#56). The security-advisory query did not parse under `sudo -n`, so no
|
||||
answer came back and the read ran into its 120 s timeout. Without a sudo password a
|
||||
privileged command now runs as root as a whole, in one `sh -c`, as it already did
|
||||
with a password; before, only its first command did. A refused sudo still reports
|
||||
its exit status at once.
|
||||
- `ping()` passes `destination` and `source` to the host's shell as one quoted word
|
||||
each (#55). A destination such as `192.0.2.1; id` ran the command after the `;` as
|
||||
the login user. `count`, `timeout`, `size` and `ttl` must be numbers; anything else
|
||||
raises `ValueError` before a command is sent. A destination or source that starts
|
||||
with `-` is refused the same way (#63): `ping` would read `-f` as its flood option,
|
||||
and no address or hostname starts with `-`.
|
||||
- dnf and yum hosts read pending updates and security advisories from the cached
|
||||
metadata only (`--cacheonly`), as apt reads its local index (#59). With an expired
|
||||
cache `check-update` downloaded the repositories' metadata first, and on an Oracle
|
||||
Linux host on OCI that outlasted netOrk's whole poll, every time. Refreshing stays
|
||||
`refresh_available_updates()` (`dnf makecache`). Without a cache the read fails at
|
||||
once and says to refresh the index. Requires the napalm-device-types release with
|
||||
NAPALM/napalm-device-types#76 for dnf's security query.
|
||||
- `get_arp_table()` reports an unknown age as `-1.0` (napalm-device-types'
|
||||
`ARP_AGE_UNKNOWN`) instead of `0.0`, which means "confirmed just now": `ip neigh`
|
||||
has no age, and a STALE entry may be hours old (NetOrk/netork#1327).
|
||||
- `install_package()` reports success by the package manager's exit status, as
|
||||
`uninstall_package()` already does (#4). It used to search the output for words like
|
||||
"failed": an install whose postinst merely mentioned a failure read as failed, and a
|
||||
failure that used none of the words read as success.
|
||||
- `get_vpn_tunnels()` makes the public-key prefix in a WireGuard peer's key URL-safe
|
||||
(`+` becomes `-`, `/` becomes `_`), as napalm-opnsense does (#43). A key with `/`
|
||||
could not be used as a URL path segment, so such a tunnel could not be edited in
|
||||
netOrk. The key of a peer whose first eight key characters hold `+` or `/` changes
|
||||
once; `public_key` is reported unchanged.
|
||||
- `get_processes()` reports a process's whole start time in `started`
|
||||
(`Tue Oct 6 08:47:15 2026`) and only the command line in `command` (#21). `started`
|
||||
held the weekday alone and `command` began with the rest of the date. The start time
|
||||
is read in the C locale, so its words are English on every host.
|
||||
- `get_packages()` on apt hosts no longer lists removed packages whose configuration
|
||||
dpkg still keeps (state `rc`) (#17). They were reported as installed: old kernels, or
|
||||
an agent that had been removed. A package that is held, unpacked or half-configured
|
||||
still counts, since its files are on disk.
|
||||
- `ping()` reads BusyBox's output, the `ping` on Alpine (#15). Its summary says
|
||||
"2 packets received", which did not match, so every target came back as an error and
|
||||
a LAN scan through an Alpine host found nothing. Replies to IPv6 targets, BusyBox's
|
||||
`seq=` replies and replies from a name (`bytes from host (address)`) now appear in
|
||||
`results`, BusyBox's `round-trip` line fills the RTT fields, and an iputils summary
|
||||
that counts errors is read as well.
|
||||
- `get_route_to()` reports a dual-stack host's IPv6 default route as `::/0` (#6). It
|
||||
came back as a second `0.0.0.0/0` with `family: ipv6`, because `ip -6 route show`
|
||||
calls its default route `default` as well. An IPv6 host route is now a `/128`
|
||||
instead of a `/32`.
|
||||
|
||||
### Removed
|
||||
- `get_cron_jobs()`: it read without root, missed other users' crontabs, `/etc/crontab`,
|
||||
run-parts, anacron and every systemd timer, and nothing called it. `get_scheduled_jobs()`
|
||||
replaces it.
|
||||
|
||||
## [0.15.1] - 2026-10-23
|
||||
|
||||
### Fixed
|
||||
- Ubuntu 26.04 hosts could not be polled (#41). systemd 258's
|
||||
`/etc/profile.d/80-systemd-osc-context.sh` wraps every command of an interactive bash
|
||||
in OSC 3008 sequences, so they ended up in every value read through the shell, the
|
||||
prompt line with them: `os_version` grew past 255 characters. The session now unsets
|
||||
`PS0` and `PROMPT_COMMAND` right after switching the history off and reads its prompt
|
||||
anew, and `_send()` strips terminal codes from what it returns.
|
||||
|
||||
## [0.15.0] - 2026-10-23
|
||||
|
||||
The first release on PyPI. It collects everything since 0.4.0, which was the last version recorded here.
|
||||
|
||||
### Changed
|
||||
- The driver follows the NAPALM driver standard
|
||||
(https://git.netork.io/NAPALM/driver-standard): CI on Gitea runs ruff, mypy, the
|
||||
tests on Python 3.10–3.13 and at the lowest declared versions, bandit, pip-audit and
|
||||
a build check, and a release tag publishes to PyPI. The package now ships `py.typed`
|
||||
and a LICENSE file. **Python 3.9 is no longer supported**; napalm-device-types never
|
||||
ran on it.
|
||||
- Exceptions the driver deliberately ignores (the PTY width at login, closing a dead
|
||||
session, unreadable route lines, the snmpd.conf community and port) are now logged
|
||||
at debug level.
|
||||
|
||||
### Added
|
||||
- apt's proxy through napalm-device-types' `AptProxyMixin` (NetOrk/netork#1397). `get_package_proxy()` is what `apt-config dump` says, not `00proxy` alone: a proxy in `90curtin-aptproxy` or `/etc/apt/apt.conf` wins over it, and was missed. New: `get_package_proxy_report()` (every line that sets it, per-host overrides, the https sources) and `check_package_proxy(url, expect)` (a fetch with `apt-helper`, past any proxy). `configure_package_proxy(url)` now also comments out other proxy lines, reads the result back and fetches one `InRelease` through the proxy; it fails when apt still fetches elsewhere. Reads run on the exec channel. Requires napalm-device-types 4.22.0; version 0.14.0.
|
||||
- `get_host_firewall()` (napalm-device-types' `HostFirewallMixin`, NetOrk/netork#1344): the host's own netfilter rules — `nft -j list ruleset`, with the tables iptables manages taken from `iptables-save` — as chains and rules in one shape. Read-only, as root, on an exec channel (the nft JSON is one long line). Requires napalm-device-types 4.21.0; version 0.13.0.
|
||||
- `get_service_packages()` (napalm-device-types' `ServicePackagesMixin`, NetOrk/netork#1236): which installed packages each systemd service is made of — the one shipping its unit file and the one shipping its `ExecStart` binary. Read-only, on an exec channel under `sh`, without sudo. Requires napalm-device-types 4.20.0; version 0.12.0.
|
||||
|
||||
### Security
|
||||
- The SSH host key is verified (NetOrk/netork#1167). `open()` hands netmiko the key the caller expects for the port in `optional_args["ssh_host_keys"]` (as a `known_hosts` file that exists only while it connects, with `ssh_strict`), so any other key is refused before the login (`SshHostKeyMismatch`); without one netmiko accepts the first key. Every key seen goes to `optional_args["ssh_host_key_observer"]`. OpenMediaVault and QNAP get this through `LinuxDriver.open()`. Requires napalm-device-types 4.19.0; version 0.11.0.
|
||||
|
||||
### Changed
|
||||
- **Breaking:** `get_device_warnings` is gone, and with it the `apt_proxy_url` argument.
|
||||
The driver reports facts and the application names warnings (napalm-device-types 4.14):
|
||||
`get_package_proxy()` says which proxy apt fetches through; pending updates were always
|
||||
in `get_available_updates()`. Requires napalm-device-types 4.14.0; version 0.9.0.
|
||||
|
||||
### Changed
|
||||
|
||||
- **Breaking:** `run_device_action` is gone, with `fix_snmp`, `fix_apt_proxy`,
|
||||
`fix_docker_permissions` and the unused `apt_update_upgrade`. The driver implements
|
||||
napalm-device-types 4.13's fix templates instead, and the caller supplies every value:
|
||||
`configure_snmp_agent(settings)` (one `rocommunity` line per allowed source, udp/161
|
||||
opened in ufw or iptables for those sources only, each step judged by its exit
|
||||
status), `configure_package_proxy(url)`, `grant_container_engine_access(user)` and
|
||||
`ensure_package(name)`. No community, contact, location or address of an application
|
||||
is built in any more. Requires napalm-device-types 4.13.0 or later; version 0.8.0.
|
||||
- The sudo hint names no application's settings.
|
||||
|
||||
### Fixed
|
||||
|
||||
- The type annotations resolve: `Dict`, `List` and `Optional` were used without an
|
||||
import (#29).
|
||||
|
||||
### Added
|
||||
|
||||
- `get_system_identity()` (napalm-device-types 4.9 `SystemIdentityMixin`): the host's
|
||||
SMBIOS system UUID, product serial and board serial, read as root on an exec channel,
|
||||
vendor placeholders empty. netOrk matches a server to its BMC on these. Requires
|
||||
napalm-device-types 4.9.0 or later; version 0.7.0.
|
||||
|
||||
### Changed
|
||||
|
||||
- Requires napalm-device-types 4.7.1 or later; version 0.6.0.
|
||||
- **Breaking:** `get_users()` is now `get_os_users()`, following napalm-device-types
|
||||
4.7, which renamed `OSDriver.get_users` because NAPALM's own `get_users` has
|
||||
another shape. The return value is unchanged (a list of `UserDict`).
|
||||
`get_users()` is NAPALM's again and raises `NotImplementedError`.
|
||||
|
||||
### Fixed
|
||||
|
||||
- Listing updates on yum hosts (RHEL 7, CentOS 7) no longer fails with
|
||||
napalm-device-types 4.7: its `parse_dnf_security` needs the `__DNF_RC=<status>`
|
||||
line `DNF_SECURITY_COMMAND` prints, and the yum security query had none, so it
|
||||
raised `ValueError`. The yum query now prints that marker the same way
|
||||
(`{ ...; echo __DNF_RC=$?; } | cat`). A yum or dnf security query that failed,
|
||||
or whose output was cut short before the marker, still leaves `security` unknown
|
||||
(`None`) instead of reporting no advisories.
|
||||
|
||||
### Security
|
||||
|
||||
- `run_command(privileged=True, stdin=...)` raises `ValueError` while a sudo
|
||||
password is set. `sudo -S` reads the password from stdin, and a sudo that does
|
||||
not prompt (NOPASSWD, a cached timestamp) left it for the command, which read
|
||||
it as the first line of the data: netOrk wrote it into a file that way
|
||||
(NetOrk/netork#1029). Stage the data without privilege and have root install
|
||||
that file. Without a sudo password (`sudo -n`) or for a root login, stdin
|
||||
still goes to the command.
|
||||
- The sudo password is no longer typed into the interactive shell
|
||||
(NetOrk/netork#1039). Every privileged command ran there as
|
||||
`echo '<password>' | sudo -S -p "" <command>`: bash kept it in its history,
|
||||
so each poll wrote the password into the login user's `~/.bash_history`, and
|
||||
while the command ran it was in the process list for every local user.
|
||||
Privileged commands (`_sudo`, `_sudo_status`, and `_run_privileged` with a
|
||||
sudo password) now run on an exec channel like `run_command(privileged=True)`:
|
||||
the password reaches `sudo -S` on stdin, there is no PTY to echo it, and the
|
||||
whole command runs as root in one `sh -c` (before, only the part up to the
|
||||
first `;`, `&&` or `|` did, so `mv … && chown root:root …` failed its chown).
|
||||
The interactive session also switches its history off before its first
|
||||
command (` unset HISTFILE; set +o history`). **History files written before
|
||||
this version may still hold the sudo password**: remove those lines from the
|
||||
login user's `~/.bash_history` on your hosts and consider changing the
|
||||
password. `_sudo_status` takes the exit status from the channel; it is `None`
|
||||
only when the channel closed without one.
|
||||
- The snmpd and apt proxy fixes no longer stage their files at a fixed path in
|
||||
/tmp (`/tmp/netork_snmpd.conf`, `/tmp/netork_00proxy`) and then `mv`,
|
||||
`chown` and `chmod` them as root. Another local user could create that path
|
||||
first as a symlink, for example to `/etc/shadow`, and root's `chown`/`chmod`
|
||||
followed it. The content now goes to a fresh `mktemp` file under `umask 077`,
|
||||
written without privilege, and root `install`s it as a new file owned by root
|
||||
(mode 644) next to the target and renames it into place
|
||||
(`_install_file_as_root`). Nothing runs as root when staging failed.
|
||||
- `get_vpn_tunnels()` without a sudo password no longer writes `wg show all dump`
|
||||
(which includes the interfaces' private keys) to the predictable
|
||||
`/tmp/.netork_wg_<hash>`; the dump comes straight from the exec channel.
|
||||
|
||||
## [0.4.0] – 2026-10-08
|
||||
|
||||
### Added
|
||||
|
||||
- `get_virtual_ips()` through napalm-device-types' `VirtualIpsMixin` (4.2.0): the
|
||||
addresses vip-manager and keepalived configuration lets float onto this host,
|
||||
whether or not it holds them right now (NetOrk/netork#829). The command goes on
|
||||
the exec channel (`run_command`): with its awk filter it is about 4 kB, past the
|
||||
line the PTY reliably takes. Root first, then without it.
|
||||
|
||||
## [0.3.0] – 2026-10-08
|
||||
|
||||
### Removed
|
||||
|
||||
- `get_docker_info()`, `get_docker_outdated()`, `reconstruct_docker_run()` and
|
||||
the `_docker_bin()` hook, with the image-ID helpers they used. netOrk reads
|
||||
and handles containers itself over the Engine API, through
|
||||
`open_container_engine()` (NetOrk/netork#765), and no longer calls them.
|
||||
`run_device_action("fix_docker_permissions")` stays: letting the login user
|
||||
use Docker is an OS action.
|
||||
|
||||
## [0.2.0] – 2026-10-07
|
||||
|
||||
### Added
|
||||
|
||||
- `run_command()` and `open_stream()`, the public command channel from
|
||||
napalm-device-types 2.6.0: an exec channel on the existing SSH transport, so
|
||||
no PTY, separate stderr and a real exit code. `privileged=True` runs as root
|
||||
directly, through `sudo -S` with the password on stdin (never on the command
|
||||
line), or through `sudo -n`, which fails instead of prompting.
|
||||
- `ContainerEngineMixin`: `container_engines()` and `open_container_engine()`,
|
||||
whose `open_api()` streams the Docker Engine API over `docker system
|
||||
dial-stdio` (NetOrk/netork#765). The existing Docker methods are unchanged.
|
||||
|
||||
### Changed
|
||||
|
||||
- Requires napalm-device-types >= 2.6.0.
|
||||
|
||||
## [0.1.0] – 2026-05-29
|
||||
|
||||
### Added
|
||||
|
||||
@@ -0,0 +1,191 @@
|
||||
Apache License
|
||||
Version 2.0, January 2004
|
||||
http://www.apache.org/licenses/
|
||||
|
||||
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
|
||||
|
||||
1. Definitions.
|
||||
|
||||
"License" shall mean the terms and conditions for use, reproduction,
|
||||
and distribution as defined by Sections 1 through 9 of this document.
|
||||
|
||||
"Licensor" shall mean the copyright owner or entity authorized by
|
||||
the copyright owner that is granting the License.
|
||||
|
||||
"Legal Entity" shall mean the union of the acting entity and all
|
||||
other entities that control, are controlled by, or are under common
|
||||
control with that entity. For the purposes of this definition,
|
||||
"control" means (i) the power, direct or indirect, to cause the
|
||||
direction or management of such entity, whether by contract or
|
||||
otherwise, or (ii) ownership of fifty percent (50%) or more of the
|
||||
outstanding shares, or (iii) beneficial ownership of such entity.
|
||||
|
||||
"You" (or "Your") shall mean an individual or Legal Entity
|
||||
exercising permissions granted by this License.
|
||||
|
||||
"Source" form shall mean the preferred form for making modifications,
|
||||
including but not limited to software source code, documentation
|
||||
source, and configuration files.
|
||||
|
||||
"Object" form shall mean any form resulting from mechanical
|
||||
transformation or translation of a Source form, including but
|
||||
not limited to compiled object code, generated documentation,
|
||||
and conversions to other media types.
|
||||
|
||||
"Work" shall mean the work of authorship made available under
|
||||
the License, as indicated by a copyright notice that is included in
|
||||
or attached to the work (an example is provided in the Appendix below).
|
||||
|
||||
"Derivative Works" shall mean any work, whether in Source or Object
|
||||
form, that is based on (or derived from) the Work and for which the
|
||||
editorial revisions, annotations, elaborations, or other transformations
|
||||
represent, as a whole, an original work of authorship. For the purposes
|
||||
of this License, Derivative Works shall not include works that remain
|
||||
separable from, or merely link (or bind by name) to the interfaces of,
|
||||
the Work and Derivative Works thereof.
|
||||
|
||||
"Contribution" shall mean, as submitted to the Licensor for inclusion
|
||||
in the Work by the copyright owner or by an individual or Legal Entity
|
||||
authorized to submit on behalf of the copyright owner. For the purposes
|
||||
of this definition, "submitted" means any form of electronic, verbal,
|
||||
or written communication sent to the Licensor or its representatives,
|
||||
including but not limited to communication on electronic mailing lists,
|
||||
source code control systems, and issue tracking systems that are managed
|
||||
by, or on behalf of, the Licensor for the purpose of discussing and
|
||||
improving the Work, but excluding communication that is conspicuously
|
||||
marked or designated in writing by the copyright owner as "Not a
|
||||
Contribution."
|
||||
|
||||
"Contributor" shall mean Licensor and any Legal Entity on behalf of
|
||||
whom a Contribution has been received by the Licensor and incorporated
|
||||
within the Work.
|
||||
|
||||
2. Grant of Copyright License. Subject to the terms and conditions of
|
||||
this License, each Contributor hereby grants to You a perpetual,
|
||||
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
||||
copyright license to reproduce, prepare Derivative Works of,
|
||||
publicly display, publicly perform, sublicense, and distribute the
|
||||
Work and such Derivative Works in Source or Object form.
|
||||
|
||||
3. Grant of Patent License. Subject to the terms and conditions of
|
||||
this License, each Contributor hereby grants to You a perpetual,
|
||||
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
||||
(except as stated in this section) patent license to make, have made,
|
||||
use, offer to sell, sell, import, and otherwise transfer the Work,
|
||||
where such license applies only to those patent claims licensable
|
||||
by such Contributor that are necessarily infringed by their
|
||||
Contribution(s) alone or by the combined Contribution(s) and the Work
|
||||
to which such Contribution(s) was submitted. If You institute patent
|
||||
litigation against any entity (including a cross-claim or counterclaim
|
||||
in a lawsuit) alleging that the Work or any Contribution embodied
|
||||
within the Work constitutes direct or contributory patent infringement,
|
||||
then any patent licenses granted to You under this License for that
|
||||
Work shall terminate as of the date such litigation is filed.
|
||||
|
||||
4. Redistribution. You may reproduce and distribute copies of the
|
||||
Work or Derivative Works thereof in any medium, with or without
|
||||
modifications, and in Source or Object form, provided that You
|
||||
meet the following conditions:
|
||||
|
||||
(a) You must give any other recipients of the Work or Derivative
|
||||
Works a copy of this License; and
|
||||
|
||||
(b) You must cause any modified files to carry prominent notices
|
||||
stating that You changed the files; and
|
||||
|
||||
(c) You must retain, in the Source form of any Derivative Works
|
||||
that You distribute, all copyright, patent, trademark, and
|
||||
attribution notices from the Source form of the Work,
|
||||
excluding those notices that do not pertain to any part of
|
||||
the Derivative Works; and
|
||||
|
||||
(d) If the Work includes a "NOTICE" text file as part of its
|
||||
distribution, You must include a readable copy of the
|
||||
attribution notices contained within such NOTICE file, in
|
||||
at least one of the following places: within a NOTICE text file
|
||||
distributed as part of the Derivative Works; within the Source
|
||||
form or documentation, if provided along with the Derivative
|
||||
Works; or, within a display generated by the Derivative Works,
|
||||
if and wherever such third-party notices normally appear. The
|
||||
contents of the NOTICE file are for informational purposes only
|
||||
and do not modify the License. You may add Your own attribution
|
||||
notices within Derivative Works that You distribute, alongside
|
||||
or as an addendum to the NOTICE text from the Work, provided
|
||||
that such additional attribution notices cannot be construed
|
||||
as modifying the License.
|
||||
|
||||
You may add Your own license statement for Your modifications and
|
||||
may provide additional grant of rights to use, copy, modify, merge,
|
||||
publish, distribute, sublicense, and/or sell copies of the Work,
|
||||
and to permit persons to whom the Work is furnished to do so,
|
||||
subject to the following conditions:
|
||||
|
||||
5. Submission of Contributions. Unless You explicitly state otherwise,
|
||||
any Contribution intentionally submitted for inclusion in the Work
|
||||
by You to the Licensor shall be under the terms and conditions of
|
||||
this License, without any additional terms or conditions.
|
||||
Notwithstanding the above, nothing herein shall supersede or modify
|
||||
the terms of any separate license agreement you may have executed
|
||||
with Licensor regarding such Contributions.
|
||||
|
||||
6. Trademarks. This License does not grant permission to use the trade
|
||||
names, trademarks, service marks, or product names of the Licensor,
|
||||
except as required for reasonable and customary use in describing the
|
||||
origin of the Work and reproducing the content of the NOTICE file.
|
||||
|
||||
7. Disclaimer of Warranty. Unless required by applicable law or
|
||||
agreed to in writing, Licensor provides the Work (and each
|
||||
Contributor provides its Contributions) on an "AS IS" BASIS,
|
||||
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
|
||||
implied, including, without limitation, any conditions of TITLE,
|
||||
MERCHANTIBILITY, or FITNESS FOR A PARTICULAR PURPOSE.
|
||||
See the License for the specific language governing permissions and
|
||||
limitations under the License.
|
||||
|
||||
8. Limitation of Liability. In no event and under no legal theory,
|
||||
whether in tort (including negligence), contract, or otherwise,
|
||||
unless required by applicable law (such as deliberate and grossly
|
||||
negligent acts) or agreed to in writing, shall any Contributor be
|
||||
liable to You for damages, including any direct, indirect, special,
|
||||
incidental, or exemplary damages of any character arising as a
|
||||
result of this License or out of the use or inability to use the
|
||||
Work (even if such Contributor has been advised of the possibility
|
||||
of such damages).
|
||||
|
||||
9. Accepting Warranty or Additional Liability. While redistributing
|
||||
the Work or Derivative Works thereof, You may choose to offer,
|
||||
and charge a fee for, acceptance of support, warranty, indemnity,
|
||||
or other liability obligations and/or rights consistent with this
|
||||
License. However, in accepting such obligations, You may offer only
|
||||
conditions consistent with this License, subject to the following
|
||||
additional conditions:
|
||||
|
||||
(a) You may offer additional warranty, indemnity, or other liability
|
||||
terms and conditions; and
|
||||
|
||||
(b) You may offer support for the Work in return for a fee.
|
||||
|
||||
END OF TERMS AND CONDITIONS
|
||||
|
||||
APPENDIX: How to apply the Apache License to your work.
|
||||
|
||||
To apply the Apache License to your work, attach the following
|
||||
boilerplate notice, with the fields enclosed by brackets "[]"
|
||||
replaced with your own identifying information. (Don't include
|
||||
the brackets!) The text should be enclosed in the appropriate
|
||||
comment syntax for the file format in question. It may also be
|
||||
possible to make it available with a creative commons license.
|
||||
|
||||
Copyright 2026 Christian Manivong
|
||||
|
||||
Licensed under the Apache License, Version 2.0 (the "License");
|
||||
you may not use this file except in compliance with the License.
|
||||
You may obtain a copy of the License at
|
||||
|
||||
http://www.apache.org/licenses/LICENSE-2.0
|
||||
|
||||
Unless required by applicable law or agreed to in writing, software
|
||||
distributed under the License is distributed on an "AS IS" BASIS,
|
||||
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
See the License for the specific language governing permissions and
|
||||
limitations under the License.
|
||||
@@ -24,7 +24,7 @@ pip install napalm napalm-linux
|
||||
Or from source:
|
||||
|
||||
```bash
|
||||
git clone https://github.com/chrismanivong/napalm-linux
|
||||
git clone https://git.netork.io/NAPALM/napalm-linux
|
||||
pip install -e napalm-linux/
|
||||
```
|
||||
|
||||
@@ -58,11 +58,11 @@ with Driver(
|
||||
|
||||
# OS-specific methods (from napalm-device-types OSDriver)
|
||||
packages = dev.get_packages()
|
||||
updates = dev.get_pending_updates()
|
||||
updates = dev.get_pending_updates()
|
||||
services = dev.get_services()
|
||||
users = dev.get_users()
|
||||
procs = dev.get_processes()
|
||||
jobs = dev.get_cron_jobs()
|
||||
users = dev.get_os_users()
|
||||
procs = dev.get_processes()
|
||||
jobs = dev.get_scheduled_jobs()["jobs"]
|
||||
|
||||
# Upgrade specific packages
|
||||
result = dev.apply_updates(["openssh-server", "curl"])
|
||||
@@ -91,7 +91,7 @@ with Driver(
|
||||
| `get_config()` | ✅ | Returns `ip addr` + `ip route` output |
|
||||
| `ping()` | ✅ | Executes `ping` on the remote host |
|
||||
| `load_merge_candidate()` | ❌ | Not applicable for generic Linux |
|
||||
| `load_replace_candidate()` | ❌ | Not applicable for generic Linux |
|
||||
| `load_replace_candidate()` | ❌ | Not applicable for generic Linux; `None`, so a caller can tell |
|
||||
| `compare_config()` | ❌ | Not applicable for generic Linux |
|
||||
| `commit_config()` | ❌ | Not applicable for generic Linux |
|
||||
| `discard_config()` | ❌ | Not applicable for generic Linux |
|
||||
@@ -106,9 +106,11 @@ with Driver(
|
||||
| `apply_updates(packages)` | ✅ | apt, dnf, yum, apk, pacman |
|
||||
| `get_services()` | ✅ | systemd, one round trip (fallback: SysV `service`) |
|
||||
| `manage_service(name, action)` | ✅ | systemd: start, stop, restart, enable, disable |
|
||||
| `get_users()` | ✅ | `/etc/passwd` + `/etc/group` |
|
||||
| `get_os_users()` | ✅ | `/etc/passwd` + `/etc/group` |
|
||||
| `get_processes()` | ✅ | `ps axo` |
|
||||
| `get_cron_jobs()` | ✅ | user crontabs + `/etc/cron.d/` |
|
||||
| `get_scheduled_jobs()` | ✅ | `/etc/crontab`, `/etc/cron.d`, user crontabs, run-parts, anacron, systemd timers (napalm-device-types' `PosixScheduledJobsMixin`) |
|
||||
| `manage_scheduled_job(key, action, digest=)` | ✅ | enable, disable, run now |
|
||||
| `put_scheduled_job(spec)` / `delete_scheduled_job(key, digest=)` | ✅ | an application's own job: a systemd timer, else `/etc/cron.d`, else the user's crontab |
|
||||
|
||||
## Package manager auto-detection
|
||||
|
||||
@@ -121,7 +123,7 @@ apt → dnf → yum → apk → pacman
|
||||
Force a specific package manager:
|
||||
|
||||
```python
|
||||
optional_args={"pkg_manager": "dnf"}
|
||||
optional_args = {"pkg_manager": "dnf"}
|
||||
```
|
||||
|
||||
## SSH user permissions
|
||||
@@ -136,11 +138,24 @@ The SSH user needs read access to:
|
||||
| `systemctl list-unit-files`, `systemctl show` | unprivileged |
|
||||
| `systemctl start/stop/restart/enable/disable` | `root`, or `sudo` (with `sudo_password`, or passwordless) |
|
||||
| `apt list --upgradable` | may require `apt-get update` (root) |
|
||||
| `dnf check-update` / `yum check-update` | unprivileged, but slower without cache |
|
||||
| `dnf --cacheonly check-update` / `yum --cacheonly check-update` | `root` or `sudo`; reads the cache that `dnf makecache` (root) fills |
|
||||
|
||||
For full functionality it is recommended to run as `root` or grant passwordless `sudo` for
|
||||
the above commands.
|
||||
|
||||
With a `sudo_password`, privileged commands run on an exec channel next to the interactive
|
||||
shell: the password reaches `sudo -S` on stdin, never a command line, so it shows neither in
|
||||
the process list nor in a shell history. The interactive session switches its history off
|
||||
before its first command.
|
||||
|
||||
Versions before that typed `echo '<password>' | sudo -S -p "" <command>` into the interactive
|
||||
shell, so the login user's history kept the password once per command.
|
||||
`get_history_sudo_lines()` counts those lines per history file without reading them, and
|
||||
`remove_history_sudo_lines()` deletes exactly them and gives `/etc/snmp/snmpd.conf` and
|
||||
`/etc/apt/apt.conf.d/00proxy` back to root where they were left to the login user
|
||||
(napalm-device-types' `SudoHistoryMixin`). Rotate the sudo password afterwards: backups,
|
||||
snapshots and audit logs may still hold it.
|
||||
|
||||
`get_services()` and `manage_service()` come from napalm-device-types'
|
||||
`SystemdServicesMixin`; this driver supplies only the transport. An action runs as
|
||||
`timeout 45 systemctl --no-ask-password <action> -- <unit>.service`, so a unit that hangs
|
||||
|
||||
@@ -0,0 +1,73 @@
|
||||
"""The packages dpkg has on a Debian-family host: the query and its parse."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from napalm_device_types.models import PackageDict
|
||||
|
||||
#: One line per package dpkg knows, its state first (``ii``, ``rc``, ``hi``, …):
|
||||
#: dpkg also lists removed packages whose configuration it still keeps (#17).
|
||||
DPKG_QUERY_COMMAND = (
|
||||
"dpkg-query -W -f='${db:Status-Abbrev}\\t${Package}\\t${Version}\\t${Installed-Size}"
|
||||
"\\t${source:Package}\\t${source:Version}\\t${binary:Summary}\\n' 2>/dev/null"
|
||||
)
|
||||
#: The second letter of ``db:Status-Abbrev`` for a package whose files are gone:
|
||||
#: ``n`` not installed, ``c`` only its configuration left (``rc``). Every other
|
||||
#: state -- half-installed, unpacked, half-configured, awaiting triggers -- has
|
||||
#: its files on disk.
|
||||
_NOT_ON_DISK = frozenset("nc")
|
||||
|
||||
|
||||
class DpkgPackageDict(PackageDict):
|
||||
"""A dpkg package with the source package it was built from."""
|
||||
|
||||
source_package: str
|
||||
source_version: str
|
||||
|
||||
|
||||
def parse_dpkg_query(out: str) -> list[PackageDict]:
|
||||
"""The packages in ``DPKG_QUERY_COMMAND``'s output whose files are on disk."""
|
||||
packages: list[PackageDict] = []
|
||||
for line in out.splitlines():
|
||||
# Summary stays last and keeps whatever it contains: maxsplit must
|
||||
# equal the number of tabs the format writes, not the field count.
|
||||
status, _, line = line.partition("\t")
|
||||
if status[1:2] in _NOT_ON_DISK:
|
||||
continue
|
||||
package = _package(line.split("\t", 5))
|
||||
if package is not None:
|
||||
packages.append(package)
|
||||
return packages
|
||||
|
||||
|
||||
def _package(parts: list[str]) -> DpkgPackageDict | None:
|
||||
if len(parts) < 2:
|
||||
return None
|
||||
name = parts[0].strip()
|
||||
version = parts[1].strip()
|
||||
size = int(parts[2].strip()) * 1024 if len(parts) > 2 and parts[2].strip().isdigit() else 0
|
||||
# Debian source package (e.g. openssh-server → openssh) for OSV matching.
|
||||
source_package = parts[3].strip() if len(parts) > 3 and parts[3].strip() else name
|
||||
# And its version, which is a different number from this package's.
|
||||
#
|
||||
# OSV states Debian ranges in *source* versions. A source package
|
||||
# that ships several binaries gives each its own upstream version:
|
||||
# libldb2 is 2:2.11.0+samba4.22.11+dfsg-… while its source, samba,
|
||||
# is 2:4.22.11+dfsg-…. A consumer matching on source_package and
|
||||
# comparing `version` compares two unrelated numbers — dpkg reads
|
||||
# ldb's 2.11.0 as older than the 2:4.17.4+dfsg-1 that fixed
|
||||
# CVE-2022-44640, and a host five releases past the fix was reported
|
||||
# vulnerable on four packages at once.
|
||||
#
|
||||
# dpkg leaves this empty when it equals `Version`; so does an older
|
||||
# dpkg that does not know the field at all.
|
||||
source_version = parts[4].strip() if len(parts) > 4 and parts[4].strip() else version
|
||||
return {
|
||||
"name": name,
|
||||
"version": version,
|
||||
"installed": True,
|
||||
"description": parts[5].strip() if len(parts) > 5 else "",
|
||||
"size": size,
|
||||
"source": "apt",
|
||||
"source_package": source_package,
|
||||
"source_version": source_version,
|
||||
}
|
||||
@@ -0,0 +1,145 @@
|
||||
"""Renaming the host: static and runtime hostname, ``/etc/hosts``, cloud-init (#45)."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import re
|
||||
from shlex import quote as _shlex_quote
|
||||
from typing import TYPE_CHECKING
|
||||
|
||||
if TYPE_CHECKING:
|
||||
from napalm_device_types import CommandResult
|
||||
from napalm_device_types.models import FixStepOutcomeDict
|
||||
|
||||
#: One label of a hostname (RFC 1123): letters, digits and inner hyphens. It
|
||||
#: also keeps every name ``set_hostname`` accepts safe in a root shell.
|
||||
_LABEL_RE = re.compile(r"^(?!-)[A-Za-z0-9-]{1,63}(?<!-)$")
|
||||
#: Names ``/etc/hosts`` keeps whatever the host was called.
|
||||
_LOOPBACK_NAMES = frozenset({"localhost", "localhost.localdomain"})
|
||||
#: What the host is called before the rename: its short name and its FQDN.
|
||||
_OLD_NAME_COMMANDS = ("hostname", "hostname -f 2>/dev/null")
|
||||
#: Without this, cloud-init's ``update_hostname`` puts the image's name back on
|
||||
#: the next boot.
|
||||
_CLOUD_INIT_PRESERVE = "/etc/cloud/cloud.cfg.d/99-preserve-hostname.cfg"
|
||||
_CLOUD_INIT_PRESERVE_CONTENT = (
|
||||
"# The hostname was set on purpose: keep it across reboots.\npreserve_hostname: true\n"
|
||||
)
|
||||
|
||||
|
||||
def _split_hostname(name: str) -> tuple[str, str | None]:
|
||||
"""``(short name, FQDN or None)`` of *name*.
|
||||
|
||||
:raises ValueError: when *name* is not a valid hostname or FQDN.
|
||||
"""
|
||||
labels = name.split(".")
|
||||
if len(name) > 253 or not all(_LABEL_RE.match(label) for label in labels):
|
||||
raise ValueError(f"not a valid hostname: {name!r}")
|
||||
return labels[0], (name if len(labels) > 1 else None)
|
||||
|
||||
|
||||
def _renamed_line(line: str, targets: set[str], new: list[str]) -> str | None:
|
||||
"""*line* of ``/etc/hosts`` with *new* where the first of *targets* stood.
|
||||
|
||||
The other names on it stay; ``None`` when the line names none of *targets*.
|
||||
"""
|
||||
entry, hash_, comment = line.partition("#")
|
||||
address, *names = entry.split() or [""]
|
||||
if not any(n.lower() in targets for n in names):
|
||||
return None
|
||||
result: list[str] = []
|
||||
inserted = False
|
||||
for name in names:
|
||||
if name.lower() not in targets:
|
||||
result.append(name)
|
||||
elif not inserted:
|
||||
result += new
|
||||
inserted = True
|
||||
tail = f" {hash_}{comment}" if hash_ else ""
|
||||
return f"{address}\t{' '.join(dict.fromkeys(result))}{tail}"
|
||||
|
||||
|
||||
def _rename_in_hosts(content: str, old_names: set[str], short: str, fqdn: str | None) -> str:
|
||||
"""*content* of ``/etc/hosts`` with the host's old names replaced by the new.
|
||||
|
||||
Every line naming the host gets the new names. When no line names it, the
|
||||
Debian ``127.0.1.1`` line takes them; a file with neither is returned
|
||||
unchanged -- nothing is appended to a host that never listed itself.
|
||||
"""
|
||||
old = {n.lower() for n in old_names} - _LOOPBACK_NAMES
|
||||
new = [fqdn, short] if fqdn else [short]
|
||||
lines = content.split("\n")
|
||||
renamed = [_renamed_line(line, old, new) for line in lines]
|
||||
if all(r is None for r in renamed):
|
||||
renamed = _renamed_self_line(lines, new)
|
||||
return "\n".join(r or line for line, r in zip(lines, renamed, strict=True))
|
||||
|
||||
|
||||
def _renamed_self_line(lines: list[str], new: list[str]) -> list[str | None]:
|
||||
"""The first ``127.0.1.1`` line of *lines* naming *new* instead, the rest ``None``."""
|
||||
result: list[str | None] = [None] * len(lines)
|
||||
for i, line in enumerate(lines):
|
||||
address, *names = line.partition("#")[0].split() or [""]
|
||||
if address == "127.0.1.1" and names:
|
||||
result[i] = _renamed_line(line, {n.lower() for n in names}, new)
|
||||
break
|
||||
return result
|
||||
|
||||
|
||||
class HostnameMixin:
|
||||
"""``set_hostname`` for a Linux host, over the driver's command channel."""
|
||||
|
||||
if TYPE_CHECKING:
|
||||
|
||||
def run_command(
|
||||
self,
|
||||
command: str,
|
||||
*,
|
||||
privileged: bool = False,
|
||||
timeout: float = 60,
|
||||
stdin: bytes | None = None,
|
||||
) -> CommandResult: ...
|
||||
|
||||
def _install_file_as_root(self, path: str, content: str) -> CommandResult: ...
|
||||
|
||||
def _root_outcome(self, command: str, timeout: float, done: str) -> FixStepOutcomeDict: ...
|
||||
|
||||
def set_hostname(self, new_hostname: str) -> None:
|
||||
"""Rename the host: static and runtime hostname, ``/etc/hosts``, cloud-init.
|
||||
|
||||
Takes a bare name or an FQDN; the hostname itself is the short name, and
|
||||
an FQDN goes to ``/etc/hosts`` in front of it. ``hostnamectl`` sets it
|
||||
where there is one, otherwise ``/etc/hostname`` and ``hostname(1)``.
|
||||
Files are installed from a staged copy (``_install_file_as_root``).
|
||||
|
||||
:raises ValueError: for a name that is not a valid hostname, before
|
||||
anything runs on the host.
|
||||
:raises RuntimeError: when the host refuses a step; the steps before it
|
||||
stay done.
|
||||
"""
|
||||
short, fqdn = _split_hostname(new_hostname)
|
||||
old_names = {self.run_command(c, timeout=30).stdout.strip() for c in _OLD_NAME_COMMANDS}
|
||||
hosts = self.run_command("cat /etc/hosts", timeout=30)
|
||||
|
||||
name = _shlex_quote(short)
|
||||
outcome = self._root_outcome(
|
||||
f"if command -v hostnamectl >/dev/null 2>&1 && hostnamectl set-hostname {name} "
|
||||
f"2>/dev/null; then :; else printf '%s\\n' {name} > /etc/hostname "
|
||||
f"&& hostname {name}; fi",
|
||||
30,
|
||||
"",
|
||||
)
|
||||
if not outcome["ok"]:
|
||||
raise RuntimeError(outcome["output"] or "the host refused the new hostname")
|
||||
|
||||
if hosts.exit_code == 0:
|
||||
renamed = _rename_in_hosts(hosts.stdout, old_names - {""}, short, fqdn)
|
||||
if renamed != hosts.stdout:
|
||||
self._install_or_raise("/etc/hosts", renamed)
|
||||
if self.run_command("test -d /etc/cloud/cloud.cfg.d", timeout=30).exit_code == 0:
|
||||
self._install_or_raise(_CLOUD_INIT_PRESERVE, _CLOUD_INIT_PRESERVE_CONTENT)
|
||||
|
||||
def _install_or_raise(self, path: str, content: str) -> None:
|
||||
"""``_install_file_as_root``, raising its output when it failed."""
|
||||
result = self._install_file_as_root(path, content)
|
||||
if result.exit_code != 0:
|
||||
reason = (result.stderr or result.stdout).strip() or f"status {result.exit_code}"
|
||||
raise RuntimeError(f"hostname set, but {path} could not be written: {reason}")
|
||||
@@ -0,0 +1,82 @@
|
||||
"""Personal accounts on a Linux host, with shadow-utils (NetOrk/netork#1793).
|
||||
|
||||
napalm-device-types' ``LocalAccountsMixin`` runs the steps; this names the
|
||||
commands. A locked account is an expired one (``usermod -L -e 1``): PAM's
|
||||
account check refuses it every login, a key's too, where a ``!`` in front of
|
||||
the password -- ``usermod -L`` alone -- stops only the password. Opening it
|
||||
again lifts the expiry and gives the old password back.
|
||||
|
||||
An account whose password is removed (NetOrk/netork#2013) gets ``*`` as its
|
||||
password field, which no hash matches: it logs in with a key only. Not an
|
||||
empty field (``passwd -d``), which pam_unix's ``nullok`` -- on by default on
|
||||
Debian and Ubuntu -- takes as "no password needed" for ``su`` and the console.
|
||||
Not ``!``, which sshd takes for a locked account and refuses a key too where
|
||||
PAM is off (``UsePAM no``). And not the expiry, which is the lock.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import shlex
|
||||
import time
|
||||
|
||||
from napalm_device_types import LocalAccountsMixin
|
||||
|
||||
#: What the password field holds when the account never had a password.
|
||||
_NO_PASSWORD = frozenset({"", "!", "!!", "!*", "*"})
|
||||
#: The password field of an account that logs in with a key only: no hash matches it.
|
||||
_KEY_ONLY = "*"
|
||||
|
||||
|
||||
class LinuxLocalAccountsMixin(LocalAccountsMixin):
|
||||
ACCOUNT_SHELL = "/bin/bash"
|
||||
#: Debian and Ubuntu grant ``%sudo``, the Red Hat family ``%wheel``, old Ubuntu ``%admin``.
|
||||
ACCOUNT_ADMIN_GROUPS = ("sudo", "wheel", "admin")
|
||||
SUDOERS_DIR = "/etc/sudoers.d"
|
||||
ROOT_GROUP = "root"
|
||||
|
||||
def _account_create(self, name: str, password_hash: str | None) -> list[list[str]]:
|
||||
password = ["-p", password_hash] if password_hash else []
|
||||
return [["useradd", "-m", "-s", self.ACCOUNT_SHELL, *password, name]]
|
||||
|
||||
def _account_create_with_uid(self, name: str, uid: int) -> list[list[str]]:
|
||||
# Below UID_MIN useradd warns and goes on: netOrk's own account is a system's.
|
||||
return [["useradd", "-m", "-u", str(uid), "-s", self.ACCOUNT_SHELL, name]]
|
||||
|
||||
def _account_open(
|
||||
self, name: str, password_hash: str | None, *, locked: bool
|
||||
) -> list[list[str]]:
|
||||
if password_hash:
|
||||
return [["usermod", "-e", "", "-p", password_hash, name]]
|
||||
# usermod -U refuses to leave an account without any password.
|
||||
had_one = self._shadow(name)[1].lstrip("!") not in _NO_PASSWORD
|
||||
return [["usermod", *(["-U"] if had_one else []), "-e", "", name]]
|
||||
|
||||
def _account_lock(self, name: str, *, locked: bool) -> list[list[str]]:
|
||||
return [] if locked else [["usermod", "-L", "-e", "1", name]]
|
||||
|
||||
def _account_locked(self, name: str, passwd: list[str]) -> bool:
|
||||
expire = self._shadow(name)[7]
|
||||
# pam_unix: expired from the day sp_expire names on.
|
||||
return bool(expire) and int(expire) <= int(time.time() // 86400)
|
||||
|
||||
def _account_leave_group(self, name: str, group: str, groups: list[str]) -> list[str]:
|
||||
return ["gpasswd", "-d", name, group]
|
||||
|
||||
def _account_clear_password(self, name: str) -> list[list[str]]:
|
||||
# usermod -p leaves the expiry -- the lock -- alone, and dates the change today,
|
||||
# so pam_unix asks for no new password at the next key login.
|
||||
return [["usermod", "-p", _KEY_ONLY, name]]
|
||||
|
||||
def _shadow(self, name: str) -> list[str]:
|
||||
"""*name*'s shadow entry, split; only the lock and the expiry are looked at.
|
||||
|
||||
:raises RuntimeError: when it cannot be read.
|
||||
"""
|
||||
result = self.run_command(
|
||||
shlex.join(["getent", "shadow", name]), privileged=True, timeout=30
|
||||
)
|
||||
fields = result.stdout.strip().split(":")
|
||||
if result.exit_code != 0 or len(fields) < 9 or fields[0] != name:
|
||||
reason = (result.stderr or result.stdout).strip() or f"exit {result.exit_code}"
|
||||
raise RuntimeError(f"cannot read the shadow entry of {name}: {reason}")
|
||||
return fields
|
||||
@@ -0,0 +1,65 @@
|
||||
"""NAPALM's ``ping()`` reply from what ``ping(8)`` prints: iputils and BusyBox, IPv4 and IPv6."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import re
|
||||
from shlex import quote
|
||||
from typing import Any
|
||||
|
||||
#: iputils: ``5 packets transmitted, 5 received, +2 errors, 0% packet loss, time 4005ms``;
|
||||
#: BusyBox: ``2 packets transmitted, 2 packets received, 0% packet loss`` (#15).
|
||||
_SUMMARY = re.compile(
|
||||
r"(\d+) packets transmitted, (\d+) (?:packets )?received,(?: [^,]*,)*? ([\d.]+)% packet loss"
|
||||
)
|
||||
#: iputils: ``rtt min/avg/max/mdev = 0.1/0.2/0.3/0.05 ms``;
|
||||
#: BusyBox: ``round-trip min/avg/max = 0.1/0.2/0.3 ms``, without a deviation.
|
||||
_RTT = re.compile(
|
||||
r"(?:rtt|round-trip) min/avg/max(?:/\w+)? = ([\d.]+)/([\d.]+)/([\d.]+)(?:/([\d.]+))? ms"
|
||||
)
|
||||
#: One reply: ``bytes from <address>:`` or, for a name, ``bytes from <name> (<address>):``.
|
||||
#: The address may be IPv6 (``2001:db8::1``, ``fe80::1%eth0``); ``icmp_seq=`` (iputils)
|
||||
#: or ``seq=`` (BusyBox), and a ``ttl=`` that is not always there, come before the time.
|
||||
_PROBE = re.compile(r"bytes from (?:\S+ \()?([^\s()]+?)\)?: .*?\btime=([\d.]+) ?ms")
|
||||
|
||||
|
||||
def ping_command(
|
||||
destination: str, source: str, ttl: int, timeout: int, size: int, count: int
|
||||
) -> str:
|
||||
"""The shell line that pings *destination*: the names quoted, the numbers numbers (#55).
|
||||
|
||||
:raises ValueError: for a count, timeout, size or ttl that is no number, and for a
|
||||
destination or source that ping would read as an option (#63): no address or
|
||||
hostname starts with ``-``.
|
||||
"""
|
||||
for name in (destination, source):
|
||||
if name.startswith("-"):
|
||||
raise ValueError(f"{name!r} would be read as a ping option, not an address")
|
||||
numbers = f"-c {int(count)} -W {int(timeout)} -s {int(size)} -t {int(ttl)}"
|
||||
src_opt = f" -I {quote(source)}" if source else ""
|
||||
return f"ping {numbers}{src_opt} {quote(destination)} 2>&1"
|
||||
|
||||
|
||||
def parse_ping(output: str) -> dict[str, Any]:
|
||||
"""``{"success": {...}}`` for *output* with a summary line, else ``{"error": output}``."""
|
||||
summary = _SUMMARY.search(output)
|
||||
if not summary:
|
||||
return {"error": output}
|
||||
sent, received = int(summary.group(1)), int(summary.group(2))
|
||||
rtt = _RTT.search(output)
|
||||
rtts = [float(v) if v else 0.0 for v in rtt.groups()] if rtt else [0.0] * 4
|
||||
results = [
|
||||
{"ip_address": probe.group(1), "rtt": float(probe.group(2))}
|
||||
for probe in map(_PROBE.search, output.splitlines())
|
||||
if probe
|
||||
]
|
||||
return {
|
||||
"success": {
|
||||
"probes_sent": sent,
|
||||
"packet_loss": sent - received,
|
||||
"rtt_min": rtts[0],
|
||||
"rtt_avg": rtts[1],
|
||||
"rtt_max": rtts[2],
|
||||
"rtt_stddev": rtts[3],
|
||||
"results": results,
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,15 @@
|
||||
"""What napalm-device-types implements for any POSIX host over ``run_command``.
|
||||
|
||||
The driver supplies ``run_command``; the readings, their parses and the writes are
|
||||
the mixins': scheduled jobs (cron, anacron, systemd timers) and time sync (chrony,
|
||||
systemd-timesyncd, ``timedatectl``). Their default paths are Debian's, which a
|
||||
Linux host shares.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from napalm_device_types import PosixScheduledJobsMixin, PosixTimeSyncMixin
|
||||
|
||||
|
||||
class LinuxPosixMixin(PosixScheduledJobsMixin, PosixTimeSyncMixin):
|
||||
"""Scheduled jobs and time sync of the host, over the driver's ``run_command``."""
|
||||
@@ -0,0 +1,42 @@
|
||||
"""Readings of the host's processes: listening sockets, log sources, running backups.
|
||||
|
||||
The first two commands are napalm-device-types' and read-only. Root only widens
|
||||
what they see -- ``ss`` names every process behind a socket, ``/proc/<pid>/fd`` shows every
|
||||
process's open files -- so both go through sudo where the driver can, and as the
|
||||
login user where it cannot; the mixins then say the reading is not ``attributed``.
|
||||
The running backups need no root: every process's command line and cgroup are
|
||||
readable to the login user (``_running_backups``).
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from typing import TYPE_CHECKING
|
||||
|
||||
from napalm_device_types import ListeningSocketsMixin, LogSourcesMixin
|
||||
|
||||
from napalm_linux._running_backups import LinuxRunningBackupsMixin
|
||||
|
||||
#: Seconds either reading may take; a busy host lists thousands of descriptors.
|
||||
_READ_TIMEOUT = 60
|
||||
|
||||
|
||||
class LinuxProcessReadingsMixin(ListeningSocketsMixin, LogSourcesMixin, LinuxRunningBackupsMixin):
|
||||
"""The transports for ``get_listening_sockets`` and ``get_log_sources``, and
|
||||
``get_running_backups``."""
|
||||
|
||||
if TYPE_CHECKING: # pragma: no cover - the driver's own, declared for type checkers
|
||||
|
||||
def _send(self, command: str, read_timeout: float = 100) -> str: ...
|
||||
|
||||
def _run_privileged(self, command: str, timeout: float = 100) -> str: ...
|
||||
|
||||
def _read_as_root_if_possible(self, command: str, privileged: bool) -> str:
|
||||
if privileged:
|
||||
return self._run_privileged(command, _READ_TIMEOUT)
|
||||
return self._send(command, read_timeout=_READ_TIMEOUT)
|
||||
|
||||
def _run_listening_sockets_command(self, command: str, *, privileged: bool) -> str:
|
||||
return self._read_as_root_if_possible(command, privileged)
|
||||
|
||||
def _run_log_sources_command(self, command: str, *, privileged: bool) -> str:
|
||||
return self._read_as_root_if_possible(command, privileged)
|
||||
@@ -0,0 +1,106 @@
|
||||
"""Routes from ``ip route show``, one address family at a time."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import re
|
||||
from collections.abc import Iterator
|
||||
from typing import NamedTuple
|
||||
|
||||
#: The command per family. ``ip -6 route show`` names its default route ``default``
|
||||
#: as well, so only the command a line came from says which family it is (#6).
|
||||
IP_ROUTE_COMMANDS = {"ipv4": "ip -4 route show", "ipv6": "ip -6 route show"}
|
||||
_DEFAULT = {"ipv4": "0.0.0.0/0", "ipv6": "::/0"}
|
||||
_HOST_PREFIX = {"ipv4": "/32", "ipv6": "/128"}
|
||||
|
||||
#: The route types ``ip route`` prints in front of the destination; a unicast route
|
||||
#: carries none (#57).
|
||||
_ROUTE_TYPES = frozenset(
|
||||
{
|
||||
"unicast",
|
||||
"local",
|
||||
"broadcast",
|
||||
"anycast",
|
||||
"multicast",
|
||||
"blackhole",
|
||||
"unreachable",
|
||||
"prohibit",
|
||||
"throw",
|
||||
"nat",
|
||||
"xresolve",
|
||||
}
|
||||
)
|
||||
#: Route types that send nothing out of an interface: no next hop, and no outgoing
|
||||
#: interface either, though IPv6 names ``lo`` for them.
|
||||
_NO_FORWARDING = frozenset({"blackhole", "unreachable", "prohibit", "throw"})
|
||||
#: The line a multipath route's next hops start with, one each, after the route.
|
||||
_NEXTHOP = "nexthop"
|
||||
|
||||
#: ``via 192.0.2.1``, or with the gateway's family in front: ``via inet6 fe80::1`` for an
|
||||
#: IPv4 route with an IPv6 next hop (RFC 8950, #65).
|
||||
_VIA = re.compile(r"via\s+(?:inet6?\s+)?(\S+)")
|
||||
_DEV = re.compile(r"dev\s+(\S+)")
|
||||
_PROTO = re.compile(r"proto\s+(\S+)")
|
||||
_METRIC = re.compile(r"metric\s+(\d+)")
|
||||
|
||||
|
||||
class IpRoute(NamedTuple):
|
||||
"""One route of ``ip route show``; a multipath route is one per next hop."""
|
||||
|
||||
network: str
|
||||
proto: str
|
||||
nexthop: str
|
||||
iface: str
|
||||
metric: int
|
||||
route_type: str = "unicast"
|
||||
|
||||
@property
|
||||
def attributes(self) -> dict[str, str]:
|
||||
"""NAPALM's ``protocol_attributes`` for this route: its type, unless unicast."""
|
||||
return {} if self.route_type == "unicast" else {"type": self.route_type}
|
||||
|
||||
|
||||
def parse_ip_route(out: str, family: str) -> Iterator[IpRoute]:
|
||||
"""The routes in *out*, the output of ``IP_ROUTE_COMMANDS[family]``."""
|
||||
route = ""
|
||||
hops: list[str] = []
|
||||
for line in out.splitlines():
|
||||
line = line.strip()
|
||||
if not line or line.startswith("#"):
|
||||
continue
|
||||
if line.split(None, 1)[0] == _NEXTHOP:
|
||||
hops.append(line)
|
||||
continue
|
||||
if route:
|
||||
yield from _routes(route, hops, family)
|
||||
route, hops = line, []
|
||||
if route:
|
||||
yield from _routes(route, hops, family)
|
||||
|
||||
|
||||
def with_length(prefix: str) -> str:
|
||||
"""*prefix* with a prefix length: a host route without one is ``/32`` or ``/128``
|
||||
by the address's family (#64)."""
|
||||
if "/" in prefix:
|
||||
return prefix
|
||||
return prefix + _HOST_PREFIX["ipv6" if ":" in prefix else "ipv4"]
|
||||
|
||||
|
||||
def _routes(line: str, hops: list[str], family: str) -> Iterator[IpRoute]:
|
||||
"""The route *line* with its multipath next-hop lines *hops*: one per next hop."""
|
||||
words = line.split()
|
||||
route_type = words.pop(0) if words[0] in _ROUTE_TYPES and len(words) > 1 else "unicast"
|
||||
network = _DEFAULT[family] if words[0] == "default" else words[0]
|
||||
if "/" not in network:
|
||||
network += _HOST_PREFIX[family]
|
||||
proto = _first(_PROTO, line) or "kernel"
|
||||
metric = int(_first(_METRIC, line) or 0)
|
||||
if route_type in _NO_FORWARDING:
|
||||
yield IpRoute(network, proto, "", "", metric, route_type)
|
||||
return
|
||||
for hop in hops or [line]:
|
||||
yield IpRoute(network, proto, _first(_VIA, hop), _first(_DEV, hop), metric, route_type)
|
||||
|
||||
|
||||
def _first(pattern: re.Pattern[str], line: str) -> str:
|
||||
match = pattern.search(line)
|
||||
return match.group(1) if match else ""
|
||||
@@ -0,0 +1,69 @@
|
||||
"""The packages rpm has on a dnf or yum host: the query and its parse."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from typing import NotRequired
|
||||
|
||||
from napalm_device_types.models import PackageDict
|
||||
|
||||
#: One line per package, the version as ``[epoch:]version-release`` the way dpkg
|
||||
#: writes it: the epoch only where the package has one. Oracle's and Red Hat's
|
||||
#: fixes name it (``1:6.2.0-13.el9``), and without it an epoch-1 fix reads as newer
|
||||
#: than every installed build (NetOrk/netork#2394). The source rpm before the
|
||||
#: summary, which stays last and keeps whatever it contains.
|
||||
RPM_QUERY_COMMAND = (
|
||||
"rpm -qa --queryformat "
|
||||
"'%{NAME}\\t%|EPOCH?{%{EPOCH}:}:{}|%{VERSION}-%{RELEASE}\\t%{SIZE}\\t%{SOURCERPM}"
|
||||
"\\t%{SUMMARY}\\n'"
|
||||
" 2>/dev/null"
|
||||
)
|
||||
|
||||
|
||||
class RpmPackageDict(PackageDict):
|
||||
"""An rpm package with the name of the source rpm it was built from.
|
||||
|
||||
``perf``, ``python3-perf`` and ``bpftool`` come from ``kernel``, and Red Hat
|
||||
lists them in every kernel CVE; their source is what tells them apart from
|
||||
user space (NetOrk/netork#2394). Deliberately not dpkg's ``source_package``:
|
||||
netOrk reads that as the name a distribution files its verdicts under, which
|
||||
holds for Debian and not for Oracle or Red Hat, whose records name the binary.
|
||||
Absent where rpm names none (``gpg-pubkey``).
|
||||
"""
|
||||
|
||||
source_rpm: NotRequired[str]
|
||||
|
||||
|
||||
def source_rpm_name(sourcerpm: str) -> str | None:
|
||||
"""``kernel-5.14.0-687.66.1.el9_8.src.rpm`` → ``kernel``; ``None`` for ``(none)``."""
|
||||
stem = sourcerpm.strip()
|
||||
for suffix in (".src.rpm", ".nosrc.rpm"):
|
||||
if stem.endswith(suffix):
|
||||
stem = stem.removesuffix(suffix)
|
||||
break
|
||||
else:
|
||||
return None
|
||||
name, *version_release = stem.rsplit("-", 2)
|
||||
return name if len(version_release) == 2 and name else None
|
||||
|
||||
|
||||
def parse_rpm_query(out: str, source: str) -> list[PackageDict]:
|
||||
"""The packages in ``RPM_QUERY_COMMAND``'s output, each marked as *source*'s."""
|
||||
packages: list[PackageDict] = []
|
||||
for line in out.splitlines():
|
||||
parts = line.split("\t", 4)
|
||||
if len(parts) < 2:
|
||||
continue
|
||||
size = parts[2].strip() if len(parts) > 2 else ""
|
||||
package: RpmPackageDict = {
|
||||
"name": parts[0].strip(),
|
||||
"version": parts[1].strip(),
|
||||
"installed": True,
|
||||
"description": parts[4].strip() if len(parts) > 4 else "",
|
||||
"size": int(size) if size.isdigit() else 0,
|
||||
"source": source,
|
||||
}
|
||||
built_from = source_rpm_name(parts[3]) if len(parts) > 3 else None
|
||||
if built_from:
|
||||
package["source_rpm"] = built_from
|
||||
packages.append(package)
|
||||
return packages
|
||||
@@ -0,0 +1,188 @@
|
||||
"""The host's own backups a restart would abort (napalm-device-types' ``RunningBackupsMixin``).
|
||||
|
||||
A file-level backup on a Linux host is a process of a backup tool -- restic, borg,
|
||||
borgmatic, duplicity, rsnapshot and the like -- started by a systemd timer, a cron
|
||||
line or by hand. One round trip, as the login user (every process's command line
|
||||
and cgroup are readable to it), reads the host's clock, the processes with their
|
||||
age, and each one's cgroup; the systemd service a backup runs in is its job, the
|
||||
service a timer starts, which is how netOrk shows the timer's scheduled job.
|
||||
|
||||
What a tool is doing is read from its subcommand: ``restic backup`` is a backup,
|
||||
``restic forget`` a prune, ``restic mount`` none. ``borg serve`` counts: it is the
|
||||
receiving end of another host's backup.
|
||||
|
||||
A ``ps`` without ``etimes`` (busybox) fails the reading rather than report nothing.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import posixpath
|
||||
import re
|
||||
from typing import TYPE_CHECKING, NamedTuple
|
||||
|
||||
from napalm_device_types import RunningBackupDict, RunningBackupKind, RunningBackupsMixin
|
||||
|
||||
#: ``NOW <epoch>``, one ``pid<TAB>elapsed<TAB>cgroup<TAB>args`` line per process, ``END``.
|
||||
RUNNING_BACKUPS_COMMAND = (
|
||||
'echo "NOW $(date +%s)"; '
|
||||
"out=$(LC_ALL=C ps -eo pid=,etimes=,args= 2>/dev/null) || exit 1; "
|
||||
"printf '%s\\n' \"$out\" | while read -r pid et args; do "
|
||||
'printf \'%s\\t%s\\t%s\\t%s\\n\' "$pid" "$et" '
|
||||
'"$(tail -n 1 /proc/$pid/cgroup 2>/dev/null)" "$args"; '
|
||||
"done; echo END"
|
||||
)
|
||||
|
||||
_READ_TIMEOUT = 30
|
||||
|
||||
|
||||
class _Tool(NamedTuple):
|
||||
#: subcommand -> what it does; None: not a backup (a mount, a restore, a listing).
|
||||
subcommands: dict[str, RunningBackupKind | None]
|
||||
#: What the tool does when no listed subcommand is given; None: nothing to stop for.
|
||||
default: RunningBackupKind | None = None
|
||||
|
||||
|
||||
_RESTIC: dict[str, RunningBackupKind | None] = {
|
||||
"backup": "backup",
|
||||
"forget": "prune",
|
||||
"prune": "prune",
|
||||
"check": "verify",
|
||||
"copy": "sync",
|
||||
}
|
||||
_BORG: dict[str, RunningBackupKind | None] = {
|
||||
"create": "backup",
|
||||
"serve": "backup",
|
||||
"prune": "prune",
|
||||
"compact": "prune",
|
||||
"check": "verify",
|
||||
}
|
||||
|
||||
_TOOLS: dict[str, _Tool] = {
|
||||
"restic": _Tool(_RESTIC),
|
||||
"resticprofile": _Tool(_RESTIC),
|
||||
"autorestic": _Tool({"backup": "backup", "forget": "prune", "check": "verify"}),
|
||||
"borg": _Tool(_BORG),
|
||||
"borgbackup": _Tool(_BORG),
|
||||
"borgmatic": _Tool(
|
||||
{"extract": None, "list": None, "info": None, "restore": None, "mount": None},
|
||||
"backup",
|
||||
),
|
||||
"duplicity": _Tool(
|
||||
{
|
||||
"restore": None,
|
||||
"collection-status": None,
|
||||
"list-current-files": None,
|
||||
"verify": "verify",
|
||||
"cleanup": "prune",
|
||||
"remove-older-than": "prune",
|
||||
"remove-all-but-n-full": "prune",
|
||||
"remove-all-inc-of-but-n-full": "prune",
|
||||
},
|
||||
"backup",
|
||||
),
|
||||
"duply": _Tool(
|
||||
{
|
||||
"backup": "backup",
|
||||
"bkp": "backup",
|
||||
"incr": "backup",
|
||||
"full": "backup",
|
||||
"purge": "prune",
|
||||
"verify": "verify",
|
||||
}
|
||||
),
|
||||
"rsnapshot": _Tool({}, "backup"),
|
||||
"rdiff-backup": _Tool(
|
||||
{"-r": None, "--restore-as-of": None, "restore": None, "list": None}, "backup"
|
||||
),
|
||||
"proxmox-backup-client": _Tool({"backup": "backup"}),
|
||||
"kopia": _Tool({"snapshot": "backup", "maintenance": "prune"}),
|
||||
"btrbk": _Tool({"run": "backup", "resume": "backup", "snapshot": "backup", "prune": "prune"}),
|
||||
}
|
||||
|
||||
#: What may stand before the tool on its command line: an interpreter or a wrapper,
|
||||
#: their options and plain numbers or durations ("nice -n 19", "timeout 3h").
|
||||
_WRAPPERS = frozenset(
|
||||
{"sh", "bash", "dash", "env", "nice", "ionice", "nocache", "timeout", "chrt", "perl"}
|
||||
)
|
||||
_PYTHON = re.compile(r"python[0-9.]*")
|
||||
_ARGUMENT = re.compile(r"-.*|\d+[smhd]?")
|
||||
|
||||
#: Services that start other people's commands: a backup run from them has no job of its own.
|
||||
_NOT_JOBS = frozenset(
|
||||
{"cron.service", "crond.service", "cronie.service", "anacron.service", "atd.service"}
|
||||
| {"ssh.service", "sshd.service"}
|
||||
)
|
||||
|
||||
|
||||
def _tool(args: str) -> tuple[_Tool, list[str]] | None:
|
||||
"""The backup tool *args* runs and its arguments, or None for any other process."""
|
||||
words = args.split()
|
||||
for index, word in enumerate(words):
|
||||
name = posixpath.basename(word)
|
||||
if name in _TOOLS:
|
||||
return _TOOLS[name], words[index + 1 :]
|
||||
if not (name in _WRAPPERS or _PYTHON.fullmatch(name) or _ARGUMENT.fullmatch(word)):
|
||||
return None
|
||||
return None
|
||||
|
||||
|
||||
def backup_kind(args: str) -> RunningBackupKind | None:
|
||||
"""What the process with command line *args* is doing for a backup, or None."""
|
||||
found = _tool(args)
|
||||
if found is None:
|
||||
return None
|
||||
tool, rest = found
|
||||
for word in rest:
|
||||
if word in tool.subcommands:
|
||||
return tool.subcommands[word]
|
||||
return tool.default
|
||||
|
||||
|
||||
def _job(cgroup: str) -> str | None:
|
||||
"""The systemd service a process runs in, when that service is its own job."""
|
||||
unit = posixpath.basename(cgroup.rsplit(":", 1)[-1])
|
||||
return unit if unit.endswith(".service") and unit not in _NOT_JOBS else None
|
||||
|
||||
|
||||
def _clock(lines: list[str]) -> int:
|
||||
if not lines or not lines[0].startswith("NOW "):
|
||||
raise RuntimeError("get_running_backups: the host did not say what time it is")
|
||||
try:
|
||||
return int(lines[0].split()[1])
|
||||
except (IndexError, ValueError) as exc:
|
||||
raise RuntimeError(f"get_running_backups: not a time: {lines[0]!r}") from exc
|
||||
|
||||
|
||||
def parse_running_backups(output: str) -> list[RunningBackupDict]:
|
||||
"""The backups in ``RUNNING_BACKUPS_COMMAND``'s *output*.
|
||||
|
||||
:raises RuntimeError: when the reading was cut short or never had the clock.
|
||||
"""
|
||||
lines = output.splitlines()
|
||||
now = _clock(lines)
|
||||
if lines[-1].strip() != "END":
|
||||
raise RuntimeError("get_running_backups: the process list was cut short")
|
||||
found: list[RunningBackupDict] = []
|
||||
for line in lines[1:-1]:
|
||||
parts = line.split("\t", 3)
|
||||
if len(parts) != 4 or not parts[1].isdigit():
|
||||
continue
|
||||
pid, elapsed, cgroup, args = parts
|
||||
kind = backup_kind(args)
|
||||
if kind is not None:
|
||||
since = now - int(elapsed)
|
||||
found.append(
|
||||
{"kind": kind, "job": _job(cgroup), "task": pid, "guests": [], "since": since}
|
||||
)
|
||||
return found
|
||||
|
||||
|
||||
class LinuxRunningBackupsMixin(RunningBackupsMixin):
|
||||
"""``get_running_backups`` over the driver's own session, as the login user."""
|
||||
|
||||
if TYPE_CHECKING: # pragma: no cover - the driver's own, declared for type checkers
|
||||
|
||||
def _send(self, command: str, read_timeout: float = 100) -> str: ...
|
||||
|
||||
def get_running_backups(self) -> list[RunningBackupDict]:
|
||||
return parse_running_backups(self._send(RUNNING_BACKUPS_COMMAND, _READ_TIMEOUT))
|
||||
@@ -0,0 +1,123 @@
|
||||
"""The interactive shell netmiko opens, made fit to be read before the first command."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import logging
|
||||
import re
|
||||
from shlex import quote
|
||||
from typing import Any
|
||||
|
||||
from napalm_device_types import run_on_transport
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
#: The end of a command's output when nothing better is known: a line that looks
|
||||
#: like a shell prompt.
|
||||
PROMPT_RE = r"[#$\>]\s*$"
|
||||
|
||||
#: A command ending in ``echo __NAME=$?`` reports its exit status on a line of its
|
||||
#: own: the driver's ``_RC_MARKER``, ``__APT_RC=`` and ``__SVC_RC=`` in
|
||||
#: napalm-device-types.
|
||||
STATUS_ECHO_RE = re.compile(r"echo\s+(__[A-Z_]+=)\$\?")
|
||||
|
||||
#: The same echo as the last command of a line: ``sudo_without_password`` keeps it
|
||||
#: outside sudo.
|
||||
_TRAILING_STATUS_ECHO_RE = re.compile(r";\s*echo\s+__[A-Z_]+=\$\?\s*$")
|
||||
|
||||
|
||||
def expect_for(command: str) -> str:
|
||||
"""The pattern that ends *command*'s output.
|
||||
|
||||
netmiko stops reading as soon as the pattern matches what it has read so far.
|
||||
A line the command prints can end in ``#``, ``$`` or ``>`` -- apt's
|
||||
``<ftpmaster@ubuntu.com>`` after a bad signature -- and was taken for the
|
||||
prompt: half the output came back, and the rest started the next command's
|
||||
(#615). A command that echoes its exit status is read until that marker, with
|
||||
a number, and the prompt line after it. The echoed command line carries a
|
||||
literal ``$?`` and cannot match.
|
||||
"""
|
||||
markers: list[str] = STATUS_ECHO_RE.findall(command)
|
||||
if not markers:
|
||||
return PROMPT_RE
|
||||
return re.escape(markers[-1]) + r"\d+\s*\n.*" + PROMPT_RE
|
||||
|
||||
|
||||
def sudo_without_password(command: str) -> str:
|
||||
"""The line that runs all of *command* as root through ``sudo -n`` (#56).
|
||||
|
||||
The command goes to ``sh -c`` as one argument: ``sudo -n <command>`` covered only
|
||||
its first simple command, and one that starts with a brace group did not parse.
|
||||
A status echo at its end stays outside and reports sh's status, the command's:
|
||||
it arrives when sudo refuses as well, where netmiko would otherwise wait for it
|
||||
until the read timeout.
|
||||
"""
|
||||
echo = _TRAILING_STATUS_ECHO_RE.search(command)
|
||||
body, tail = (command[: echo.start()], echo.group()) if echo else (command, "")
|
||||
return f"sudo -n sh -c {quote(body)}{tail}"
|
||||
|
||||
|
||||
#: Whether sudo runs a command for the login user without a password now: in
|
||||
#: the shape every privileged command takes (``sh -c``), so a sudoers rule that
|
||||
#: covers one covers the other.
|
||||
SUDO_ASKS_NOTHING = "sudo -n sh -c true"
|
||||
|
||||
|
||||
def unprompted_stream(
|
||||
transport: Any, command: str, line: str, prefix: bytes | None
|
||||
) -> tuple[str, bytes | None]:
|
||||
"""The line and stdin prefix a privileged stream of *command* starts with.
|
||||
|
||||
With a sudo password (*prefix*) sudo is asked first whether it wants it: a
|
||||
sudo that does not prompt -- NOPASSWD, a cached timestamp -- would leave the
|
||||
password on stdin, where the stream's own data follows it, the Podman API
|
||||
over ``sudo podman system dial-stdio`` say (NetOrk/netork#818). Such a sudo
|
||||
gets *command* through ``sudo -n`` and no password; one that asks gets it.
|
||||
"""
|
||||
if not prefix:
|
||||
return line, prefix
|
||||
if run_on_transport(transport, SUDO_ASKS_NOTHING, timeout=15).exit_code == 0:
|
||||
return f"sudo -n sh -c {quote(command)}", None
|
||||
return line, prefix
|
||||
|
||||
|
||||
#: Sent before anything else in the interactive session (NetOrk/netork#1039):
|
||||
#: the shell writes no history file and records nothing more. The leading space
|
||||
#: keeps this line itself out of a history under ``HISTCONTROL=ignorespace``;
|
||||
#: a shell without ``set -o history`` (dash) only complains, to /dev/null.
|
||||
HISTORY_OFF = " unset HISTFILE; set +o history 2>/dev/null; true"
|
||||
|
||||
#: Sent right after ``HISTORY_OFF`` (#41): systemd 258's
|
||||
#: ``/etc/profile.d/80-systemd-osc-context.sh`` wraps every command in OSC 3008
|
||||
#: sequences from ``PS0`` and ``PROMPT_COMMAND``, each with a fresh UUID. It appends
|
||||
#: to ``PROMPT_COMMAND`` as an array, so only ``unset`` removes its hook.
|
||||
PROMPT_HOOKS_OFF = " unset PS0 PROMPT_COMMAND; true"
|
||||
|
||||
#: Keeps the PTY from wrapping long output lines (e.g. docker JSON).
|
||||
NO_LINE_WRAP = "stty cols 10000 2>/dev/null || true"
|
||||
|
||||
|
||||
def prepare_shell(device: Any, hostname: str) -> None:
|
||||
"""Make netmiko's fresh shell *device* fit to read, one step at a time.
|
||||
|
||||
A step the shell refuses is logged and skipped: none of them is worth
|
||||
failing the connection for.
|
||||
"""
|
||||
# No history before anything else is typed (NetOrk/netork#1039).
|
||||
try:
|
||||
device.send_command(HISTORY_OFF, expect_string=PROMPT_RE)
|
||||
except Exception:
|
||||
logger.debug("Could not switch the shell history off on %s", hostname, exc_info=True)
|
||||
|
||||
# No systemd OSC 3008 context around every command (#41). netmiko learned
|
||||
# the prompt with those sequences in front, and a prompt carrying a fresh
|
||||
# UUID never matches again, so it reads the prompt anew once they are gone.
|
||||
try:
|
||||
device.send_command(PROMPT_HOOKS_OFF, expect_string=PROMPT_RE)
|
||||
device.set_base_prompt()
|
||||
except Exception:
|
||||
logger.debug("Could not switch the prompt hooks off on %s", hostname, exc_info=True)
|
||||
|
||||
try:
|
||||
device.send_command(NO_LINE_WRAP, expect_string=PROMPT_RE)
|
||||
except Exception:
|
||||
logger.debug("%s: ignored", hostname, exc_info=True)
|
||||
@@ -0,0 +1,80 @@
|
||||
"""The SNMP agent a fix sets up: net-snmp's configuration and the firewall rule for it."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import ipaddress
|
||||
import re
|
||||
from shlex import quote as _shlex_quote
|
||||
|
||||
from napalm_device_types.models import SnmpAgentSettingsDict
|
||||
|
||||
#: Where net-snmp reads its configuration, and how each package manager installs it.
|
||||
_SNMPD_CONF = "/etc/snmp/snmpd.conf"
|
||||
_SNMP_INSTALL = {
|
||||
"apt": (
|
||||
"apt-get update -y >/dev/null 2>&1; "
|
||||
"DEBIAN_FRONTEND=noninteractive apt-get install -y snmpd snmp 2>&1"
|
||||
),
|
||||
"dnf": "dnf install -y net-snmp net-snmp-utils 2>&1",
|
||||
"yum": "yum install -y net-snmp net-snmp-utils 2>&1",
|
||||
"apk": "apk add --no-cache net-snmp net-snmp-tools 2>&1",
|
||||
"pacman": "pacman -Sy --noconfirm net-snmp 2>&1",
|
||||
}
|
||||
#: What may stand in an snmpd.conf value: no whitespace, no quote, no comment.
|
||||
_SNMP_WORD = re.compile(r"^[^\s\"#]+$")
|
||||
|
||||
|
||||
def _source(value: str) -> str:
|
||||
"""An allowed source as an address or network, or ValueError."""
|
||||
return str(ipaddress.ip_network(value.strip(), strict=False))
|
||||
|
||||
|
||||
#: The zones a firewalld rule must reach: the default one, which takes every interface
|
||||
#: in no zone (a WireGuard ``wg0``), and each zone holding an interface or a source.
|
||||
_FIREWALLD_ZONES = (
|
||||
"$( { firewall-cmd --get-default-zone;"
|
||||
" firewall-cmd --get-active-zones | grep -v '^[[:space:]]'; } | sort -u )"
|
||||
)
|
||||
|
||||
|
||||
def firewalld_allow_snmp(sources: list[str]) -> str:
|
||||
"""The shell that opens udp/161 for *sources* (already normalised) in firewalld.
|
||||
|
||||
A rich rule per source in every zone of ``_FIREWALLD_ZONES``, at runtime and
|
||||
permanently, each only when the zone lacks it -- no ``--reload``, which would drop
|
||||
the runtime rules others (Docker) put there.
|
||||
"""
|
||||
steps = []
|
||||
for source in sources:
|
||||
family = f"ipv{ipaddress.ip_network(source).version}"
|
||||
rule = _shlex_quote(
|
||||
f'rule family="{family}" source address="{source}"'
|
||||
' port port="161" protocol="udp" accept'
|
||||
)
|
||||
for scope in ("", "--permanent "):
|
||||
zone = f'firewall-cmd {scope}--zone="$z"'
|
||||
steps.append(
|
||||
f"{{ {zone} --query-rich-rule={rule} >/dev/null 2>&1"
|
||||
f" || {zone} --add-rich-rule={rule}; }}"
|
||||
)
|
||||
return f"for z in {_FIREWALLD_ZONES}; do {' && '.join(steps)} || exit 1; done"
|
||||
|
||||
|
||||
def render_snmpd_conf(settings: SnmpAgentSettingsDict) -> str:
|
||||
"""net-snmp's configuration for *settings*: read-only v2c, per allowed source."""
|
||||
community = settings["community"]
|
||||
if not _SNMP_WORD.match(community):
|
||||
raise ValueError("the community must be one word without quotes or #")
|
||||
listen = settings.get("listen")
|
||||
lines = [f"agentAddress udp:{listen + ':' if listen else ''}161"]
|
||||
sources = [_source(s) for s in settings.get("allowed_sources", [])]
|
||||
lines += [f"rocommunity {community} {s}" for s in sources] or [f"rocommunity {community}"]
|
||||
for key, directive, value in (
|
||||
("location", "sysLocation", settings.get("location", "")),
|
||||
("contact", "sysContact", settings.get("contact", "")),
|
||||
):
|
||||
if value:
|
||||
if "\n" in value:
|
||||
raise ValueError(f"{key} must be one line")
|
||||
lines.append(f"{directive} {value}")
|
||||
return "\n".join(lines) + "\n"
|
||||
@@ -0,0 +1,19 @@
|
||||
"""What the old ``_sudo`` left on every host it reached (NetOrk/netork#1090).
|
||||
|
||||
Until NetOrk/netork#1039, ``_sudo`` typed ``echo '<password>' | sudo -S -p ""
|
||||
<command>`` into netmiko's interactive shell, and only the part before the first
|
||||
``&&`` ran as root. napalm-device-types' ``SudoHistoryMixin`` counts and deletes
|
||||
those lines and gives the files back to root; this says what to look for.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from napalm_device_types import AptProxyMixin, SudoHistoryMixin
|
||||
|
||||
|
||||
class LinuxSudoHistoryMixin(SudoHistoryMixin):
|
||||
#: Every line the old ``_sudo`` typed carries it, with the sudo password before it.
|
||||
SUDO_HISTORY_MARKER = "| sudo -S -p "
|
||||
#: Written as the login user where the part that should have been root's came
|
||||
#: after the first ``&&``: snmpd.conf (``configure_snmp_agent``) and apt's proxy.
|
||||
SUDO_ROOT_FILES = ("/etc/snmp/snmpd.conf", AptProxyMixin.APT_PROXY_FILE)
|
||||
+853
-1290
File diff suppressed because it is too large.
Load diff
Whitespace-only changes.
+48
-16
@@ -1,14 +1,14 @@
|
||||
[build-system]
|
||||
requires = ["setuptools>=68", "wheel"]
|
||||
requires = ["setuptools>=77"]
|
||||
build-backend = "setuptools.build_meta"
|
||||
|
||||
[project]
|
||||
name = "napalm-linux"
|
||||
version = "0.1.0"
|
||||
version = "0.17.0"
|
||||
description = "NAPALM driver for generic Linux systems via SSH"
|
||||
readme = "README.md"
|
||||
requires-python = ">=3.9"
|
||||
license = { text = "Apache-2.0" }
|
||||
requires-python = ">=3.12"
|
||||
license = "Apache-2.0"
|
||||
authors = [
|
||||
{ name = "Christian Manivong", email = "christian@manivong.de" },
|
||||
]
|
||||
@@ -24,43 +24,75 @@ classifiers = [
|
||||
"Development Status :: 3 - Alpha",
|
||||
"Intended Audience :: Developers",
|
||||
"Intended Audience :: System Administrators",
|
||||
"License :: OSI Approved :: Apache Software License",
|
||||
"Operating System :: OS Independent",
|
||||
"Programming Language :: Python :: 3",
|
||||
"Programming Language :: Python :: 3.9",
|
||||
"Programming Language :: Python :: 3.10",
|
||||
"Programming Language :: Python :: 3.11",
|
||||
"Programming Language :: Python :: 3.12",
|
||||
"Programming Language :: Python :: 3.13",
|
||||
"Topic :: System :: Networking",
|
||||
"Topic :: System :: Systems Administration",
|
||||
"Typing :: Typed",
|
||||
]
|
||||
dependencies = [
|
||||
"napalm>=4.0",
|
||||
"napalm-device-types>=2.2.0",
|
||||
"napalm-device-types>=4.37.0",
|
||||
"netmiko>=4.0.0",
|
||||
"paramiko>=5.0.0", # CVE-2026-44405
|
||||
]
|
||||
|
||||
[project.optional-dependencies]
|
||||
dev = [
|
||||
"pytest",
|
||||
"pytest-cov",
|
||||
"black",
|
||||
"ruff",
|
||||
"mypy",
|
||||
"pytest>=8",
|
||||
"pytest-cov>=5",
|
||||
"ruff>=0.6",
|
||||
"mypy>=1.11",
|
||||
]
|
||||
|
||||
[project.entry-points."napalm.drivers"]
|
||||
linux = "napalm_linux:LinuxDriver"
|
||||
|
||||
[project.urls]
|
||||
Repository = "https://github.com/chrismanivong/napalm-linux"
|
||||
Repository = "https://git.netork.io/NAPALM/napalm-linux"
|
||||
Issues = "https://git.netork.io/NAPALM/napalm-linux/issues"
|
||||
Changelog = "https://git.netork.io/NAPALM/napalm-linux/src/branch/main/CHANGELOG.md"
|
||||
|
||||
[tool.setuptools.packages.find]
|
||||
where = ["."]
|
||||
include = ["napalm_linux*"]
|
||||
|
||||
[tool.setuptools.package-data]
|
||||
napalm_linux = ["py.typed"]
|
||||
|
||||
[tool.ruff]
|
||||
line-length = 100
|
||||
target-version = "py39"
|
||||
target-version = "py312"
|
||||
|
||||
[tool.ruff.lint]
|
||||
select = ["E", "F", "I", "UP", "B"]
|
||||
|
||||
[tool.ruff.lint.per-file-ignores]
|
||||
# Recorded device output keeps its lines.
|
||||
"tests/**" = ["E501"]
|
||||
|
||||
[tool.mypy]
|
||||
python_version = "3.12"
|
||||
strict = true
|
||||
# napalm itself is untyped, so every driver subclasses Any.
|
||||
disallow_subclassing_any = false
|
||||
|
||||
[[tool.mypy.overrides]]
|
||||
module = ["napalm.*", "netmiko.*", "paramiko.*"]
|
||||
ignore_missing_imports = true
|
||||
|
||||
[[tool.mypy.overrides]]
|
||||
# Not yet under strict mypy (quality baseline); may only shrink.
|
||||
module = ["napalm_linux.linux"]
|
||||
ignore_errors = true
|
||||
|
||||
[tool.pytest.ini_options]
|
||||
testpaths = ["tests"]
|
||||
|
||||
[tool.coverage.run]
|
||||
source = ["napalm_linux"]
|
||||
|
||||
[tool.coverage.report]
|
||||
fail_under = 57
|
||||
@@ -0,0 +1,26 @@
|
||||
{
|
||||
"coverage_floor": 57.0,
|
||||
"function_complexity": {
|
||||
"napalm_linux/linux.py::LinuxDriver._collect_platform_info": 24,
|
||||
"napalm_linux/linux.py::LinuxDriver.get_networks": 13,
|
||||
"napalm_linux/linux.py::LinuxDriver.get_route_to": 13,
|
||||
"napalm_linux/linux.py::LinuxDriver.get_snmp_config": 13,
|
||||
"napalm_linux/linux.py::LinuxDriver.get_vpn_tunnels": 28,
|
||||
"napalm_linux/linux.py::LinuxDriver.search_packages": 26
|
||||
},
|
||||
"function_lines": {
|
||||
"napalm_linux/linux.py::LinuxDriver._collect_platform_info": 106,
|
||||
"napalm_linux/linux.py::LinuxDriver.get_networks": 52,
|
||||
"napalm_linux/linux.py::LinuxDriver.get_route_to": 101,
|
||||
"napalm_linux/linux.py::LinuxDriver.get_vpn_tunnels": 152,
|
||||
"napalm_linux/linux.py::LinuxDriver.search_packages": 106,
|
||||
"napalm_linux/linux.py::LinuxDriver.uninstall_package": 51
|
||||
},
|
||||
"mypy_relaxed": [
|
||||
"napalm_linux.linux"
|
||||
],
|
||||
"python_file_lines": {
|
||||
"napalm_linux/linux.py": 2009
|
||||
},
|
||||
"untyped_public": []
|
||||
}
|
||||
@@ -0,0 +1,238 @@
|
||||
"""The public command channel and container engine access (napalm-device-types 2.6.0).
|
||||
|
||||
netOrk used to reach a Linux host's shell through the private ``_send``: an
|
||||
interactive PTY, stdout and stderr merged, no exit code. ``run_command`` and
|
||||
``open_stream`` go through an exec channel on the same SSH transport instead,
|
||||
and ``open_container_engine`` builds on them (NetOrk/netork#765). Privileges
|
||||
work as they do everywhere else in this driver: root runs directly, a sudo
|
||||
password goes to ``sudo -S`` on stdin and never onto a command line, and
|
||||
without one ``sudo -n`` fails at once instead of hanging.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from types import SimpleNamespace
|
||||
|
||||
import pytest
|
||||
from napalm.base.exceptions import ConnectionClosedException
|
||||
|
||||
from napalm_linux import LinuxDriver
|
||||
from napalm_linux._shell import SUDO_ASKS_NOTHING
|
||||
|
||||
|
||||
class FakeChannel:
|
||||
def __init__(self, exits):
|
||||
self.command = None
|
||||
self.sent = b""
|
||||
self._exits = exits
|
||||
|
||||
def exec_command(self, command):
|
||||
self.command = command
|
||||
|
||||
def settimeout(self, timeout):
|
||||
pass
|
||||
|
||||
def sendall(self, data):
|
||||
self.sent += data
|
||||
|
||||
def shutdown_write(self):
|
||||
pass
|
||||
|
||||
def close(self):
|
||||
pass
|
||||
|
||||
def recv_ready(self):
|
||||
return False
|
||||
|
||||
def recv(self, size):
|
||||
return b""
|
||||
|
||||
def recv_stderr_ready(self):
|
||||
return False
|
||||
|
||||
def recv_stderr(self, size):
|
||||
return b""
|
||||
|
||||
def exit_status_ready(self):
|
||||
return True
|
||||
|
||||
def recv_exit_status(self):
|
||||
return self._exits.get(self.command, 0)
|
||||
|
||||
|
||||
#: The probe a privileged stream sends first, and how a sudo that asks for its
|
||||
#: password answers it.
|
||||
SUDO_PROBE = SUDO_ASKS_NOTHING
|
||||
ASKS = {SUDO_PROBE: 1}
|
||||
|
||||
|
||||
class FakeTransport:
|
||||
def __init__(self, exits=None):
|
||||
self.channels = []
|
||||
self.exits = ASKS if exits is None else exits
|
||||
|
||||
def open_session(self):
|
||||
self.channels.append(FakeChannel(self.exits))
|
||||
return self.channels[-1]
|
||||
|
||||
|
||||
def _driver(*, root=False, sudo_password=None, exits=None):
|
||||
driver = LinuxDriver("h", "u", "p", optional_args={"sudo_password": sudo_password})
|
||||
transport = FakeTransport(exits)
|
||||
driver._device = SimpleNamespace(
|
||||
remote_conn_pre=SimpleNamespace(get_transport=lambda: transport)
|
||||
)
|
||||
driver._root = root
|
||||
return driver, transport
|
||||
|
||||
|
||||
def test_an_unprivileged_command_runs_as_given():
|
||||
driver, transport = _driver()
|
||||
|
||||
result = driver.run_command("docker version", timeout=5)
|
||||
|
||||
assert transport.channels[-1].command == "docker version"
|
||||
assert transport.channels[-1].sent == b""
|
||||
assert result.exit_code == 0
|
||||
|
||||
|
||||
def test_a_privileged_command_with_a_sudo_password_reads_it_from_stdin():
|
||||
driver, transport = _driver(sudo_password="s3cr3t")
|
||||
|
||||
driver.run_command("usermod -aG docker u", privileged=True, timeout=5)
|
||||
|
||||
channel = transport.channels[-1]
|
||||
assert channel.command == "sudo -S -p '' sh -c 'usermod -aG docker u'"
|
||||
assert channel.sent == b"s3cr3t\n"
|
||||
assert "s3cr3t" not in channel.command
|
||||
|
||||
|
||||
def test_a_privileged_command_without_a_password_fails_fast_instead_of_prompting():
|
||||
driver, transport = _driver()
|
||||
|
||||
driver.run_command("id", privileged=True, timeout=5)
|
||||
|
||||
assert transport.channels[-1].command == "sudo -n sh -c id"
|
||||
|
||||
|
||||
def test_a_root_login_needs_no_sudo():
|
||||
driver, transport = _driver(root=True, sudo_password="s3cr3t")
|
||||
|
||||
driver.run_command("id", privileged=True, timeout=5)
|
||||
|
||||
assert transport.channels[-1].command == "id"
|
||||
assert transport.channels[-1].sent == b""
|
||||
|
||||
|
||||
def test_a_privileged_command_with_a_sudo_password_takes_no_stdin():
|
||||
"""sudo -S reads the password from stdin. A sudo that does not prompt --
|
||||
NOPASSWD, a cached timestamp -- leaves it there, and the command reads it as
|
||||
its first line: it wrote the password into an sshd drop-in (NetOrk/netork#1029)."""
|
||||
driver, transport = _driver(sudo_password="pw")
|
||||
|
||||
with pytest.raises(ValueError, match="stdin"):
|
||||
driver.run_command("tee /etc/x", privileged=True, stdin=b"data", timeout=5)
|
||||
|
||||
assert transport.channels == [] # nothing reached the host
|
||||
|
||||
|
||||
def test_privileged_stdin_without_a_sudo_password_goes_to_the_command():
|
||||
"""sudo -n reads nothing from stdin: the data is the command's alone."""
|
||||
driver, transport = _driver()
|
||||
|
||||
driver.run_command("tee /etc/x", privileged=True, stdin=b"data", timeout=5)
|
||||
|
||||
channel = transport.channels[-1]
|
||||
assert channel.command == "sudo -n sh -c 'tee /etc/x'"
|
||||
assert channel.sent == b"data"
|
||||
|
||||
|
||||
def test_privileged_stdin_for_a_root_login_goes_to_the_command():
|
||||
driver, transport = _driver(root=True, sudo_password="pw")
|
||||
|
||||
driver.run_command("tee /etc/x", privileged=True, stdin=b"data", timeout=5)
|
||||
|
||||
assert transport.channels[-1].command == "tee /etc/x"
|
||||
assert transport.channels[-1].sent == b"data"
|
||||
|
||||
|
||||
def test_unprivileged_stdin_with_a_sudo_password_goes_to_the_command():
|
||||
driver, transport = _driver(sudo_password="pw")
|
||||
|
||||
driver.run_command("cat > /tmp/x", stdin=b"data", timeout=5)
|
||||
|
||||
assert transport.channels[-1].command == "cat > /tmp/x"
|
||||
assert transport.channels[-1].sent == b"data"
|
||||
|
||||
|
||||
def test_a_privileged_stream_gets_the_password_first():
|
||||
driver, transport = _driver(sudo_password="pw")
|
||||
|
||||
driver.open_stream("journalctl -f", privileged=True)
|
||||
|
||||
channel = transport.channels[-1]
|
||||
assert channel.command == "sudo -S -p '' sh -c 'journalctl -f'"
|
||||
assert channel.sent == b"pw\n"
|
||||
|
||||
|
||||
class TestNoPasswordIntoAStream:
|
||||
"""A privileged stream carries data after the password: the Podman API over
|
||||
``sudo podman system dial-stdio`` (NetOrk/netork#818). A sudo that does not ask
|
||||
-- NOPASSWD, a cached timestamp -- would hand the password to the command as
|
||||
the first bytes of that data. So the stream asks sudo first, and sends the
|
||||
password only to a sudo that wants it."""
|
||||
|
||||
def test_sudo_is_asked_first(self):
|
||||
driver, transport = _driver(sudo_password="pw")
|
||||
|
||||
driver.open_stream("podman system dial-stdio", privileged=True)
|
||||
|
||||
assert transport.channels[0].command == SUDO_PROBE
|
||||
assert transport.channels[0].sent == b""
|
||||
|
||||
def test_a_sudo_that_asks_nothing_gets_no_password(self):
|
||||
driver, transport = _driver(sudo_password="pw", exits={})
|
||||
|
||||
driver.open_stream("podman system dial-stdio", privileged=True)
|
||||
|
||||
channel = transport.channels[-1]
|
||||
assert channel.command == "sudo -n sh -c 'podman system dial-stdio'"
|
||||
assert channel.sent == b""
|
||||
|
||||
def test_without_a_password_there_is_nothing_to_ask(self):
|
||||
driver, transport = _driver()
|
||||
|
||||
driver.open_stream("podman system dial-stdio", privileged=True)
|
||||
|
||||
assert [c.command for c in transport.channels] == [
|
||||
"sudo -n sh -c 'podman system dial-stdio'"
|
||||
]
|
||||
|
||||
def test_a_root_login_asks_nothing_either(self):
|
||||
driver, transport = _driver(root=True, sudo_password="pw")
|
||||
|
||||
driver.open_stream("podman system dial-stdio", privileged=True)
|
||||
|
||||
assert [c.command for c in transport.channels] == ["podman system dial-stdio"]
|
||||
|
||||
def test_podman_is_reached_as_root(self):
|
||||
driver, transport = _driver(root=True)
|
||||
|
||||
driver.open_container_engine("podman").open_api()
|
||||
|
||||
assert transport.channels[-1].command == "podman system dial-stdio"
|
||||
|
||||
|
||||
def test_the_container_engine_api_is_a_stream_over_dial_stdio():
|
||||
driver, transport = _driver()
|
||||
|
||||
driver.open_container_engine("docker").open_api()
|
||||
|
||||
assert transport.channels[-1].command == "docker system dial-stdio"
|
||||
|
||||
|
||||
def test_the_channel_needs_an_open_connection():
|
||||
driver = LinuxDriver("h", "u", "p")
|
||||
|
||||
with pytest.raises(ConnectionClosedException):
|
||||
driver.run_command("true")
|
||||
@@ -0,0 +1,17 @@
|
||||
"""The driver cannot replace a device's configuration, and says so by not having the method.
|
||||
|
||||
A ``load_replace_candidate`` that only raises looks like a replace to anyone who asks
|
||||
whether the driver has one: netOrk offered a config restore for these devices that
|
||||
could only fail (NetOrk/netork#2503). ``None`` is how a driver switches off a method
|
||||
it would otherwise inherit, the convention of napalm-device-types and netOrk's
|
||||
capability checks.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from napalm_linux import LinuxDriver
|
||||
|
||||
|
||||
def test_the_driver_has_no_config_replace():
|
||||
assert LinuxDriver.load_replace_candidate is None
|
||||
assert not callable(getattr(LinuxDriver, "load_replace_candidate", None))
|
||||
@@ -0,0 +1,398 @@
|
||||
"""The fix templates (napalm-device-types ``fixes``): the caller supplies every value.
|
||||
|
||||
They replace ``run_device_action``. The driver knows how each step is done on a
|
||||
Linux host; the community, the allowed sources, the proxy and the user are the
|
||||
caller's (napalm-device-types docs/STRUCTURE.md).
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from unittest.mock import MagicMock
|
||||
|
||||
import pytest
|
||||
|
||||
from napalm_linux import LinuxDriver
|
||||
from napalm_linux.linux import render_snmpd_conf
|
||||
|
||||
|
||||
class TestSnmpdConf:
|
||||
def test_one_read_only_line_per_allowed_source(self):
|
||||
conf = render_snmpd_conf(
|
||||
{
|
||||
"community": "c0mm",
|
||||
"allowed_sources": ["10.0.0.5", "10.1.0.0/24"],
|
||||
"contact": "ops",
|
||||
"location": "rack 1",
|
||||
}
|
||||
)
|
||||
|
||||
assert conf == (
|
||||
"agentAddress udp:161\n"
|
||||
"rocommunity c0mm 10.0.0.5/32\n"
|
||||
"rocommunity c0mm 10.1.0.0/24\n"
|
||||
"sysLocation rack 1\n"
|
||||
"sysContact ops\n"
|
||||
)
|
||||
|
||||
def test_without_sources_every_address_may_ask(self):
|
||||
assert "rocommunity c0mm\n" in render_snmpd_conf(
|
||||
{"community": "c0mm", "allowed_sources": []}
|
||||
)
|
||||
|
||||
def test_a_listen_address_binds_the_agent(self):
|
||||
conf = render_snmpd_conf({"community": "c", "allowed_sources": [], "listen": "10.0.0.1"})
|
||||
assert conf.startswith("agentAddress udp:10.0.0.1:161\n")
|
||||
|
||||
def test_no_application_name_is_written(self):
|
||||
conf = render_snmpd_conf({"community": "c", "allowed_sources": []})
|
||||
assert "netork" not in conf.lower()
|
||||
|
||||
@pytest.mark.parametrize("community", ["two words", 'quo"te', "has#hash", ""])
|
||||
def test_a_community_that_would_break_the_file_is_refused(self, community):
|
||||
with pytest.raises(ValueError):
|
||||
render_snmpd_conf({"community": community, "allowed_sources": []})
|
||||
|
||||
def test_a_source_that_is_no_address_is_refused(self):
|
||||
with pytest.raises(ValueError):
|
||||
render_snmpd_conf({"community": "c", "allowed_sources": ["10.0.0.5; rm -rf /"]})
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def driver():
|
||||
d = LinuxDriver("h", "admin", "p")
|
||||
d._device = MagicMock()
|
||||
d._pkg_manager = "apt"
|
||||
d._root = True
|
||||
return d
|
||||
|
||||
|
||||
class TestSnmpAgentSteps:
|
||||
SETTINGS = {"community": "c0mm", "allowed_sources": ["10.0.0.5"]}
|
||||
|
||||
def _record(self, driver, status=0, firewall="ufw", firewalld=False):
|
||||
ran: list[str] = []
|
||||
|
||||
def sudo_status(command, read_timeout=100):
|
||||
ran.append(command)
|
||||
return ("", status)
|
||||
|
||||
def send(command, read_timeout=100):
|
||||
if command == "systemctl is-active firewalld 2>/dev/null":
|
||||
return "active" if firewalld else "inactive"
|
||||
return (
|
||||
f"/usr/sbin/{firewall}" if command == f"command -v {firewall} 2>/dev/null" else ""
|
||||
)
|
||||
|
||||
driver._sudo_status = sudo_status
|
||||
driver._send = send
|
||||
driver._install_file_as_root = MagicMock(
|
||||
return_value=MagicMock(exit_code=0, stdout="", stderr="")
|
||||
)
|
||||
return ran
|
||||
|
||||
def test_installs_writes_opens_and_starts(self, driver):
|
||||
ran = self._record(driver)
|
||||
|
||||
result = driver.configure_snmp_agent(self.SETTINGS)
|
||||
|
||||
assert result["success"] is True
|
||||
assert [s["step"] for s in result["steps"]] == ["install", "configure", "firewall", "start"]
|
||||
assert "apt-get install -y snmpd snmp" in ran[0]
|
||||
path, content = driver._install_file_as_root.call_args.args
|
||||
assert path == "/etc/snmp/snmpd.conf" and "rocommunity c0mm 10.0.0.5/32" in content
|
||||
assert ran[1] == "ufw allow from 10.0.0.5/32 to any port 161 proto udp"
|
||||
assert "systemctl restart snmpd" in ran[2]
|
||||
|
||||
def test_the_firewall_opens_only_for_the_given_sources_with_iptables(self, driver):
|
||||
ran = self._record(driver, firewall="iptables")
|
||||
|
||||
driver.configure_snmp_agent(self.SETTINGS)
|
||||
|
||||
assert "iptables -I INPUT -s 10.0.0.5/32 -p udp --dport 161 -j ACCEPT" in ran[1]
|
||||
|
||||
def test_a_running_firewalld_gets_a_rich_rule_not_an_iptables_one(self, driver):
|
||||
"""An iptables ACCEPT does not lift firewalld's reject: with nftables both
|
||||
tables see the packet, and the drop in either wins (Oracle Linux, RHEL)."""
|
||||
ran = self._record(driver, firewall="iptables", firewalld=True)
|
||||
|
||||
result = driver.configure_snmp_agent(self.SETTINGS)
|
||||
|
||||
assert result["success"] is True
|
||||
assert "iptables" not in ran[1]
|
||||
assert (
|
||||
'rule family="ipv4" source address="10.0.0.5/32" port port="161" protocol="udp" accept'
|
||||
) in ran[1]
|
||||
assert "--permanent" in ran[1]
|
||||
assert "--reload" not in ran[1]
|
||||
|
||||
def test_the_firewalld_rule_goes_to_the_default_and_every_active_zone(self, tmp_path):
|
||||
"""An interface in no zone (a WireGuard wg0) is the default zone's; one in a
|
||||
zone of its own is that zone's. The rule goes in now and stays after a reload."""
|
||||
from napalm_linux._snmp_agent import firewalld_allow_snmp
|
||||
|
||||
log = tmp_path / "calls"
|
||||
fake = tmp_path / "firewall-cmd"
|
||||
fake.write_text(
|
||||
"#!/bin/sh\n"
|
||||
f'echo "$*" >> {log}\n'
|
||||
'case "$*" in\n'
|
||||
" --get-default-zone) echo public ;;\n"
|
||||
' --get-active-zones) printf "docker\\n interfaces: docker0\\n'
|
||||
'public\\n interfaces: enp0s6\\n" ;;\n'
|
||||
" *--query-rich-rule*) exit 1 ;;\n"
|
||||
"esac\n"
|
||||
)
|
||||
fake.chmod(0o755)
|
||||
|
||||
import os
|
||||
import subprocess
|
||||
|
||||
done = subprocess.run(
|
||||
["sh", "-c", firewalld_allow_snmp(["10.0.0.5/32", "fd00::/64"])],
|
||||
env={**os.environ, "PATH": f"{tmp_path}:{os.environ['PATH']}"},
|
||||
capture_output=True,
|
||||
text=True,
|
||||
)
|
||||
|
||||
assert done.returncode == 0, done.stdout + done.stderr
|
||||
adds = [line for line in log.read_text().splitlines() if "--add-rich-rule" in line]
|
||||
v4 = 'rule family="ipv4" source address="10.0.0.5/32" port port="161" protocol="udp" accept'
|
||||
v6 = 'rule family="ipv6" source address="fd00::/64" port port="161" protocol="udp" accept'
|
||||
for zone in ("public", "docker"):
|
||||
for rule in (v4, v6):
|
||||
assert f"--zone={zone} --add-rich-rule={rule}" in adds
|
||||
assert f"--permanent --zone={zone} --add-rich-rule={rule}" in adds
|
||||
assert len(adds) == 8
|
||||
|
||||
def test_a_rule_firewalld_holds_already_is_not_added_twice(self, tmp_path):
|
||||
from napalm_linux._snmp_agent import firewalld_allow_snmp
|
||||
|
||||
log = tmp_path / "calls"
|
||||
fake = tmp_path / "firewall-cmd"
|
||||
fake.write_text(
|
||||
"#!/bin/sh\n"
|
||||
f'echo "$*" >> {log}\n'
|
||||
'case "$*" in\n'
|
||||
" --get-default-zone) echo public ;;\n"
|
||||
" --get-active-zones) ;;\n"
|
||||
"esac\n"
|
||||
)
|
||||
fake.chmod(0o755)
|
||||
|
||||
import os
|
||||
import subprocess
|
||||
|
||||
done = subprocess.run(
|
||||
["sh", "-c", firewalld_allow_snmp(["10.0.0.5/32"])],
|
||||
env={**os.environ, "PATH": f"{tmp_path}:{os.environ['PATH']}"},
|
||||
capture_output=True,
|
||||
text=True,
|
||||
)
|
||||
|
||||
assert done.returncode == 0
|
||||
assert "--add-rich-rule" not in log.read_text()
|
||||
|
||||
def test_no_sources_change_no_firewall(self, driver):
|
||||
ran = self._record(driver)
|
||||
|
||||
result = driver.configure_snmp_agent({"community": "c0mm", "allowed_sources": []})
|
||||
|
||||
assert result["success"] is True
|
||||
assert not any("ufw" in c or "iptables" in c for c in ran)
|
||||
|
||||
def test_a_failed_install_stops_the_fix(self, driver):
|
||||
ran = self._record(driver, status=100)
|
||||
|
||||
result = driver.configure_snmp_agent(self.SETTINGS)
|
||||
|
||||
assert result["success"] is False
|
||||
assert len(ran) == 1
|
||||
driver._install_file_as_root.assert_not_called()
|
||||
|
||||
|
||||
_REPORT = (
|
||||
"APROXY_BEGIN\n[dump]\n{dump}[parts]\n{parts}[main]\n[sources]\n"
|
||||
"http://deb.debian.org/debian/dists/trixie/\nAPROXY_END\n"
|
||||
)
|
||||
|
||||
|
||||
def _host(driver, proxy="", parts="", fetched=0):
|
||||
"""What the host answers on the exec channel: apt's report, then a fetch."""
|
||||
ran: list[str] = []
|
||||
|
||||
def run_command(command, *, privileged=False, timeout=60, stdin=None):
|
||||
ran.append(command)
|
||||
if "apt-config dump" in command:
|
||||
dump = f'Acquire::http::Proxy "{proxy}";\n' if proxy else ""
|
||||
return MagicMock(exit_code=0, stdout=_REPORT.format(dump=dump, parts=parts), stderr="")
|
||||
out = f"APROXY_BEGIN\n[fetch]\nGet:1 x\n[rc]\n{fetched}\nAPROXY_END\n"
|
||||
return MagicMock(exit_code=0, stdout=out, stderr="")
|
||||
|
||||
driver.run_command = run_command
|
||||
return ran
|
||||
|
||||
|
||||
class TestPackageProxyAndEngineAccess:
|
||||
def test_the_proxy_is_the_caller_s(self, driver):
|
||||
driver._install_file_as_root = MagicMock(
|
||||
return_value=MagicMock(exit_code=0, stdout="", stderr="")
|
||||
)
|
||||
_host(driver, proxy="http://cache.lan:3142")
|
||||
|
||||
result = driver.configure_package_proxy("http://cache.lan:3142")
|
||||
|
||||
assert result["success"] is True, result["output"]
|
||||
path, content = driver._install_file_as_root.call_args.args
|
||||
assert (path, content) == (
|
||||
"/etc/apt/apt.conf.d/00proxy",
|
||||
'Acquire::http::Proxy "http://cache.lan:3142";\n',
|
||||
)
|
||||
|
||||
def test_it_reads_back_and_fetches_through_it(self, driver):
|
||||
driver._install_file_as_root = MagicMock(
|
||||
return_value=MagicMock(exit_code=0, stdout="", stderr="")
|
||||
)
|
||||
ran = _host(driver, proxy="http://cache.lan:3142")
|
||||
|
||||
result = driver.configure_package_proxy("http://cache.lan:3142")
|
||||
|
||||
# The steps napalm-device-types runs on this driver's transports; later ones
|
||||
# (https, NetOrk/netork#1811) are the mixin's own.
|
||||
steps = [s["step"] for s in result["steps"]]
|
||||
assert steps[:4] == ["configure", "conflicts", "verify", "fetch"]
|
||||
assert any("dists/trixie/InRelease" in c for c in ran)
|
||||
|
||||
def test_another_file_s_proxy_is_commented_out_as_root(self, driver):
|
||||
driver._install_file_as_root = MagicMock(
|
||||
return_value=MagicMock(exit_code=0, stdout="", stderr="")
|
||||
)
|
||||
_host(
|
||||
driver,
|
||||
proxy="http://cache.lan:3142",
|
||||
parts='/etc/apt/apt.conf.d/90curtin-aptproxy:1:Acquire::http::Proxy "http://old:3128";\n',
|
||||
)
|
||||
ran = []
|
||||
driver._sudo_status = lambda command, read_timeout=100: ran.append(command) or ("", 0)
|
||||
|
||||
driver.configure_package_proxy("http://cache.lan:3142")
|
||||
|
||||
assert ran and ran[0].startswith("sed -i -e '1{")
|
||||
assert ran[0].endswith("/etc/apt/apt.conf.d/90curtin-aptproxy")
|
||||
|
||||
def test_a_proxy_url_that_would_break_the_file_is_refused(self, driver):
|
||||
driver._install_file_as_root = MagicMock()
|
||||
|
||||
result = driver.configure_package_proxy('http://x"; Acquire::x "y')
|
||||
|
||||
assert result["success"] is False
|
||||
driver._install_file_as_root.assert_not_called()
|
||||
|
||||
def test_only_apt_takes_a_proxy(self, driver):
|
||||
driver._pkg_manager = "dnf"
|
||||
|
||||
assert driver.configure_package_proxy("http://cache.lan:3142")["success"] is False
|
||||
|
||||
def test_the_proxy_answers_past_apt_s_proxy(self, driver):
|
||||
out = "APROXY_BEGIN\n[fetch]\nGet:1 x\n[rc]\n0\n[match]\n3\nAPROXY_END\n"
|
||||
driver.run_command = MagicMock(return_value=MagicMock(exit_code=0, stdout=out, stderr=""))
|
||||
|
||||
result = driver.check_package_proxy("http://c:3142/acng-report.html", expect="Cache")
|
||||
|
||||
assert result == {"reachable": True, "expected": True, "error": ""}
|
||||
assert "Proxy::c=DIRECT" in driver.run_command.call_args.args[0]
|
||||
|
||||
def test_engine_access_for_the_user_the_caller_names(self, driver):
|
||||
ran = []
|
||||
driver._sudo_status = lambda command, read_timeout=100: ran.append(command) or ("", 0)
|
||||
|
||||
result = driver.grant_container_engine_access("deploy")
|
||||
|
||||
assert result["success"] is True
|
||||
assert ran == ["usermod -aG docker deploy"]
|
||||
|
||||
def test_a_user_name_that_is_no_user_name_is_refused(self, driver):
|
||||
driver._sudo_status = MagicMock()
|
||||
|
||||
assert driver.grant_container_engine_access("x; reboot")["success"] is False
|
||||
driver._sudo_status.assert_not_called()
|
||||
|
||||
|
||||
def test_run_device_action_is_gone():
|
||||
assert (
|
||||
not hasattr(LinuxDriver, "run_device_action")
|
||||
or LinuxDriver.run_device_action is None
|
||||
or ("run_device_action" not in vars(LinuxDriver))
|
||||
)
|
||||
for name in (
|
||||
"_action_fix_snmp",
|
||||
"_action_fix_apt_proxy",
|
||||
"_action_fix_docker_permissions",
|
||||
"_action_apt_update_upgrade",
|
||||
):
|
||||
assert not hasattr(LinuxDriver, name), name
|
||||
|
||||
|
||||
def test_every_annotation_resolves():
|
||||
"""``Dict``, ``List`` and ``Optional`` were used without being imported (#29);
|
||||
``from __future__ import annotations`` hid it until something resolved them."""
|
||||
import inspect
|
||||
import typing
|
||||
|
||||
for _name, member in inspect.getmembers(LinuxDriver, inspect.isfunction):
|
||||
if member.__module__ == "napalm_linux.linux":
|
||||
typing.get_type_hints(member)
|
||||
|
||||
|
||||
class TestManagementPeer:
|
||||
"""The address the host sees this connection come from (``SSH_CONNECTION``)."""
|
||||
|
||||
def _driver(self, answer):
|
||||
d = LinuxDriver("h", "admin", "p")
|
||||
d._device = MagicMock()
|
||||
d.run_command = MagicMock(return_value=MagicMock(stdout=answer, exit_code=0))
|
||||
return d
|
||||
|
||||
def test_the_client_side_of_ssh_connection(self):
|
||||
assert (
|
||||
self._driver("10.7.224.20 51234 10.0.0.5 22\n").get_management_peer() == "10.7.224.20"
|
||||
)
|
||||
|
||||
def test_an_ipv6_client(self):
|
||||
assert self._driver("fd00::20 51234 fd00::5 22\n").get_management_peer() == "fd00::20"
|
||||
|
||||
@pytest.mark.parametrize("answer", ["", "\n", "garbage", "not-an-ip 1 2 3"])
|
||||
def test_nothing_usable_is_none(self, answer):
|
||||
assert self._driver(answer).get_management_peer() is None
|
||||
|
||||
|
||||
class TestFactsNotWarnings:
|
||||
"""The driver reports facts; the application names warnings (#28, netOrk #1111)."""
|
||||
|
||||
def test_no_warnings_of_its_own(self):
|
||||
assert "get_device_warnings" not in vars(LinuxDriver)
|
||||
|
||||
def test_the_package_proxy_apt_fetches_through(self, driver):
|
||||
_host(driver, proxy="http://c:3142")
|
||||
assert driver.get_package_proxy() == "http://c:3142"
|
||||
|
||||
def test_no_proxy_set(self, driver):
|
||||
_host(driver)
|
||||
assert driver.get_package_proxy() is None
|
||||
|
||||
def test_where_apt_s_proxy_is_set(self, driver):
|
||||
_host(
|
||||
driver,
|
||||
proxy="http://old:3128",
|
||||
parts='/etc/apt/apt.conf.d/90curtin-aptproxy:1:Acquire::http::Proxy "http://old:3128";\n',
|
||||
)
|
||||
report = driver.get_package_proxy_report()
|
||||
assert report["settings"][0]["file"] == "/etc/apt/apt.conf.d/90curtin-aptproxy"
|
||||
|
||||
def test_not_an_apt_host(self, driver):
|
||||
driver._pkg_manager = "dnf"
|
||||
assert driver.get_package_proxy() is None
|
||||
assert driver.get_package_proxy_report() is None
|
||||
|
||||
def test_the_applications_proxy_url_is_no_argument_any_more(self):
|
||||
d = LinuxDriver("h", "admin", "p", optional_args={"apt_proxy_url": "http://c:3142"})
|
||||
assert not hasattr(d, "_apt_proxy_url")
|
||||
+1732
-315
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,232 @@
|
||||
"""get_lldp_neighbors: every neighbour of a port, its chassis MAC and its port (#58).
|
||||
|
||||
lldpd's ``lldpctl -f keyvalue`` is parsed by napalm-device-types'
|
||||
``parse_lldpctl_keyvalue``. Before, the driver grouped the lines by interface,
|
||||
so a second neighbour on a port overwrote the first; it looked for
|
||||
``chassis.id.subtype``/``chassis.id.value`` and ``port.id.value``, keys lldpd
|
||||
never prints, so the chassis MAC was never reported and a port given by MAC or
|
||||
local id came back empty; and it cut ``eth0.100`` at its dot.
|
||||
|
||||
#66: the running check took systemctl's ``inactive`` for running, and a failed
|
||||
lldpctl read as no neighbours.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import subprocess
|
||||
|
||||
import pytest
|
||||
from napalm_device_types import LLDPCTL_KEYVALUE_COMMAND
|
||||
|
||||
from napalm_linux.linux import LinuxDriver
|
||||
|
||||
_RC = "__LLDPCTL_RC"
|
||||
|
||||
# Laid out the way lldpd's keyvalue writer prints ``show neighbors details``
|
||||
# (src/client/display.c, kv_writer.c): every neighbour opens with ``via``, an id
|
||||
# is printed under its type. Not recorded from a device. On eth0 a phone and the
|
||||
# PC behind it (an unmanaged switch between them and the host), on the VLAN
|
||||
# interface eth0.100 a switch that names its port by a local id.
|
||||
LLDPCTL_KEYVALUE = """\
|
||||
lldp.eth0.via=LLDP
|
||||
lldp.eth0.rid=1
|
||||
lldp.eth0.age=0 day, 00:10:00
|
||||
lldp.eth0.chassis.mac=00:11:22:33:44:AA
|
||||
lldp.eth0.chassis.name=desk-phone
|
||||
lldp.eth0.chassis.descr=SIP phone
|
||||
lldp.eth0.chassis.Tel.enabled=on
|
||||
lldp.eth0.port.mac=00:11:22:33:44:aa
|
||||
lldp.eth0.port.descr=WAN
|
||||
lldp.eth0.port.ttl=120
|
||||
lldp.eth0.via=LLDP
|
||||
lldp.eth0.rid=2
|
||||
lldp.eth0.age=0 day, 00:09:00
|
||||
lldp.eth0.chassis.mac=00:11:22:33:44:bb
|
||||
lldp.eth0.chassis.name=desk-pc
|
||||
lldp.eth0.chassis.Station.enabled=on
|
||||
lldp.eth0.port.ifname=eno1
|
||||
lldp.eth0.port.ttl=120
|
||||
lldp.eth0.100.via=LLDP
|
||||
lldp.eth0.100.rid=3
|
||||
lldp.eth0.100.age=1 day, 02:00:00
|
||||
lldp.eth0.100.chassis.local=access-sw-01
|
||||
lldp.eth0.100.chassis.name=access-sw
|
||||
lldp.eth0.100.chassis.Bridge.enabled=on
|
||||
lldp.eth0.100.port.local=gi1/0/7
|
||||
lldp.eth0.100.port.descr=GigabitEthernet1/0/7
|
||||
"""
|
||||
|
||||
|
||||
#: Shell stubs for the host's lldpd state: ``systemctl`` and ``service`` as a
|
||||
#: systemd host answers them, ``pgrep`` as procps does.
|
||||
_RUNNING = (
|
||||
"systemctl() { case $* in *--quiet*) ;; *) echo active ;; esac; return 0; }; "
|
||||
"service() { echo ' Active: active (running)'; return 0; }; "
|
||||
"pgrep() { return 0; }; "
|
||||
)
|
||||
_STOPPED = (
|
||||
"systemctl() { case $* in *--quiet*) ;; *) echo inactive ;; esac; return 3; }; "
|
||||
"service() { echo ' Active: inactive (dead)'; return 3; }; "
|
||||
"pgrep() { return 1; }; "
|
||||
)
|
||||
_FAILED = (
|
||||
"systemctl() { case $* in *--quiet*) ;; *) echo failed ;; esac; return 3; }; "
|
||||
"service() { echo ' Active: failed (Result: exit-code)'; return 3; }; "
|
||||
"pgrep() { return 1; }; "
|
||||
)
|
||||
#: No systemd, lldpd started by its init script: only pgrep finds it.
|
||||
_RUNNING_WITHOUT_SYSTEMD = (
|
||||
"systemctl() { return 127; }; service() { return 1; }; pgrep() { return 0; }; "
|
||||
)
|
||||
|
||||
|
||||
def _shell(stubs: str, command: str) -> str:
|
||||
"""What *command* prints in ``sh`` with the state commands stubbed out."""
|
||||
done = subprocess.run( # a local sh, no network
|
||||
["sh", "-c", stubs + command], capture_output=True, text=True, check=False, timeout=10
|
||||
)
|
||||
return done.stdout.strip()
|
||||
|
||||
|
||||
def _answer(
|
||||
driver: LinuxDriver,
|
||||
lldpctl: str,
|
||||
*,
|
||||
installed: bool = True,
|
||||
state: str = _RUNNING,
|
||||
lldpctl_error: str = "",
|
||||
lldpctl_status: int = 0,
|
||||
):
|
||||
"""Answer ``_send`` the way the host's shell would.
|
||||
|
||||
lldpctl prints *lldpctl* on stdout, *lldpctl_error* on stderr and exits with
|
||||
*lldpctl_status*; the redirections and the status echo of the command sent
|
||||
decide what of that comes back.
|
||||
"""
|
||||
sent: list[str] = []
|
||||
|
||||
def send(command: str, read_timeout: float = 100) -> str:
|
||||
sent.append(command)
|
||||
if command.startswith("command -v lldpctl"):
|
||||
return "/usr/sbin/lldpctl" if installed else ""
|
||||
if "lldpd" in command and "lldpctl" not in command:
|
||||
return _shell(state, command)
|
||||
if command.startswith("lldpctl"):
|
||||
out = lldpctl
|
||||
if "2>&1" in command:
|
||||
out += lldpctl_error
|
||||
if f"echo {_RC}" in command:
|
||||
out += f"\n{_RC}={lldpctl_status}"
|
||||
return out.strip()
|
||||
raise AssertionError(f"unexpected command {command!r}")
|
||||
|
||||
driver._send = send # type: ignore[method-assign]
|
||||
return sent
|
||||
|
||||
|
||||
@pytest.fixture()
|
||||
def driver() -> LinuxDriver:
|
||||
return LinuxDriver.__new__(LinuxDriver)
|
||||
|
||||
|
||||
class TestNeighbours:
|
||||
def test_every_neighbour_of_a_port_is_reported(self, driver):
|
||||
_answer(driver, LLDPCTL_KEYVALUE)
|
||||
|
||||
result = driver.get_lldp_neighbors()
|
||||
|
||||
assert [n["hostname"] for n in result["eth0"]] == ["desk-phone", "desk-pc"]
|
||||
|
||||
def test_the_chassis_mac_is_reported_in_lower_case(self, driver):
|
||||
_answer(driver, LLDPCTL_KEYVALUE)
|
||||
|
||||
phone, pc = driver.get_lldp_neighbors()["eth0"]
|
||||
|
||||
assert phone["mac"] == "00:11:22:33:44:aa"
|
||||
assert pc["mac"] == "00:11:22:33:44:bb"
|
||||
|
||||
def test_a_port_given_by_mac_or_local_id_is_reported(self, driver):
|
||||
_answer(driver, LLDPCTL_KEYVALUE)
|
||||
|
||||
result = driver.get_lldp_neighbors()
|
||||
|
||||
assert result["eth0"][0]["port"] == "00:11:22:33:44:aa"
|
||||
assert result["eth0"][1]["port"] == "eno1"
|
||||
assert result["eth0.100"][0]["port"] == "gi1/0/7"
|
||||
|
||||
def test_a_dotted_interface_name_stays_whole(self, driver):
|
||||
_answer(driver, LLDPCTL_KEYVALUE)
|
||||
|
||||
assert sorted(driver.get_lldp_neighbors()) == ["eth0", "eth0.100"]
|
||||
|
||||
def test_a_chassis_not_named_by_a_mac_has_no_mac(self, driver):
|
||||
_answer(driver, LLDPCTL_KEYVALUE)
|
||||
|
||||
assert driver.get_lldp_neighbors()["eth0.100"] == [
|
||||
{"hostname": "access-sw", "port": "gi1/0/7"}
|
||||
]
|
||||
|
||||
def test_a_chassis_mac_that_is_no_mac_address_is_left_out(self, driver):
|
||||
_answer(driver, "lldp.eth0.via=LLDP\nlldp.eth0.chassis.mac=00:11\n")
|
||||
|
||||
assert driver.get_lldp_neighbors() == {"eth0": [{"hostname": "", "port": ""}]}
|
||||
|
||||
|
||||
class TestWithoutLldpd:
|
||||
def test_without_lldpctl_there_are_no_neighbours(self, driver):
|
||||
sent = _answer(driver, LLDPCTL_KEYVALUE, installed=False)
|
||||
|
||||
assert driver.get_lldp_neighbors() == {}
|
||||
assert not any(c.startswith("lldpctl") for c in sent)
|
||||
|
||||
def test_lldpd_without_neighbours_lists_none(self, driver):
|
||||
_answer(driver, "")
|
||||
|
||||
assert driver.get_lldp_neighbors() == {}
|
||||
|
||||
|
||||
class TestLldpdState:
|
||||
"""Only a running lldpd is asked; a stopped one is no neighbours (#66)."""
|
||||
|
||||
@pytest.mark.parametrize("state", [_STOPPED, _FAILED], ids=["inactive", "failed"])
|
||||
def test_a_stopped_lldpd_is_not_asked(self, driver, state):
|
||||
sent = _answer(driver, LLDPCTL_KEYVALUE, state=state)
|
||||
|
||||
assert driver.get_lldp_neighbors() == {}
|
||||
assert not any(c.startswith("lldpctl") for c in sent)
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
"state", [_RUNNING, _RUNNING_WITHOUT_SYSTEMD], ids=["systemd", "without-systemd"]
|
||||
)
|
||||
def test_a_running_lldpd_is_asked(self, driver, state):
|
||||
_answer(driver, LLDPCTL_KEYVALUE, state=state)
|
||||
|
||||
assert sorted(driver.get_lldp_neighbors()) == ["eth0", "eth0.100"]
|
||||
|
||||
|
||||
class TestFailedRead:
|
||||
"""With lldpd running, a failed lldpctl raises instead of reading as none (#66)."""
|
||||
|
||||
def test_lldpctl_is_asked_with_its_exit_status(self, driver):
|
||||
sent = _answer(driver, LLDPCTL_KEYVALUE)
|
||||
|
||||
driver.get_lldp_neighbors()
|
||||
|
||||
assert sent[-1] == LLDPCTL_KEYVALUE_COMMAND
|
||||
|
||||
def test_an_unreachable_lldpd_raises(self, driver):
|
||||
_answer(
|
||||
driver,
|
||||
"",
|
||||
lldpctl_error="[WARN/control] unable to connect to socket /run/lldpd.socket: "
|
||||
"Permission denied",
|
||||
lldpctl_status=1,
|
||||
)
|
||||
|
||||
with pytest.raises(ValueError, match="Permission denied"):
|
||||
driver.get_lldp_neighbors()
|
||||
|
||||
def test_lldpctl_without_neighbours_lists_none(self, driver):
|
||||
_answer(driver, "")
|
||||
|
||||
assert driver.get_lldp_neighbors() == {}
|
||||
@@ -0,0 +1,232 @@
|
||||
"""Personal accounts on a Linux host (NetOrk/netork#1793).
|
||||
|
||||
napalm-device-types' ``LocalAccountsMixin`` runs the steps; the driver names
|
||||
shadow-utils' commands. A locked account is an expired one (``usermod -e 1``):
|
||||
PAM refuses it a key login too, where a ``!`` in front of the password alone
|
||||
stops only the password.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import shlex
|
||||
import time
|
||||
|
||||
import pytest
|
||||
from napalm_device_types import CommandResult, LocalAccountsMixin
|
||||
|
||||
from napalm_linux import LinuxDriver
|
||||
|
||||
HASH = "$6$salt$" + "x" * 86
|
||||
_TODAY = int(time.time() // 86400)
|
||||
|
||||
|
||||
class _Driver(LinuxDriver):
|
||||
"""A Linux driver whose host answers ``getent shadow`` with *shadow*."""
|
||||
|
||||
def __init__(self, shadow: str = "alice:$6$old:20000:0:99999:7:::") -> None:
|
||||
super().__init__("host", "netadmin", "pw")
|
||||
self.shadow = shadow
|
||||
self.ran: list[tuple[str, bool]] = []
|
||||
|
||||
def run_command(self, command, *, privileged=False, timeout=60, stdin=None):
|
||||
self.ran.append((command, privileged))
|
||||
if command == "getent shadow alice":
|
||||
return CommandResult(self.shadow + "\n", "", 0 if self.shadow else 2)
|
||||
return CommandResult("", "", 0)
|
||||
|
||||
|
||||
def _passwd() -> list[str]:
|
||||
return "alice:x:1001:1001::/home/alice:/bin/bash".split(":")
|
||||
|
||||
|
||||
def test_a_linux_host_can_add_and_lock_personal_accounts() -> None:
|
||||
assert issubclass(LinuxDriver, LocalAccountsMixin)
|
||||
assert LinuxDriver.ACCOUNT_PASSWORD_SCHEME == "sha512"
|
||||
assert LinuxDriver.ACCOUNT_SHELL == "/bin/bash"
|
||||
# Debian and Ubuntu grant %sudo, the Red Hat family %wheel, old Ubuntu %admin.
|
||||
assert set(LinuxDriver.ACCOUNT_ADMIN_GROUPS) == {"sudo", "wheel", "admin"}
|
||||
|
||||
|
||||
def test_a_new_account_gets_a_home_and_bash() -> None:
|
||||
d = _Driver()
|
||||
assert d._account_create("alice", HASH) == [
|
||||
["useradd", "-m", "-s", "/bin/bash", "-p", HASH, "alice"]
|
||||
]
|
||||
assert d._account_create("alice", None) == [["useradd", "-m", "-s", "/bin/bash", "alice"]]
|
||||
|
||||
|
||||
def test_locking_expires_the_account_and_locks_its_password() -> None:
|
||||
d = _Driver()
|
||||
assert d._account_lock("alice", locked=False) == [["usermod", "-L", "-e", "1", "alice"]]
|
||||
assert d._account_lock("alice", locked=True) == []
|
||||
|
||||
|
||||
def test_opening_lifts_the_expiry_and_sets_the_new_password() -> None:
|
||||
d = _Driver()
|
||||
assert d._account_open("alice", HASH, locked=True) == [
|
||||
["usermod", "-e", "", "-p", HASH, "alice"]
|
||||
]
|
||||
|
||||
|
||||
def test_opening_without_a_new_password_gives_back_the_old_one() -> None:
|
||||
d = _Driver(shadow="alice:!$6$old:20000:0:99999:7::1:")
|
||||
assert d._account_open("alice", None, locked=True) == [["usermod", "-U", "-e", "", "alice"]]
|
||||
|
||||
|
||||
def test_an_account_that_never_had_a_password_keeps_it_locked() -> None:
|
||||
# usermod -U refuses to leave an account without a password.
|
||||
for field in ("!", "!!", "!*", "*"):
|
||||
d = _Driver(shadow=f"alice:{field}:20000:0:99999:7::1:")
|
||||
assert d._account_open("alice", None, locked=True) == [["usermod", "-e", "", "alice"]]
|
||||
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
("expire", "locked"),
|
||||
[("", False), ("1", True), (str(_TODAY), True), (str(_TODAY + 30), False)],
|
||||
)
|
||||
def test_an_expired_account_is_locked(expire: str, locked: bool) -> None:
|
||||
d = _Driver(shadow=f"alice:$6$old:20000:0:99999:7::{expire}:")
|
||||
assert d._account_locked("alice", _passwd()) is locked
|
||||
assert d.ran == [("getent shadow alice", True)]
|
||||
|
||||
|
||||
def test_a_shadow_that_cannot_be_read_raises() -> None:
|
||||
with pytest.raises(RuntimeError, match="alice"):
|
||||
_Driver(shadow="")._account_locked("alice", _passwd())
|
||||
|
||||
|
||||
def test_leaving_a_group_is_gpasswd() -> None:
|
||||
assert _Driver()._account_leave_group("alice", "sudo", ["alice", "sudo"]) == [
|
||||
"gpasswd",
|
||||
"-d",
|
||||
"alice",
|
||||
"sudo",
|
||||
]
|
||||
|
||||
|
||||
def test_netorks_own_account_is_made_with_its_uid() -> None:
|
||||
"""A fixed uid on every host, below UID_MIN (NetOrk/netork#1817)."""
|
||||
assert _Driver()._account_create_with_uid("netork", 900) == [
|
||||
["useradd", "-m", "-u", "900", "-s", "/bin/bash", "netork"]
|
||||
]
|
||||
|
||||
|
||||
# -- what a person changes follows them (NetOrk/netork#2013) ----------------------------
|
||||
|
||||
ALICE_KEY = "ssh-ed25519 AAAAC3NzaC1lZDI1NTE5AAAAIAlice alice@laptop"
|
||||
OLD_KEY = "ssh-ed25519 AAAAC3NzaC1lZDI1NTE5AAAAIOld alice@lost-laptop"
|
||||
OWN_KEY = "ssh-rsa AAAAB3NzaC1yc2EAAAADAQABAAABAQOwn own@desktop"
|
||||
_KEYS = "/home/alice/.ssh/authorized_keys"
|
||||
|
||||
|
||||
class _Host(LinuxDriver):
|
||||
"""A Linux host with Alice's account, her key files and what ran as whom."""
|
||||
|
||||
def __init__(self, shadow: str, keys: str) -> None:
|
||||
super().__init__("host", "netadmin", "pw")
|
||||
self.shadow = shadow
|
||||
self.files = {_KEYS: keys}
|
||||
self.ran: list[tuple[str, bool]] = []
|
||||
|
||||
def run_command(self, command, *, privileged=False, timeout=60, stdin=None):
|
||||
self.ran.append((command, privileged))
|
||||
if stdin is not None:
|
||||
self.files["/tmp/staged"] = stdin.decode()
|
||||
return CommandResult("/tmp/staged", "", 0)
|
||||
argv = shlex.split(command)
|
||||
answers = {
|
||||
"id -un": "netadmin\n",
|
||||
"getent passwd alice": "alice:x:1001:1001::/home/alice:/bin/bash\n",
|
||||
"getent shadow alice": self.shadow + "\n",
|
||||
"id -Gn alice": "alice sudo\n",
|
||||
"sudo -l -U alice": "User alice is not allowed to run sudo on host.\n",
|
||||
}
|
||||
if command in answers:
|
||||
return CommandResult(answers[command], "", 0)
|
||||
if argv[:2] == ["test", "-e"]:
|
||||
return CommandResult("", "", 0 if argv[2] in self.files else 1)
|
||||
if argv[:4] == ["sudo", "-n", "-u", "alice"]:
|
||||
return self._as_alice(argv[4:])
|
||||
return CommandResult("", "", 0)
|
||||
|
||||
def _as_alice(self, argv: list[str]) -> CommandResult:
|
||||
if argv[0] == "cat":
|
||||
return CommandResult(self.files.get(argv[-1], ""), "", 0)
|
||||
if argv[0] == "install":
|
||||
self.files[argv[-1]] = self.files[argv[-2]]
|
||||
return CommandResult("", "", 0)
|
||||
|
||||
def as_root(self) -> list[list[str]]:
|
||||
"""What root ran that changes something: no reads, nothing as Alice."""
|
||||
reads = ("getent", "id", "test")
|
||||
words = [shlex.split(c) for c, privileged in self.ran if privileged]
|
||||
return [
|
||||
w for w in words if w[0] not in reads and w[:2] not in (["sudo", "-n"], ["sudo", "-l"])
|
||||
]
|
||||
|
||||
|
||||
_OPEN = "alice:$6$old:20000:0:99999:7:::"
|
||||
|
||||
|
||||
def test_clearing_the_password_is_a_star_no_hash_matches() -> None:
|
||||
# Not passwd -d: an empty password and pam_unix's nullok let anyone su to it.
|
||||
# Not "!": sshd without PAM takes it for a lock and refuses the key too.
|
||||
# Not an expiry: that is the lock, and PAM refuses a key of an expired account.
|
||||
assert _Driver()._account_clear_password("alice") == [["usermod", "-p", "*", "alice"]]
|
||||
|
||||
|
||||
def test_a_key_only_account_opens_again_without_its_password_coming_back() -> None:
|
||||
d = _Driver(shadow="alice:!*:20000:0:99999:7::1:")
|
||||
assert d._account_open("alice", None, locked=True) == [["usermod", "-e", "", "alice"]]
|
||||
|
||||
|
||||
def test_removing_the_password_runs_usermod_and_takes_sudo_away() -> None:
|
||||
host = _Host(_OPEN, keys=ALICE_KEY + "\n")
|
||||
|
||||
result = host.add_local_account("alice", ALICE_KEY, clear_password=True)
|
||||
|
||||
assert result["success"], result["output"]
|
||||
assert host.as_root() == [
|
||||
["usermod", "-U", "-e", "", "alice"],
|
||||
["rm", "-f", "--", "/etc/sudoers.d/80-account-alice"],
|
||||
["gpasswd", "-d", "alice", "sudo"],
|
||||
["usermod", "-p", "*", "alice"],
|
||||
]
|
||||
|
||||
|
||||
def test_a_replaced_key_is_written_out_of_the_key_file_as_the_person() -> None:
|
||||
host = _Host(_OPEN, keys=f"{OLD_KEY}\n{OWN_KEY}\n")
|
||||
|
||||
result = host.add_local_account("alice", ALICE_KEY, replaces=[OLD_KEY])
|
||||
|
||||
assert result["success"], result["output"]
|
||||
assert host.files[_KEYS] == f"{OWN_KEY}\n{ALICE_KEY}\n"
|
||||
installs = [c for c, _ in host.ran if "install -m 600" in c]
|
||||
assert installs and all(c.startswith("sudo -n -u alice install") for c in installs)
|
||||
|
||||
|
||||
def test_a_deleted_key_takes_the_password_and_sudo_with_it_when_asked() -> None:
|
||||
"""NetOrk/netork#2033: the password went with the person's key, so it goes from the
|
||||
host too, with sudo; the account stays open."""
|
||||
host = _Host(_OPEN, keys=f"{ALICE_KEY}\n{OWN_KEY}\n")
|
||||
|
||||
result = host.remove_local_account_keys("alice", [ALICE_KEY], clear_password=True)
|
||||
|
||||
assert result["success"], result["output"]
|
||||
assert [s["step"] for s in result["steps"]] == ["keys", "password", "sudo"]
|
||||
assert host.files[_KEYS] == f"{OWN_KEY}\n"
|
||||
assert host.as_root() == [
|
||||
["usermod", "-p", "*", "alice"],
|
||||
["rm", "-f", "--", "/etc/sudoers.d/80-account-alice"],
|
||||
["gpasswd", "-d", "alice", "sudo"],
|
||||
]
|
||||
|
||||
|
||||
def test_a_deleted_key_goes_and_the_account_stays_open() -> None:
|
||||
host = _Host(_OPEN, keys=f"{ALICE_KEY}\n{OWN_KEY}\n")
|
||||
|
||||
result = host.remove_local_account_keys("alice", [ALICE_KEY])
|
||||
|
||||
assert result["success"], result["output"]
|
||||
assert host.files[_KEYS] == f"{OWN_KEY}\n"
|
||||
assert host.as_root() == []
|
||||
@@ -0,0 +1,141 @@
|
||||
"""get_running_backups: the host's own file-level backups that a restart would abort.
|
||||
|
||||
A restic, borg, borgmatic, duplicity ... run -- from a systemd timer, a cron line
|
||||
or by hand -- is a process of a backup tool. The driver reads the processes, the
|
||||
host's clock and each process's cgroup in one round trip, and names a backup by
|
||||
the systemd service it runs in, which is the scheduled job netOrk shows for the
|
||||
timer (NetOrk/netork#2318, #1933). A failed read raises: an empty list would say
|
||||
nothing runs.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from unittest.mock import MagicMock
|
||||
|
||||
import pytest
|
||||
|
||||
from napalm_linux import LinuxDriver
|
||||
from napalm_linux._running_backups import RUNNING_BACKUPS_COMMAND, parse_running_backups
|
||||
|
||||
NOW = 1793664000
|
||||
|
||||
|
||||
def _reading(*rows: str, now: int = NOW, end: bool = True) -> str:
|
||||
lines = [f"NOW {now}", *rows]
|
||||
if end:
|
||||
lines.append("END")
|
||||
return "\n".join(lines)
|
||||
|
||||
|
||||
def _row(pid: int, elapsed: int, cgroup: str, args: str) -> str:
|
||||
return f"{pid}\t{elapsed}\t{cgroup}\t{args}"
|
||||
|
||||
|
||||
def test_nothing_runs():
|
||||
out = _reading(
|
||||
_row(1, 99999, "0::/init.scope", "/sbin/init"),
|
||||
_row(812, 3600, "0::/system.slice/ssh.service", "sshd: /usr/sbin/sshd -D"),
|
||||
)
|
||||
assert parse_running_backups(out) == []
|
||||
|
||||
|
||||
def test_a_timers_restic_backup_is_named_by_its_service():
|
||||
out = _reading(
|
||||
_row(4242, 600, "0::/system.slice/restic-backup.service", "/usr/bin/restic backup /srv")
|
||||
)
|
||||
assert parse_running_backups(out) == [
|
||||
{
|
||||
"kind": "backup",
|
||||
"job": "restic-backup.service",
|
||||
"task": "4242",
|
||||
"guests": [],
|
||||
"since": NOW - 600,
|
||||
}
|
||||
]
|
||||
|
||||
|
||||
def test_a_cron_run_has_no_job_of_its_own():
|
||||
out = _reading(_row(77, 30, "0::/system.slice/cron.service", "borg create ::{now} /etc"))
|
||||
[backup] = parse_running_backups(out)
|
||||
assert backup["job"] is None
|
||||
assert backup["kind"] == "backup"
|
||||
|
||||
|
||||
def test_cgroup_v1_is_read_too():
|
||||
out = _reading(_row(9, 5, "1:name=systemd:/system.slice/borgmatic.service", "borgmatic"))
|
||||
assert parse_running_backups(out)[0]["job"] == "borgmatic.service"
|
||||
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
("args", "kind"),
|
||||
[
|
||||
("/usr/bin/restic backup --files-from /etc/restic/files", "backup"),
|
||||
("restic forget --prune --keep-daily 7", "prune"),
|
||||
("restic -r s3:example check", "verify"),
|
||||
("restic copy --from-repo /srv/a", "sync"),
|
||||
("/usr/bin/borg create --stats ::{now} /home", "backup"),
|
||||
("borg --lock-wait 60 prune --keep-daily 7", "prune"),
|
||||
("borg compact", "prune"),
|
||||
("borg check --verify-data", "verify"),
|
||||
("borg serve --restrict-to-path /srv/borg", "backup"),
|
||||
("/usr/bin/python3 /usr/bin/borgmatic --verbosity 1", "backup"),
|
||||
("duplicity incremental /home file:///mnt/b", "backup"),
|
||||
("/bin/bash /usr/bin/duply home backup", "backup"),
|
||||
("rsnapshot daily", "backup"),
|
||||
("rdiff-backup /home /mnt/b", "backup"),
|
||||
("proxmox-backup-client backup root.pxar:/", "backup"),
|
||||
("kopia snapshot create /home", "backup"),
|
||||
("btrbk run", "backup"),
|
||||
("resticprofile backup", "backup"),
|
||||
("autorestic backup -a", "backup"),
|
||||
],
|
||||
)
|
||||
def test_the_tools_and_what_they_do(args, kind):
|
||||
[backup] = parse_running_backups(_reading(_row(1, 1, "0::/user.slice", args)))
|
||||
assert backup["kind"] == kind
|
||||
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
"args",
|
||||
[
|
||||
"restic mount /mnt/restic",
|
||||
"restic snapshots",
|
||||
"restic restore latest --target /",
|
||||
"borg mount ::archive /mnt",
|
||||
"borg list",
|
||||
"kopia server start",
|
||||
"vim /etc/restic/backup.sh",
|
||||
"grep borg /var/log/syslog",
|
||||
],
|
||||
)
|
||||
def test_what_is_no_backup(args):
|
||||
assert parse_running_backups(_reading(_row(1, 1, "0::/user.slice", args))) == []
|
||||
|
||||
|
||||
def test_a_session_or_scope_is_no_job():
|
||||
out = _reading(_row(5, 1, "0::/user.slice/user-1000.slice/session-3.scope", "restic backup /"))
|
||||
assert parse_running_backups(out)[0]["job"] is None
|
||||
|
||||
|
||||
def test_a_reading_cut_short_raises():
|
||||
with pytest.raises(RuntimeError):
|
||||
parse_running_backups(_reading(_row(1, 1, "", "restic backup /"), end=False))
|
||||
|
||||
|
||||
def test_no_clock_raises():
|
||||
with pytest.raises(RuntimeError):
|
||||
parse_running_backups("END")
|
||||
|
||||
|
||||
def test_the_driver_reads_as_the_login_user_in_one_round_trip():
|
||||
drv = LinuxDriver.__new__(LinuxDriver)
|
||||
drv._send = MagicMock(return_value=_reading())
|
||||
assert drv.get_running_backups() == []
|
||||
drv._send.assert_called_once()
|
||||
assert drv._send.call_args.args[0] == RUNNING_BACKUPS_COMMAND
|
||||
|
||||
|
||||
def test_the_command_says_when_ps_failed():
|
||||
"""Busybox's ps knows no etimes: the reading must not end as if nothing ran."""
|
||||
assert "|| exit" in RUNNING_BACKUPS_COMMAND
|
||||
assert RUNNING_BACKUPS_COMMAND.rstrip().endswith("echo END")
|
||||
@@ -0,0 +1,58 @@
|
||||
"""Scheduled jobs on a Linux host: napalm-device-types' POSIX implementation (#67).
|
||||
|
||||
The report, its parse and every write are ``PosixScheduledJobsMixin``'s; the
|
||||
driver carries the command across ``run_command``, as root, in one round trip.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from unittest.mock import MagicMock
|
||||
|
||||
from napalm_device_types import CommandResult, PosixScheduledJobsMixin
|
||||
|
||||
from napalm_linux import LinuxDriver
|
||||
|
||||
REPORT = """SJ_BEGIN
|
||||
[system /etc/cron.d/certbot]
|
||||
|0 */12 * * * root certbot -q renew
|
||||
[tz]
|
||||
/usr/share/zoneinfo/Europe/Berlin
|
||||
[owners]
|
||||
certbot: /etc/cron.d/certbot
|
||||
SJ_END
|
||||
"""
|
||||
|
||||
|
||||
def _driver() -> LinuxDriver:
|
||||
driver = LinuxDriver("host", "user", "pw")
|
||||
driver.run_command = MagicMock(return_value=CommandResult(REPORT, "", 0)) # type: ignore[method-assign]
|
||||
return driver
|
||||
|
||||
|
||||
def test_a_linux_host_offers_every_verb():
|
||||
assert issubclass(LinuxDriver, PosixScheduledJobsMixin)
|
||||
for verb in (
|
||||
"get_scheduled_jobs",
|
||||
"manage_scheduled_job",
|
||||
"put_scheduled_job",
|
||||
"delete_scheduled_job",
|
||||
):
|
||||
assert callable(getattr(LinuxDriver, verb))
|
||||
|
||||
|
||||
def test_the_jobs_are_read_as_root_in_one_round_trip():
|
||||
driver = _driver()
|
||||
reading = driver.get_scheduled_jobs()
|
||||
assert reading["time_zone"] == "Europe/Berlin"
|
||||
(job,) = reading["jobs"]
|
||||
assert (job["run_as"], job["managed_by"], job["command"]) == (
|
||||
"root",
|
||||
"package",
|
||||
"certbot -q renew",
|
||||
)
|
||||
driver.run_command.assert_called_once()
|
||||
assert driver.run_command.call_args.kwargs["privileged"] is True
|
||||
|
||||
|
||||
def test_the_old_cron_reader_is_gone():
|
||||
assert not hasattr(LinuxDriver, "get_cron_jobs")
|
||||
@@ -0,0 +1,289 @@
|
||||
"""``set_hostname`` renames the host itself, not only what netOrk calls it (#45).
|
||||
|
||||
The static and runtime hostname take the short name; ``/etc/hosts`` follows, so
|
||||
the host still resolves its own name; and a cloud-init host is told to keep the
|
||||
name, or its next boot puts the image's name back. Every file root writes is
|
||||
staged without privilege first, as ``_install_file_as_root`` does for the fixes.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import shlex
|
||||
from types import SimpleNamespace
|
||||
from unittest.mock import MagicMock
|
||||
|
||||
import pytest
|
||||
|
||||
from napalm_linux import LinuxDriver
|
||||
from napalm_linux._hostname import _rename_in_hosts, _split_hostname
|
||||
|
||||
_PW = "pw-45"
|
||||
_STAGED = "/tmp/netork-stage.Xy34Zw"
|
||||
_HOSTS = "127.0.0.1\tlocalhost\n127.0.1.1\told.example.net old\n\n::1 localhost ip6-localhost\n"
|
||||
|
||||
|
||||
class Host:
|
||||
"""The host's exec channels: every line, its stdin, and whether it ran as root."""
|
||||
|
||||
def __init__(self, *, hosts=_HOSTS, cloud_init=False, rename_status=0, hosts_status=0):
|
||||
self.runs: list[SimpleNamespace] = []
|
||||
self.hosts = hosts
|
||||
self.cloud_init = cloud_init
|
||||
self.rename_status = rename_status
|
||||
self.hosts_status = hosts_status
|
||||
|
||||
def open_session(self):
|
||||
return _Channel(self)
|
||||
|
||||
def answer(self, command: str, script: str) -> tuple[str, int]:
|
||||
if command.startswith("sudo -n "):
|
||||
return "sudo: a password is required\n", 1
|
||||
if script == "hostname":
|
||||
return "old\n", 0
|
||||
if script.startswith("hostname -f"):
|
||||
return "old.example.net\n", 0
|
||||
if script == "cat /etc/hosts":
|
||||
return self.hosts, 0
|
||||
if script.startswith("test -d /etc/cloud"):
|
||||
return "", 0 if self.cloud_init else 1
|
||||
if "mktemp" in script:
|
||||
return _STAGED, 0
|
||||
if "hostnamectl" in script:
|
||||
return (
|
||||
"hostname: you must be root\n" if self.rename_status else ""
|
||||
), self.rename_status
|
||||
if "/etc/hosts" in script and "install" in script:
|
||||
return ("install: cannot create\n" if self.hosts_status else ""), self.hosts_status
|
||||
return "", 0
|
||||
|
||||
@property
|
||||
def root_scripts(self) -> list[str]:
|
||||
return [run.script for run in self.runs if run.root]
|
||||
|
||||
def staged(self) -> list[bytes]:
|
||||
return [run.stdin for run in self.runs if "mktemp" in run.script]
|
||||
|
||||
|
||||
class _Channel:
|
||||
def __init__(self, host: Host):
|
||||
self._host = host
|
||||
self._run: SimpleNamespace | None = None
|
||||
self._out = b""
|
||||
self._status = 0
|
||||
|
||||
def exec_command(self, command):
|
||||
assert _PW not in command
|
||||
root = command.startswith(("sudo ", "sh -c "))
|
||||
parts = shlex.split(command)
|
||||
script = parts[parts.index("-c") + 1] if root else command
|
||||
script = script.removeprefix("exec </dev/null; ")
|
||||
self._run = SimpleNamespace(line=command, script=script, root=root, stdin=b"")
|
||||
self._host.runs.append(self._run)
|
||||
output, self._status = self._host.answer(command, script)
|
||||
self._out = output.encode()
|
||||
|
||||
def settimeout(self, timeout):
|
||||
pass
|
||||
|
||||
def sendall(self, data):
|
||||
self._run.stdin += data
|
||||
|
||||
def shutdown_write(self):
|
||||
pass
|
||||
|
||||
def close(self):
|
||||
pass
|
||||
|
||||
def recv_ready(self):
|
||||
return bool(self._out)
|
||||
|
||||
def recv(self, size):
|
||||
chunk, self._out = self._out[:size], self._out[size:]
|
||||
return chunk
|
||||
|
||||
def recv_stderr_ready(self):
|
||||
return False
|
||||
|
||||
def recv_stderr(self, size):
|
||||
return b""
|
||||
|
||||
def exit_status_ready(self):
|
||||
return not self._out
|
||||
|
||||
def recv_exit_status(self):
|
||||
return self._status
|
||||
|
||||
|
||||
def _driver(host: Host, *, sudo_password: str | None = _PW) -> LinuxDriver:
|
||||
optional_args = {"sudo_password": sudo_password} if sudo_password else {}
|
||||
driver = LinuxDriver("h", "admin", "p", optional_args=optional_args)
|
||||
driver._device = MagicMock()
|
||||
driver._device.remote_conn_pre = SimpleNamespace(get_transport=lambda: host)
|
||||
driver._root = False
|
||||
driver._pkg_manager = "apt"
|
||||
return driver
|
||||
|
||||
|
||||
def _hosts_written(host: Host) -> str:
|
||||
"""What was staged for /etc/hosts, or "" when it was left alone."""
|
||||
staged = b""
|
||||
for run in host.runs:
|
||||
if "mktemp" in run.script:
|
||||
staged = run.stdin
|
||||
elif run.root and "/etc/hosts" in run.script:
|
||||
return staged.decode()
|
||||
return ""
|
||||
|
||||
|
||||
class TestSplitHostname:
|
||||
@pytest.mark.parametrize(
|
||||
"name, expected",
|
||||
[
|
||||
("web-01", ("web-01", None)),
|
||||
("web-01.example.net", ("web-01", "web-01.example.net")),
|
||||
("A1", ("A1", None)),
|
||||
("a" * 63, ("a" * 63, None)),
|
||||
],
|
||||
)
|
||||
def test_valid(self, name, expected):
|
||||
assert _split_hostname(name) == expected
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
"name",
|
||||
[
|
||||
"",
|
||||
"web_01",
|
||||
"-web",
|
||||
"web-",
|
||||
"a" * 64,
|
||||
".".join(["a" * 60] * 5),
|
||||
"web 01",
|
||||
"web;reboot",
|
||||
"web.",
|
||||
".web",
|
||||
"web..example",
|
||||
"$(id)",
|
||||
],
|
||||
)
|
||||
def test_invalid(self, name):
|
||||
with pytest.raises(ValueError):
|
||||
_split_hostname(name)
|
||||
|
||||
|
||||
class TestRenameInHosts:
|
||||
def test_old_names_replaced_on_every_line_they_appear(self):
|
||||
content = "127.0.0.1 localhost old\n10.0.0.5 old.example.net old # me\n"
|
||||
assert _rename_in_hosts(content, {"old", "old.example.net"}, "new", "new.example.net") == (
|
||||
"127.0.0.1\tlocalhost new.example.net new\n10.0.0.5\tnew.example.net new # me\n"
|
||||
)
|
||||
|
||||
def test_other_aliases_and_lines_kept(self):
|
||||
content = "# static\n127.0.1.1 old mail\n::1 localhost\n"
|
||||
assert _rename_in_hosts(content, {"old"}, "new", None) == (
|
||||
"# static\n127.0.1.1\tnew mail\n::1 localhost\n"
|
||||
)
|
||||
|
||||
def test_names_compared_without_case(self):
|
||||
assert _rename_in_hosts("127.0.1.1 OLD\n", {"old"}, "new", None) == "127.0.1.1\tnew\n"
|
||||
|
||||
def test_no_old_name_but_a_127_0_1_1_line_takes_the_new_name(self):
|
||||
content = "127.0.0.1 localhost\n127.0.1.1 ubuntu\n"
|
||||
assert _rename_in_hosts(content, {"old"}, "new", "new.example.net") == (
|
||||
"127.0.0.1 localhost\n127.0.1.1\tnew.example.net new\n"
|
||||
)
|
||||
|
||||
def test_neither_leaves_the_file_alone(self):
|
||||
content = "127.0.0.1 localhost localhost.localdomain\n::1 localhost\n"
|
||||
assert _rename_in_hosts(content, {"old"}, "new", None) == content
|
||||
|
||||
def test_localhost_is_never_renamed(self):
|
||||
content = "127.0.0.1 localhost\n"
|
||||
assert _rename_in_hosts(content, {"localhost"}, "new", None) == content
|
||||
|
||||
|
||||
class TestSetHostname:
|
||||
def test_short_name_set_as_root(self):
|
||||
host = Host()
|
||||
|
||||
_driver(host).set_hostname("new")
|
||||
|
||||
rename = host.root_scripts[0]
|
||||
assert "hostnamectl set-hostname new" in rename
|
||||
assert "/etc/hostname" in rename and "hostname new" in rename
|
||||
|
||||
def test_fqdn_sets_the_short_name_and_both_in_hosts(self):
|
||||
host = Host()
|
||||
|
||||
_driver(host).set_hostname("new.example.net")
|
||||
|
||||
assert "hostnamectl set-hostname new " in host.root_scripts[0]
|
||||
assert "example" not in host.root_scripts[0]
|
||||
assert _hosts_written(host) == (
|
||||
"127.0.0.1\tlocalhost\n127.0.1.1\tnew.example.net new\n\n::1 localhost ip6-localhost\n"
|
||||
)
|
||||
|
||||
def test_hosts_installed_from_a_staged_file_never_privileged_stdin(self):
|
||||
host = Host()
|
||||
|
||||
_driver(host).set_hostname("new")
|
||||
|
||||
hosts_install = [s for s in host.root_scripts if "/etc/hosts" in s]
|
||||
assert len(hosts_install) == 1
|
||||
assert f"install -m 644 -o root -g root -- {_STAGED}" in hosts_install[0]
|
||||
for run in host.runs:
|
||||
if run.root:
|
||||
assert run.stdin == f"{_PW}\n".encode()
|
||||
|
||||
def test_unchanged_hosts_not_rewritten(self):
|
||||
host = Host(hosts="127.0.0.1 localhost\n")
|
||||
|
||||
_driver(host).set_hostname("new")
|
||||
|
||||
assert not any("/etc/hosts" in s for s in host.root_scripts)
|
||||
|
||||
def test_cloud_init_host_keeps_the_name(self):
|
||||
host = Host(cloud_init=True)
|
||||
|
||||
_driver(host).set_hostname("new")
|
||||
|
||||
assert any(
|
||||
"/etc/cloud/cloud.cfg.d/99-preserve-hostname.cfg" in s for s in host.root_scripts
|
||||
)
|
||||
assert any(b"preserve_hostname: true" in staged for staged in host.staged())
|
||||
|
||||
def test_no_cloud_init_no_drop_in(self):
|
||||
host = Host()
|
||||
|
||||
_driver(host).set_hostname("new")
|
||||
|
||||
assert not any("cloud.cfg.d" in s for s in host.root_scripts)
|
||||
|
||||
def test_invalid_name_runs_nothing(self):
|
||||
host = Host()
|
||||
driver = _driver(host)
|
||||
|
||||
with pytest.raises(ValueError):
|
||||
driver.set_hostname("new;reboot")
|
||||
|
||||
assert host.runs == []
|
||||
driver._device.send_command.assert_not_called()
|
||||
|
||||
def test_failed_rename_raises_and_writes_nothing(self):
|
||||
host = Host(rename_status=1)
|
||||
|
||||
with pytest.raises(RuntimeError):
|
||||
_driver(host).set_hostname("new")
|
||||
|
||||
assert not any("/etc/hosts" in s for s in host.root_scripts)
|
||||
|
||||
def test_sudo_without_password_says_what_to_do(self):
|
||||
host = Host()
|
||||
|
||||
with pytest.raises(RuntimeError, match="no sudo password was given"):
|
||||
_driver(host, sudo_password=None).set_hostname("new")
|
||||
|
||||
def test_failed_hosts_write_raises(self):
|
||||
host = Host(hosts_status=1)
|
||||
|
||||
with pytest.raises(RuntimeError, match="/etc/hosts"):
|
||||
_driver(host).set_hostname("new")
|
||||
@@ -0,0 +1,115 @@
|
||||
"""open() hands netmiko the host key to expect, and reports the one it saw (NetOrk/netork#1167).
|
||||
|
||||
OpenMediaVault and QNAP open through ``LinuxDriver.open()`` and get this too.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import os
|
||||
from unittest.mock import MagicMock, patch
|
||||
|
||||
import paramiko
|
||||
import pytest
|
||||
from napalm_device_types.ssh_host_keys import (
|
||||
KNOWN_KEYS_ARG,
|
||||
OBSERVER_ARG,
|
||||
SshHostKey,
|
||||
SshHostKeyMismatch,
|
||||
)
|
||||
from netmiko.exceptions import NetmikoTimeoutException
|
||||
|
||||
from napalm_linux.linux import LinuxDriver
|
||||
|
||||
SERVER_KEY = paramiko.ECDSAKey.generate()
|
||||
OTHER_KEY = paramiko.ECDSAKey.generate()
|
||||
|
||||
|
||||
def _device() -> MagicMock:
|
||||
device = MagicMock()
|
||||
device.send_command.return_value = "/usr/bin/apt"
|
||||
device.remote_conn_pre.get_transport.return_value.get_remote_server_key.return_value = (
|
||||
SERVER_KEY
|
||||
)
|
||||
return device
|
||||
|
||||
|
||||
def _driver(seen: list, known: SshHostKey | None = None) -> LinuxDriver:
|
||||
args: dict = {"port": 2222, OBSERVER_ARG: seen.append}
|
||||
if known is not None:
|
||||
args[KNOWN_KEYS_ARG] = {"2222": known.as_dict()}
|
||||
return LinuxDriver("10.0.0.8", "admin", "s3cret", optional_args=args)
|
||||
|
||||
|
||||
def test_first_use_lets_netmiko_accept_and_reports_the_key():
|
||||
seen: list = []
|
||||
with patch("napalm_linux.linux.ConnectHandler", return_value=_device()) as handler:
|
||||
_driver(seen).open()
|
||||
kwargs = handler.call_args.kwargs
|
||||
assert kwargs["ssh_strict"] is False
|
||||
assert kwargs["alt_host_keys"] is False
|
||||
assert kwargs["system_host_keys"] is False
|
||||
assert seen[0]["accepted"] is True
|
||||
assert seen[0]["seen"]["fingerprint"] == SshHostKey.of(SERVER_KEY).fingerprint
|
||||
assert (seen[0]["host"], seen[0]["port"]) == ("10.0.0.8", 2222)
|
||||
|
||||
|
||||
def test_a_known_key_is_the_only_one_netmiko_accepts():
|
||||
seen: list = []
|
||||
known = SshHostKey.of(SERVER_KEY)
|
||||
files: list[str] = []
|
||||
|
||||
def connect(**kwargs):
|
||||
files.append(kwargs["alt_key_file"])
|
||||
with open(kwargs["alt_key_file"]) as f:
|
||||
assert f.read().strip() == known.known_hosts_line("10.0.0.8", 2222)
|
||||
assert kwargs["ssh_strict"] is True and kwargs["alt_host_keys"] is True
|
||||
return _device()
|
||||
|
||||
with patch("napalm_linux.linux.ConnectHandler", side_effect=connect):
|
||||
_driver(seen, known).open()
|
||||
assert not os.path.exists(files[0])
|
||||
assert seen[0]["accepted"] is True
|
||||
|
||||
|
||||
def test_a_changed_key_is_refused():
|
||||
seen: list = []
|
||||
|
||||
def refuse(**kwargs):
|
||||
try:
|
||||
raise paramiko.BadHostKeyException("10.0.0.8", SERVER_KEY, OTHER_KEY)
|
||||
except paramiko.SSHException as exc: # what netmiko does with it
|
||||
raise NetmikoTimeoutException(f"A paramiko SSHException occurred: {exc}") from exc
|
||||
|
||||
driver = _driver(seen, SshHostKey.of(OTHER_KEY))
|
||||
with patch("napalm_linux.linux.ConnectHandler", side_effect=refuse):
|
||||
with pytest.raises(SshHostKeyMismatch):
|
||||
driver.open()
|
||||
assert driver._device is None
|
||||
assert seen[0]["accepted"] is False
|
||||
|
||||
|
||||
def test_a_connection_sshd_turns_away_is_tried_again(monkeypatch):
|
||||
"""OpenSSH 9.8+ closes every connection from a source it has just penalised,
|
||||
before its banner; the penalty ends after seconds (NetOrk/netork#1800)."""
|
||||
from napalm_device_types import ssh_host_keys
|
||||
|
||||
slept: list[float] = []
|
||||
monkeypatch.setattr(ssh_host_keys.time, "sleep", slept.append)
|
||||
attempts: list[int] = []
|
||||
|
||||
def turned_away(**kwargs):
|
||||
attempts.append(1)
|
||||
if len(attempts) < 3:
|
||||
try:
|
||||
raise paramiko.SSHException("Error reading SSH protocol banner")
|
||||
except paramiko.SSHException as exc:
|
||||
raise NetmikoTimeoutException(f"A paramiko SSHException occurred: {exc}") from exc
|
||||
return _device()
|
||||
|
||||
driver = _driver([])
|
||||
with patch("napalm_linux.linux.ConnectHandler", side_effect=turned_away):
|
||||
driver.open()
|
||||
|
||||
assert driver._device is not None
|
||||
assert len(attempts) == 3
|
||||
assert slept == list(ssh_host_keys.REFUSED_RETRY_WAITS[:2])
|
||||
@@ -0,0 +1,255 @@
|
||||
"""Files root writes are staged in a fresh file, never at a fixed path in /tmp (NetOrk/netork#1039).
|
||||
|
||||
The snmpd and apt proxy fixes wrote their content to ``/tmp/netork_snmpd.conf``
|
||||
or ``/tmp/netork_00proxy`` as the login user, then ran ``mv … && chown root:root
|
||||
… && chmod 644 …``. Once the whole of a ``_sudo`` command ran as root, that was
|
||||
a local privilege escalation: another user creates the fixed path first as a
|
||||
symlink to ``/etc/shadow``, the login user's write fails (protected_symlinks),
|
||||
root moves the symlink into place, and root's ``chown``/``chmod`` follow it --
|
||||
``/etc/shadow`` mode 644.
|
||||
|
||||
Now the content goes to a ``mktemp`` file under ``umask 077``, unprivileged, and
|
||||
root ``install``s that file as a new regular file next to the target, then
|
||||
renames it over the target. Nothing root runs changes the owner or mode of a
|
||||
path that could be a symlink.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import re
|
||||
import shlex
|
||||
from types import SimpleNamespace
|
||||
from unittest.mock import MagicMock, patch
|
||||
|
||||
import pytest
|
||||
|
||||
from napalm_linux import LinuxDriver
|
||||
|
||||
_PW = "pw-1039"
|
||||
_STAGED = "/tmp/netork-stage.Ab12Cd"
|
||||
#: What another local user planted where the fixes used to stage their content.
|
||||
_PLANTED = {
|
||||
"/tmp/netork_snmpd.conf": "/etc/shadow",
|
||||
"/tmp/netork_00proxy": "/etc/shadow",
|
||||
}
|
||||
|
||||
|
||||
class Host:
|
||||
"""The host's exec channels: every line, its stdin, and whether it ran as root."""
|
||||
|
||||
def __init__(self, *, stage_output=_STAGED, stage_status=0):
|
||||
self.runs: list[SimpleNamespace] = []
|
||||
self._stage = (stage_output, stage_status)
|
||||
|
||||
def open_session(self):
|
||||
return _Channel(self)
|
||||
|
||||
def answer(self, command: str) -> tuple[str, int]:
|
||||
if "mktemp" in command:
|
||||
return self._stage
|
||||
return "", 0
|
||||
|
||||
@property
|
||||
def root_scripts(self) -> list[str]:
|
||||
return [run.script for run in self.runs if run.root]
|
||||
|
||||
@property
|
||||
def unprivileged(self) -> list[SimpleNamespace]:
|
||||
return [run for run in self.runs if not run.root]
|
||||
|
||||
|
||||
class _Channel:
|
||||
def __init__(self, host: Host):
|
||||
self._host = host
|
||||
self._run: SimpleNamespace | None = None
|
||||
self._out = b""
|
||||
|
||||
def exec_command(self, command):
|
||||
assert _PW not in command
|
||||
root = command.startswith(("sudo ", "sh -c "))
|
||||
script = shlex.split(command)[shlex.split(command).index("-c") + 1] if root else command
|
||||
self._run = SimpleNamespace(line=command, script=script, root=root, stdin=b"")
|
||||
self._host.runs.append(self._run)
|
||||
output, self._status = self._host.answer(command)
|
||||
self._out = output.encode()
|
||||
|
||||
def settimeout(self, timeout):
|
||||
pass
|
||||
|
||||
def sendall(self, data):
|
||||
self._run.stdin += data
|
||||
|
||||
def shutdown_write(self):
|
||||
pass
|
||||
|
||||
def close(self):
|
||||
pass
|
||||
|
||||
def recv_ready(self):
|
||||
return bool(self._out)
|
||||
|
||||
def recv(self, size):
|
||||
chunk, self._out = self._out[:size], self._out[size:]
|
||||
return chunk
|
||||
|
||||
def recv_stderr_ready(self):
|
||||
return False
|
||||
|
||||
def recv_stderr(self, size):
|
||||
return b""
|
||||
|
||||
def exit_status_ready(self):
|
||||
return not self._out
|
||||
|
||||
def recv_exit_status(self):
|
||||
return self._status
|
||||
|
||||
|
||||
def _shell(command: str, **_kwargs) -> str:
|
||||
"""The interactive shell, for what the fixes still ask it."""
|
||||
if command.startswith("command -v apt"):
|
||||
return "/usr/bin/apt"
|
||||
if command.startswith("cat /etc/snmp/snmpd.conf"):
|
||||
return "agentAddress udp:161\nrocommunity public\n"
|
||||
if command.startswith("cat /etc/apt/apt.conf.d/00proxy"):
|
||||
return 'Acquire::http::Proxy "http://proxy:3142";'
|
||||
if command.startswith("snmpget"):
|
||||
return "STRING: Linux"
|
||||
return ""
|
||||
|
||||
|
||||
def _driver(host: Host) -> LinuxDriver:
|
||||
driver = LinuxDriver(
|
||||
"h",
|
||||
"admin",
|
||||
"p",
|
||||
optional_args={"sudo_password": _PW},
|
||||
)
|
||||
driver._device = MagicMock()
|
||||
driver._device.send_command.side_effect = _shell
|
||||
driver._device.remote_conn_pre = SimpleNamespace(get_transport=lambda: host)
|
||||
driver._root = False
|
||||
driver._pkg_manager = "apt"
|
||||
return driver
|
||||
|
||||
|
||||
def _every_line(driver: LinuxDriver, host: Host) -> list[str]:
|
||||
typed = [c.args[0] for c in driver._device.send_command.call_args_list]
|
||||
return typed + [run.line for run in host.runs]
|
||||
|
||||
|
||||
_SETTINGS = {"community": "c0mm", "allowed_sources": []}
|
||||
|
||||
ACTIONS = [
|
||||
(
|
||||
lambda driver: driver.configure_snmp_agent(_SETTINGS),
|
||||
"/etc/snmp/snmpd.conf",
|
||||
b"agentAddress udp:161",
|
||||
),
|
||||
(
|
||||
lambda driver: driver.configure_package_proxy("http://proxy:3142"),
|
||||
"/etc/apt/apt.conf.d/00proxy",
|
||||
b'Acquire::http::Proxy "http://proxy:3142";',
|
||||
),
|
||||
]
|
||||
|
||||
|
||||
@pytest.fixture(autouse=True)
|
||||
def _no_waiting():
|
||||
with patch("time.sleep"):
|
||||
yield
|
||||
|
||||
|
||||
@pytest.mark.parametrize("action, target, content", ACTIONS)
|
||||
class TestStagedWrite:
|
||||
def test_the_old_fixed_path_is_never_touched(self, action, target, content):
|
||||
host = Host()
|
||||
driver = _driver(host)
|
||||
|
||||
action(driver)
|
||||
|
||||
for planted in _PLANTED:
|
||||
assert not any(planted in line for line in _every_line(driver, host))
|
||||
|
||||
def test_the_content_is_staged_unprivileged_in_a_fresh_private_file(
|
||||
self, action, target, content
|
||||
):
|
||||
host = Host()
|
||||
driver = _driver(host)
|
||||
|
||||
action(driver)
|
||||
|
||||
stage = next(run for run in host.unprivileged if "mktemp" in run.line)
|
||||
assert "umask 077" in stage.line
|
||||
assert "mktemp /tmp/netork-stage.XXXXXX" in stage.line
|
||||
assert content in stage.stdin
|
||||
|
||||
def test_root_installs_a_new_file_and_renames_it_over_the_target(self, action, target, content):
|
||||
host = Host()
|
||||
driver = _driver(host)
|
||||
|
||||
action(driver)
|
||||
|
||||
install = next(script for script in host.root_scripts if "install -m" in script)
|
||||
part = f"{target}.netork-tmp"
|
||||
assert f"install -m 644 -o root -g root -- {_STAGED} {part}" in install
|
||||
assert f"mv -f -- {part} {target}" in install
|
||||
assert f"rm -f -- {_STAGED} {part}" in install
|
||||
|
||||
def test_nothing_root_runs_changes_owner_or_mode_of_a_path(self, action, target, content):
|
||||
host = Host()
|
||||
driver = _driver(host)
|
||||
|
||||
action(driver)
|
||||
|
||||
assert not any(re.search(r"\bch(own|mod)\b", script) for script in host.root_scripts)
|
||||
|
||||
def test_nothing_runs_as_root_when_staging_failed(self, action, target, content):
|
||||
host = Host(stage_output="mktemp: No space left on device\n", stage_status=1)
|
||||
driver = _driver(host)
|
||||
|
||||
action(driver)
|
||||
|
||||
assert not any("install -m" in script for script in host.root_scripts)
|
||||
|
||||
def test_a_staged_path_it_did_not_ask_for_is_refused(self, action, target, content):
|
||||
host = Host(stage_output="/etc/shadow")
|
||||
driver = _driver(host)
|
||||
|
||||
action(driver)
|
||||
|
||||
assert not any("/etc/shadow" in script for script in host.root_scripts)
|
||||
|
||||
|
||||
def test_a_failed_install_is_reported():
|
||||
host = Host()
|
||||
host.answer = lambda command: ( # type: ignore[method-assign]
|
||||
(_STAGED, 0) if "mktemp" in command else ("install: cannot create\n", 1)
|
||||
)
|
||||
driver = _driver(host)
|
||||
driver._device.send_command.side_effect = lambda command, **_k: ""
|
||||
|
||||
result = driver.configure_package_proxy("http://proxy:3142")
|
||||
|
||||
assert result["success"] is False
|
||||
assert "install: cannot create" in result["output"]
|
||||
|
||||
|
||||
class TestWireGuardWithoutASudoPassword:
|
||||
"""It went through ``/tmp/.netork_wg_<hash>``: a name anyone can predict, and
|
||||
a file holding the interfaces' private keys."""
|
||||
|
||||
def test_no_temp_file_and_the_dump_comes_from_the_exec_channel(self):
|
||||
host = Host()
|
||||
dump = (
|
||||
"wg0\tPRIV\tPUB\t51820\toff\nwg0\tPEER\t(none)\t1.2.3.4:1\t10.0.0.2/32\t0\t1\t2\toff\n"
|
||||
)
|
||||
host.answer = lambda command: (dump, 0) # type: ignore[method-assign]
|
||||
driver = _driver(host)
|
||||
driver._sudo_password = None
|
||||
|
||||
tunnels = driver.get_vpn_tunnels()
|
||||
|
||||
assert list(tunnels) == ["wireguard-wg0-PEER"]
|
||||
assert not any("/tmp" in line for line in _every_line(driver, host))
|
||||
assert host.runs[0].line.startswith("sudo -n sh -c ")
|
||||
@@ -0,0 +1,140 @@
|
||||
"""What the old ``_sudo`` left on every host, and taking it back (NetOrk/netork#1090).
|
||||
|
||||
Until NetOrk/netork#1039, ``_sudo`` typed ``echo '<password>' | sudo -S -p ""
|
||||
<command>`` into netmiko's interactive shell: the login user's history kept the
|
||||
password once per command. Where only the part before the first ``&&`` ran as
|
||||
root, snmpd.conf and apt's proxy file were left to the login user. The driver
|
||||
says so through napalm-device-types' ``SudoHistoryMixin``, which counts and
|
||||
deletes the lines and gives the files back to root.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import shlex
|
||||
from types import SimpleNamespace
|
||||
from unittest.mock import MagicMock
|
||||
|
||||
from napalm_device_types import SudoHistoryMixin
|
||||
|
||||
from napalm_linux import LinuxDriver
|
||||
from napalm_linux.linux import _SNMPD_CONF
|
||||
|
||||
_PW = "s3cr3t"
|
||||
|
||||
|
||||
class _Channel:
|
||||
def __init__(self, transport: _Transport):
|
||||
self.transport = transport
|
||||
self.command = ""
|
||||
self.stdin = b""
|
||||
self._out = b""
|
||||
|
||||
def exec_command(self, command):
|
||||
self.command = command
|
||||
self.transport.commands.append(command)
|
||||
self._out = self.transport.answer(command).encode()
|
||||
|
||||
def settimeout(self, timeout):
|
||||
pass
|
||||
|
||||
def sendall(self, data):
|
||||
self.stdin += data
|
||||
|
||||
def shutdown_write(self):
|
||||
pass
|
||||
|
||||
def close(self):
|
||||
pass
|
||||
|
||||
def recv_ready(self):
|
||||
return bool(self._out)
|
||||
|
||||
def recv(self, size):
|
||||
chunk, self._out = self._out[:size], self._out[size:]
|
||||
return chunk
|
||||
|
||||
def recv_stderr_ready(self):
|
||||
return False
|
||||
|
||||
def recv_stderr(self, size):
|
||||
return b""
|
||||
|
||||
def exit_status_ready(self):
|
||||
return not self._out
|
||||
|
||||
def recv_exit_status(self):
|
||||
return 0
|
||||
|
||||
|
||||
class _Transport:
|
||||
def __init__(self, answers: dict[str, str]):
|
||||
self.answers = answers
|
||||
self.commands: list[str] = []
|
||||
self.channels: list[_Channel] = []
|
||||
|
||||
def answer(self, command: str) -> str:
|
||||
return next((out for key, out in self.answers.items() if key in command), "")
|
||||
|
||||
def open_session(self):
|
||||
self.channels.append(_Channel(self))
|
||||
return self.channels[-1]
|
||||
|
||||
|
||||
def _driver(answers: dict[str, str]) -> tuple[LinuxDriver, _Transport]:
|
||||
driver = LinuxDriver("h", "admin", "p", optional_args={"sudo_password": _PW})
|
||||
transport = _Transport(answers)
|
||||
driver._device = MagicMock()
|
||||
driver._device.remote_conn_pre = SimpleNamespace(get_transport=lambda: transport)
|
||||
driver._root = False
|
||||
return driver, transport
|
||||
|
||||
|
||||
def test_the_marker_is_what_the_old_sudo_typed():
|
||||
typed = f'echo {shlex.quote(_PW)} | sudo -S -p "" apt-get update'
|
||||
assert isinstance(LinuxDriver.SUDO_HISTORY_MARKER, str)
|
||||
assert LinuxDriver.SUDO_HISTORY_MARKER in typed
|
||||
|
||||
|
||||
def test_the_files_the_partial_sudo_left_to_the_login_user():
|
||||
assert LinuxDriver.SUDO_ROOT_FILES == (
|
||||
_SNMPD_CONF,
|
||||
LinuxDriver.APT_PROXY_FILE,
|
||||
)
|
||||
assert LinuxDriver.APT_PROXY_FILE == "/etc/apt/apt.conf.d/00proxy"
|
||||
|
||||
|
||||
def test_it_is_the_device_types_mixin():
|
||||
assert issubclass(LinuxDriver, SudoHistoryMixin)
|
||||
|
||||
|
||||
def test_counting_runs_as_the_login_user_on_the_exec_channel():
|
||||
driver, transport = _driver({"grep -c": "121 .bash_history\n0 .zsh_history\n"})
|
||||
|
||||
assert driver.get_history_sudo_lines() == [{"file": "~/.bash_history", "lines": 121}]
|
||||
|
||||
# No sudo, no password on stdin, nothing typed into the interactive shell
|
||||
# (whose history is where the lines came from).
|
||||
assert not transport.channels[-1].command.startswith("sudo")
|
||||
assert transport.channels[-1].stdin == b""
|
||||
driver._device.send_command.assert_not_called()
|
||||
|
||||
|
||||
def test_the_owner_fix_runs_as_root_without_stdin_but_the_password():
|
||||
driver, transport = _driver(
|
||||
{
|
||||
"sed -i": "done 3 0 .bash_history\n",
|
||||
"id -u": "1000\nadmin\n",
|
||||
"chown": "fixed /etc/snmp/snmpd.conf\n",
|
||||
}
|
||||
)
|
||||
|
||||
result = driver.remove_history_sudo_lines()
|
||||
|
||||
assert result["success"] is True
|
||||
assert result["removed"] == 3
|
||||
assert result["owners_restored"] == ["/etc/snmp/snmpd.conf"]
|
||||
root = [c for c in transport.channels if c.command.startswith("sudo -S")]
|
||||
assert len(root) == 1 and "chown -h 0:0" in root[0].command
|
||||
# sudo -S reads the password, and the command itself reads nothing.
|
||||
assert root[0].stdin == f"{_PW}\n".encode()
|
||||
assert all(c.stdin == b"" for c in transport.channels if c is not root[0])
|
||||
@@ -0,0 +1,262 @@
|
||||
"""The sudo password never goes into a command line or a shell history (NetOrk/netork#1039).
|
||||
|
||||
``_sudo`` typed ``echo '<password>' | sudo -S -p "" <command>`` into netmiko's
|
||||
interactive shell. That shell keeps a history, so every poll appended the
|
||||
password to the login user's ``~/.bash_history`` -- 121 lines of it on one host
|
||||
-- and while the command ran it was in the process list for every local user.
|
||||
|
||||
Privileged commands now run on an exec channel next to netmiko's PTY, the way
|
||||
``run_command(privileged=True)`` does: the password reaches ``sudo -S`` on
|
||||
stdin, and an exec channel has no history and no PTY to echo it back. The
|
||||
interactive session switches its history off before anything else, in case
|
||||
anything ever slips through again.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import shlex
|
||||
from types import SimpleNamespace
|
||||
from unittest.mock import MagicMock, patch
|
||||
|
||||
import pytest
|
||||
|
||||
from napalm_linux import LinuxDriver
|
||||
from napalm_linux._shell import HISTORY_OFF as _HISTORY_OFF
|
||||
|
||||
_PW = "s3cr3t 'q' $x"
|
||||
|
||||
|
||||
class Channel:
|
||||
"""An exec channel answering with *output* and *status*; it refuses a line
|
||||
that holds the password, which is what ``ps`` would show."""
|
||||
|
||||
def __init__(self, host: Transport):
|
||||
self.host = host
|
||||
self.command = ""
|
||||
self.stdin = b""
|
||||
self.timeout = None
|
||||
self._out = b""
|
||||
|
||||
def exec_command(self, command):
|
||||
assert _PW not in command, f"sudo password in a command line: {command!r}"
|
||||
self.command = command
|
||||
output, status = self.host.answer
|
||||
self._out = output.encode()
|
||||
self.status = status
|
||||
|
||||
def settimeout(self, timeout):
|
||||
self.timeout = timeout
|
||||
|
||||
def sendall(self, data):
|
||||
self.stdin += data
|
||||
|
||||
def shutdown_write(self):
|
||||
pass
|
||||
|
||||
def close(self):
|
||||
pass
|
||||
|
||||
def recv_ready(self):
|
||||
return bool(self._out)
|
||||
|
||||
def recv(self, size):
|
||||
chunk, self._out = self._out[:size], self._out[size:]
|
||||
return chunk
|
||||
|
||||
def recv_stderr_ready(self):
|
||||
return False
|
||||
|
||||
def recv_stderr(self, size):
|
||||
return b""
|
||||
|
||||
def exit_status_ready(self):
|
||||
return not self._out
|
||||
|
||||
def recv_exit_status(self):
|
||||
return self.status
|
||||
|
||||
|
||||
class Transport:
|
||||
def __init__(self, output="", status=0):
|
||||
self.answer = (output, status)
|
||||
self.channels: list[Channel] = []
|
||||
|
||||
def open_session(self):
|
||||
self.channels.append(Channel(self))
|
||||
return self.channels[-1]
|
||||
|
||||
|
||||
def _driver(*, sudo_password=_PW, root=False, output="", status=0):
|
||||
driver = LinuxDriver("h", "admin", "p", optional_args={"sudo_password": sudo_password})
|
||||
transport = Transport(output, status)
|
||||
driver._device = MagicMock()
|
||||
driver._device.remote_conn_pre = SimpleNamespace(get_transport=lambda: transport)
|
||||
driver._root = root
|
||||
return driver, transport
|
||||
|
||||
|
||||
def _script(command_line: str) -> str:
|
||||
"""What ``sh -c`` runs in *command_line*, unquoted."""
|
||||
parts = shlex.split(command_line)
|
||||
return parts[parts.index("-c") + 1]
|
||||
|
||||
|
||||
class TestSudo:
|
||||
def test_the_password_goes_to_sudo_on_stdin(self):
|
||||
driver, transport = _driver(output="ok\n")
|
||||
|
||||
assert driver._sudo("apt-get update 2>&1") == "ok"
|
||||
|
||||
channel = transport.channels[-1]
|
||||
assert channel.command.startswith("sudo -S -p '' sh -c ")
|
||||
assert channel.stdin == f"{_PW}\n".encode()
|
||||
|
||||
def test_nothing_goes_through_the_interactive_shell(self):
|
||||
"""Its history is where the password ended up."""
|
||||
driver, _ = _driver()
|
||||
|
||||
driver._sudo("apt-get update")
|
||||
|
||||
driver._device.send_command.assert_not_called()
|
||||
|
||||
def test_the_whole_command_runs_as_root(self):
|
||||
"""``echo pw | sudo -S mv a b && chown …`` ran only ``mv`` as root."""
|
||||
driver, transport = _driver()
|
||||
|
||||
driver._sudo("mv /tmp/x /etc/x && chown root:root /etc/x")
|
||||
|
||||
assert _script(transport.channels[-1].command).endswith(
|
||||
"mv /tmp/x /etc/x && chown root:root /etc/x"
|
||||
)
|
||||
|
||||
def test_a_sudo_that_does_not_prompt_leaves_the_password_to_nobody(self):
|
||||
"""NOPASSWD or a cached timestamp leave the password on stdin; the
|
||||
command's stdin is /dev/null, so nothing it runs reads it."""
|
||||
driver, transport = _driver()
|
||||
|
||||
driver._sudo("dpkg --configure -a")
|
||||
|
||||
assert _script(transport.channels[-1].command).startswith("exec </dev/null; ")
|
||||
|
||||
def test_sudos_own_complaints_are_in_the_output(self):
|
||||
"""``sudo: a password is required`` goes to stderr; callers read it from the output."""
|
||||
driver, transport = _driver()
|
||||
|
||||
driver._sudo("true")
|
||||
|
||||
assert transport.channels[-1].command.endswith(" 2>&1")
|
||||
|
||||
def test_without_a_password_sudo_never_waits_for_one(self):
|
||||
driver, transport = _driver(sudo_password=None)
|
||||
|
||||
driver._sudo("apt-get update")
|
||||
|
||||
assert transport.channels[-1].command.startswith("sudo -n sh -c ")
|
||||
assert transport.channels[-1].stdin == b""
|
||||
|
||||
def test_a_root_login_needs_no_sudo(self):
|
||||
driver, transport = _driver(root=True)
|
||||
|
||||
driver._sudo("apt-get update")
|
||||
|
||||
assert transport.channels[-1].command.startswith("sh -c ")
|
||||
assert transport.channels[-1].stdin == b""
|
||||
|
||||
def test_the_read_timeout_is_the_channels(self):
|
||||
driver, transport = _driver()
|
||||
|
||||
driver._sudo("apt-get upgrade -y", read_timeout=600)
|
||||
|
||||
assert transport.channels[-1].timeout == 600
|
||||
|
||||
|
||||
class TestSudoStatus:
|
||||
def test_the_exit_status_is_the_commands_own(self):
|
||||
driver, _ = _driver(output="E: Unable to locate package nope\n", status=100)
|
||||
|
||||
assert driver._sudo_status("apt-get remove -y nope 2>&1") == (
|
||||
"E: Unable to locate package nope",
|
||||
100,
|
||||
)
|
||||
|
||||
def test_a_refused_sudo_is_a_failure(self):
|
||||
driver, _ = _driver(output="Sorry, try again.\n", status=1)
|
||||
|
||||
assert driver._sudo_status("apt-get remove -y x")[1] == 1
|
||||
|
||||
|
||||
class TestRunPrivileged:
|
||||
def test_with_a_password_it_takes_the_exec_channel(self):
|
||||
driver, transport = _driver(output="__NETORK_RC=0\n")
|
||||
|
||||
driver._run_privileged("apt-get update -q 2>&1; echo __NETORK_RC=$?", 180)
|
||||
|
||||
driver._device.send_command.assert_not_called()
|
||||
assert transport.channels[-1].stdin == f"{_PW}\n".encode()
|
||||
|
||||
def test_a_refresh_reads_its_status_from_the_exec_channel(self):
|
||||
driver, _ = _driver(output="Hit:1 http://deb.debian.org\n__NETORK_RC=0\n")
|
||||
driver._pkg_manager = "apt"
|
||||
|
||||
assert driver.refresh_available_updates()["success"] is True
|
||||
|
||||
|
||||
class TestWireGuardWithSudo:
|
||||
def test_the_dump_comes_straight_from_the_exec_channel(self):
|
||||
"""No PTY to turn its tabs into spaces, so no file in /tmp holding the
|
||||
interfaces' private keys."""
|
||||
dump = "wg0\tPRIV\tPUB\t51820\toff\nwg0\tPEER\t(none)\t1.2.3.4:51820\t10.0.0.2/32\t0\t1\t2\toff\n"
|
||||
driver, transport = _driver(output=dump)
|
||||
|
||||
tunnels = driver.get_vpn_tunnels()
|
||||
|
||||
assert list(tunnels) == ["wireguard-wg0-PEER"]
|
||||
assert "/tmp" not in transport.channels[-1].command
|
||||
driver._device.send_command.assert_not_called()
|
||||
|
||||
|
||||
class TestHistoryOff:
|
||||
"""Defense in depth: the interactive session keeps no history at all."""
|
||||
|
||||
def test_it_is_the_first_thing_the_session_sends(self):
|
||||
driver = LinuxDriver("h", "admin", "p", optional_args={"sudo_password": _PW})
|
||||
device = MagicMock()
|
||||
device.send_command.return_value = "/usr/bin/apt"
|
||||
with patch("napalm_linux.linux.ConnectHandler", return_value=device):
|
||||
driver.open()
|
||||
|
||||
first = device.send_command.call_args_list[0].args[0]
|
||||
assert first == _HISTORY_OFF
|
||||
|
||||
def test_it_leaves_no_history_file_and_records_nothing_more(self):
|
||||
assert _HISTORY_OFF.startswith(" ") # HISTCONTROL=ignorespace skips the line itself
|
||||
assert "unset HISTFILE" in _HISTORY_OFF
|
||||
assert "set +o history" in _HISTORY_OFF
|
||||
|
||||
def test_a_shell_that_refuses_it_does_not_stop_the_connection(self):
|
||||
driver = LinuxDriver("h", "admin", "p")
|
||||
device = MagicMock()
|
||||
# history off (refused), prompt hooks off (#41), stty, package manager
|
||||
device.send_command.side_effect = [Exception("no prompt"), "", "", "/usr/bin/apt"]
|
||||
with patch("napalm_linux.linux.ConnectHandler", return_value=device):
|
||||
driver.open()
|
||||
|
||||
assert driver._device is device
|
||||
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
"method, args",
|
||||
[
|
||||
("install_package", ("curl",)),
|
||||
("uninstall_package", ("curl",)),
|
||||
("apply_updates", ([],)),
|
||||
],
|
||||
)
|
||||
def test_package_work_never_types_the_password(method, args):
|
||||
driver, transport = _driver(output="done\n")
|
||||
driver._pkg_manager = "apt"
|
||||
|
||||
getattr(driver, method)(*args)
|
||||
|
||||
driver._device.send_command.assert_not_called()
|
||||
assert transport.channels and all(c.stdin == f"{_PW}\n".encode() for c in transport.channels)
|
||||
@@ -0,0 +1,199 @@
|
||||
"""Without a sudo password the whole command runs as root, in one ``sh -c`` (#56).
|
||||
|
||||
A login that is not root and has no sudo password (NOPASSWD sudo, e.g. netOrk's
|
||||
own account from NetOrk/netork#1817) types its privileged commands into the
|
||||
interactive shell. ``sudo -n <command>`` covered only the first simple command of
|
||||
the line, and a command that starts with a brace group did not even parse:
|
||||
``sudo -n { LC_ALL=C dnf …; echo __DNF_RC=$?; } | cat`` is a syntax error, so dnf's
|
||||
and yum's security advisories were always unknown.
|
||||
|
||||
The command now goes to ``sudo -n sh -c`` as one argument, as ``_as_root`` does.
|
||||
A status echo at its end (``; echo __NETORK_RC=$?``) stays outside: it reports
|
||||
sh's status, which is the command's, and still arrives when sudo refuses.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import re
|
||||
import shutil
|
||||
import subprocess
|
||||
from pathlib import Path
|
||||
from shlex import quote
|
||||
from unittest.mock import MagicMock
|
||||
|
||||
import pytest
|
||||
from napalm_device_types import DNF_SECURITY_COMMAND
|
||||
|
||||
from napalm_linux import LinuxDriver
|
||||
from napalm_linux.linux import _YUM_SECURITY_COMMAND
|
||||
|
||||
BASH = shutil.which("bash")
|
||||
needs_bash = pytest.mark.skipif(BASH is None, reason="needs bash")
|
||||
|
||||
#: dnf's answer on a Fedora 40 host with one pending security advisory.
|
||||
_ADVISORY = "FEDORA-2024-1a2b3c4d5e Important/Sec. openssl-libs-1:3.1.4-2.fc40.x86_64"
|
||||
|
||||
|
||||
def _driver(pkg_manager: str = "dnf", answers: list[str] | None = None) -> LinuxDriver:
|
||||
"""A driver logged in as a user that is not root, without a sudo password."""
|
||||
d = LinuxDriver.__new__(LinuxDriver)
|
||||
d.hostname = "testhost"
|
||||
d._sudo_password = None
|
||||
d._pkg_manager = pkg_manager
|
||||
d._root = False
|
||||
d._device = MagicMock()
|
||||
d._device.send_command.side_effect = answers or []
|
||||
return d
|
||||
|
||||
|
||||
def _sent(driver: LinuxDriver) -> list[str]:
|
||||
return [c[0][0] for c in driver._device.send_command.call_args_list]
|
||||
|
||||
|
||||
def _bash_parses(line: str) -> str:
|
||||
"""bash's complaint about *line*, empty when it parses."""
|
||||
assert BASH is not None
|
||||
checked = subprocess.run( # noqa: S603 - a fixed interpreter, the line only parsed
|
||||
[BASH, "-n", "-c", line], capture_output=True, text=True, check=False
|
||||
)
|
||||
return checked.stderr
|
||||
|
||||
|
||||
class TestTheSecurityAdvisories:
|
||||
@needs_bash
|
||||
@pytest.mark.parametrize("manager", ["dnf", "yum"])
|
||||
def test_the_line_parses(self, manager):
|
||||
driver = _driver(manager, [f"{_ADVISORY}\n__DNF_RC=0\n__NETORK_RC=0"])
|
||||
|
||||
driver._rpm_security_names()
|
||||
|
||||
assert _bash_parses(_sent(driver)[0]) == ""
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
("manager", "command"), [("dnf", DNF_SECURITY_COMMAND), ("yum", _YUM_SECURITY_COMMAND)]
|
||||
)
|
||||
def test_all_of_it_runs_as_root_and_the_status_stays_outside(self, manager, command):
|
||||
driver = _driver(manager, [f"{_ADVISORY}\n__DNF_RC=0\n__NETORK_RC=0"])
|
||||
|
||||
driver._rpm_security_names()
|
||||
|
||||
assert _sent(driver) == [f"sudo -n sh -c {quote(command)}; echo __NETORK_RC=$?"]
|
||||
|
||||
def test_the_advisories_are_read(self):
|
||||
driver = _driver("dnf", [f"{_ADVISORY}\n__DNF_RC=0\n__NETORK_RC=0"])
|
||||
|
||||
assert driver._rpm_security_names() == {"openssl-libs"}
|
||||
|
||||
|
||||
#: Every caller of ``_run_privileged``, with an answer that satisfies it.
|
||||
_CALLERS = {
|
||||
"reboot_host": (lambda d: d.reboot_host(), ["__NETORK_RC=0"]),
|
||||
"refresh apt": (lambda d: d.refresh_available_updates(), ["__NETORK_RC=0"]),
|
||||
"check-update": (
|
||||
lambda d: d.get_available_updates(),
|
||||
["__NETORK_RC=0", "__DNF_RC=0\n__NETORK_RC=0"],
|
||||
),
|
||||
"manage_service": (lambda d: d.manage_service("wg-quick@wg0", "restart"), ["__SVC_RC=0"]),
|
||||
"listening sockets": (
|
||||
lambda d: d._run_listening_sockets_command("sh -c 'ss -H -ltn'", privileged=True),
|
||||
[""],
|
||||
),
|
||||
}
|
||||
|
||||
|
||||
@needs_bash
|
||||
@pytest.mark.parametrize("caller", sorted(_CALLERS))
|
||||
def test_every_privileged_line_parses_and_runs_whole_as_root(caller):
|
||||
call, answers = _CALLERS[caller]
|
||||
driver = _driver("apt" if caller == "refresh apt" else "dnf", answers)
|
||||
|
||||
call(driver)
|
||||
|
||||
for line in _sent(driver):
|
||||
assert line.startswith("sudo -n sh -c '")
|
||||
assert _bash_parses(line) == ""
|
||||
|
||||
|
||||
def test_the_service_status_stays_outside():
|
||||
driver = _driver(answers=["__SVC_RC=0"])
|
||||
|
||||
driver.manage_service("cron", "restart")
|
||||
|
||||
assert _sent(driver) == [
|
||||
"sudo -n sh -c 'timeout 45 systemctl --no-ask-password restart -- cron.service 2>&1';"
|
||||
" echo __SVC_RC=$?"
|
||||
]
|
||||
|
||||
|
||||
def test_a_command_without_a_status_echo_is_wrapped_whole():
|
||||
driver = _driver(answers=[""])
|
||||
|
||||
driver._run_privileged("ss -H -ltnp | sort")
|
||||
|
||||
assert _sent(driver) == ["sudo -n sh -c 'ss -H -ltnp | sort'"]
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# The lines run in a real bash, with a stand-in sudo and package manager
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
_SUDO_OK = '#!/bin/sh\n[ "$1" = -n ] && shift\nexec "$@"\n'
|
||||
_SUDO_REFUSES = "#!/bin/sh\necho 'sudo: a password is required' >&2\nexit 1\n"
|
||||
_DNF = f"#!/bin/sh\necho '{_ADVISORY}'\n"
|
||||
|
||||
|
||||
def _shell_host(tmp_path: Path, sudo: str) -> LinuxDriver:
|
||||
"""A driver whose interactive shell is a real bash with stand-ins on its PATH.
|
||||
|
||||
Like netmiko, it reads until the command's expect pattern matches and fails
|
||||
when it never does.
|
||||
"""
|
||||
for name, script in (("sudo", sudo), ("dnf", _DNF)):
|
||||
stub = tmp_path / name
|
||||
stub.write_text(script)
|
||||
stub.chmod(0o755)
|
||||
env = {"PATH": f"{tmp_path}:/usr/bin:/bin", "LC_ALL": "C"}
|
||||
|
||||
def send_command(command, *, expect_string, **_kwargs):
|
||||
assert BASH is not None
|
||||
ran = subprocess.run( # noqa: S603 - a fixed interpreter and stand-ins
|
||||
[BASH, "-c", command],
|
||||
stdout=subprocess.PIPE,
|
||||
stderr=subprocess.STDOUT, # one stream, in order, as on the PTY
|
||||
text=True,
|
||||
env=env,
|
||||
check=False,
|
||||
)
|
||||
output = f"{ran.stdout}user@host:~$ "
|
||||
if not re.search(expect_string, output):
|
||||
raise TimeoutError(f"pattern not detected: {expect_string!r} in {output!r}")
|
||||
return output
|
||||
|
||||
driver = _driver("dnf")
|
||||
driver._device.send_command.side_effect = send_command
|
||||
return driver
|
||||
|
||||
|
||||
@needs_bash
|
||||
def test_a_real_shell_reads_the_advisories(tmp_path):
|
||||
driver = _shell_host(tmp_path, _SUDO_OK)
|
||||
|
||||
assert driver._rpm_security_names() == {"openssl-libs"}
|
||||
|
||||
|
||||
@needs_bash
|
||||
def test_a_refused_sudo_still_reports_its_status(tmp_path):
|
||||
driver = _shell_host(tmp_path, _SUDO_REFUSES)
|
||||
|
||||
result = driver.refresh_available_updates()
|
||||
|
||||
assert result["success"] is False
|
||||
assert "a password is required" in result["output"]
|
||||
assert "NOPASSWD" in result["output"] # the hint
|
||||
|
||||
|
||||
@needs_bash
|
||||
def test_a_refused_sudo_leaves_the_advisories_unknown(tmp_path):
|
||||
driver = _shell_host(tmp_path, _SUDO_REFUSES)
|
||||
|
||||
assert driver._rpm_security_names() is None
|
||||
@@ -0,0 +1,79 @@
|
||||
"""systemd's shell context sequences stay out of every command's output (#41).
|
||||
|
||||
systemd 258 (Ubuntu 26.04) ships ``/etc/profile.d/80-systemd-osc-context.sh``.
|
||||
An interactive bash then wraps every command in OSC 3008 sequences, from ``PS0``
|
||||
before it runs and from ``PROMPT_COMMAND`` before the next prompt, each with a
|
||||
fresh UUID. netmiko's interactive shell is such a bash: the sequences ended up in
|
||||
every parsed value, and since the prompt never looked the same twice, netmiko
|
||||
left the prompt line in the output as well. ``os_version`` grew past 255
|
||||
characters and netOrk could not store the poll.
|
||||
"""
|
||||
|
||||
from unittest.mock import MagicMock, patch
|
||||
|
||||
from napalm_linux._shell import HISTORY_OFF, PROMPT_HOOKS_OFF
|
||||
from napalm_linux.linux import LinuxDriver
|
||||
|
||||
#: What ``cat /etc/os-release | grep PRETTY_NAME ...`` returned through netmiko on
|
||||
#: an Ubuntu 26.04.1 host (2026-10-23), the prompt line already gone.
|
||||
_UBUNTU_2604_OS_RELEASE = (
|
||||
"\x1b]3008;end=87c2e1c5-f850-4429-9f06-749e9be783e6;exit=success\x1b\\"
|
||||
"\x1b]3008;start=bc3bc23b-2652-4826-8192-be447f97dd6f;type=command;"
|
||||
"machineid=35cf42f3beb446bbb9aa95b937a0cf48;user=netork;hostname=ubuntu;"
|
||||
"bootid=d32bd88c-dfce-40fe-9869-257bf50ef0e0;pid=20059;cwd=/home/netork\x1b\\"
|
||||
"Ubuntu 26.04.1 LTS\n"
|
||||
)
|
||||
|
||||
|
||||
def _opened(device: MagicMock) -> LinuxDriver:
|
||||
driver = LinuxDriver("h", "admin", "p")
|
||||
with patch("napalm_linux.linux.ConnectHandler", return_value=device):
|
||||
driver.open()
|
||||
return driver
|
||||
|
||||
|
||||
class TestPromptHooksOff:
|
||||
def test_the_session_drops_the_hooks_right_after_the_history(self):
|
||||
device = MagicMock()
|
||||
device.send_command.return_value = "/usr/bin/apt"
|
||||
|
||||
_opened(device)
|
||||
|
||||
sent = [c.args[0] for c in device.send_command.call_args_list]
|
||||
assert sent[:2] == [HISTORY_OFF, PROMPT_HOOKS_OFF]
|
||||
|
||||
def test_it_unsets_both_hooks_including_an_array_prompt_command(self):
|
||||
# The script appends to PROMPT_COMMAND as an array; assigning the empty
|
||||
# string would only clear element 0 and leave systemd's hook running.
|
||||
assert PROMPT_HOOKS_OFF.startswith(" ")
|
||||
assert "unset PS0 PROMPT_COMMAND" in PROMPT_HOOKS_OFF
|
||||
|
||||
def test_the_prompt_is_read_again_once_the_hooks_are_gone(self):
|
||||
# netmiko learned the prompt with the sequences in front of it; a prompt
|
||||
# carrying a UUID never matches again, so strip_prompt would keep failing.
|
||||
device = MagicMock()
|
||||
device.send_command.return_value = "/usr/bin/apt"
|
||||
|
||||
_opened(device)
|
||||
|
||||
calls = [(c[0], c.args[0] if c.args else None) for c in device.mock_calls]
|
||||
hooks_off = calls.index(("send_command", PROMPT_HOOKS_OFF))
|
||||
assert "set_base_prompt" in [name for name, _ in calls[hooks_off + 1 :]]
|
||||
|
||||
def test_a_shell_that_refuses_it_does_not_stop_the_connection(self):
|
||||
device = MagicMock()
|
||||
device.send_command.side_effect = ["", Exception("no prompt"), "", "/usr/bin/apt"]
|
||||
|
||||
driver = _opened(device)
|
||||
|
||||
assert driver._device is device
|
||||
|
||||
|
||||
class TestSendStripsTerminalCodes:
|
||||
def test_os_version_comes_back_without_the_context_sequences(self):
|
||||
device = MagicMock()
|
||||
device.send_command.return_value = _UBUNTU_2604_OS_RELEASE
|
||||
driver = LinuxDriver("h", "admin", "p")
|
||||
driver._device = device
|
||||
|
||||
assert driver._send("cat /etc/os-release") == "Ubuntu 26.04.1 LTS"
|
||||
@@ -0,0 +1,104 @@
|
||||
"""Time sync on a Linux host: napalm-device-types' POSIX implementation (NetOrk/netork#2361).
|
||||
|
||||
The reading, its parse and every write are ``PosixTimeSyncMixin``'s; the driver
|
||||
carries the commands across ``run_command`` -- the reading as the login user in one
|
||||
round trip, the writes as root, and root never reads stdin.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from napalm_device_types import CommandResult, PosixTimeSyncMixin, TimeSyncMixin
|
||||
|
||||
from napalm_linux import LinuxDriver
|
||||
|
||||
#: Debian 12 with chrony: the reading as PosixTimeSyncMixin's command prints it.
|
||||
READING = """\
|
||||
@@ts timedatectl
|
||||
Timezone=Europe/Berlin
|
||||
NTP=yes
|
||||
NTPSynchronized=yes
|
||||
@@ts zone
|
||||
Europe/Berlin
|
||||
@@ts active
|
||||
chrony chrony active
|
||||
chronyd chrony active
|
||||
systemd-timesyncd systemd-timesyncd inactive
|
||||
@@ts timesync
|
||||
@@ts chronyc
|
||||
MS Name/IP address Stratum Poll Reach LastRx Last sample
|
||||
===============================================================================
|
||||
^* 192.168.1.1 2 6 377 40 -45us[ -63us] +/- 10ms
|
||||
@@ts chrony 0 main /etc/chrony/chrony.conf
|
||||
pool 2.debian.pool.ntp.org iburst
|
||||
sourcedir /etc/chrony/sources.d
|
||||
|
||||
@@ts end
|
||||
"""
|
||||
|
||||
|
||||
class _Channel:
|
||||
"""Records every command; answers the reading, and a staged file's path."""
|
||||
|
||||
def __init__(self) -> None:
|
||||
self.calls: list[tuple[str, bool, bytes | None]] = []
|
||||
|
||||
def __call__(self, command, *, privileged=False, timeout=60, stdin=None): # type: ignore[no-untyped-def]
|
||||
self.calls.append((command, privileged, stdin))
|
||||
if "@@ts" in command:
|
||||
return CommandResult(READING, "", 0)
|
||||
if "mktemp" in command:
|
||||
return CommandResult("/tmp/tmp.abc123", "", 0)
|
||||
return CommandResult("", "", 0)
|
||||
|
||||
|
||||
def _driver() -> tuple[LinuxDriver, _Channel]:
|
||||
driver = LinuxDriver("host", "user", "pw", optional_args={"sudo_password": "pw"})
|
||||
channel = _Channel()
|
||||
driver.run_command = channel # type: ignore[method-assign]
|
||||
return driver, channel
|
||||
|
||||
|
||||
def test_a_linux_host_keeps_its_clock_through_the_posix_mixin():
|
||||
assert issubclass(LinuxDriver, PosixTimeSyncMixin)
|
||||
assert issubclass(LinuxDriver, TimeSyncMixin)
|
||||
assert callable(getattr(LinuxDriver, "get_time_sync", None))
|
||||
assert callable(getattr(LinuxDriver, "configure_time_sync", None))
|
||||
assert LinuxDriver.time_sync_writes == frozenset({"ntp_servers", "timezone"})
|
||||
|
||||
|
||||
def test_the_reading_is_one_round_trip_as_the_login_user():
|
||||
driver, channel = _driver()
|
||||
|
||||
assert driver.get_time_sync() == {
|
||||
"ntp_servers": ["2.debian.pool.ntp.org"],
|
||||
"timezone": "Europe/Berlin",
|
||||
"synchronized": True,
|
||||
"daemon": "chrony",
|
||||
# napalm-device-types 4.36.0: the servers it got by DHCP, none here (#75).
|
||||
"dhcp_ntp_servers": [],
|
||||
}
|
||||
assert [privileged for _, privileged, _ in channel.calls] == [False]
|
||||
|
||||
|
||||
def test_the_zone_is_set_as_root():
|
||||
driver, channel = _driver()
|
||||
result = driver.configure_time_sync(timezone="Europe/Berlin")
|
||||
|
||||
assert result["success"] is True, result["output"]
|
||||
assert ("timedatectl set-timezone Europe/Berlin", True, None) in channel.calls
|
||||
|
||||
|
||||
def test_root_never_reads_stdin():
|
||||
# With a sudo password, sudo -S reads it from stdin: a privileged command given
|
||||
# stdin as well would hand the password on (LinuxDriver refuses it).
|
||||
driver, channel = _driver()
|
||||
result = driver.configure_time_sync(["ntp1.example.org"], "UTC")
|
||||
|
||||
assert result["steps"][0]["step"] == "ntp_servers"
|
||||
assert result["steps"][0]["ok"] is True, result["output"]
|
||||
assert any(stdin for _, privileged, stdin in channel.calls if not privileged)
|
||||
assert all(stdin is None for _, privileged, stdin in channel.calls if privileged)
|
||||
installed = [c for c, privileged, _ in channel.calls if privileged and c.startswith("install")]
|
||||
assert installed == [
|
||||
"install -D -m 644 -- /tmp/tmp.abc123 /etc/chrony/sources.d/netork.sources"
|
||||
]
|
||||
Reference in new issue
Block a user