Compare commits

..
Author SHA1 Message Date
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 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 ddc9316fb5 Merge pull request 'feat(services-restart): the services that still run replaced code (NetOrk/netork#2700)' (#132) from feature/services-need-restart into main
driver / types (push) Successful in 1m6s
driver / standard (push) Successful in 21s
driver / lint (push) Successful in 17s
driver / test (3.12) (push) Successful in 1m31s
driver / test (3.13) (push) Successful in 1m19s
driver / lowest (push) Successful in 51s
driver / build (push) Successful in 33s
driver / security (push) Successful in 1m6s
driver / publish (push) Successful in 32s
CI / driver (push) Successful in 3m44s
2026-11-26 18:31:38 +00: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 a38f07513f chore(release): 4.45.0
driver / lint (pull_request) Successful in 14s
driver / standard (pull_request) Successful in 18s
driver / types (pull_request) Successful in 59s
driver / test (3.13) (pull_request) Successful in 1m16s
driver / test (3.12) (pull_request) Successful in 1m20s
driver / lowest (pull_request) Successful in 41s
driver / build (pull_request) Successful in 33s
driver / security (pull_request) Successful in 1m10s
CI / driver (pull_request) Successful in 2m44s
driver / publish (pull_request) Skipped
2026-11-26 19:24:36 +01:00
christianmanivong ddcd9ebc0a Merge remote-tracking branch 'origin/main' into feature/services-need-restart
# Conflicts:
#	CHANGELOG.md
2026-11-26 19:24:17 +01:00
christianmanivong 494b9ed046 refactor(services-restart): its shapes live in its own module, within the quality ratchet
driver / standard (pull_request) Successful in 19s
driver / lint (pull_request) Successful in 15s
driver / types (pull_request) Successful in 1m8s
driver / test (3.13) (pull_request) Successful in 1m26s
driver / test (3.12) (pull_request) Successful in 1m30s
driver / lowest (pull_request) Successful in 46s
driver / build (pull_request) Successful in 32s
driver / security (pull_request) Successful in 1m7s
CI / driver (pull_request) Successful in 2m56s
driver / publish (pull_request) Skipped
models.py had grown past its recorded size; ServicesRestartDict and
RestartProcessDict move to services_restart, exported from the package.
2026-11-26 19:06:23 +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
christianmanivong 5517464e1f chore(release): 4.44.0
driver / lint (pull_request) Successful in 17s
driver / standard (pull_request) Failing after 20s
driver / types (pull_request) Successful in 1m1s
driver / test (3.13) (pull_request) Successful in 1m14s
driver / test (3.12) (pull_request) Successful in 1m23s
driver / lowest (pull_request) Successful in 37s
driver / build (pull_request) Successful in 30s
driver / security (pull_request) Successful in 1m2s
CI / driver (pull_request) Failing after 2m36s
driver / publish (pull_request) Skipped
2026-11-26 17:39:04 +01:00
christianmanivong 9c889f3715 feat(services-restart): the services that still run replaced code (NetOrk/netork#2700)
ServicesRestartMixin.get_services_need_restart reads, as root and in one
fixed read-only command, which systemd services still run code an update
replaced on disk: needs-restarting -s on the dnf family, else needrestart
in batch list-only mode (-r l and NEEDRESTART_MODE=l, whatever its config
says), else the processes whose /proc/<pid>/maps maps deleted code, each
named by its cgroup's service as the listening sockets are. A refused root
raises instead of reading clean.
2026-11-26 17:39:04 +01:00
9 changed files with 1384 additions and 1 deletions

No files matched your search

+45
View File
@@ -7,6 +7,51 @@ recorded here; their history is the git log.
## [Unreleased]
## [4.48.0] - 2026-11-26
### 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.46.0] - 2026-11-26
### Fixed
- `get_services_need_restart()` leaves an LXC container's processes out of the `/proc` scan,
as it does Docker's and Podman's (NetOrk/netork#2750). On a Proxmox VE node a container
updates itself, and its own systemd's units (`/lxc/<vmid>/ns/system.slice/nginx.service`)
read as host services that need a restart. Left out: `/lxc/<name>/` (Proxmox VE, cgroup v1)
and `/lxc.payload.<name>/` (LXC 4 and later); `/lxc.monitor/<name>` still counts, since
`lxc-start` runs the host's binary.
## [4.45.0] - 2026-11-26
### Added
- `ServicesRestartMixin.get_services_need_restart()`: the systemd services that still run
code an update replaced on disk, so they keep the old library until they restart
(NetOrk/netork#2700). One fixed, read-only command as root: `needs-restarting -s` (the dnf
family), else `needrestart -b -r l` (Debian, Ubuntu; list only, by option and by
`NEEDRESTART_MODE=l`, whatever `needrestart.conf` says), else a scan of
`/proc/<pid>/maps` for executable mappings of deleted files under `/usr`, `/lib*`, `/bin`,
`/sbin` or `/opt`, each process mapped to its service through `/proc/<pid>/cgroup` as the
listening sockets do. A user's own systemd counts as `user@<uid>`, a container's process is
left out, and a process in no service is listed under `processes`. A refused root gives
no report and raises, never a clean reading. A driver supplies
`_run_services_restart_command(command)`.
- `parse_services_restart`, `SERVICES_RESTART_COMMAND`, `DELETED_CODE_PATTERN`, and the
`ServicesRestartDict` and `RestartProcessDict` shapes (in `services_restart`).
## [4.44.0] - 2026-11-26
### Added
+22
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
@@ -208,6 +219,17 @@ without `ss` is read with `netstat -lntup` (OpenWrt's busybox, old net-tools); o
cgroup names the procd service (`/services/<name>/<instance>`). A host with neither raises
`ListeningSocketsUnavailable`.
`ServicesRestartMixin` (`get_services_need_restart`) is mixed in the same way: the systemd
services that still run code an update replaced on disk -- an openssl or glibc update is not
finished until they restart. One fixed, read-only command, as root: `needs-restarting -s`
where dnf-utils has it, else `needrestart -b -r l` (list only, whatever `needrestart.conf`
says), else the processes whose `/proc/<pid>/maps` maps deleted code
(`DELETED_CODE_PATTERN`), each named by the service its cgroup gives, as for the listening
sockets. A container's processes are left out, an LXC container's as well (a Proxmox node's
containers update themselves). A driver supplies `_run_services_restart_command(command)`; the command arrives as
one `sh -c` argument and reads no stdin. Without root there is no reading: one that saw only
the login user's processes would read as clean.
`LogSourcesMixin` (`get_log_sources`) is mixed in the same way: every log the host writes, in
one round trip. The units journald holds entries for (`journalctl -F _SYSTEMD_UNIT`, services
only), the log files running processes hold open (`/proc/<pid>/fd`: `*.log`, `*.log.N` and
+1
View File
@@ -156,6 +156,7 @@ the driver.
| `package_managers` | rpm, dnf and yum history, apk's and opkg's databases, `/proc/<pid>/comm` |
| `kernel` | `/proc`, `/lib/modules`, gzip, base64 |
| `listening` | `ss`, `netstat`, `/proc/<pid>/cgroup` |
| `services_restart` | `needs-restarting`, `needrestart`, `/proc/<pid>/maps` and `cgroup` |
| `systemd` | `systemctl` |
| `virtual_ips` | vip-manager, keepalived, awk |
| `system_identity` | SMBIOS via sysfs and `dmidecode` |
+26
View File
@@ -44,6 +44,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`
@@ -61,6 +62,7 @@ instead of being restated on every role that happens to need it:
* :class:`~napalm_device_types.running_backups.RunningBackupsMixin`
* :class:`~napalm_device_types.service_clusters.ServiceClustersMixin`
* :class:`~napalm_device_types.service_packages.ServicePackagesMixin`
* :class:`~napalm_device_types.services_restart.ServicesRestartMixin`
* :class:`~napalm_device_types.ssh_server_auth.SshServerAuthMixin`
* :class:`~napalm_device_types.sudo_history.SudoHistoryMixin`
* :class:`~napalm_device_types.scheduled_jobs.ScheduledJobsMixin`
@@ -162,6 +164,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,
@@ -306,6 +315,13 @@ from napalm_device_types.service_packages import (
parse_service_packages,
)
from napalm_device_types.services import ServiceControlMixin
from napalm_device_types.services_restart import (
SERVICES_RESTART_COMMAND,
RestartProcessDict,
ServicesRestartDict,
ServicesRestartMixin,
parse_services_restart,
)
from napalm_device_types.snmp_health_profile import (
SnmpHealthProfile,
SnmpInterfacesSpec,
@@ -533,7 +549,17 @@ __all__ = [
"KernelFactsMixin",
"KERNEL_FACTS_COMMAND",
"parse_kernel_facts",
"HARDENING_COMMAND",
"HardeningMixin",
"HardeningDict",
"cpu_vulnerability_state",
"parse_hardening",
"SERVICE_PACKAGES_COMMAND",
"SERVICES_RESTART_COMMAND",
"ServicesRestartMixin",
"ServicesRestartDict",
"RestartProcessDict",
"parse_services_restart",
"ServicePackagesMixin",
"parse_service_packages",
"LISTENING_SOCKETS_COMMAND",
+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))
+223
View File
@@ -0,0 +1,223 @@
"""Services that still run replaced code: what an update did not finish without a restart.
An upgrade of openssl or glibc replaces the files on disk. Every daemon that had
them loaded keeps running the old code, vulnerable or not, until it restarts
(NetOrk/netork#2700). Whether the *host* needs a reboot is
:mod:`napalm_device_types.host_status`'s; this asks which *services* need a restart.
It is read the same way on every Linux host, so the command and its parse live
here once, and a driver only carries the command across.
**Three sources, in this order:**
- ``needs-restarting -s`` (dnf-utils, the dnf family): the services it names.
- ``needrestart -b -r l`` (Debian, Ubuntu): batch mode, list only. ``-r l`` and
``NEEDRESTART_MODE=l`` both say so, so whatever the host's ``needrestart.conf``
asks for, this never restarts anything.
- Neither there, or both failed: every process whose ``/proc/<pid>/maps`` maps
deleted code (:data:`DELETED_CODE_PATTERN`) -- an executable mapping of a file
under ``/usr``, ``/lib*``, ``/bin``, ``/sbin`` or ``/opt`` that is gone from
disk. Shared memory, memfd and temporary files are deleted on purpose and do not
count, nor data such as the locale archive.
**Units from cgroups.** For the ``/proc`` scan, ``/proc/<pid>/cgroup`` names the
systemd service a process runs in, as for the listening sockets: a process of a
user's own systemd is that user's manager (``user@1000``), one of a container --
Docker, Podman, or LXC as on a Proxmox node -- is left out (the container runs its
own libraries, which no host update replaces, and its own systemd's units are none
of the host's services), and one in no service -- a login session, systemd itself --
is listed as a process. The host's tools name services only, so ``processes`` stays empty
for them.
**Root, or nothing.** Only root sees every process's memory. The script goes to
the host as one ``sh -c`` argument, so a ``sudo`` prefix covers all of it. A
reading without root would miss every other user's process and read as clean, so
there is none: when root is refused, no report comes back and the parse raises.
It is one fixed command, read-only, so it fits a sudoers allowlist.
"""
from __future__ import annotations
import re
from shlex import quote
from typing import TYPE_CHECKING, TypedDict
from napalm_device_types.listening import _cgroup_paths, _container, _unit
from napalm_device_types.terminal import strip_terminal_codes
class RestartProcessDict(TypedDict):
"""A process that runs replaced code and belongs to no systemd service."""
pid: int
name: str # /proc/<pid>/comm
class ServicesRestartDict(TypedDict):
"""What :meth:`ServicesRestartMixin.get_services_need_restart` read.
``units`` are the systemd services, without ".service", that still run code
an update replaced on disk; empty when none does. ``processes`` are the ones
that belong to no service (a login session, systemd itself), read only by the
``/proc`` scan; the host's own tools name services only.
"""
source: str # "needs-restarting", "needrestart" or "maps"
units: list[str]
processes: list[RestartProcessDict]
_BEGIN = "RST_BEGIN"
_END = "RST_END"
NEEDS_RESTARTING = "needs-restarting"
NEEDRESTART = "needrestart"
MAPS = "maps"
_SOURCES = (NEEDS_RESTARTING, NEEDRESTART, MAPS)
#: A line of ``/proc/<pid>/maps`` that maps deleted code: executable, from a
#: directory packages install into, and gone from disk. POSIX ERE, for ``grep -E``.
DELETED_CODE_PATTERN = (
r"^[0-9a-f]+-[0-9a-f]+ ..x. .* /(usr|lib|lib32|lib64|bin|sbin|opt)/.* \(deleted\)$"
)
#: One line, POSIX ``sh``, read-only. The frame markers are printed in two halves
#: so that a transport which echoes the command does not show them early. The
#: tools are in ``/usr/sbin`` on some systems, outside a login user's ``PATH``.
SERVICES_RESTART_COMMAND = (
"PATH=$PATH:/usr/sbin:/sbin; "
"printf '%s%s\\n' RST_ BEGIN; s=; "
"if command -v needs-restarting >/dev/null 2>&1 "
"&& o=$(needs-restarting -s 2>/dev/null); then s=needs-restarting; "
"elif command -v needrestart >/dev/null 2>&1 "
"&& o=$(NEEDRESTART_MODE=l needrestart -b -r l 2>/dev/null); then s=needrestart; fi; "
'if [ -n "$s" ]; then echo "[$s]"; printf \'%s\\n\' "$o"; else p=; '
"for d in /proc/[0-9]*; do "
f'grep -qE \'{DELETED_CODE_PATTERN}\' "$d/maps" 2>/dev/null && p="$p ${{d#/proc/}}"; '
"done; "
"echo '[maps]'; for i in $p; do "
'printf \'%s %s\\n\' "$i" "$(cat /proc/$i/comm 2>/dev/null)"; done; '
"echo '[cgroups]'; for i in $p; do "
'sed "s|^|$i |" /proc/$i/cgroup 2>/dev/null; done; fi; '
"printf '%s%s\\n' RST_ END"
)
#: A service as ``needs-restarting -s`` names it; anything else it prints is noise
#: ("Updating Subscription Management repositories.").
_SERVICE_LINE = re.compile(r"^([\w:.@\\-]+)\.service$")
_NEEDRESTART_SVC = re.compile(r"^NEEDRESTART-SVC:\s*(.+?)\s*$")
#: A process of a user's own systemd: that user's manager is what restarts it.
_USER_MANAGER = re.compile(r"/(user@\d+)\.service(?=/|$)")
#: A process inside an LXC container: ``/lxc/<name>/`` (Proxmox VE, which nests the
#: container's own cgroups under ``ns``; cgroup v1) or ``/lxc.payload.<name>/`` (LXC 4
#: and later). Not ``/lxc.monitor/<name>``: ``lxc-start`` runs the host's binary.
_LXC = re.compile(r"^/lxc(?:/|\.payload\.)[^/]+(?:/|$)")
_SERVICE_SUFFIX = ".service"
def _sections(output: str) -> dict[str, list[str]]:
lines = [line.strip() for line in strip_terminal_codes(output).splitlines()]
try:
start = lines.index(_BEGIN)
end = lines.index(_END, start)
except ValueError:
raise ValueError("no intact services restart report in the output") from None
sections: dict[str, list[str]] = {}
current: list[str] = []
for line in lines[start + 1 : end]:
if line.startswith("[") and line.endswith("]") and " " not in line:
current = sections.setdefault(line[1:-1], [])
elif line:
current.append(line)
return sections
def _without_suffix(unit: str) -> str:
return unit[: -len(_SERVICE_SUFFIX)] if unit.endswith(_SERVICE_SUFFIX) else unit
def _needs_restarting(lines: list[str]) -> list[str]:
return [m.group(1) for m in map(_SERVICE_LINE.match, lines) if m]
def _needrestart(lines: list[str]) -> list[str]:
return [_without_suffix(m.group(1)) for m in map(_NEEDRESTART_SVC.match, lines) if m]
def _process_unit(path: str | None) -> str | None:
manager = _USER_MANAGER.search(path or "")
return manager.group(1) if manager else _unit(path)
def _maps(sections: dict[str, list[str]]) -> tuple[list[str], list[RestartProcessDict]]:
paths = _cgroup_paths(sections.get("cgroups", []))
units: list[str] = []
processes: list[RestartProcessDict] = []
for line in sections.get(MAPS, []):
pid, _, name = line.partition(" ")
if not pid.isdigit():
continue
path = paths.get(int(pid))
if _container(path) or _LXC.match(path or ""):
continue
unit = _process_unit(path)
if unit:
units.append(unit)
else:
processes.append({"pid": int(pid), "name": name.strip()})
return units, sorted(processes, key=lambda p: p["pid"])
def parse_services_restart(output: str) -> ServicesRestartDict:
"""Parse what :data:`SERVICES_RESTART_COMMAND` printed.
:raises ValueError: when the output carries no intact report, or one without a source.
"""
sections = _sections(output)
source = next((s for s in _SOURCES if s in sections), None)
if source is None:
raise ValueError("the services restart report names no source")
processes: list[RestartProcessDict] = []
if source == NEEDS_RESTARTING:
units = _needs_restarting(sections[source])
elif source == NEEDRESTART:
units = _needrestart(sections[source])
else:
units, processes = _maps(sections)
return {"source": source, "units": sorted(set(units)), "processes": processes}
class ServicesRestartMixin:
"""Adds :meth:`get_services_need_restart` to a driver that can run a command on a
Linux host as root.
The template form (README, "Function classes"): the command and its parse are
the same everywhere, and a driver supplies only
:meth:`_run_services_restart_command` -- how a command reaches its host as
root. Mixed in by the drivers that can, so
``hasattr(driver, "get_services_need_restart")`` stays a truthful answer.
"""
if TYPE_CHECKING: # pragma: no cover - declared for type checkers only
def _run_services_restart_command(self, command: str) -> str:
"""Run *command* on the host as root and return what it printed. The
command is a single ``sh -c`` invocation; it reads nothing from stdin."""
...
def get_services_need_restart(self) -> ServicesRestartDict:
"""
Returns the systemd services that still run code an update replaced.
* source (string) - ``needs-restarting``, ``needrestart`` or ``maps``
* units (list of strings) - the services, without ``.service``; empty when none
* processes (list of {pid, name}) - replaced code outside any service
(``maps`` only)
Example::
{"source": "needrestart", "units": ["nginx", "ssh"], "processes": []}
:raises ValueError: if the host's output carried no intact report -- root
refused, or the command cut short.
"""
command = f"sh -c {quote(SERVICES_RESTART_COMMAND)}"
return parse_services_restart(self._run_services_restart_command(command))
+1 -1
View File
@@ -4,7 +4,7 @@ build-backend = "setuptools.build_meta"
[project]
name = "napalm-device-types"
version = "4.44.0"
version = "4.48.0"
description = "Abstract device-type base classes for NAPALM drivers"
readme = "README.md"
requires-python = ">=3.12"
+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
+334
View File
@@ -0,0 +1,334 @@
"""get_services_need_restart: which services still run the code an update replaced.
An upgrade of openssl or glibc replaces the files on disk; every daemon that had
them loaded keeps running the old code until it restarts (NetOrk/netork#2700).
The host's own tools say which: ``needs-restarting -s`` on the dnf family,
``needrestart -b`` on Debian and Ubuntu, and on a host with neither the
processes that map a deleted library (``/proc/<pid>/maps``). Each process is
then the systemd unit its cgroup names, as for the listening sockets.
"""
from __future__ import annotations
import shutil
import subprocess
import pytest
from napalm_device_types import OSDriver
from napalm_device_types.services_restart import (
DELETED_CODE_PATTERN,
SERVICES_RESTART_COMMAND,
ServicesRestartMixin,
parse_services_restart,
)
CID = "4f1c" + "0" * 60
#: One host after an openssl update: sshd, nginx (two workers), postgres and a
#: user's systemd manager still map the old library.
NEEDS_RESTARTING = """Updating Subscription Management repositories.
sshd.service
nginx.service
postgresql@16-main.service
user@1000.service
"""
NEEDRESTART = """NEEDRESTART-VER: 3.6
NEEDRESTART-KCUR: 6.8.0-87-generic
NEEDRESTART-KEXP: 6.8.0-87-generic
NEEDRESTART-KSTA: 1
NEEDRESTART-SVC: sshd.service
NEEDRESTART-SVC: nginx.service
NEEDRESTART-SVC: postgresql@16-main.service
NEEDRESTART-SVC: user@1000.service
NEEDRESTART-SESS: alice @ session #3
"""
MAPS = """700 sshd
900 nginx
901 nginx
812 postgres
1500 systemd
1501 tmux: server
1300 node_exporter
"""
CGROUPS = f"""700 0::/system.slice/sshd.service
900 0::/system.slice/nginx.service
901 0::/system.slice/nginx.service
812 0::/system.slice/system-postgresql.slice/postgresql@16-main.service
1500 0::/user.slice/user-1000.slice/user@1000.service/init.scope
1501 0::/user.slice/user-1000.slice/session-3.scope
1300 0::/system.slice/docker-{CID}.scope
"""
UNITS = ["nginx", "postgresql@16-main", "sshd", "user@1000"]
def _wire(*sections: tuple[str, str], noise: str = "") -> str:
"""The report as the command prints it, framed."""
body = "".join(f"[{name}]\n{text}" for name, text in sections)
return f"{noise}RST_BEGIN\n{body}RST_END\n"
class TestTheThreeSourcesAgree:
def test_needs_restarting(self):
reading = parse_services_restart(_wire(("needs-restarting", NEEDS_RESTARTING)))
assert reading == {"source": "needs-restarting", "units": UNITS, "processes": []}
def test_needrestart(self):
reading = parse_services_restart(_wire(("needrestart", NEEDRESTART)))
assert reading == {"source": "needrestart", "units": UNITS, "processes": []}
def test_the_maps_scan(self):
reading = parse_services_restart(_wire(("maps", MAPS), ("cgroups", CGROUPS)))
assert reading["source"] == "maps"
assert reading["units"] == UNITS
def test_the_maps_scan_names_the_processes_without_a_unit(self):
reading = parse_services_restart(_wire(("maps", MAPS), ("cgroups", CGROUPS)))
assert reading["processes"] == [{"pid": 1501, "name": "tmux: server"}]
class TestNothingToRestart:
@pytest.mark.parametrize(
"sections",
[
(("needs-restarting", ""),),
(("needrestart", "NEEDRESTART-VER: 3.6\nNEEDRESTART-KSTA: 1\n"),),
(("maps", ""), ("cgroups", "")),
],
)
def test_a_clean_reading_is_an_empty_list(self, sections):
reading = parse_services_restart(_wire(*sections))
assert reading["units"] == [] and reading["processes"] == []
class TestTheMapsScan:
def test_a_container_is_left_out(self):
"""A container runs its image's libraries, which no host update replaces."""
reading = parse_services_restart(
_wire(("maps", "1300 node_exporter\n"), ("cgroups", CGROUPS))
)
assert reading == {"source": "maps", "units": [], "processes": []}
@pytest.mark.parametrize(
"cgroup",
[
# Proxmox VE: the container's own systemd, under lxc/<vmid>/ns.
"0::/lxc/101/ns/system.slice/nginx.service",
"0::/lxc/101/ns/init.scope",
# LXC 4 and later by default.
"0::/lxc.payload.web/system.slice/nginx.service",
# cgroup v1, systemd's hierarchy.
"12:name=systemd:/lxc/web/system.slice/nginx.service",
],
)
def test_an_lxc_container_is_left_out(self, cgroup):
"""A Proxmox node's containers update themselves: the host sees their processes'
mappings, and their own systemd's units, which are no services of the host's."""
cgroups = f"2100 {cgroup}\n"
reading = parse_services_restart(_wire(("maps", "2100 nginx\n"), ("cgroups", cgroups)))
assert reading == {"source": "maps", "units": [], "processes": []}
def test_an_lxc_monitor_is_the_hosts(self):
"""``lxc-start`` runs the host's own binary, outside the container."""
reading = parse_services_restart(
_wire(("maps", "2090 lxc-start\n"), ("cgroups", "2090 0::/lxc.monitor/101\n"))
)
assert reading["processes"] == [{"pid": 2090, "name": "lxc-start"}]
def test_a_process_gone_before_its_cgroup_was_read_has_no_unit(self):
reading = parse_services_restart(_wire(("maps", "4242 cron\n"), ("cgroups", "")))
assert reading["processes"] == [{"pid": 4242, "name": "cron"}]
def test_cgroup_v1_reads_the_systemd_hierarchy(self):
cgroups = "700 12:name=systemd:/system.slice/sshd.service\n700 3:cpu:/\n"
reading = parse_services_restart(_wire(("maps", "700 sshd\n"), ("cgroups", cgroups)))
assert reading["units"] == ["sshd"]
def test_pid_1_is_a_process_without_a_unit(self):
"""systemd itself needs ``daemon-reexec``, not a unit restart."""
reading = parse_services_restart(
_wire(("maps", "1 systemd\n"), ("cgroups", "1 0::/init.scope\n"))
)
assert reading["processes"] == [{"pid": 1, "name": "systemd"}]
@pytest.mark.parametrize(
"line",
[
"7f2a1c000000-7f2a1c1a0000 r-xp 00028000 fd:00 131 /usr/lib/x86_64-linux-gnu/libc.so.6 (deleted)",
"55d0c0000000-55d0c0100000 r-xp 00000000 fd:00 99 /usr/sbin/sshd (deleted)",
"7f00-7f10 r-xp 00000000 fd:00 7 /lib64/libssl.so.3 (deleted)",
"7f00-7f10 r-xp 00000000 fd:00 7 /opt/app/lib/libfoo.so (deleted)",
],
)
def test_replaced_code_counts(self, line):
assert (
subprocess.run(["grep", "-qE", DELETED_CODE_PATTERN], input=line, text=True).returncode
== 0
)
@pytest.mark.parametrize(
"line",
[
# Code still on disk.
"7f2a1c000000-7f2a1c1a0000 r-xp 00028000 fd:00 131 /usr/lib/x86_64-linux-gnu/libc.so.6",
# Data, not code: the locale archive an update replaced.
"7f00-7f10 r--p 00000000 fd:00 7 /usr/lib/locale/locale-archive (deleted)",
# Deleted on purpose: shared memory, memfd, a temporary file.
"7f00-7f10 rw-s 00000000 00:01 7 /SYSV00000000 (deleted)",
"7f00-7f10 r-xp 00000000 00:01 7 /memfd:jit (deleted)",
"7f00-7f10 r-xp 00000000 00:01 7 /tmp/ffiXyz (deleted)",
"7f00-7f10 r-xp 00000000 00:01 7 /dev/shm/pulse-shm-1 (deleted)",
],
)
def test_what_is_not_replaced_code(self, line):
assert (
subprocess.run(["grep", "-qE", DELETED_CODE_PATTERN], input=line, text=True).returncode
== 1
)
class TestFailures:
def test_whatever_surrounds_the_frame_is_ignored(self):
reading = parse_services_restart(
_wire(("needs-restarting", "sshd.service\n"), noise="[sudo] password for netork:\n")
)
assert reading["units"] == ["sshd"]
def test_output_without_the_frame_raises(self):
"""sudo refused: the script never ran, and that is no clean reading."""
with pytest.raises(ValueError):
parse_services_restart("sudo: a password is required\n")
def test_a_report_cut_short_raises(self):
with pytest.raises(ValueError):
parse_services_restart("RST_BEGIN\n[needs-restarting]\nsshd.service\n")
def test_a_report_without_a_source_raises(self):
with pytest.raises(ValueError):
parse_services_restart("RST_BEGIN\nRST_END\n")
def _stub(tmp_path, name: str, script: str) -> None:
stub = tmp_path / name
stub.write_text(f"#!/bin/sh\n{script}\n")
stub.chmod(0o755)
def _run(tmp_path) -> str:
for tool in ("cat", "grep", "sed", "printf"):
if shutil.which(tool):
(tmp_path / tool).symlink_to(shutil.which(tool))
return subprocess.run(
["/bin/sh", "-c", SERVICES_RESTART_COMMAND],
capture_output=True,
text=True,
env={"PATH": str(tmp_path)},
timeout=60,
).stdout
class TestTheOrderOfPreference:
def test_needs_restarting_first(self, tmp_path):
_stub(tmp_path, "needs-restarting", f"cat <<'EOF'\n{NEEDS_RESTARTING}EOF")
_stub(tmp_path, "needrestart", "echo NEEDRESTART-SVC: other.service")
assert parse_services_restart(_run(tmp_path))["source"] == "needs-restarting"
def test_needrestart_when_needs_restarting_fails(self, tmp_path):
_stub(tmp_path, "needs-restarting", "exit 1")
_stub(tmp_path, "needrestart", f"cat <<'EOF'\n{NEEDRESTART}EOF")
reading = parse_services_restart(_run(tmp_path))
assert reading == {"source": "needrestart", "units": UNITS, "processes": []}
def test_needrestart_only_lists(self, tmp_path):
"""Batch mode, list only, by its option and by its environment: whatever the
host's needrestart.conf says, it restarts nothing."""
_stub(tmp_path, "needrestart", 'echo "NEEDRESTART-SVC: $NEEDRESTART_MODE $*.service"')
reading = parse_services_restart(_run(tmp_path))
assert reading["units"] == ["l -b -r l"]
def test_the_maps_scan_when_both_fail(self, tmp_path):
"""Stubs that fail stand in for the host's own tools, which ``/usr/sbin``
on this host may hold."""
_stub(tmp_path, "needs-restarting", "exit 1")
_stub(tmp_path, "needrestart", "exit 1")
assert parse_services_restart(_run(tmp_path))["source"] == "maps"
class TestTheCommand:
def test_the_frame_is_not_in_the_command_itself(self):
assert "RST_BEGIN" not in SERVICES_RESTART_COMMAND
assert "RST_END" not in SERVICES_RESTART_COMMAND
def test_it_writes_and_changes_nothing(self):
for verb in ("sudo", " > ", ">>", "kill", "rm ", "systemctl ", "-r a", "-r i"):
assert verb not in SERVICES_RESTART_COMMAND
def test_it_is_posix_sh(self):
result = subprocess.run(
["sh", "-n", "-c", SERVICES_RESTART_COMMAND], capture_output=True, text=True
)
assert result.returncode == 0, result.stderr
def test_it_runs_and_parses_on_this_host(self):
out = subprocess.run(
["sh", "-c", SERVICES_RESTART_COMMAND], capture_output=True, text=True, timeout=120
).stdout
reading = parse_services_restart(out)
assert reading["source"] in ("needs-restarting", "needrestart", "maps")
class _Driver(ServicesRestartMixin):
def __init__(self, output: str):
self.output = output
self.commands: list[str] = []
def _run_services_restart_command(self, command: str) -> str:
self.commands.append(command)
return self.output
class TestTheTemplate:
def test_a_driver_supplies_only_the_transport(self):
driver = _Driver(_wire(("needs-restarting", "sshd.service\n")))
assert driver.get_services_need_restart()["units"] == ["sshd"]
def test_the_command_reaches_root_as_one_shell(self):
driver = _Driver(_wire(("needs-restarting", "")))
driver.get_services_need_restart()
(command,) = driver.commands
assert command.startswith("sh -c '")
assert subprocess.run(["sh", "-n", "-c", command]).returncode == 0
def test_a_refused_root_raises_rather_than_reads_clean(self):
driver = _Driver("sudo: a password is required\n")
with pytest.raises(ValueError):
driver.get_services_need_restart()
def test_not_every_os_driver_has_it(self):
assert not hasattr(OSDriver, "get_services_need_restart")