Compare commits

..
16 Commits
Author SHA1 Message Date
christianmanivong 07920941c8 Merge pull request 'feat(access-point): a radio's runtime state beside its configuration, 4.49.0 (NetOrk/netork#31)' (#137) from feature/radio-runtime-state into main
driver / standard (push) Successful in 16s
driver / lint (push) Successful in 14s
driver / types (push) Successful in 1m0s
driver / test (3.12) (push) Successful in 1m15s
driver / test (3.13) (push) Successful in 1m11s
driver / lowest (push) Successful in 42s
driver / build (push) Successful in 32s
driver / security (push) Successful in 1m15s
driver / publish (push) Successful in 29s
CI / driver (push) Successful in 4m29s
2026-11-28 02:07:50 +00:00
christianmanivong 92b1b6402b chore(release): 4.49.0
driver / lint (pull_request) Successful in 15s
driver / standard (pull_request) Successful in 18s
driver / types (pull_request) Successful in 1m2s
driver / lowest (pull_request) Successful in 51s
driver / test (3.12) (pull_request) Successful in 1m39s
driver / test (3.13) (pull_request) Successful in 1m36s
driver / build (pull_request) Successful in 38s
driver / security (pull_request) Successful in 1m11s
CI / driver (pull_request) Successful in 3m5s
driver / publish (pull_request) Skipped
2026-11-28 03:02:13 +01:00
christianmanivong e4fde2283a feat(access-point): a radio's runtime state beside its configuration (NetOrk/netork#31)
RadioStatusDict carries up, pending and setup_failed, each optional: a
driver that cannot read the state leaves them out. A radio can be enabled
and not run, as on 2026-07-16, when a rejected value kept every radio of
a fleet in a restart loop the configuration never showed.

The access point shapes move to access_point_models.py for the file size
ratchet; models re-exports each where it was.
2026-11-28 03:02:13 +01:00
christianmanivong 419d3ee0e0 Merge pull request 'feat(hardening): how a Linux host is hardened, as one read-only reading, 4.48.0 (NetOrk/netork#2706)' (#136) from feature/hardening-reading into main
driver / types (push) Successful in 52s
driver / standard (push) Successful in 15s
driver / lint (push) Successful in 14s
driver / test (3.12) (push) Successful in 1m10s
driver / test (3.13) (push) Successful in 1m2s
driver / lowest (push) Successful in 35s
driver / build (push) Successful in 25s
driver / security (push) Successful in 53s
driver / publish (push) Successful in 25s
CI / driver (push) Successful in 2m58s
2026-11-28 01:44:02 +00:00
christianmanivong c93ceeb320 Merge NAPALM/napalm-device-types main (4.47.0) into feature/hardening-reading
driver / standard (pull_request) Successful in 30s
driver / lint (pull_request) Successful in 59s
driver / types (pull_request) Successful in 2m12s
driver / test (3.12) (pull_request) Successful in 2m16s
driver / lowest (pull_request) Successful in 39s
driver / test (3.13) (pull_request) Successful in 1m26s
driver / build (pull_request) Successful in 39s
driver / security (pull_request) Successful in 1m18s
CI / driver (pull_request) Successful in 5m3s
driver / publish (pull_request) Skipped
4.47.0 (#135) is released; this branch stays 4.48.0, its changelog section
above 4.47.0's.
2026-11-27 05:52:44 +01:00
christianmanivong d77a8982a8 Merge pull request 'chore(release): 4.47.0' (#135) from feature/update-history-2728 into main
driver / types (push) Successful in 1m0s
driver / standard (push) Successful in 19s
driver / lint (push) Successful in 16s
driver / test (3.12) (push) Successful in 1m22s
driver / test (3.13) (push) Successful in 1m6s
driver / lowest (push) Successful in 1m4s
driver / build (push) Successful in 1m24s
driver / security (push) Successful in 2m54s
driver / publish (push) Successful in 28s
CI / driver (push) Successful in 9m58s
2026-11-27 04:49:50 +00:00
christianmanivong 594cc5e486 refactor(hardening): the SELinux part as three small questions (NetOrk/netork#2706)
driver / lint (pull_request) Successful in 17s
driver / standard (pull_request) Successful in 19s
driver / types (pull_request) Successful in 1m1s
driver / test (3.13) (pull_request) Successful in 1m12s
driver / test (3.12) (pull_request) Successful in 1m19s
driver / lowest (pull_request) Successful in 39s
driver / build (pull_request) Successful in 29s
driver / security (pull_request) Successful in 1m0s
CI / driver (pull_request) Successful in 2m31s
driver / publish (pull_request) Skipped
_selinux_configured, _selinux_running and _selinux_seen, each on its own, so
_selinux stays within napalm-standard's complexity limit. The parse is
unchanged.
2026-11-27 01:45:12 +01:00
christianmanivong e440bee9e1 chore(release): 4.48.0
driver / standard (pull_request) Failing after 16s
driver / lint (pull_request) Successful in 14s
driver / types (pull_request) Successful in 56s
driver / test (3.12) (pull_request) Successful in 1m16s
driver / test (3.13) (pull_request) Successful in 1m7s
driver / lowest (pull_request) Successful in 40s
driver / build (pull_request) Successful in 29s
driver / security (pull_request) Successful in 1m2s
CI / driver (pull_request) Failing after 2m48s
driver / publish (pull_request) Skipped
2026-11-26 23:13:28 +01:00
christianmanivong 3cd0e3621a feat(hardening): how a Linux host is hardened, as one read-only reading (NetOrk/netork#2706)
HardeningMixin.get_hardening() reads, with one fixed command: the active
security modules, SELinux's mode and its configured mode, AppArmor's switch
and (as root) its profiles per mode, the crypto policy and FIPS mode, the
kernel's text for each CPU vulnerability, mitigations= and nosmt from the
command line, and the distribution's IDs. Read as root first, as the login
user where root is refused. What was not read is None, never off.
2026-11-26 23:11:57 +01:00
christianmanivong 3813aee3a8 chore(release): 4.47.0
driver / lint (pull_request) Successful in 17s
driver / standard (pull_request) Successful in 21s
driver / types (pull_request) Successful in 1m0s
driver / test (3.13) (pull_request) Successful in 1m7s
driver / test (3.12) (pull_request) Successful in 1m21s
driver / lowest (pull_request) Successful in 41s
driver / build (pull_request) Successful in 29s
driver / security (pull_request) Successful in 1m1s
CI / driver (pull_request) Successful in 2m29s
driver / publish (pull_request) Skipped
2026-11-26 23:09:58 +01:00
christianmanivong e3420269b7 feat(updates): the update history from apt's own log, with Proxmox VE 9.3's ids (NetOrk/netork#2728)
AptHistoryMixin implements get_update_history over run_command: history.log and its
rotations in one round trip as the login user, root only for a file that user may not
read. Dates are read in the host's zone; a transaction's id is its start and the number
of earlier ones with that start in the same file, as GET /nodes/{node}/apt/history names
it. Malformed blocks are left out, a report cut short raises.
2026-11-26 23:04:41 +01:00
christianmanivong 5985c87cc8 Merge pull request 'fix(services-restart): an LXC container's processes are left out, 4.46.0 (NetOrk/netork#2750)' (#134) from feature/services-need-restart-lxc into main
driver / types (push) Successful in 1m3s
driver / standard (push) Successful in 19s
driver / lint (push) Successful in 16s
driver / test (3.12) (push) Successful in 1m27s
driver / test (3.13) (push) Successful in 1m22s
driver / lowest (push) Successful in 50s
driver / build (push) Successful in 35s
driver / security (push) Successful in 1m8s
driver / publish (push) Successful in 33s
CI / driver (push) Successful in 11m9s
2026-11-26 18:56:35 +00:00
christianmanivong 6c90373c80 Merge remote-tracking branch 'origin/main' into feature/services-need-restart-lxc
driver / lint (pull_request) Successful in 14s
driver / standard (pull_request) Successful in 18s
driver / types (pull_request) Successful in 1m0s
driver / test (3.13) (pull_request) Successful in 1m12s
driver / test (3.12) (pull_request) Successful in 1m20s
driver / lowest (pull_request) Successful in 42s
driver / build (pull_request) Successful in 33s
driver / security (pull_request) Successful in 1m12s
CI / driver (pull_request) Successful in 2m42s
driver / publish (pull_request) Skipped
2026-11-26 19:46:33 +01:00
christianmanivong f8c456d784 chore(release): 4.46.0
driver / standard (pull_request) Successful in 17s
driver / lint (pull_request) Successful in 14s
driver / types (pull_request) Successful in 1m5s
driver / test (3.12) (pull_request) Successful in 1m22s
driver / test (3.13) (pull_request) Successful in 1m17s
driver / lowest (pull_request) Successful in 55s
driver / build (pull_request) Successful in 34s
driver / security (pull_request) Successful in 1m5s
CI / driver (pull_request) Successful in 2m58s
driver / publish (pull_request) Skipped
2026-11-26 19:25:55 +01:00
christianmanivong a5275d4c4d Merge NAPALM/napalm-device-types#132 (4.45.0) into feature/services-need-restart-lxc 2026-11-26 19:25:55 +01:00
christianmanivong 67ffee4e9e fix(services-restart): an LXC container's processes are left out (NetOrk/netork#2750)
driver / standard (pull_request) Failing after 17s
driver / lint (pull_request) Successful in 15s
driver / types (pull_request) Successful in 1m5s
driver / test (3.12) (pull_request) Successful in 1m23s
driver / test (3.13) (pull_request) Successful in 1m22s
driver / lowest (pull_request) Successful in 44s
driver / build (pull_request) Successful in 32s
driver / security (pull_request) Successful in 1m4s
CI / driver (pull_request) Failing after 3m0s
driver / publish (pull_request) Skipped
On a Proxmox node the /proc scan sees every container's processes: an LXC
container updates itself, and its own systemd's units (lxc/<vmid>/ns/...
.service) would read as the host's services needing a restart. They are
left out like Docker's and Podman's: /lxc/<name>/ (Proxmox VE, cgroup v1)
and /lxc.payload.<name>/ (LXC 4 and later). The monitor, lxc.monitor/<name>,
runs the host's lxc-start and still counts.
2026-11-26 18:53:07 +01:00
15 changed files with 1839 additions and 104 deletions

No files matched your search

+56
View File
@@ -7,6 +7,62 @@ recorded here; their history is the git log.
## [Unreleased]
## [4.49.0] - 2026-11-28
### Added
- `RadioStatusDict` carries a radio's runtime state beside its configuration
(NetOrk/netork#31): `up` (the radio runs), `pending` (the device is still bringing it
up or down) and `setup_failed` (the device gave up bringing it up after its retries).
All three are optional: a driver that cannot read the state leaves them out. A radio
can be `enabled` and not run, as on 2026-07-16, when a rejected value kept every radio
of a fleet in a restart loop the configuration never showed.
## [4.48.0] - 2026-11-27
### Added
- `HardeningMixin.get_hardening()`: how a Linux host is hardened, read with one fixed,
read-only command (NetOrk/netork#2706). The active security modules
(`/sys/kernel/security/lsm`), SELinux's mode (`getenforce`, else
`/sys/fs/selinux/enforce`) and its configured mode (`SELINUX=` in `/etc/selinux/config`),
AppArmor's switch and, as root, its profiles per mode (`aa-status --json`), the crypto
policy (`update-crypto-policies --show`) and FIPS mode (`/proc/sys/crypto/fips_enabled`),
the kernel's text for each file under `/sys/devices/system/cpu/vulnerabilities`, the
kernel command line with `mitigations=` (`auto` when not given) and `nosmt`, and
`ID`/`ID_LIKE` from `/etc/os-release`. Read as root first; where root is refused, as the
login user, without the profile counts. Anything not read is `None`, never "off". A
driver supplies `_run_hardening_command(command, *, privileged)`.
- `parse_hardening`, `HARDENING_COMMAND`, `cpu_vulnerability_state` (`not_affected`,
`mitigated`, `vulnerable` or `unknown`, from the kernel's words), and the
`HardeningDict`, `SelinuxDict` and `AppArmorDict` shapes (in `hardening`).
## [4.47.0] - 2026-11-26
### Added
- `AptHistoryMixin.get_update_history(since)`: apt's own history log as past transactions
(NetOrk/netork#2728), for every driver of a Debian-family host that has `run_command`.
`APT_HISTORY_COMMAND` prints `/var/log/apt/history.log` and its rotations
(`history.log.<n>.gz` through `zcat`) in one round trip, as the login user (the files
are 0644), with the host's time zone (`/etc/localtime`'s link, `/etc/timezone`) and
`date +%z` for a zone without a name; only a file that user may not read makes the
mixin read it again as root. `parse_apt_history(text, since)` reads apt's dates in that
zone and names each transaction as Proxmox VE 9.3's `GET /nodes/{node}/apt/history`
does: start time and the number of earlier transactions with that start in the same
file, so a node that moves to 9.3 keeps its ids. Strict: a block whose package lines
do not read as apt writes them is left out (and still counted), one without
`End-Date` has `end` None, a report cut short or a file that could not be read raises.
- `apt_history_command(log_dir)`, `host_zone(name, offset)` and `AptHistoryUnreadable`
(a `PermissionError`), in `apt_history`.
## [4.46.0] - 2026-11-26
### Fixed
- `get_services_need_restart()` leaves an LXC container's processes out of the `/proc` scan,
as it does Docker's and Podman's (NetOrk/netork#2750). On a Proxmox VE node a container
updates itself, and its own systemd's units (`/lxc/<vmid>/ns/system.slice/nginx.service`)
read as host services that need a restart. Left out: `/lxc/<name>/` (Proxmox VE, cgroup v1)
and `/lxc.payload.<name>/` (LXC 4 and later); `/lxc.monitor/<name>` still counts, since
`lxc-start` runs the host's binary.
## [4.45.0] - 2026-11-26
### Added
+20 -1
View File
@@ -160,6 +160,17 @@ everywhere, so the command and its parse are concrete here and a driver supplies
`_run_kernel_facts_command`. `OSDriver` does not carry it — a Windows host is an OS driver
too, and `hasattr(driver, "get_kernel_facts")` has to stay truthful.
`HardeningMixin` (`get_hardening`) is mixed in the same way: how the host is hardened, as
its kernel and its own tools say it, in one read-only command. The active security modules
(`/sys/kernel/security/lsm`), SELinux's mode (`getenforce`) and the mode it boots in
(`/etc/selinux/config`), AppArmor's switch and its profiles per mode (`aa-status --json`,
the one part that needs root), the crypto policy (`update-crypto-policies --show`) and FIPS
mode, the kernel's answer for each CPU vulnerability (`/sys/devices/system/cpu/vulnerabilities`,
put in one word by `cpu_vulnerability_state`), `mitigations=` and `nosmt` from the kernel
command line, and `ID`/`ID_LIKE` from `/etc/os-release`. Read as root first and, where root
is refused, as the login user without the profile counts. A driver supplies
`_run_hardening_command(command, privileged=)`; what was not read is `None`, never "off".
`ServicePackagesMixin` (`get_service_packages`) is mixed in the same way: which installed
packages each systemd service is made of — the one shipping its unit file and the one
shipping the binary its `ExecStart` runs, by `dpkg -S` or `rpm -qf`, not the libraries
@@ -185,6 +196,13 @@ another release than the host's is the caller's to judge (`suite_release` gives
source file to *codename*, after fetching each new suite's `InRelease` with apt's downloader:
where the vendor has none, the file stays as it is.
`AptHistoryMixin` (`napalm_device_types.apt_history`) implements
`UpdateMixin.get_update_history` from apt's own log over the driver's `run_command`: every
transaction in `/var/log/apt/history.log` and its rotations, newest first, with the same
ids Proxmox VE 9.3's `GET /nodes/{node}/apt/history` gives (start time and the index among
those that started in the same second of the same file). A driver whose host may run
another package manager gates it, as napalm-linux does.
`HostStatusMixin` (`get_host_status`) is mixed in the same way: whether a Linux host needs
a reboot to finish an update (`/var/run/reboot-required`, `needs-restarting -r`, or a newer
kernel of the running flavour installed), whether it patches itself (unattended-upgrades,
@@ -214,7 +232,8 @@ finished until they restart. One fixed, read-only command, as root: `needs-resta
where dnf-utils has it, else `needrestart -b -r l` (list only, whatever `needrestart.conf`
says), else the processes whose `/proc/<pid>/maps` maps deleted code
(`DELETED_CODE_PATTERN`), each named by the service its cgroup gives, as for the listening
sockets. A driver supplies `_run_services_restart_command(command)`; the command arrives as
sockets. A container's processes are left out, an LXC container's as well (a Proxmox node's
containers update themselves). A driver supplies `_run_services_restart_command(command)`; the command arrives as
one `sh -c` argument and reads no stdin. Without root there is no reading: one that saw only
the login user's processes would read as clean.
+1
View File
@@ -161,6 +161,7 @@ the driver.
| `virtual_ips` | vip-manager, keepalived, awk |
| `system_identity` | SMBIOS via sysfs and `dmidecode` |
| `package_updates` | apt and dnf output |
| `apt_history` | apt's history log, `zcat`, `/etc/localtime` |
| `apt_releases` | apt's source files (one-line and deb822), `/etc/os-release`, `apt-helper` |
| `ssh_server` | OpenSSH (`sshd -T`, `sshd -t`, `sshd_config`); which algorithms to drop stays the caller's |
| `terminal` | ANSI escape codes in shell output |
+28
View File
@@ -37,6 +37,7 @@ Function classes -- what a device *can do*. Shared behaviour lives here once
instead of being restated on every role that happens to need it:
* :class:`~napalm_device_types.channel.CommandChannelMixin`
* :class:`~napalm_device_types.apt_history.AptHistoryMixin`
* :class:`~napalm_device_types.config_lifecycle.ConfigLifecycleMixin`
* :class:`~napalm_device_types.config_revisions.ConfigRevisionsMixin`
* :class:`~napalm_device_types.config_sync.ConfigSyncMixin`
@@ -44,6 +45,7 @@ instead of being restated on every role that happens to need it:
* :class:`~napalm_device_types.credential_expiry.CredentialExpiryMixin`
* :class:`~napalm_device_types.dhcp.DhcpServerMixin`
* :class:`~napalm_device_types.firewall_rules.FirewallRuleMixin`
* :class:`~napalm_device_types.hardening.HardeningMixin`
* :class:`~napalm_device_types.health_metrics.HealthMetricsMixin`
* :class:`~napalm_device_types.host_status.HostStatusMixin`
* :class:`~napalm_device_types.host_reboot.HostRebootMixin`
@@ -80,6 +82,14 @@ Introspection -- :func:`~napalm_device_types.roles.roles_of`,
"""
from napalm_device_types.access_point import AccessPointDriver
from napalm_device_types.apt_history import (
APT_HISTORY_COMMAND,
AptHistoryMixin,
AptHistoryUnreadable,
apt_history_command,
host_zone,
parse_apt_history,
)
from napalm_device_types.apt_proxy import (
APT_PROXY_COMMAND,
AptProxyMixin,
@@ -163,6 +173,13 @@ from napalm_device_types.fixes import (
ZabbixAgentMixin,
run_fix_steps,
)
from napalm_device_types.hardening import (
HARDENING_COMMAND,
HardeningDict,
HardeningMixin,
cpu_vulnerability_state,
parse_hardening,
)
from napalm_device_types.health_metrics import HealthMetricsMixin
from napalm_device_types.host_firewall import (
HostFirewallMixin,
@@ -442,6 +459,12 @@ __all__ = [
"FixStepOutcomeDict",
"LldpAgentMixin",
"PackageProxyMixin",
"APT_HISTORY_COMMAND",
"AptHistoryMixin",
"AptHistoryUnreadable",
"apt_history_command",
"host_zone",
"parse_apt_history",
"APT_PROXY_COMMAND",
"AptProxyMixin",
"https_proxy_for",
@@ -541,6 +564,11 @@ __all__ = [
"KernelFactsMixin",
"KERNEL_FACTS_COMMAND",
"parse_kernel_facts",
"HARDENING_COMMAND",
"HardeningMixin",
"HardeningDict",
"cpu_vulnerability_state",
"parse_hardening",
"SERVICE_PACKAGES_COMMAND",
"SERVICES_RESTART_COMMAND",
"ServicesRestartMixin",
+115
View File
@@ -0,0 +1,115 @@
"""The shapes an access point's getters return (models.py's Access Point part).
Apart from ``models.py`` for its size; ``models`` re-exports each, so
``napalm_device_types.models.RadioStatusDict`` stays where callers import it.
"""
from typing import NotRequired
from typing_extensions import TypedDict
class WirelessClientDict(TypedDict):
mac: str
ssid: str
radio: str
signal: int
noise: int
tx_rate: float
rx_rate: float
uptime: int
# Optional fields populated by DHCP cross-reference (e.g. from firewall)
ip: NotRequired[str]
hostname: NotRequired[str]
lease_end: NotRequired[int] # Unix timestamp when DHCP lease expires
class SSIDDict(TypedDict):
enabled: bool
radio: str
bssid: str
encryption: str
hidden: bool
clients: int
class RadioStatusDict(TypedDict):
"""One radio: ``enabled`` is the configuration, the rest what the radio does.
The runtime state is left out where the driver cannot read it, never guessed
(NetOrk/netork#31): ``up`` whether the radio runs, ``pending`` whether the
device is still bringing it up or down, ``setup_failed`` whether the device
gave up bringing it up after its retries.
"""
enabled: bool
band: str
channel: int
channel_width: int
tx_power: int
frequency: float
up: NotRequired[bool]
pending: NotRequired[bool]
setup_failed: NotRequired[bool]
class ChannelScanEntryDict(TypedDict):
"""One neighboring AP entry as returned by get_channel_scan()."""
bssid: str
ssid: str
frequency: int # centre frequency in MHz, e.g. 2437
channel: int # channel number, e.g. 6
signal_dbm: int # RSSI in dBm, e.g. -72
channel_width: int # MHz: 20 / 40 / 80 / 160; 0 if unknown
band: str # "2.4GHz" | "5GHz" | "6GHz"
class WirelessConfigDict(TypedDict):
country_code: str
regulatory_domain: str
beacon_interval: int
dtim_period: int
rts_threshold: int
fragmentation_threshold: int
short_preamble: bool
wmm_enabled: bool
class FastTransitionConfigDict(TypedDict):
enabled: bool
ssid: str
mobility_domain: str
reassociation_deadline: int
r0_key_lifetime: int
r1_key_holder: str
pmk_r1_push: bool
over_ds: bool
class MeshPeerDict(TypedDict):
mac: str
radio: str
signal: int
tx_rate: float
rx_rate: float
uptime: int
hop_count: int
class MeshConfigDict(TypedDict):
enabled: bool
radio: str
mesh_id: str
path_metric: str
gate_announcements: bool
is_gate: bool
encryption: str
class SSIDBridgeDict(TypedDict):
ssid: str
bridge: str
vlan_id: int
tagged: bool
client_isolation: bool
+402
View File
@@ -0,0 +1,402 @@
"""apt's history log as past transactions (``UpdateMixin.get_update_history``, NetOrk/netork#2728).
apt appends a block to ``/var/log/apt/history.log`` for every run that changed a
package, also those no caller started (an operator's ``apt``, unattended-upgrades,
PackageKit)::
Start-Date: 2026-11-26 10:00:00
Commandline: apt-get -y upgrade
Requested-By: admin (1000)
Install: linux-image-6.12.57+deb13-amd64:amd64 (6.12.57-1, automatic)
Upgrade: openssh-server:amd64 (1:10.0p1-7, 1:10.0p1-7+deb13u1)
Remove: ifupdown:amd64 (0.8.44)
Error: Sub-process /usr/bin/dpkg returned an error code (1)
End-Date: 2026-11-26 10:01:00
logrotate moves it to ``history.log.1.gz`` and on, monthly, twelve deep by default.
The file is 0644 on Debian and Ubuntu, so :data:`APT_HISTORY_COMMAND` reads it
as the login user; :class:`AptHistoryMixin` asks for root only where a file is
not readable that way. One round trip prints every file behind a marker line,
the host's time zone (``/etc/localtime``'s link, ``/etc/timezone``) and its UTC
offset (``date +%z``), which stands in where the zone has no name.
The dates are the host's local time. A transaction is named like Proxmox VE 9.3's
``GET /nodes/{node}/apt/history`` names it: its start in unix seconds and the
number of earlier transactions with the same start **in the same log file**, so
a Proxmox VE node that moves to 9.3 keeps the ids it had. The count takes every
block with a readable start, also one skipped below; it never depends on *since*.
Strict: a block whose package lines or end do not read as apt writes them is left
out, never guessed at; a block without ``End-Date`` is one that is running or was
interrupted (``end`` None). A report cut short, or a file that could not be read,
raises: an empty list means no transaction, never "could not read".
"""
from __future__ import annotations
import re
from collections.abc import Callable
from datetime import datetime, timedelta, timezone, tzinfo
from typing import TYPE_CHECKING
from zoneinfo import ZoneInfo, ZoneInfoNotFoundError
from napalm_device_types._time_sync_reading import _zone_name
from napalm_device_types.updates import (
UpdateHistoryAction,
UpdateHistoryDict,
UpdateHistoryPackageDict,
)
if TYPE_CHECKING: # pragma: no cover - for type checkers only
from napalm_device_types.channel import CommandResult
#: Where apt keeps its history log.
APT_HISTORY_DIR = "/var/log/apt"
_MARK = "### apt-history"
#: Seconds the read may take: twelve rotated months of a busy host.
_READ_TIMEOUT = 120
def apt_history_command(log_dir: str = APT_HISTORY_DIR) -> str:
"""``sh`` that prints the time zone, the UTC offset and every history file in *log_dir*.
Each file follows a ``### apt-history file <path>`` line and ends with a
``### apt-history status <exit code>`` line; one the login user may not read
is only named (``unreadable``). ``### apt-history end`` closes the report.
"""
return (
f"m='{_MARK}'; "
"z=$( { readlink /etc/localtime || cat /etc/timezone; } 2>/dev/null | head -n 1); "
'printf "%s zone %s\\n" "$m" "$z"; '
'printf "%s offset %s\\n" "$m" "$(date +%z)"; '
f"for f in {log_dir}/history.log {log_dir}/history.log.*; do "
'[ -f "$f" ] || continue; '
'if [ ! -r "$f" ]; then printf "%s unreadable %s\\n" "$m" "$f"; continue; fi; '
'printf "%s file %s\\n" "$m" "$f"; '
'case "$f" in *.gz) zcat -- "$f";; *) cat -- "$f";; esac 2>/dev/null; '
'printf "\\n%s status %s\\n" "$m" "$?"; '
"done; "
'printf "%s end\\n" "$m"'
)
#: Prints apt's history log, rotated files too, with the host's time zone.
APT_HISTORY_COMMAND = apt_history_command()
class AptHistoryUnreadable(PermissionError):
"""A history file the user that read the log may not read."""
#: The package lines apt writes, and the action each stands for.
_ACTIONS: dict[str, UpdateHistoryAction] = {
"Install": "install",
"Reinstall": "reinstall",
"Upgrade": "upgrade",
"Downgrade": "downgrade",
"Remove": "remove",
"Purge": "purge",
"Disappeared": "disappear",
}
#: ``name[:arch] (versions)``; neither a name nor a Debian version holds ``,``, ``(`` or ``)``.
_ENTRY = re.compile(r"([^\s,()]+) \(([^()]*)\)")
#: ``Disappeared`` names a package without a version where apt no longer knows it.
_DISAPPEARED = re.compile(r"([^\s,()]+)(?: \(([^\s,()]+)\))?")
_REQUESTED_BY = re.compile(r"(.+) \(\d+\)")
_DATE = "%Y-%m-%d %H:%M:%S"
_OFFSET = re.compile(r"([+-])(\d\d)(\d\d)")
#: ``history.log``, ``history.log.<n>`` and ``history.log.<n>.gz``.
_ROTATED = re.compile(r"history\.log(?:\.(\d+)(?:\.gz)?)?")
def host_zone(name: str, offset: str) -> tzinfo:
"""The host's zone from its name, else the fixed UTC offset ``date +%z`` printed.
:raises ValueError: when neither says.
"""
zone = _zone_name(name)
if zone:
try:
return ZoneInfo(zone)
except (ZoneInfoNotFoundError, ValueError):
pass
match = _OFFSET.fullmatch(offset.strip())
if match is None:
raise ValueError(f"the host named no time zone ({name!r}) and no UTC offset ({offset!r})")
sign = -1 if match.group(1) == "-" else 1
return timezone(sign * timedelta(hours=int(match.group(2)), minutes=int(match.group(3))))
def _local(value: str, zone: tzinfo) -> int | None:
"""apt's ``YYYY-MM-DD HH:MM:SS`` in *zone* as unix seconds; None for anything else."""
try:
when = datetime.strptime(" ".join(value.split()), _DATE)
except ValueError:
return None
return int(when.replace(tzinfo=zone).timestamp())
_Versions = tuple[str | None, str | None] | None
def _installed(v: list[str]) -> _Versions:
return (None, v[0]) if v[1:] in ([], ["automatic"]) else None
def _changed(v: list[str]) -> _Versions:
return (v[0], v[1]) if len(v) == 2 else None
def _same(v: list[str]) -> _Versions:
return (v[0], v[0]) if len(v) == 1 else None
def _removed(v: list[str]) -> _Versions:
# A package removed earlier and purged now has no installed version: ``Purge: name ()``.
return (v[0] or None, None) if len(v) == 1 else None
def _gone(v: list[str]) -> _Versions:
return ((v[0] if v else None), None) if len(v) <= 1 else None
#: Per action: ``(old, new)`` from the versions apt wrote in a package's brackets.
_VERSIONS: dict[UpdateHistoryAction, Callable[[list[str]], _Versions]] = {
"install": _installed,
"reinstall": _same,
"upgrade": _changed,
"downgrade": _changed,
"remove": _removed,
"purge": _removed,
"disappear": _gone,
}
def _versions(action: UpdateHistoryAction, versions: list[str]) -> _Versions:
"""``(old, new)`` of one package; None where what apt wrote does not fit *action*."""
if action not in ("remove", "purge") and not all(versions):
return None
return _VERSIONS[action](versions)
def _disappeared(value: str) -> list[tuple[str, list[str]]] | None:
found = [_DISAPPEARED.fullmatch(item) for item in value.split(", ")]
if not all(found):
return None
return [(m.group(1), [m.group(2)] if m.group(2) else []) for m in found if m]
def _entries(action: UpdateHistoryAction, value: str) -> list[tuple[str, list[str]]] | None:
"""``(name[:arch], versions)`` per package of a line; None unless all of it reads."""
if action == "disappear":
return _disappeared(value)
matches = list(_ENTRY.finditer(value))
if not matches or ", ".join(m.group(0) for m in matches) != value:
return None
return [(m.group(1), [v.strip() for v in m.group(2).split(",")]) for m in matches]
def _packages(action: UpdateHistoryAction, value: str) -> list[UpdateHistoryPackageDict] | None:
"""The packages of one ``Install:``-style line; None unless every one reads."""
entries = _entries(action, value.strip())
if entries is None:
return None
packages: list[UpdateHistoryPackageDict] = []
for name, versions in entries:
pair = _versions(action, versions)
if pair is None:
return None
packages.append(
{
"name": name.split(":", 1)[0],
"action": action,
"old_version": pair[0],
"new_version": pair[1],
}
)
return packages
def _transaction(start: int, lines: list[str], zone: tzinfo) -> UpdateHistoryDict | None:
"""One block after its ``Start-Date``; None where a line does not read."""
found: UpdateHistoryDict = {
"id": "",
"start": start,
"end": None,
"packages": [],
"requested_by": None,
"command": None,
"error": None,
}
for line in lines:
key, sep, value = line.partition(": ")
if not sep:
return None
if key in _ACTIONS:
packages = _packages(_ACTIONS[key], value)
if packages is None:
return None
found["packages"].extend(packages)
elif key == "End-Date":
found["end"] = _local(value, zone)
if found["end"] is None:
return None
elif key in ("Commandline", "Requested-By", "Error"):
_text(found, key, value.strip())
return found
def _text(found: UpdateHistoryDict, key: str, value: str) -> None:
if key == "Commandline":
found["command"] = value or None
elif key == "Requested-By":
match = _REQUESTED_BY.fullmatch(value)
found["requested_by"] = (match.group(1) if match else value) or None
else:
found["error"] = value or None
def _blocks(lines: list[str]) -> list[tuple[str, list[str]]]:
"""``(Start-Date value, the lines after it)`` per block of one file."""
blocks: list[tuple[str, list[str]]] = []
for line in lines:
line = line.rstrip("\r")
if line.startswith("Start-Date:"):
blocks.append((line.partition(":")[2], []))
elif blocks and line.strip():
blocks[-1][1].append(line)
return blocks
def _file_transactions(lines: list[str], zone: tzinfo) -> list[UpdateHistoryDict]:
"""One file's transactions in the order it holds them, each with its id."""
seen: dict[int, int] = {}
found: list[UpdateHistoryDict] = []
for date, body in _blocks(lines):
start = _local(date, zone)
if start is None:
continue
index = seen.get(start, 0)
seen[start] = index + 1
transaction = _transaction(start, body, zone)
if transaction is not None:
transaction["id"] = f"{start}-{index}"
found.append(transaction)
return found
def _rotation(path: str) -> int | None:
"""0 for ``history.log``, *n* for its *n*-th rotation; None for another file."""
match = _ROTATED.fullmatch(path.rpartition("/")[2])
if match is None:
return None
return int(match.group(1) or 0)
def _marker(
kind: str, rest: str, values: dict[str, str], files: dict[int, list[str]]
) -> list[str] | None:
"""Take one marker line; the lines of the history file it opens, if it opens one.
:raises AptHistoryUnreadable: for a history file the user may not read.
"""
rotation = _rotation(rest.strip())
if kind == "unreadable" and rotation is not None:
raise AptHistoryUnreadable(f"{rest.strip()} is not readable")
if kind == "file" and rotation is not None:
return files.setdefault(rotation, [])
if kind in ("zone", "offset"):
values[kind] = rest
return None
def _report(text: str) -> tuple[dict[str, str], dict[int, list[str]]]:
"""The report's ``zone`` and ``offset``, and each history file's lines by rotation.
:raises ValueError: for a report cut short or a file that could not be read.
:raises AptHistoryUnreadable: for a file the user may not read.
"""
values: dict[str, str] = {}
files: dict[int, list[str]] = {}
current: list[str] | None = None
for line in text.splitlines():
if not line.startswith(_MARK + " "):
if current is not None:
current.append(line)
continue
kind, _, rest = line[len(_MARK) + 1 :].partition(" ")
if kind == "end":
return values, files
if kind == "status" and current is not None and rest.strip() != "0":
raise ValueError(f"apt's history log could not be read (exit {rest.strip()})")
current = _marker(kind, rest, values, files)
raise ValueError("apt's history log came back cut short")
def parse_apt_history(text: str, since: int | None = None) -> list[UpdateHistoryDict]:
""":data:`APT_HISTORY_COMMAND`'s report as transactions, newest first.
:param since: Unix seconds; only transactions that started at or after it.
:raises ValueError: for a report cut short, a file that could not be read, or
a host that named neither its time zone nor its UTC offset.
:raises AptHistoryUnreadable: for a file the user may not read.
"""
values, files = _report(text)
zone = host_zone(values.get("zone", ""), values.get("offset", ""))
oldest_first: list[UpdateHistoryDict] = []
for rotation in sorted(files, reverse=True):
oldest_first.extend(_file_transactions(files[rotation], zone))
newest = sorted(reversed(oldest_first), key=lambda t: t["start"], reverse=True)
return [t for t in newest if since is None or t["start"] >= since]
class AptHistoryMixin:
"""Adds :meth:`get_update_history` from apt's log, over the driver's ``run_command``.
Mixed in by the drivers of Debian-family hosts, so
``hasattr(driver, "get_update_history")`` stays a truthful answer. The log is
read as the login user; only a file that user may not read makes it read as root.
"""
if TYPE_CHECKING: # pragma: no cover - declared for type checkers only
def run_command(
self,
command: str,
*,
privileged: bool = False,
timeout: float = 60,
stdin: bytes | None = None,
) -> CommandResult: ...
def get_update_history(self, since: int | None = None) -> list[UpdateHistoryDict]:
"""apt's transactions on the host, newest first, from *since* (unix seconds) on.
:raises RuntimeError: when the log could not be read.
:raises ValueError: when the report came back cut short.
:raises AptHistoryUnreadable: when even root could not read a file.
"""
try:
return parse_apt_history(self._read_apt_history(privileged=False), since)
except AptHistoryUnreadable:
return parse_apt_history(self._read_apt_history(privileged=True), since)
def _read_apt_history(self, *, privileged: bool) -> str:
result = self.run_command(APT_HISTORY_COMMAND, privileged=privileged, timeout=_READ_TIMEOUT)
if result.exit_code != 0:
said = (result.stderr or result.stdout).strip()[-300:]
raise RuntimeError(f"cannot read apt's history log: {said or result.exit_code}")
return result.stdout
__all__ = [
"APT_HISTORY_COMMAND",
"APT_HISTORY_DIR",
"AptHistoryMixin",
"AptHistoryUnreadable",
"apt_history_command",
"host_zone",
"parse_apt_history",
]
+341
View File
@@ -0,0 +1,341 @@
"""How a Linux host is hardened, as its kernel and its own tools say it (NetOrk/netork#2706).
Five things, each read where the host itself keeps it:
- **The security modules in force:** ``/sys/kernel/security/lsm`` lists the active
LSMs. SELinux's mode comes from ``getenforce`` (or ``/sys/fs/selinux/enforce``), the
mode it boots in from ``SELINUX=`` in ``/etc/selinux/config``. AppArmor's switch is
``/sys/module/apparmor/parameters/enabled``, its profiles per mode come from
``aa-status --json`` -- the one part that needs root.
- **The crypto policy:** ``update-crypto-policies --show`` (the dnf family; Debian and
Ubuntu have none) and FIPS mode from ``/proc/sys/crypto/fips_enabled``.
- **The CPU vulnerabilities:** each file under ``/sys/devices/system/cpu/vulnerabilities``
holds the kernel's own answer for one of them: ``Not affected``, ``Mitigation: ...``,
``Vulnerable...``, or ``Unknown: ...`` (:func:`cpu_vulnerability_state`).
- **The kernel command line:** ``mitigations=`` (``auto`` when not given, as in the
kernel) and ``nosmt``.
- **The distribution's IDs** (``ID`` and ``ID_LIKE`` from ``/etc/os-release``), so a
consumer can tell an Enterprise Linux host, where SELinux is the distribution's own
module, from one that merely has it installed.
One fixed command, read-only, the same on every Linux host, so it and its parse live
here once and a driver only carries the command across. **Not read is None, never
empty or off:** a section the command did not print -- a file missing, a tool not
installed, root refused -- comes back ``None``, so a consumer never reads "not looked"
as "clean".
"""
from __future__ import annotations
import json
import re
from shlex import quote
from typing import TYPE_CHECKING, Literal, TypedDict
from napalm_device_types.terminal import strip_terminal_codes
_BEGIN = "HARDENING_BEGIN"
_END = "HARDENING_END"
_VULNERABILITIES = "/sys/devices/system/cpu/vulnerabilities"
#: One line, POSIX ``sh``, read-only. The frame markers are printed in two halves so
#: that a transport which echoes the command does not show them early. The tools are in
#: ``/usr/sbin`` on some systems, outside a login user's ``PATH``. ``r`` prints a file
#: under a section header and ends it with a newline: ``/sys/kernel/security/lsm`` has
#: none of its own.
HARDENING_COMMAND = (
"PATH=$PATH:/usr/sbin:/sbin; "
'r() { if [ -r "$2" ]; then echo "[$1]"; cat "$2" 2>/dev/null; echo; fi; }; '
"printf '%s%s\\n' HARDENING_ BEGIN; "
"r lsm /sys/kernel/security/lsm; "
"r cmdline /proc/cmdline; "
"r fips /proc/sys/crypto/fips_enabled; "
"r apparmor_enabled /sys/module/apparmor/parameters/enabled; "
"if [ -r /etc/os-release ]; then echo '[os]'; grep -E '^(ID|ID_LIKE)=' /etc/os-release; fi; "
"if command -v getenforce >/dev/null 2>&1; then echo '[selinux]'; getenforce 2>/dev/null; "
"else r selinux_enforce /sys/fs/selinux/enforce; fi; "
"if [ -r /etc/selinux/config ]; then echo '[selinux_config]'; "
"grep -E '^SELINUX=' /etc/selinux/config; fi; "
"if command -v update-crypto-policies >/dev/null 2>&1; then echo '[crypto_policy]'; "
"update-crypto-policies --show 2>/dev/null; fi; "
f"if [ -d {_VULNERABILITIES} ]; then echo '[cpu_vulnerabilities]'; "
f"grep -H . {_VULNERABILITIES}/* 2>/dev/null; fi; "
"if command -v aa-status >/dev/null 2>&1; then echo '[aa_status]'; "
"aa-status --json 2>/dev/null; echo; fi; "
"printf '%s%s\\n' HARDENING_ END"
)
CpuVulnerabilityState = Literal["not_affected", "mitigated", "vulnerable", "unknown"]
_SELINUX_MODES = frozenset({"enforcing", "permissive", "disabled"})
_ENFORCE_FILE = {"1": "enforcing", "0": "permissive"}
_SECTION = re.compile(r"^\[([a-z_]+)\]$")
class SelinuxDict(TypedDict):
"""SELinux on the host. ``None`` in a field: could not be read."""
mode: str | None # "enforcing", "permissive" or "disabled"
configured: str | None # SELINUX= in /etc/selinux/config: the mode it boots in
class AppArmorDict(TypedDict):
"""AppArmor on the host. ``None`` in a field: could not be read."""
enabled: bool | None # /sys/module/apparmor/parameters/enabled, else the LSM list
#: Loaded profiles per mode ("enforce", "complain", ...), from ``aa-status --json``;
#: None without root, which it needs.
profiles: dict[str, int] | None
class HardeningDict(TypedDict):
"""What :meth:`HardeningMixin.get_hardening` read. ``None``: not read, never "off"."""
lsm: list[str] | None # /sys/kernel/security/lsm, in the kernel's order
selinux: SelinuxDict | None # None: no sign of SELinux on the host
apparmor: AppArmorDict | None # None: no sign of AppArmor on the host
crypto_policy: str | None # update-crypto-policies --show, e.g. "DEFAULT:SHA1"
fips: bool | None # /proc/sys/crypto/fips_enabled
#: File name under /sys/devices/system/cpu/vulnerabilities -> the kernel's text.
cpu_vulnerabilities: dict[str, str] | None
cmdline: str | None # /proc/cmdline
mitigations: str | None # mitigations= on the command line; "auto" when not given
nosmt: bool | None # SMT switched off by the command line
os_ids: list[str] | None # ID, then ID_LIKE, from /etc/os-release, lowercased
def cpu_vulnerability_state(text: str) -> CpuVulnerabilityState:
"""What the kernel's text for one CPU vulnerability says, in one word.
The kernel writes ``Not affected``, ``Mitigation: ...`` (also behind a prefix, as
``KVM: Mitigation: VMX disabled``), ``Vulnerable...`` or ``Processor vulnerable``,
and ``Unknown: ...`` where it cannot tell (a guest that cannot see its host's
microcode). A mitigation that leaves SMT exposed is still the kernel's
``Mitigation``: the text keeps the rest.
"""
lowered = text.strip().lower()
if lowered.startswith("not affected"):
return "not_affected"
if lowered.startswith(("vulnerable", "processor vulnerable")):
return "vulnerable"
if lowered.startswith("mitigation") or ": mitigation" in lowered:
return "mitigated"
return "unknown"
def _sections(output: str) -> dict[str, list[str]]:
lines = [line.strip() for line in strip_terminal_codes(output).splitlines()]
try:
start = lines.index(_BEGIN)
end = lines.index(_END, start)
except ValueError:
raise ValueError("no intact hardening report in the output") from None
sections: dict[str, list[str]] = {}
current: list[str] = []
for line in lines[start + 1 : end]:
header = _SECTION.match(line)
if header:
current = sections.setdefault(header.group(1), [])
elif line:
current.append(line)
return sections
def _first(sections: dict[str, list[str]], key: str) -> str | None:
lines = sections.get(key)
return lines[0] if lines else None
def _unquote(value: str) -> str:
value = value.strip()
return value[1:-1] if len(value) >= 2 and value[0] == value[-1] and value[0] in "\"'" else value
def _lsm(sections: dict[str, list[str]]) -> list[str] | None:
line = _first(sections, "lsm")
if line is None:
return None
return [name.strip() for name in line.split(",") if name.strip()]
def _selinux_configured(sections: dict[str, list[str]]) -> str | None:
"""The mode it boots in: ``SELINUX=`` in ``/etc/selinux/config``, the last one."""
configured = None
for line in sections.get("selinux_config", []):
key, _, value = line.partition("=")
if key.strip() == "SELINUX":
configured = _unquote(value).lower() or None
return configured
def _selinux_running(sections: dict[str, list[str]]) -> str | None:
"""The mode it runs in: ``getenforce``'s word, else ``/sys/fs/selinux/enforce``."""
said = (_first(sections, "selinux") or "").lower()
if said in _SELINUX_MODES:
return said
return _ENFORCE_FILE.get(_first(sections, "selinux_enforce") or "")
def _selinux_seen(sections: dict[str, list[str]], lsm: list[str] | None, mode: str | None) -> bool:
"""Whether the host shows any sign of SELinux: a mode, its configuration, the LSM list."""
return mode is not None or "selinux_config" in sections or "selinux" in (lsm or [])
def _selinux(sections: dict[str, list[str]], lsm: list[str] | None) -> SelinuxDict | None:
mode = _selinux_running(sections)
if not _selinux_seen(sections, lsm, mode):
return None
if mode is None and "selinux_config" in sections and lsm is not None:
# Installed, but not among the modules the kernel runs: switched off at boot.
mode = None if "selinux" in lsm else "disabled"
return {"mode": mode, "configured": _selinux_configured(sections)}
def _profiles(sections: dict[str, list[str]]) -> dict[str, int] | None:
text = "".join(sections.get("aa_status", []))
try:
profiles = json.loads(text).get("profiles")
except (ValueError, AttributeError):
return None
if not isinstance(profiles, dict):
return None
counts: dict[str, int] = {}
for mode in profiles.values():
counts[str(mode)] = counts.get(str(mode), 0) + 1
return dict(sorted(counts.items()))
def _apparmor(sections: dict[str, list[str]], lsm: list[str] | None) -> AppArmorDict | None:
switch = _first(sections, "apparmor_enabled")
profiles = _profiles(sections)
in_lsm = "apparmor" in (lsm or [])
if switch is None and profiles is None and not in_lsm:
return None
if switch is not None:
enabled: bool | None = switch.upper().startswith("Y")
else:
enabled = True if in_lsm else None
return {"enabled": enabled, "profiles": profiles}
def _cpu_vulnerabilities(sections: dict[str, list[str]]) -> dict[str, str] | None:
if "cpu_vulnerabilities" not in sections:
return None
found: dict[str, str] = {}
for line in sections["cpu_vulnerabilities"]:
path, sep, text = line.partition(":")
if sep:
found[path.rsplit("/", 1)[-1]] = text.strip()
return dict(sorted(found.items()))
def _command_line(cmdline: str | None) -> tuple[str | None, bool | None]:
"""``mitigations=`` (the last one wins, as in the kernel) and whether SMT is off."""
if cmdline is None:
return None, None
mitigations = "auto"
nosmt = False
for word in cmdline.split():
key, _, value = word.partition("=")
if key == "mitigations":
mitigations = value
elif key == "nosmt":
nosmt = True
return mitigations, nosmt or "nosmt" in mitigations.split(",")
def _os_ids(sections: dict[str, list[str]]) -> list[str] | None:
if "os" not in sections:
return None
values = {}
for line in sections["os"]:
key, _, value = line.partition("=")
values[key.strip()] = _unquote(value)
ids: list[str] = []
for word in f"{values.get('ID', '')} {values.get('ID_LIKE', '')}".lower().split():
if word not in ids:
ids.append(word)
return ids
def parse_hardening(output: str) -> HardeningDict:
"""Parse what :data:`HARDENING_COMMAND` printed.
:raises ValueError: when the output carries no intact report.
"""
sections = _sections(output)
lsm = _lsm(sections)
cmdline = _first(sections, "cmdline")
mitigations, nosmt = _command_line(cmdline)
fips = _first(sections, "fips")
return {
"lsm": lsm,
"selinux": _selinux(sections, lsm),
"apparmor": _apparmor(sections, lsm),
"crypto_policy": _first(sections, "crypto_policy"),
"fips": None if fips is None else fips == "1",
"cpu_vulnerabilities": _cpu_vulnerabilities(sections),
"cmdline": cmdline,
"mitigations": mitigations,
"nosmt": nosmt,
"os_ids": _os_ids(sections),
}
class HardeningMixin:
"""Adds :meth:`get_hardening` to a driver that can run a command on a Linux host.
The template form (README, "Function classes"): the command and its parse are the
same everywhere, and a driver supplies only :meth:`_run_hardening_command` -- how a
command reaches its host, and how it gains root there. Mixed in by the drivers that
can, so ``hasattr(driver, "get_hardening")`` stays a truthful answer.
"""
if TYPE_CHECKING: # pragma: no cover - declared for type checkers only
def _run_hardening_command(self, command: str, *, privileged: bool) -> str:
"""Run *command* on the host and return what it printed; as root when
*privileged*. The command is a single ``sh -c`` invocation; it reads no stdin."""
...
def get_hardening(self) -> HardeningDict:
"""
Returns how the host is hardened: its security modules, crypto policy, CPU
vulnerabilities and kernel command line.
* lsm (list or None) - the active security modules, in the kernel's order
* selinux ({mode, configured} or None) - None without any sign of SELinux
* apparmor ({enabled, profiles} or None) - profiles per mode need root
* crypto_policy (str or None) - ``update-crypto-policies --show``
* fips (bool or None) - FIPS mode
* cpu_vulnerabilities (dict or None) - name -> the kernel's text
* cmdline (str or None), mitigations (str or None), nosmt (bool or None)
* os_ids (list or None) - ``ID`` and ``ID_LIKE`` from ``/etc/os-release``
``None`` means not read. Read as root first, for AppArmor's profiles; where root
is refused, as the login user, without them.
Example::
{
"lsm": ["lockdown", "capability", "yama", "selinux", "bpf"],
"selinux": {"mode": "enforcing", "configured": "enforcing"},
"apparmor": None,
"crypto_policy": "DEFAULT",
"fips": False,
"cpu_vulnerabilities": {"meltdown": "Not affected",
"spectre_v2": "Mitigation: Retpolines; ..."},
"cmdline": "BOOT_IMAGE=... ro",
"mitigations": "auto",
"nosmt": False,
"os_ids": ["almalinux", "rhel", "centos", "fedora"],
}
:raises ValueError: if neither reading carried an intact report.
"""
command = f"sh -c {quote(HARDENING_COMMAND)}"
try:
return parse_hardening(self._run_hardening_command(command, privileged=True))
except ValueError:
pass
return parse_hardening(self._run_hardening_command(command, privileged=False))
+13 -96
View File
@@ -8,7 +8,19 @@ from typing import Literal, NotRequired, get_args
from typing_extensions import TypedDict
# The SNMP health profile shapes live in snmp_health_profile.py; re-exported here, where they were.
# The SNMP health profile shapes live in snmp_health_profile.py, those of the access
# point getters in access_point_models.py; re-exported here, where they were.
from napalm_device_types.access_point_models import ChannelScanEntryDict as ChannelScanEntryDict
from napalm_device_types.access_point_models import (
FastTransitionConfigDict as FastTransitionConfigDict,
)
from napalm_device_types.access_point_models import MeshConfigDict as MeshConfigDict
from napalm_device_types.access_point_models import MeshPeerDict as MeshPeerDict
from napalm_device_types.access_point_models import RadioStatusDict as RadioStatusDict
from napalm_device_types.access_point_models import SSIDBridgeDict as SSIDBridgeDict
from napalm_device_types.access_point_models import SSIDDict as SSIDDict
from napalm_device_types.access_point_models import WirelessClientDict as WirelessClientDict
from napalm_device_types.access_point_models import WirelessConfigDict as WirelessConfigDict
from napalm_device_types.snmp_health_profile import SnmpHealthProfile as SnmpHealthProfile
from napalm_device_types.snmp_health_profile import SnmpInterfacesSpec as SnmpInterfacesSpec
from napalm_device_types.snmp_health_profile import SnmpMemorySpec as SnmpMemorySpec
@@ -130,101 +142,6 @@ class HostStatusDict(TypedDict):
# ---------------------------------------------------------------------------
class WirelessClientDict(TypedDict):
mac: str
ssid: str
radio: str
signal: int
noise: int
tx_rate: float
rx_rate: float
uptime: int
# Optional fields populated by DHCP cross-reference (e.g. from firewall)
ip: NotRequired[str]
hostname: NotRequired[str]
lease_end: NotRequired[int] # Unix timestamp when DHCP lease expires
class SSIDDict(TypedDict):
enabled: bool
radio: str
bssid: str
encryption: str
hidden: bool
clients: int
class RadioStatusDict(TypedDict):
enabled: bool
band: str
channel: int
channel_width: int
tx_power: int
frequency: float
class ChannelScanEntryDict(TypedDict):
"""One neighboring AP entry as returned by get_channel_scan()."""
bssid: str
ssid: str
frequency: int # centre frequency in MHz, e.g. 2437
channel: int # channel number, e.g. 6
signal_dbm: int # RSSI in dBm, e.g. -72
channel_width: int # MHz: 20 / 40 / 80 / 160; 0 if unknown
band: str # "2.4GHz" | "5GHz" | "6GHz"
class WirelessConfigDict(TypedDict):
country_code: str
regulatory_domain: str
beacon_interval: int
dtim_period: int
rts_threshold: int
fragmentation_threshold: int
short_preamble: bool
wmm_enabled: bool
class FastTransitionConfigDict(TypedDict):
enabled: bool
ssid: str
mobility_domain: str
reassociation_deadline: int
r0_key_lifetime: int
r1_key_holder: str
pmk_r1_push: bool
over_ds: bool
class MeshPeerDict(TypedDict):
mac: str
radio: str
signal: int
tx_rate: float
rx_rate: float
uptime: int
hop_count: int
class MeshConfigDict(TypedDict):
enabled: bool
radio: str
mesh_id: str
path_metric: str
gate_announcements: bool
is_gate: bool
encryption: str
class SSIDBridgeDict(TypedDict):
ssid: str
bridge: str
vlan_id: int
tagged: bool
client_isolation: bool
class Dot1XConfigDict(TypedDict):
"""802.1X / WPA-Enterprise config for an access-point SSID."""
+10 -5
View File
@@ -21,10 +21,11 @@ here once, and a driver only carries the command across.
**Units from cgroups.** For the ``/proc`` scan, ``/proc/<pid>/cgroup`` names the
systemd service a process runs in, as for the listening sockets: a process of a
user's own systemd is that user's manager (``user@1000``), one of a container is
left out (the container runs its image's libraries, which no host update
replaces), and one in no service -- a login session, systemd itself -- is listed
as a process. The host's tools name services only, so ``processes`` stays empty
user's own systemd is that user's manager (``user@1000``), one of a container --
Docker, Podman, or LXC as on a Proxmox node -- is left out (the container runs its
own libraries, which no host update replaces, and its own systemd's units are none
of the host's services), and one in no service -- a login session, systemd itself --
is listed as a process. The host's tools name services only, so ``processes`` stays empty
for them.
**Root, or nothing.** Only root sees every process's memory. The script goes to
@@ -105,6 +106,10 @@ _SERVICE_LINE = re.compile(r"^([\w:.@\\-]+)\.service$")
_NEEDRESTART_SVC = re.compile(r"^NEEDRESTART-SVC:\s*(.+?)\s*$")
#: A process of a user's own systemd: that user's manager is what restarts it.
_USER_MANAGER = re.compile(r"/(user@\d+)\.service(?=/|$)")
#: A process inside an LXC container: ``/lxc/<name>/`` (Proxmox VE, which nests the
#: container's own cgroups under ``ns``; cgroup v1) or ``/lxc.payload.<name>/`` (LXC 4
#: and later). Not ``/lxc.monitor/<name>``: ``lxc-start`` runs the host's binary.
_LXC = re.compile(r"^/lxc(?:/|\.payload\.)[^/]+(?:/|$)")
_SERVICE_SUFFIX = ".service"
@@ -151,7 +156,7 @@ def _maps(sections: dict[str, list[str]]) -> tuple[list[str], list[RestartProces
if not pid.isdigit():
continue
path = paths.get(int(pid))
if _container(path):
if _container(path) or _LXC.match(path or ""):
continue
unit = _process_unit(path)
if unit:
+1 -1
View File
@@ -4,7 +4,7 @@ build-backend = "setuptools.build_meta"
[project]
name = "napalm-device-types"
version = "4.45.0"
version = "4.49.0"
description = "Abstract device-type base classes for NAPALM drivers"
readme = "README.md"
requires-python = ">=3.12"
+1 -1
View File
@@ -31,7 +31,7 @@
},
"mypy_relaxed": [],
"python_file_lines": {
"napalm_device_types/models.py": 1436
"napalm_device_types/models.py": 1353
},
"untyped_public": []
}
+402
View File
@@ -0,0 +1,402 @@
"""apt's history log as past transactions (NetOrk/netork#2728).
The blocks below are written as apt writes them (``apt-pkg/deb/dpkgpm.cc``): two
spaces between date and time, ``name:arch (version[, ...])`` entries joined by
``, ``, ``Install``'s ``automatic``, ``Upgrade``/``Downgrade`` with old and new,
``Remove``/``Purge`` with the version that was installed, ``Error`` before
``End-Date``. The ids follow Proxmox VE 9.3's ``GET /nodes/{node}/apt/history``:
start time, and the count of earlier transactions with that start in the same file.
"""
from __future__ import annotations
import gzip
import os
import subprocess
from datetime import UTC, datetime, timedelta, timezone
from pathlib import Path
import pytest
from napalm_device_types import (
APT_HISTORY_COMMAND,
AptHistoryMixin,
AptHistoryUnreadable,
apt_history_command,
host_zone,
parse_apt_history,
)
from napalm_device_types.channel import CommandResult
def _utc(text: str) -> int:
return int(datetime.strptime(text, "%Y-%m-%d %H:%M:%S").replace(tzinfo=UTC).timestamp())
CURRENT = """
Start-Date: 2026-11-26 10:00:00
Commandline: apt-get -y upgrade
Requested-By: admin (1000)
Install: linux-image-6.12.57+deb13-amd64:amd64 (6.12.57-1, automatic), linux-headers-6.12.57+deb13-common:all (6.12.57-1, automatic), htop:amd64 (3.4.1-5)
Upgrade: openssh-server:amd64 (1:10.0p1-7, 1:10.0p1-7+deb13u1), libssl3t64:amd64 (3.5.1-1, 3.5.1-1+deb13u1), libssl3t64:i386 (3.5.1-1, 3.5.1-1+deb13u1)
End-Date: 2026-11-26 10:01:00
Start-Date: 2026-11-26 10:01:00
Commandline: /usr/bin/apt remove wazuh-agent
Remove: wazuh-agent:amd64 (4.14.8-1)
Error: Sub-process /usr/bin/dpkg returned an error code (1)
End-Date: 2026-11-26 10:01:00
Start-Date: 2026-11-26 10:01:00
Commandline: /usr/bin/apt purge wazuh-agent
Purge: wazuh-agent:amd64 (4.14.8-1), linux-image-6.12.48+deb13-amd64:amd64 ()
End-Date: 2026-11-26 10:01:00
Start-Date: 2026-11-26 10:05:13
Commandline: /usr/bin/unattended-upgrade
Upgrade: tzdata:all (2025b-4, 2025b-4+deb13u1)
"""
ROTATED = """
Start-Date: 2026-07-14 03:12:40
Commandline: apt-get install --reinstall libvulkan1
Requested-By: admin (1000)
Reinstall: libvulkan1:amd64 (1.4.309.0-1), libvulkan1:i386 (1.4.309.0-1)
End-Date: 2026-07-14 03:12:41
Start-Date: 2026-07-14 03:13:05
Commandline: apt-get install pve-manager=9.0.10
Downgrade: pve-manager:amd64 (9.0.11, 9.0.10)
Disappeared: libfoo1 (1.2-3), libbar0
End-Date: 2026-07-14 03:13:20
"""
OLDEST = """
Start-Date: 2026-01-12 06:25:01
Commandline: apt-get dist-upgrade
Remove: caribou (0.4.21-9)
End-Date: 2026-01-12 06:25:30
"""
def _report(files: dict[str, str], zone: str = "/usr/share/zoneinfo/Europe/Berlin") -> str:
"""What :data:`APT_HISTORY_COMMAND` prints for *files* (path -> content)."""
lines = [f"### apt-history zone {zone}", "### apt-history offset +0100"]
for path, content in files.items():
lines += [f"### apt-history file {path}", content, "", "### apt-history status 0"]
return "\n".join([*lines, "### apt-history end", ""])
LOGS = {
"/var/log/apt/history.log": CURRENT,
"/var/log/apt/history.log.1.gz": ROTATED,
"/var/log/apt/history.log.10.gz": OLDEST,
}
class TestParse:
def test_newest_first_over_every_file(self):
ids = [t["id"] for t in parse_apt_history(_report(LOGS))]
assert ids == [
f"{_utc('2026-11-26 09:05:13')}-0",
f"{_utc('2026-11-26 09:01:00')}-1",
f"{_utc('2026-11-26 09:01:00')}-0",
f"{_utc('2026-11-26 09:00:00')}-0",
f"{_utc('2026-07-14 01:13:05')}-0",
f"{_utc('2026-07-14 01:12:40')}-0",
f"{_utc('2026-01-12 05:25:01')}-0",
]
def test_a_transaction_with_its_packages(self):
upgrade = parse_apt_history(_report(LOGS))[3]
assert upgrade == {
"id": f"{_utc('2026-11-26 09:00:00')}-0",
"start": _utc("2026-11-26 09:00:00"),
"end": _utc("2026-11-26 09:01:00"),
"packages": [
{
"name": "linux-image-6.12.57+deb13-amd64",
"action": "install",
"old_version": None,
"new_version": "6.12.57-1",
},
{
"name": "linux-headers-6.12.57+deb13-common",
"action": "install",
"old_version": None,
"new_version": "6.12.57-1",
},
{
"name": "htop",
"action": "install",
"old_version": None,
"new_version": "3.4.1-5",
},
{
"name": "openssh-server",
"action": "upgrade",
"old_version": "1:10.0p1-7",
"new_version": "1:10.0p1-7+deb13u1",
},
{
"name": "libssl3t64",
"action": "upgrade",
"old_version": "3.5.1-1",
"new_version": "3.5.1-1+deb13u1",
},
{
"name": "libssl3t64",
"action": "upgrade",
"old_version": "3.5.1-1",
"new_version": "3.5.1-1+deb13u1",
},
],
"requested_by": "admin",
"command": "apt-get -y upgrade",
"error": None,
}
def test_the_error_a_run_ended_with(self):
failed = parse_apt_history(_report(LOGS))[2]
assert failed["error"] == "Sub-process /usr/bin/dpkg returned an error code (1)"
assert failed["requested_by"] is None
assert failed["packages"] == [
{
"name": "wazuh-agent",
"action": "remove",
"old_version": "4.14.8-1",
"new_version": None,
}
]
def test_a_purge_of_what_was_removed_before_had_no_version(self):
purge = parse_apt_history(_report(LOGS))[1]
assert [(p["name"], p["action"], p["old_version"]) for p in purge["packages"]] == [
("wazuh-agent", "purge", "4.14.8-1"),
("linux-image-6.12.48+deb13-amd64", "purge", None),
]
def test_a_run_without_end_is_running_or_interrupted(self):
newest = parse_apt_history(_report(LOGS))[0]
assert newest["end"] is None
assert newest["command"] == "/usr/bin/unattended-upgrade"
def test_reinstall_downgrade_disappeared_and_arch_less_names(self):
history = parse_apt_history(_report(LOGS))
downgrade, reinstall, oldest = history[4], history[5], history[6]
assert [(p["name"], p["old_version"], p["new_version"]) for p in reinstall["packages"]] == [
("libvulkan1", "1.4.309.0-1", "1.4.309.0-1"),
("libvulkan1", "1.4.309.0-1", "1.4.309.0-1"),
]
assert [
(p["action"], p["name"], p["old_version"], p["new_version"])
for p in downgrade["packages"]
] == [
("downgrade", "pve-manager", "9.0.11", "9.0.10"),
("disappear", "libfoo1", "1.2-3", None),
("disappear", "libbar0", None, None),
]
assert oldest["packages"] == [
{"name": "caribou", "action": "remove", "old_version": "0.4.21-9", "new_version": None}
]
def test_summer_time_is_the_zones(self):
reinstall = parse_apt_history(_report(LOGS))[5]
assert reinstall["start"] == _utc("2026-07-14 01:12:40") # CEST, UTC+2
def test_since_filters_by_start_and_keeps_the_ids(self):
since = _utc("2026-11-26 09:01:00")
ids = [t["id"] for t in parse_apt_history(_report(LOGS), since=since)]
assert ids == [f"{_utc('2026-11-26 09:05:13')}-0", f"{since}-1", f"{since}-0"]
def test_nothing_logged_is_an_empty_list(self):
assert parse_apt_history(_report({})) == []
assert parse_apt_history(_report({"/var/log/apt/history.log": ""})) == []
def test_the_index_is_counted_per_file(self):
same = "\nStart-Date: 2026-11-26 10:00:00\nInstall: htop:amd64 (3.4.1-5)\nEnd-Date: 2026-11-26 10:00:00\n"
history = parse_apt_history(
_report({"/var/log/apt/history.log": same * 2, "/var/log/apt/history.log.1.gz": same})
)
start = _utc("2026-11-26 09:00:00")
assert [t["id"] for t in history] == [f"{start}-1", f"{start}-0", f"{start}-0"]
class TestStrict:
@pytest.mark.parametrize(
"line",
[
"Upgrade: openssh-server:amd64 (1:10.0p1-7)", # an upgrade names old and new
"Install: htop:amd64 (3.4.1-5, manual)",
"Remove: htop:amd64 (3.4.1-5), ",
"Install: htop:amd64 (3.4.1-5", # cut short
"Upgrade: htop:amd64 (, 3.4.1-5)",
"Disappeared: libfoo1 (1.2-3) (1.2-4)",
"a line apt never writes",
],
)
def test_a_malformed_block_is_left_out_but_counted(self, line):
log = (
f"Start-Date: 2026-11-26 10:00:00\n{line}\nEnd-Date: 2026-11-26 10:00:01\n\n"
"Start-Date: 2026-11-26 10:00:00\nInstall: htop:amd64 (3.4.1-5)\n"
"End-Date: 2026-11-26 10:00:02\n"
)
history = parse_apt_history(_report({"/var/log/apt/history.log": log}))
assert [t["id"] for t in history] == [f"{_utc('2026-11-26 09:00:00')}-1"]
def test_an_unreadable_date_is_no_transaction(self):
log = (
"Start-Date: yesterday\nInstall: htop:amd64 (3.4.1-5)\n\n"
"Start-Date: 2026-11-26 10:00:00\nInstall: htop:amd64 (3.4.1-5)\n"
"End-Date: soon\n"
)
assert parse_apt_history(_report({"/var/log/apt/history.log": log})) == []
def test_lines_before_the_first_block_are_ignored(self):
log = "Install: htop:amd64 (3.4.1-5)\n" + OLDEST
assert len(parse_apt_history(_report({"/var/log/apt/history.log": log}))) == 1
def test_a_report_cut_short_raises(self):
with pytest.raises(ValueError, match="cut short"):
parse_apt_history(_report(LOGS).replace("### apt-history end\n", ""))
def test_a_file_that_could_not_be_read_raises(self):
report = _report(LOGS).replace("status 0", "status 1", 1)
with pytest.raises(ValueError, match="exit 1"):
parse_apt_history(report)
def test_a_file_the_user_may_not_read_raises(self):
report = _report(LOGS).replace(
"### apt-history end",
"### apt-history unreadable /var/log/apt/history.log.2.gz\n### apt-history end",
)
with pytest.raises(AptHistoryUnreadable, match="history.log.2.gz"):
parse_apt_history(report)
def test_other_files_in_the_directory_are_not_read(self):
report = _report({**LOGS, "/var/log/apt/history.log.dpkg-old": OLDEST}).replace(
"### apt-history end",
"### apt-history unreadable /var/log/apt/history.log.bak\n### apt-history end",
)
assert len(parse_apt_history(report)) == 7
class TestZone:
def test_a_named_zone(self):
assert str(host_zone("Europe/Berlin\n", "+0100")) == "Europe/Berlin"
assert str(host_zone("/usr/share/zoneinfo/America/New_York", "-0500")) == "America/New_York"
@pytest.mark.parametrize("name", ["", "Mars/Olympus_Mons", "../../etc/passwd"])
def test_without_a_known_name_the_offset(self, name):
assert host_zone(name, "+0530") == timezone(timedelta(hours=5, minutes=30))
assert host_zone(name, "-0300\n") == timezone(-timedelta(hours=3))
def test_neither_raises(self):
with pytest.raises(ValueError, match="no time zone"):
host_zone("", "")
def test_a_host_on_its_offset_alone(self):
history = parse_apt_history(_report({"/var/log/apt/history.log": OLDEST}, zone=""))
assert history[0]["start"] == _utc("2026-01-12 05:25:01") # +0100
class TestCommand:
"""The command run for real with ``sh`` against a log directory in a temp directory."""
@staticmethod
def _run(log_dir: Path) -> str:
done = subprocess.run(
["sh", "-c", apt_history_command(str(log_dir))],
capture_output=True,
text=True,
check=True,
)
return done.stdout
@staticmethod
def _logs(log_dir: Path) -> None:
(log_dir / "history.log").write_text(CURRENT)
(log_dir / "history.log.1.gz").write_bytes(gzip.compress(ROTATED.encode()))
(log_dir / "history.log.10.gz").write_bytes(gzip.compress(OLDEST.encode()))
(log_dir / "term.log").write_text("Log started: 2026-11-26 10:00:00\n")
def test_every_file_rotated_or_not(self, tmp_path):
self._logs(tmp_path)
history = parse_apt_history(self._run(tmp_path))
# Dated in this machine's zone: the order and the fields, not the seconds.
assert len(history) == 7
assert history[0]["command"] == "/usr/bin/unattended-upgrade"
assert history[-1]["command"] == "apt-get dist-upgrade"
def test_the_zone_and_offset_are_printed(self, tmp_path):
out = self._run(tmp_path)
assert "### apt-history zone " in out
assert "### apt-history offset " in out
assert out.endswith("### apt-history end\n")
def test_no_log_is_no_transaction(self, tmp_path):
assert parse_apt_history(self._run(tmp_path / "missing")) == []
@pytest.mark.skipif(os.geteuid() == 0, reason="root reads every file")
def test_an_unreadable_file_is_named(self, tmp_path):
self._logs(tmp_path)
(tmp_path / "history.log.1.gz").chmod(0)
with pytest.raises(AptHistoryUnreadable):
parse_apt_history(self._run(tmp_path))
def test_the_constant_reads_apts_own_directory(self):
assert APT_HISTORY_COMMAND == apt_history_command("/var/log/apt")
class _Host(AptHistoryMixin):
def __init__(self, *answers: CommandResult) -> None:
self.answers = list(answers)
self.ran: list[bool] = []
def run_command(
self,
command: str,
*,
privileged: bool = False,
timeout: float = 60,
stdin: bytes | None = None,
) -> CommandResult:
assert command == APT_HISTORY_COMMAND
assert stdin is None
self.ran.append(privileged)
return self.answers.pop(0)
UNREADABLE = _report(LOGS).replace(
"### apt-history end",
"### apt-history unreadable /var/log/apt/history.log.2.gz\n### apt-history end",
)
class TestMixin:
def test_read_as_the_login_user(self):
host = _Host(CommandResult(_report(LOGS), "", 0))
assert len(host.get_update_history()) == 7
assert host.ran == [False]
def test_since_is_applied(self):
host = _Host(CommandResult(_report(LOGS), "", 0))
assert len(host.get_update_history(since=_utc("2026-11-26 09:01:00"))) == 3
def test_a_file_only_root_may_read_is_read_as_root(self):
host = _Host(CommandResult(UNREADABLE, "", 0), CommandResult(_report(LOGS), "", 0))
assert len(host.get_update_history()) == 7
assert host.ran == [False, True]
def test_unreadable_even_as_root_raises(self):
host = _Host(CommandResult(UNREADABLE, "", 0), CommandResult(UNREADABLE, "", 0))
with pytest.raises(AptHistoryUnreadable):
host.get_update_history()
def test_a_failed_run_raises(self):
host = _Host(
CommandResult(UNREADABLE, "", 0),
CommandResult("", "sudo: a password is required", 1),
)
with pytest.raises(RuntimeError, match="password is required"):
host.get_update_history()
+391
View File
@@ -0,0 +1,391 @@
"""get_hardening: how a Linux host is hardened, as the kernel and the host's tools say it.
The security modules in force (``/sys/kernel/security/lsm``, SELinux's mode, AppArmor's
profiles), the system-wide crypto policy and FIPS mode, what the kernel reports for each
known CPU vulnerability, and the command line it booted with (NetOrk/netork#2706). One
read-only command, the same on every Linux host, so it lives here once and a driver only
carries it across. Root only adds AppArmor's profile counts.
"""
from __future__ import annotations
import json
import os
import subprocess
import pytest
from napalm_device_types import OSDriver
from napalm_device_types.hardening import (
HARDENING_COMMAND,
HardeningMixin,
cpu_vulnerability_state,
parse_hardening,
)
#: AlmaLinux 9 on a KVM guest: SELinux enforcing, the DEFAULT policy, no FIPS.
ALMA_9 = [
("lsm", "lockdown,capability,yama,selinux,bpf"),
("cmdline", "BOOT_IMAGE=(hd0,gpt2)/vmlinuz-5.14.0-503.el9.x86_64 root=/dev/vda4 ro"),
("fips", "0"),
("os", 'ID="almalinux"\nID_LIKE="rhel centos fedora"'),
("selinux", "Enforcing"),
("selinux_config", "SELINUX=enforcing"),
("crypto_policy", "DEFAULT"),
(
"cpu_vulnerabilities",
"/sys/devices/system/cpu/vulnerabilities/meltdown:Not affected\n"
"/sys/devices/system/cpu/vulnerabilities/spec_rstack_overflow:Mitigation: Safe RET\n"
"/sys/devices/system/cpu/vulnerabilities/spectre_v1:Mitigation: usercopy/swapgs "
"barriers and __user pointer sanitization\n"
"/sys/devices/system/cpu/vulnerabilities/spectre_v2:Mitigation: Retpolines; IBPB: "
"conditional; IBRS_FW; STIBP: always-on; RSB filling; PBRSB-eIBRS: Not affected; "
"BHI: Not affected\n"
"/sys/devices/system/cpu/vulnerabilities/mmio_stale_data:Unknown: No mitigations",
),
]
AA_STATUS = {
"version": "2",
"profiles": {
"/snap/snapd/21759/usr/lib/snapd/snap-confine": "enforce",
"lsb_release": "enforce",
"rsyslogd": "enforce",
"unprivileged_userns": "enforce",
"ubuntu_pro_apt_news": "complain",
"Discord": "unconfined",
},
"processes": {
"/usr/sbin/rsyslogd": [{"profile": "rsyslogd", "pid": "812", "status": "enforce"}]
},
}
#: Ubuntu 24.04, read as root: AppArmor with its profiles, no crypto-policies, no SELinux.
UBUNTU_2404 = [
("lsm", "lockdown,capability,landlock,yama,apparmor,ima,evm"),
("cmdline", "BOOT_IMAGE=/vmlinuz-6.8.0-49-generic root=/dev/mapper/vg-root ro quiet splash"),
("fips", "0"),
("apparmor_enabled", "Y"),
("os", "ID=ubuntu\nID_LIKE=debian"),
(
"cpu_vulnerabilities",
"/sys/devices/system/cpu/vulnerabilities/meltdown:Not affected\n"
"/sys/devices/system/cpu/vulnerabilities/spectre_v2:Mitigation: Enhanced / Automatic "
"IBRS; IBPB: conditional; RSB filling; PBRSB-eIBRS: SW sequence; BHI: BHI_DIS_S",
),
("aa_status", json.dumps(AA_STATUS)),
]
#: Debian 12 booted with mitigations=off.
MITIGATIONS_OFF = [
("lsm", "lockdown,capability,landlock,yama,apparmor,tomoyo"),
("cmdline", "BOOT_IMAGE=/boot/vmlinuz-6.1.0-25-amd64 root=UUID=1b2c ro quiet mitigations=off"),
("apparmor_enabled", "Y"),
("os", "ID=debian"),
(
"cpu_vulnerabilities",
"/sys/devices/system/cpu/vulnerabilities/meltdown:Vulnerable\n"
"/sys/devices/system/cpu/vulnerabilities/mds:Vulnerable; SMT vulnerable\n"
"/sys/devices/system/cpu/vulnerabilities/spectre_v1:Vulnerable: __user pointer "
"sanitization and usercopy barriers only; no swapgs barriers\n"
"/sys/devices/system/cpu/vulnerabilities/spectre_v2:Vulnerable; IBPB: disabled; "
"STIBP: disabled; PBRSB-eIBRS: Vulnerable; BHI: Vulnerable",
),
("aa_status", ""),
]
def _wire(sections: list[tuple[str, str]], *, noise: str = "") -> str:
"""The report as the command prints it, framed."""
body = "".join(f"[{name}]\n{text}\n" for name, text in sections)
return f"{noise}HARDENING_BEGIN\n{body}HARDENING_END\n"
class TestTheFixtures:
def test_alma_9_selinux_enforcing_default_policy(self):
reading = parse_hardening(_wire(ALMA_9))
assert reading == {
"lsm": ["lockdown", "capability", "yama", "selinux", "bpf"],
"selinux": {"mode": "enforcing", "configured": "enforcing"},
"apparmor": None,
"crypto_policy": "DEFAULT",
"fips": False,
"cpu_vulnerabilities": {
"meltdown": "Not affected",
"mmio_stale_data": "Unknown: No mitigations",
"spec_rstack_overflow": "Mitigation: Safe RET",
"spectre_v1": "Mitigation: usercopy/swapgs barriers and __user pointer "
"sanitization",
"spectre_v2": "Mitigation: Retpolines; IBPB: conditional; IBRS_FW; STIBP: "
"always-on; RSB filling; PBRSB-eIBRS: Not affected; BHI: Not affected",
},
"cmdline": "BOOT_IMAGE=(hd0,gpt2)/vmlinuz-5.14.0-503.el9.x86_64 root=/dev/vda4 ro",
"mitigations": "auto",
"nosmt": False,
"os_ids": ["almalinux", "rhel", "centos", "fedora"],
}
def test_ubuntu_24_04_apparmor_with_its_profiles(self):
reading = parse_hardening(_wire(UBUNTU_2404))
assert reading["selinux"] is None
assert reading["apparmor"] == {
"enabled": True,
"profiles": {"complain": 1, "enforce": 4, "unconfined": 1},
}
assert reading["crypto_policy"] is None
assert reading["os_ids"] == ["ubuntu", "debian"]
def test_mitigations_off(self):
reading = parse_hardening(_wire(MITIGATIONS_OFF))
assert reading["mitigations"] == "off"
assert reading["nosmt"] is False
assert {cpu_vulnerability_state(v) for v in reading["cpu_vulnerabilities"].values()} == {
"vulnerable"
}
def test_apparmor_without_root_has_no_profile_counts(self):
"""``aa-status`` needs root: without it the profiles are unread, never zero."""
reading = parse_hardening(_wire(MITIGATIONS_OFF))
assert reading["apparmor"] == {"enabled": True, "profiles": None}
class TestNotReadIsNone:
def test_a_section_never_printed_is_none(self):
"""``None`` is "could not read": an old kernel without the ``lsm`` file, a
host without ``update-crypto-policies``."""
reading = parse_hardening(_wire([]))
assert reading == {
"lsm": None,
"selinux": None,
"apparmor": None,
"crypto_policy": None,
"fips": None,
"cpu_vulnerabilities": None,
"cmdline": None,
"mitigations": None,
"nosmt": None,
"os_ids": None,
}
def test_an_empty_vulnerabilities_directory_is_read_and_empty(self):
reading = parse_hardening(_wire([("cpu_vulnerabilities", "")]))
assert reading["cpu_vulnerabilities"] == {}
def test_output_without_the_frame_raises(self):
with pytest.raises(ValueError):
parse_hardening("sudo: a password is required\n")
def test_whatever_surrounds_the_frame_is_ignored(self):
noise = "Last login: today\nprintf '%s%s\\n' HARDENING_ BEGIN; ...\n"
assert parse_hardening(_wire(ALMA_9, noise=noise))["crypto_policy"] == "DEFAULT"
def test_aa_status_output_that_is_not_json_is_unread(self):
reading = parse_hardening(
_wire([("apparmor_enabled", "Y"), ("aa_status", "apparmor not present.")])
)
assert reading["apparmor"] == {"enabled": True, "profiles": None}
class TestSelinux:
def test_getenforce_permissive(self):
reading = parse_hardening(_wire([("selinux", "Permissive")]))
assert reading["selinux"] == {"mode": "permissive", "configured": None}
def test_disabled_by_getenforce(self):
reading = parse_hardening(
_wire([("selinux", "Disabled"), ("selinux_config", "SELINUX=disabled")])
)
assert reading["selinux"] == {"mode": "disabled", "configured": "disabled"}
@pytest.mark.parametrize("value, mode", [("1", "enforcing"), ("0", "permissive")])
def test_without_getenforce_the_enforce_file_answers(self, value, mode):
reading = parse_hardening(_wire([("selinux_enforce", value)]))
assert reading["selinux"]["mode"] == mode
def test_configured_but_not_among_the_active_modules_is_disabled(self):
"""The policy is installed (``/etc/selinux/config``), the kernel runs without it."""
reading = parse_hardening(
_wire([("lsm", "capability,yama"), ("selinux_config", 'SELINUX="enforcing"')])
)
assert reading["selinux"] == {"mode": "disabled", "configured": "enforcing"}
def test_configured_without_a_list_of_modules_is_unknown(self):
reading = parse_hardening(_wire([("selinux_config", "SELINUX=enforcing")]))
assert reading["selinux"] == {"mode": None, "configured": "enforcing"}
class TestSelinuxParts:
"""The three questions the SELinux part answers, each on its own (napalm-standard's
complexity limit): the mode it boots in, the mode it runs in, and whether the
host has SELinux at all."""
def test_the_configured_mode_is_the_last_selinux_line(self):
from napalm_device_types.hardening import _selinux_configured
lines = ["SELINUXTYPE=targeted", 'SELINUX="Permissive"']
assert _selinux_configured({"selinux_config": lines}) == "permissive"
assert _selinux_configured({"selinux_config": ["SELINUX="]}) is None
assert _selinux_configured({}) is None
@pytest.mark.parametrize(
"sections, mode",
[
({"selinux": ["Enforcing"]}, "enforcing"),
({"selinux": ["something else"], "selinux_enforce": ["0"]}, "permissive"),
({"selinux_enforce": ["1"]}, "enforcing"),
({"selinux_enforce": ["2"]}, None),
({}, None),
],
)
def test_the_running_mode_getenforce_first(self, sections, mode):
from napalm_device_types.hardening import _selinux_running
assert _selinux_running(sections) == mode
@pytest.mark.parametrize(
"sections, lsm, seen",
[
({}, ["capability", "selinux"], True),
({"selinux_config": []}, None, True),
({}, ["capability", "apparmor"], False),
({}, None, False),
],
)
def test_whether_the_host_has_it(self, sections, lsm, seen):
from napalm_device_types.hardening import _selinux_seen
assert _selinux_seen(sections, lsm, None) is seen
assert _selinux_seen(sections, lsm, "enforcing") is True
class TestAppArmor:
def test_in_the_list_of_modules_without_the_parameter_file(self):
reading = parse_hardening(_wire([("lsm", "capability,apparmor")]))
assert reading["apparmor"] == {"enabled": True, "profiles": None}
def test_switched_off(self):
reading = parse_hardening(_wire([("lsm", "capability"), ("apparmor_enabled", "N")]))
assert reading["apparmor"] == {"enabled": False, "profiles": None}
class TestCommandLine:
@pytest.mark.parametrize(
"cmdline, mitigations, nosmt",
[
("ro quiet", "auto", False),
("ro mitigations=off", "off", False),
("ro mitigations=auto,nosmt", "auto,nosmt", True),
("ro nosmt", "auto", True),
("ro nosmt=force", "auto", True),
("ro mitigations=auto mitigations=off", "off", False),
],
)
def test_mitigations_and_smt(self, cmdline, mitigations, nosmt):
"""The last ``mitigations=`` wins, as in the kernel; ``nosmt`` comes alone or
with ``mitigations=auto,nosmt``."""
reading = parse_hardening(_wire([("cmdline", cmdline)]))
assert (reading["mitigations"], reading["nosmt"]) == (mitigations, nosmt)
class TestCryptoPolicy:
def test_a_subpolicy_is_kept(self):
reading = parse_hardening(_wire([("crypto_policy", "LEGACY:AD-SUPPORT"), ("fips", "1")]))
assert (reading["crypto_policy"], reading["fips"]) == ("LEGACY:AD-SUPPORT", True)
def test_no_output_is_unread(self):
assert parse_hardening(_wire([("crypto_policy", "")]))["crypto_policy"] is None
class TestCpuVulnerabilityState:
@pytest.mark.parametrize(
"text, state",
[
("Not affected", "not_affected"),
("Mitigation: Retpolines; IBPB: conditional", "mitigated"),
("KVM: Mitigation: VMX disabled", "mitigated"),
(
"Mitigation: PTE Inversion; VMX: conditional cache flushes, SMT vulnerable",
"mitigated",
),
("Vulnerable", "vulnerable"),
("Vulnerable: Clear CPU buffers attempted, no microcode; SMT vulnerable", "vulnerable"),
("Processor vulnerable", "vulnerable"),
("Unknown: Dependent on hypervisor status", "unknown"),
("", "unknown"),
],
)
def test_the_kernels_words(self, text, state):
assert cpu_vulnerability_state(text) == state
class _Driver(OSDriver, HardeningMixin):
def __init__(self, outputs):
self.outputs = list(outputs)
self.calls: list[tuple[str, bool]] = []
def _run_hardening_command(self, command: str, *, privileged: bool) -> str:
self.calls.append((command, privileged))
return self.outputs.pop(0)
class TestTheMixin:
def test_read_as_root_first(self):
driver = _Driver([_wire(UBUNTU_2404)])
reading = driver.get_hardening()
assert driver.calls[0][1] is True
assert reading["apparmor"]["profiles"]["enforce"] == 4
def test_root_refused_reads_as_the_login_user(self):
driver = _Driver(["sudo: a password is required\n", _wire(MITIGATIONS_OFF)])
reading = driver.get_hardening()
assert [privileged for _, privileged in driver.calls] == [True, False]
assert reading["mitigations"] == "off"
def test_the_command_goes_to_sh(self):
driver = _Driver([_wire(ALMA_9)])
driver.get_hardening()
assert driver.calls[0][0].startswith("sh -c ")
class TestTheCommand:
def test_the_frame_is_not_in_the_command_itself(self):
assert "HARDENING_BEGIN" not in HARDENING_COMMAND
assert "HARDENING_END" not in HARDENING_COMMAND
def test_it_changes_nothing(self):
for verb in ("setenforce", "--set", "aa-enforce", "aa-complain", " > ", ">>", "sudo"):
assert verb not in HARDENING_COMMAND
@pytest.mark.skipif(os.uname().sysname != "Linux", reason="reads a Linux host")
def test_it_runs_and_parses_on_this_host(self):
out = subprocess.run(
["sh", "-c", HARDENING_COMMAND], capture_output=True, text=True, timeout=60
).stdout
reading = parse_hardening(out)
assert reading["cmdline"] is not None
assert reading["mitigations"] is not None
+29
View File
@@ -0,0 +1,29 @@
"""A radio's runtime state beside its configuration (NetOrk/netork#31).
A radio can be enabled in the configuration and still not run: the 2026-07-16
incident put every radio of a fleet into a restart loop that the configuration
never showed. The state the device reports is three facts, each optional,
because a driver that cannot read it leaves it out rather than guessing.
"""
from __future__ import annotations
from typing import get_type_hints
from napalm_device_types.models import RadioStatusDict
RUNTIME = {"up", "pending", "setup_failed"}
def test_a_radio_may_say_whether_it_runs():
hints = get_type_hints(RadioStatusDict)
assert RUNTIME <= set(hints)
assert all(hints[key] is bool for key in RUNTIME)
def test_the_runtime_state_is_optional():
assert RUNTIME <= RadioStatusDict.__optional_keys__
def test_the_configured_fields_stay_required():
assert {"enabled", "band", "channel"} <= RadioStatusDict.__required_keys__
+29
View File
@@ -115,6 +115,35 @@ class TestTheMapsScan:
assert reading == {"source": "maps", "units": [], "processes": []}
@pytest.mark.parametrize(
"cgroup",
[
# Proxmox VE: the container's own systemd, under lxc/<vmid>/ns.
"0::/lxc/101/ns/system.slice/nginx.service",
"0::/lxc/101/ns/init.scope",
# LXC 4 and later by default.
"0::/lxc.payload.web/system.slice/nginx.service",
# cgroup v1, systemd's hierarchy.
"12:name=systemd:/lxc/web/system.slice/nginx.service",
],
)
def test_an_lxc_container_is_left_out(self, cgroup):
"""A Proxmox node's containers update themselves: the host sees their processes'
mappings, and their own systemd's units, which are no services of the host's."""
cgroups = f"2100 {cgroup}\n"
reading = parse_services_restart(_wire(("maps", "2100 nginx\n"), ("cgroups", cgroups)))
assert reading == {"source": "maps", "units": [], "processes": []}
def test_an_lxc_monitor_is_the_hosts(self):
"""``lxc-start`` runs the host's own binary, outside the container."""
reading = parse_services_restart(
_wire(("maps", "2090 lxc-start\n"), ("cgroups", "2090 0::/lxc.monitor/101\n"))
)
assert reading["processes"] == [{"pid": 2090, "name": "lxc-start"}]
def test_a_process_gone_before_its_cgroup_was_read_has_no_unit(self):
reading = parse_services_restart(_wire(("maps", "4242 cron\n"), ("cgroups", "")))