Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
e2970831f8 | ||
|
|
7451fc9dfc | ||
|
|
5faf9a1021 | ||
|
|
b8a50fffab | ||
|
|
3f35d05a73 | ||
|
|
5b4195f028 | ||
|
|
9d921c4ce8 | ||
|
|
e25aebbe45 | ||
|
|
780e4247a1 | ||
|
|
4b4797e383 | ||
|
|
61b7b68626 | ||
|
|
b9b6297815 | ||
|
|
14217b6eeb | ||
|
|
91b939236f |
No files matched your search
@@ -7,6 +7,70 @@ recorded here; their history is the git log.
|
||||
|
||||
## [Unreleased]
|
||||
|
||||
## [4.53.0] - 2026-11-28
|
||||
|
||||
### Added
|
||||
- `get_hardening()` reads whether the host runs on its own hardware, and whose CPU it is
|
||||
(NetOrk/netork#2838): `virtualization`, `systemd-detect-virt`'s word (`none` on bare
|
||||
metal, else the hypervisor or container engine, lowercased), else `vm` or `none` from the
|
||||
`hypervisor` flag of `/proc/cpuinfo` where systemd-detect-virt is not installed; and
|
||||
`cpu_vendor`, the first `vendor_id` of `/proc/cpuinfo` (`GenuineIntel`, `AuthenticAMD`;
|
||||
None without one, as on ARM). Read-only, like the rest of the reading.
|
||||
- `CpuMicrocodeMixin.install_cpu_microcode()`: the CPU vendor's microcode on a host that
|
||||
runs on its own CPU, in three steps. `read` refuses a guest (a guest loads no microcode,
|
||||
its host does) and a host whose virtualization could not be told, and picks the package
|
||||
(`microcode_package`): `intel-microcode`/`amd64-microcode` on Debian and Ubuntu,
|
||||
`microcode_ctl`/`linux-firmware` on Enterprise Linux and Fedora,
|
||||
`ucode-intel`/`ucode-amd` on SUSE; none elsewhere. `sources`, on a Debian host only,
|
||||
adds Debian's firmware component (`firmware_component`: `non-free-firmware`, `non-free`
|
||||
up to bullseye) to every enabled source of Debian's own archive that has `main`, and
|
||||
loads the package index again; another vendor's source is never touched
|
||||
(`add_component`). `install` is `ensure_package`'s. The microcode loads at the next boot;
|
||||
the restart is the caller's. Returns `CpuMicrocodeFixDict` (the fix, `package`,
|
||||
`sources_changed`). On no role base: a driver mixes it in. The index is loaded again through
|
||||
`_reload_package_index`, `refresh_available_updates` by default; a driver whose refresh only
|
||||
starts a task overrides it with one that waits.
|
||||
|
||||
## [4.52.0] - 2026-11-28
|
||||
|
||||
### Added
|
||||
- `get_kernel_facts()` reads the kernel's live patches (NetOrk/netork#2701), in the new
|
||||
`live_patches` key: `loaded`, every patch under `/sys/kernel/livepatch` with `enabled` and
|
||||
`transition` (None on a kernel without live patching); `kpatch`, `kpatch list`'s loaded
|
||||
modules with their state and the installed ones with their kernel (None without kpatch);
|
||||
`canonical`, Canonical Livepatch's status for the running kernel -- its kernel as Canonical
|
||||
names it, `state` (`applied`, ...), `check_state`, `version` and the CVEs it names with
|
||||
whether each is patched (`canonical-livepatch status --format json`, the 10.x client's list
|
||||
and the 9.x client's text; None when not installed or not read), and
|
||||
`canonical_installed`. Read-only: `status` reads the daemon's last state, `refresh` is never
|
||||
run. Where the client is installed and its status did not read without root, a driver that
|
||||
supplies `_run_livepatch_status_command(command)` has `LIVEPATCH_STATUS_COMMAND` read again
|
||||
as root; a refusal leaves it unread.
|
||||
- `parse_canonical_status`, `canonical_release` (Canonical's `5.15.0-91.101-generic` as
|
||||
`uname -r` names it), `LIVEPATCH_STATUS_COMMAND`, and the `LivePatchesDict` and
|
||||
`CanonicalLivepatchDict` shapes (in `livepatch`).
|
||||
|
||||
## [4.51.0] - 2026-11-28
|
||||
|
||||
### Added
|
||||
- `LoginAccountsMixin.get_login_accounts()`: every account on a Linux host a person can
|
||||
log in with, read with one fixed, read-only command (NetOrk/netork#2707). Root and UID
|
||||
1000 on with a login shell (`login_capable`), from `/etc/passwd` -- name, UID, home and
|
||||
shell only, never the comment field; accounts from a directory are not there and not
|
||||
read. Each with its last login (ISO, UTC), where it came from and which tool told it:
|
||||
the newest of `lastlog2`, `lastlog`, `wtmpdb last` and `last`, so a host upgraded to
|
||||
lastlog2 or a desktop login only wtmp saw still reads right. Its password state
|
||||
(`passwd -S`: `set`, `locked`, `none`), password change, password and account expiry
|
||||
(`chage -l`: an ISO date, `never`, `must_change`), and `locked` -- the password locked or
|
||||
the account expired on the host's date. The failed attempts since the last login as a
|
||||
number: from `lastb` (the newest `FAILED_LOGINS_READ`, 1000, per account;
|
||||
`failed_logins_capped` when reached), else `pam_faillock`'s tally. `LC_ALL=C`, no stdin,
|
||||
no password hash read. Root first; where root is refused, as the login user, when the
|
||||
lock, the expiry and the failures are `None`. A driver supplies
|
||||
`_run_login_accounts_command(command, *, privileged)`.
|
||||
- `parse_login_accounts`, `LOGIN_ACCOUNTS_COMMAND`, `login_capable`, and the
|
||||
`LoginAccountDict` and `LoginAccountsDict` shapes (in `login_accounts`).
|
||||
|
||||
## [4.50.0] - 2026-11-28
|
||||
|
||||
### Added
|
||||
|
||||
@@ -129,6 +129,9 @@ else Zabbix's repository, configure, firewall, enable and restart; the driver wr
|
||||
configuration and opens the firewall; an `active_only` agent gets `StartAgents=0` and no
|
||||
firewall opening), `EnsurePackageMixin.ensure_package(name)`,
|
||||
`PackageProxyMixin.configure_package_proxy(url)`,
|
||||
`CpuMicrocodeMixin.install_cpu_microcode()` (the CPU vendor's microcode on a host that runs
|
||||
on its own CPU; on Debian with its archive's firmware component added first;
|
||||
`napalm_device_types.cpu_microcode`),
|
||||
`TimeSyncMixin.configure_time_sync(ntp_servers, timezone)` and
|
||||
`ContainerEngineMixin.grant_container_engine_access(user)`. A driver whose device takes the
|
||||
change in one call overrides the template method. A driver mixes in the fixes its device
|
||||
@@ -159,6 +162,13 @@ rather than by a role base: what a Linux kernel has built and loaded is read the
|
||||
everywhere, so the command and its parse are concrete here and a driver supplies only
|
||||
`_run_kernel_facts_command`. `OSDriver` does not carry it — a Windows host is an OS driver
|
||||
too, and `hasattr(driver, "get_kernel_facts")` has to stay truthful.
|
||||
The kernel facts carry the kernel's live patches too (`live_patches`, from
|
||||
`napalm_device_types.livepatch`): the patches loaded in `/sys/kernel/livepatch` with whether
|
||||
each is enabled, `kpatch list`, and Canonical Livepatch's status for the running kernel with
|
||||
the CVEs it fixes (`canonical-livepatch status --format json`, the daemon's last state; never
|
||||
`refresh`). Where Canonical's client is installed and its status does not read without root, a
|
||||
driver that can gain root supplies `_run_livepatch_status_command` and the mixin reads
|
||||
`LIVEPATCH_STATUS_COMMAND` again through it.
|
||||
|
||||
`HardeningMixin` (`get_hardening`) is mixed in the same way: how the host is hardened, as
|
||||
its kernel and its own tools say it, in one read-only command. The active security modules
|
||||
@@ -167,10 +177,21 @@ its kernel and its own tools say it, in one read-only command. The active securi
|
||||
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
|
||||
command line, `ID`/`ID_LIKE` from `/etc/os-release`, whether the host runs virtualized
|
||||
(`systemd-detect-virt`, else the `hypervisor` CPU flag) and the CPU's `vendor_id`. Read as root first and, where root
|
||||
is refused, as the login user without the profile counts. A driver supplies
|
||||
`_run_hardening_command(command, privileged=)`; what was not read is `None`, never "off".
|
||||
|
||||
`LoginAccountsMixin` (`get_login_accounts`) is mixed in the same way: every account on the
|
||||
host a person can log in with -- root and UID 1000 on, with a shell that is not `nologin` or
|
||||
`false`, from `/etc/passwd` (name, UID, home and shell only; directory accounts are not read)
|
||||
-- with its last login, the newest any of `lastlog2`, `lastlog`, `wtmpdb last` and `last`
|
||||
knows, and where it came from; its lock and expiry from `passwd -S` and `chage -l`; and the
|
||||
failed attempts since that login, from `lastb` (the newest 1000 per account) or else
|
||||
`pam_faillock`'s tally. Read as root first and, where root is refused, as the login user,
|
||||
when the lock, the expiry and the failures are `None`. A driver supplies
|
||||
`_run_login_accounts_command(command, privileged=)`.
|
||||
|
||||
`ServicePackagesMixin` (`get_service_packages`) is mixed in the same way: which installed
|
||||
packages each systemd service is made of — the one shipping its unit file and the one
|
||||
shipping the binary its `ExecStart` runs, by `dpkg -S` or `rpm -qf`, not the libraries
|
||||
|
||||
@@ -54,6 +54,7 @@ instead of being restated on every role that happens to need it:
|
||||
* :class:`~napalm_device_types.kernel.KernelFactsMixin`
|
||||
* :class:`~napalm_device_types.listening.ListeningSocketsMixin`
|
||||
* :class:`~napalm_device_types.local_accounts.LocalAccountsMixin`
|
||||
* :class:`~napalm_device_types.login_accounts.LoginAccountsMixin`
|
||||
* :class:`~napalm_device_types.log_sources.LogSourcesMixin`
|
||||
* :class:`~napalm_device_types.host_firewall.HostFirewallMixin`
|
||||
* :class:`~napalm_device_types.mac_acl.MacAclMixin`
|
||||
@@ -155,6 +156,13 @@ from napalm_device_types.container_engine import (
|
||||
ContainerEngineMixin,
|
||||
ContainerEngineUnavailable,
|
||||
)
|
||||
from napalm_device_types.cpu_microcode import (
|
||||
CpuMicrocodeFixDict,
|
||||
CpuMicrocodeMixin,
|
||||
add_component,
|
||||
firmware_component,
|
||||
microcode_package,
|
||||
)
|
||||
from napalm_device_types.credential_expiry import (
|
||||
CredentialExpiryDict,
|
||||
CredentialExpiryMixin,
|
||||
@@ -191,7 +199,12 @@ from napalm_device_types.host_shutdown import HostShutdownMixin
|
||||
from napalm_device_types.host_status import HOST_STATUS_COMMAND, HostStatusMixin, parse_host_status
|
||||
from napalm_device_types.hypervisor import HypervisorDriver
|
||||
from napalm_device_types.interface_filter import InterfaceFilterMixin
|
||||
from napalm_device_types.kernel import KERNEL_FACTS_COMMAND, KernelFactsMixin, parse_kernel_facts
|
||||
from napalm_device_types.kernel import (
|
||||
KERNEL_FACTS_COMMAND,
|
||||
LIVEPATCH_STATUS_COMMAND,
|
||||
KernelFactsMixin,
|
||||
parse_kernel_facts,
|
||||
)
|
||||
from napalm_device_types.lag import add_lag_interfaces
|
||||
from napalm_device_types.licenses import LicenseMixin
|
||||
from napalm_device_types.listening import (
|
||||
@@ -200,6 +213,12 @@ from napalm_device_types.listening import (
|
||||
ListeningSocketsUnavailable,
|
||||
parse_listening_sockets,
|
||||
)
|
||||
from napalm_device_types.livepatch import (
|
||||
CanonicalLivepatchDict,
|
||||
LivePatchesDict,
|
||||
canonical_release,
|
||||
parse_canonical_status,
|
||||
)
|
||||
from napalm_device_types.lldp import (
|
||||
LldpNeighborDict,
|
||||
LldpNeighborRow,
|
||||
@@ -227,6 +246,14 @@ from napalm_device_types.log_sources import (
|
||||
parse_log_forwarding,
|
||||
parse_log_sources,
|
||||
)
|
||||
from napalm_device_types.login_accounts import (
|
||||
LOGIN_ACCOUNTS_COMMAND,
|
||||
LoginAccountDict,
|
||||
LoginAccountsDict,
|
||||
LoginAccountsMixin,
|
||||
login_capable,
|
||||
parse_login_accounts,
|
||||
)
|
||||
from napalm_device_types.login_sources import (
|
||||
LOGIN_FACTORS,
|
||||
LoginFactors,
|
||||
@@ -570,11 +597,27 @@ __all__ = [
|
||||
"KernelFactsMixin",
|
||||
"KERNEL_FACTS_COMMAND",
|
||||
"parse_kernel_facts",
|
||||
"LIVEPATCH_STATUS_COMMAND",
|
||||
"CanonicalLivepatchDict",
|
||||
"LivePatchesDict",
|
||||
"canonical_release",
|
||||
"parse_canonical_status",
|
||||
"HARDENING_COMMAND",
|
||||
"HardeningMixin",
|
||||
"CpuMicrocodeFixDict",
|
||||
"CpuMicrocodeMixin",
|
||||
"add_component",
|
||||
"firmware_component",
|
||||
"microcode_package",
|
||||
"HardeningDict",
|
||||
"cpu_vulnerability_state",
|
||||
"parse_hardening",
|
||||
"LOGIN_ACCOUNTS_COMMAND",
|
||||
"LoginAccountDict",
|
||||
"LoginAccountsDict",
|
||||
"LoginAccountsMixin",
|
||||
"login_capable",
|
||||
"parse_login_accounts",
|
||||
"SERVICE_PACKAGES_COMMAND",
|
||||
"SERVICES_RESTART_COMMAND",
|
||||
"ServicesRestartMixin",
|
||||
|
||||
@@ -0,0 +1,309 @@
|
||||
"""The CPU vendor's microcode, installed on a host that runs on its own CPU (NetOrk/netork#2706).
|
||||
|
||||
A CPU vulnerability the kernel reports ``Vulnerable: ... no microcode`` closes with the
|
||||
microcode the CPU's vendor ships: the distribution packages it, and the initramfs loads
|
||||
it early at the next boot. Installing it is the fix; the restart that loads it is the
|
||||
caller's to schedule.
|
||||
|
||||
- **Which package** (:func:`microcode_package`): by the distribution's family
|
||||
(``ID``/``ID_LIKE``) and the CPU's ``vendor_id``. Debian and Ubuntu:
|
||||
``intel-microcode``, ``amd64-microcode``; Enterprise Linux and Fedora:
|
||||
``microcode_ctl``, ``linux-firmware``; SUSE: ``ucode-intel``, ``ucode-amd``. Elsewhere
|
||||
(Arch, Alpine, an appliance) the boot loader has to load it, which is not a package's
|
||||
to change: no package.
|
||||
- **Not on a guest.** A guest loads no microcode and sees only the CPU features its
|
||||
hypervisor passes through: the hardening reading's ``virtualization`` must be
|
||||
``none``.
|
||||
- **Debian's component** (:func:`firmware_component`, :func:`add_component`): Debian keeps
|
||||
the packages in ``non-free-firmware`` (``non-free`` up to bullseye), which a Proxmox VE or
|
||||
Proxmox Backup Server install does not enable. On a Debian host (``ID=debian``) every
|
||||
enabled source of Debian's own archive (a host under ``debian.org``) that has ``main``
|
||||
gets the component, and the package index is loaded again. Another vendor's source is
|
||||
never touched; Ubuntu ships the packages in its own components.
|
||||
|
||||
A template like the fixes of :mod:`napalm_device_types.fixes`: a driver mixes
|
||||
:class:`CpuMicrocodeMixin` in where it has ``get_hardening``, ``ensure_package`` (with
|
||||
``get_packages``), :class:`~napalm_device_types.apt_releases.AptReleaseMixin`'s transports
|
||||
and ``refresh_available_updates`` (or its own ``_reload_package_index``, where the refresh
|
||||
only starts a task). It is on no role base, so
|
||||
``callable(getattr(driver, "install_cpu_microcode", None))`` stays a truthful answer.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import base64
|
||||
import shlex
|
||||
from collections.abc import Sequence
|
||||
from dataclasses import dataclass
|
||||
from typing import TYPE_CHECKING, Any
|
||||
from urllib.parse import urlsplit
|
||||
|
||||
from napalm_device_types.apt_releases import _LIST_LINE, _code, _is_deb822, _paragraphs
|
||||
from napalm_device_types.fixes import run_fix_steps
|
||||
from napalm_device_types.models import FixResultDict, FixStepOutcomeDict
|
||||
|
||||
if TYPE_CHECKING: # pragma: no cover
|
||||
from napalm_device_types.apt_releases import AptReleasesDict, AptSourceDict
|
||||
|
||||
_INTEL = "GenuineIntel"
|
||||
_AMD = "AuthenticAMD"
|
||||
|
||||
#: Family -> the IDs that name it, and the package per CPU vendor.
|
||||
_FAMILIES: tuple[tuple[frozenset[str], dict[str, str]], ...] = (
|
||||
(frozenset({"debian", "ubuntu"}), {_INTEL: "intel-microcode", _AMD: "amd64-microcode"}),
|
||||
(frozenset({"rhel", "centos", "fedora"}), {_INTEL: "microcode_ctl", _AMD: "linux-firmware"}),
|
||||
(frozenset({"suse", "opensuse", "sles"}), {_INTEL: "ucode-intel", _AMD: "ucode-amd"}),
|
||||
)
|
||||
_DEBIAN_PACKAGES = frozenset(_FAMILIES[0][1].values())
|
||||
|
||||
#: Debian's releases before bookworm, which had no ``non-free-firmware``.
|
||||
_BEFORE_FIRMWARE = frozenset({"squeeze", "wheezy", "jessie", "stretch", "buster", "bullseye"})
|
||||
|
||||
|
||||
def _family_ids(os_ids: Sequence[str]) -> set[str]:
|
||||
ids = {i.lower() for i in os_ids}
|
||||
if any(i.startswith("opensuse") for i in ids):
|
||||
ids.add("opensuse")
|
||||
return ids
|
||||
|
||||
|
||||
def microcode_package(os_ids: Sequence[str] | None, cpu_vendor: str | None) -> str | None:
|
||||
"""The package that brings the CPU's microcode on this distribution; None where none does.
|
||||
|
||||
*os_ids* are ``ID`` then ``ID_LIKE`` (the hardening reading's ``os_ids``),
|
||||
*cpu_vendor* is ``/proc/cpuinfo``'s ``vendor_id``.
|
||||
"""
|
||||
if not os_ids or not cpu_vendor:
|
||||
return None
|
||||
ids = _family_ids(os_ids)
|
||||
for names, packages in _FAMILIES:
|
||||
if ids & names:
|
||||
return packages.get(cpu_vendor)
|
||||
return None
|
||||
|
||||
|
||||
def firmware_component(codename: str) -> str:
|
||||
"""Debian's component for firmware and microcode in release *codename*."""
|
||||
return "non-free" if codename.strip().lower() in _BEFORE_FIRMWARE else "non-free-firmware"
|
||||
|
||||
|
||||
def _is_debian_archive(uri: str) -> bool:
|
||||
try:
|
||||
host = (urlsplit(uri).hostname or "").lower()
|
||||
except ValueError:
|
||||
return False
|
||||
return host == "debian.org" or host.endswith(".debian.org")
|
||||
|
||||
|
||||
def _wants(uris: Sequence[str], components: Sequence[str], component: str) -> bool:
|
||||
"""Whether a source of Debian's own archive, with ``main``, lacks *component*."""
|
||||
return (
|
||||
bool(uris)
|
||||
and all(_is_debian_archive(u) for u in uris)
|
||||
and "main" in components
|
||||
and component not in components
|
||||
)
|
||||
|
||||
|
||||
def _add_to_list_line(line: str, component: str) -> tuple[str, int]:
|
||||
code = _code(line)
|
||||
entry = _LIST_LINE.match(code)
|
||||
if not entry or not _wants([entry.group(3)], entry.group(5).split(), component):
|
||||
return line, 0
|
||||
stripped = code.rstrip()
|
||||
return f"{stripped} {component}{code[len(stripped) :]}{line[len(code) :]}", 1
|
||||
|
||||
|
||||
def _add_to_deb822(lines: list[str], component: str) -> int:
|
||||
changed = 0
|
||||
for paragraph in _paragraphs(lines):
|
||||
components = paragraph.fields.get("components")
|
||||
if not paragraph.enabled or components is None:
|
||||
continue
|
||||
if not _wants(paragraph.value("uris").split(), components.value.split(), component):
|
||||
continue
|
||||
last = components.lines[-1]
|
||||
lines[last] = f"{lines[last].rstrip()} {component}"
|
||||
changed += 1
|
||||
return changed
|
||||
|
||||
|
||||
def add_component(text: str, component: str, *, deb822: bool) -> tuple[str, int]:
|
||||
"""*text*, an apt source file, with *component* on each of Debian's own sources; and how many.
|
||||
|
||||
Only enabled sources (not a commented-out line, not a paragraph with ``Enabled: no``)
|
||||
whose URIs are all under ``debian.org`` and that have ``main``. A source that has it
|
||||
already, and every other vendor's, stays as it is; so do comments.
|
||||
"""
|
||||
lines = text.split("\n")
|
||||
if deb822:
|
||||
changed = _add_to_deb822(lines, component)
|
||||
else:
|
||||
changed = 0
|
||||
for index, line in enumerate(lines):
|
||||
lines[index], count = _add_to_list_line(line, component)
|
||||
changed += count
|
||||
return "\n".join(lines), changed
|
||||
|
||||
|
||||
class CpuMicrocodeFixDict(FixResultDict):
|
||||
"""What ``install_cpu_microcode`` did: the fix, its package, whether apt's sources changed."""
|
||||
|
||||
package: str | None
|
||||
sources_changed: bool
|
||||
|
||||
|
||||
@dataclass
|
||||
class _Plan:
|
||||
package: str | None = None
|
||||
debian: bool = False
|
||||
installed: bool = False
|
||||
sources_changed: bool = False
|
||||
|
||||
|
||||
class CpuMicrocodeMixin:
|
||||
"""Installs the CPU vendor's microcode on a host that runs on its own CPU.
|
||||
|
||||
Three steps: ``read`` (the hardening reading: not a guest, and a package for this
|
||||
distribution and CPU), ``sources`` (on Debian, its archive's firmware component) and
|
||||
``install``. Nothing is installed or written when a step before fails. The microcode
|
||||
loads at the next boot; restarting is the caller's.
|
||||
"""
|
||||
|
||||
if TYPE_CHECKING: # pragma: no cover - declared for type checkers only
|
||||
|
||||
def get_hardening(self) -> Any: ...
|
||||
|
||||
def get_packages(self) -> Any: ...
|
||||
|
||||
def ensure_package(self, name: str) -> FixResultDict: ...
|
||||
|
||||
def get_apt_source_releases(self) -> AptReleasesDict | None: ...
|
||||
|
||||
def _run_apt_command(self, command: str) -> str: ...
|
||||
|
||||
def _write_apt_file(self, path: str, content: str) -> FixStepOutcomeDict: ...
|
||||
|
||||
def refresh_available_updates(self) -> dict[str, Any]: ...
|
||||
|
||||
def install_cpu_microcode(self) -> CpuMicrocodeFixDict:
|
||||
"""Install the microcode package for the host's CPU and distribution."""
|
||||
plan = _Plan()
|
||||
result = run_fix_steps(
|
||||
[
|
||||
("read", lambda: self._microcode_read(plan)),
|
||||
("sources", lambda: self._microcode_sources(plan)),
|
||||
("install", lambda: self._microcode_install(plan)),
|
||||
]
|
||||
)
|
||||
return {**result, "package": plan.package, "sources_changed": plan.sources_changed}
|
||||
|
||||
def _microcode_read(self, plan: _Plan) -> FixStepOutcomeDict:
|
||||
reading = self.get_hardening()
|
||||
refused = _refused_guest(reading.get("virtualization"))
|
||||
if refused:
|
||||
return {"ok": False, "output": refused}
|
||||
os_ids = list(reading.get("os_ids") or [])
|
||||
vendor = reading.get("cpu_vendor")
|
||||
plan.package = microcode_package(os_ids, vendor)
|
||||
if plan.package is None:
|
||||
return {"ok": False, "output": _no_package(os_ids, vendor)}
|
||||
plan.debian = plan.package in _DEBIAN_PACKAGES and os_ids[:1] == ["debian"]
|
||||
plan.installed = any(
|
||||
p.get("name") == plan.package and p.get("installed") for p in self.get_packages()
|
||||
)
|
||||
return {"ok": True, "output": f"{vendor} CPU on {' '.join(os_ids)}: {plan.package}"}
|
||||
|
||||
def _microcode_sources(self, plan: _Plan) -> FixStepOutcomeDict:
|
||||
if plan.installed:
|
||||
return {"ok": True, "output": f"{plan.package} is installed already: nothing to add"}
|
||||
if not plan.debian:
|
||||
return {"ok": True, "output": "the distribution's own sources carry it"}
|
||||
releases = self.get_apt_source_releases()
|
||||
if releases is None:
|
||||
return {"ok": False, "output": "not an apt host"}
|
||||
component = firmware_component(releases["codename"])
|
||||
files = _files_wanting(releases["sources"], component)
|
||||
if not files:
|
||||
return {"ok": True, "output": f"Debian's sources already carry {component}"}
|
||||
said: list[str] = []
|
||||
for path in files:
|
||||
outcome = self._add_component_to(path, component, plan)
|
||||
if not outcome["ok"]:
|
||||
return {"ok": False, "output": "\n".join([*said, outcome["output"]])}
|
||||
said.append(outcome["output"])
|
||||
if not plan.sources_changed:
|
||||
return {"ok": True, "output": "\n".join(said)}
|
||||
loaded = self._reload_package_index()
|
||||
return {"ok": loaded["ok"], "output": "\n".join([*said, loaded["output"]])}
|
||||
|
||||
def _reload_package_index(self) -> FixStepOutcomeDict:
|
||||
"""Load the package index again, and be done when it returns: the install comes next.
|
||||
|
||||
``refresh_available_updates`` by default. A driver whose refresh only starts a task
|
||||
(Proxmox's ``POST apt/update``) overrides this with one that waits.
|
||||
"""
|
||||
refreshed = self.refresh_available_updates()
|
||||
output = str(refreshed.get("output", "")).strip()
|
||||
if not refreshed.get("success"):
|
||||
return {"ok": False, "output": f"apt-get update: {output}"}
|
||||
return {"ok": True, "output": "package index loaded again"}
|
||||
|
||||
def _add_component_to(self, path: str, component: str, plan: _Plan) -> FixStepOutcomeDict:
|
||||
encoded = "".join(self._run_apt_command(f"base64 {shlex.quote(path)}").split())
|
||||
text = base64.b64decode(encoded).decode()
|
||||
new, count = add_component(text, component, deb822=_is_deb822(path))
|
||||
if not count:
|
||||
return {"ok": True, "output": f"{path} carries {component} already"}
|
||||
written = self._write_apt_file(path, new)
|
||||
if not written["ok"]:
|
||||
return written
|
||||
plan.sources_changed = True
|
||||
return {"ok": True, "output": f"{path}: {component} added"}
|
||||
|
||||
def _microcode_install(self, plan: _Plan) -> FixStepOutcomeDict:
|
||||
if plan.package is None: # pragma: no cover - the read step failed otherwise
|
||||
return {"ok": False, "output": "no package"}
|
||||
result = self.ensure_package(plan.package)
|
||||
if not result["steps"]:
|
||||
return {"ok": False, "output": result["output"] or f"{plan.package} not installed"}
|
||||
step = result["steps"][-1]
|
||||
if not step["ok"]:
|
||||
return {"ok": False, "output": step["output"]}
|
||||
return {"ok": True, "output": f"{step['output']}; the microcode loads at the next boot"}
|
||||
|
||||
|
||||
def _refused_guest(virtualization: str | None) -> str | None:
|
||||
"""Why a host with this ``virtualization`` takes no microcode; None on bare metal."""
|
||||
if virtualization is None:
|
||||
return "could not tell whether the host is virtual"
|
||||
if virtualization != "none":
|
||||
return f"runs virtualized ({virtualization}): a guest loads no microcode: its host does"
|
||||
return None
|
||||
|
||||
|
||||
def _no_package(os_ids: Sequence[str], vendor: str | None) -> str:
|
||||
if not vendor:
|
||||
return "the CPU vendor was not read"
|
||||
if microcode_package(os_ids, _INTEL) is None:
|
||||
return f"no microcode package is known for {' '.join(os_ids) or 'this distribution'}"
|
||||
return f"no microcode package is known for a {vendor} CPU"
|
||||
|
||||
|
||||
def _files_wanting(sources: Sequence[AptSourceDict], component: str) -> list[str]:
|
||||
"""The source files with a source of Debian's archive that lacks *component*, in order."""
|
||||
files: list[str] = []
|
||||
for source in sources:
|
||||
wants = _wants([source["uri"]], source["components"], component)
|
||||
if wants and source["file"] not in files:
|
||||
files.append(source["file"])
|
||||
return files
|
||||
|
||||
|
||||
__all__ = [
|
||||
"CpuMicrocodeFixDict",
|
||||
"CpuMicrocodeMixin",
|
||||
"add_component",
|
||||
"firmware_component",
|
||||
"microcode_package",
|
||||
]
|
||||
@@ -1,6 +1,6 @@
|
||||
"""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:
|
||||
Six 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
|
||||
@@ -17,6 +17,11 @@ Five things, each read where the host itself keeps it:
|
||||
- **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.
|
||||
- **Whether the host runs on its own hardware, and whose CPU it is:**
|
||||
``systemd-detect-virt`` (``none`` on bare metal, else the hypervisor or container
|
||||
engine), else the ``hypervisor`` flag a hypervisor sets in its guests' ``/proc/cpuinfo``;
|
||||
and the CPU's ``vendor_id``. A CPU vulnerability on a guest is its host's to close: a
|
||||
guest loads no microcode and sees only the CPU features its hypervisor passes through.
|
||||
|
||||
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
|
||||
@@ -62,6 +67,11 @@ HARDENING_COMMAND = (
|
||||
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; "
|
||||
"if command -v systemd-detect-virt >/dev/null 2>&1; then echo '[virtualization]'; "
|
||||
"systemd-detect-virt 2>/dev/null; fi; "
|
||||
"if [ -r /proc/cpuinfo ]; then echo '[cpu_hypervisor]'; "
|
||||
"grep -c -m1 -E '^flags.*[[:space:]]hypervisor([[:space:]]|$)' /proc/cpuinfo; "
|
||||
"echo '[cpu_vendor]'; grep -m1 '^vendor_id' /proc/cpuinfo; fi; "
|
||||
"printf '%s%s\\n' HARDENING_ END"
|
||||
)
|
||||
|
||||
@@ -102,6 +112,11 @@ class HardeningDict(TypedDict):
|
||||
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
|
||||
#: ``systemd-detect-virt``, lowercased: "none" on the host's own hardware, else the
|
||||
#: hypervisor or container engine ("kvm", "vmware", "lxc", ...); "vm" where only the
|
||||
#: ``hypervisor`` CPU flag tells it.
|
||||
virtualization: str | None
|
||||
cpu_vendor: str | None # the first vendor_id of /proc/cpuinfo: "GenuineIntel", ...
|
||||
|
||||
|
||||
def cpu_vulnerability_state(text: str) -> CpuVulnerabilityState:
|
||||
@@ -258,6 +273,24 @@ def _os_ids(sections: dict[str, list[str]]) -> list[str] | None:
|
||||
return ids
|
||||
|
||||
|
||||
def _virtualization(sections: dict[str, list[str]]) -> str | None:
|
||||
"""``systemd-detect-virt``'s word first, else the ``hypervisor`` CPU flag."""
|
||||
detected = _first(sections, "virtualization")
|
||||
if detected:
|
||||
return detected.lower()
|
||||
flag = _first(sections, "cpu_hypervisor")
|
||||
if flag is None or not flag.isdigit():
|
||||
return None
|
||||
return "vm" if int(flag) else "none"
|
||||
|
||||
|
||||
def _cpu_vendor(sections: dict[str, list[str]]) -> str | None:
|
||||
line = _first(sections, "cpu_vendor")
|
||||
if line is None:
|
||||
return None
|
||||
return line.partition(":")[2].strip() or None
|
||||
|
||||
|
||||
def parse_hardening(output: str) -> HardeningDict:
|
||||
"""Parse what :data:`HARDENING_COMMAND` printed.
|
||||
|
||||
@@ -279,6 +312,8 @@ def parse_hardening(output: str) -> HardeningDict:
|
||||
"mitigations": mitigations,
|
||||
"nosmt": nosmt,
|
||||
"os_ids": _os_ids(sections),
|
||||
"virtualization": _virtualization(sections),
|
||||
"cpu_vendor": _cpu_vendor(sections),
|
||||
}
|
||||
|
||||
|
||||
@@ -311,6 +346,9 @@ class HardeningMixin:
|
||||
* 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``
|
||||
* virtualization (str or None) - ``systemd-detect-virt``: "none" on the host's
|
||||
own hardware; "vm" where only the ``hypervisor`` CPU flag tells it
|
||||
* cpu_vendor (str or None) - ``vendor_id`` of ``/proc/cpuinfo``
|
||||
|
||||
``None`` means not read. Read as root first, for AppArmor's profiles; where root
|
||||
is refused, as the login user, without them.
|
||||
@@ -329,6 +367,8 @@ class HardeningMixin:
|
||||
"mitigations": "auto",
|
||||
"nosmt": False,
|
||||
"os_ids": ["almalinux", "rhel", "centos", "fedora"],
|
||||
"virtualization": "none",
|
||||
"cpu_vendor": "GenuineIntel",
|
||||
}
|
||||
|
||||
:raises ValueError: if neither reading carried an intact report.
|
||||
|
||||
@@ -16,6 +16,13 @@ What the four lists mean for a module, and why "not loaded" alone is never
|
||||
"absent": a module that is not loaded can still be loaded on demand -- by an
|
||||
attacker too, where autoloading reaches it. Only a module that is neither
|
||||
loaded, nor compiled in, nor shipped for this kernel is one it cannot have.
|
||||
|
||||
**The live patches** the kernel carries come with it (NetOrk/netork#2701,
|
||||
:mod:`napalm_device_types.livepatch`): the patches loaded in ``/sys/kernel/livepatch``,
|
||||
``kpatch list``, and Canonical Livepatch's status with the CVEs it fixes. That status
|
||||
may need root: where the client is installed and its status did not read without, a
|
||||
driver that supplies ``_run_livepatch_status_command`` reads it again as root, one
|
||||
fixed, read-only command (:data:`LIVEPATCH_STATUS_COMMAND`).
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
@@ -26,7 +33,8 @@ import gzip
|
||||
import zlib
|
||||
from typing import TYPE_CHECKING
|
||||
|
||||
from napalm_device_types.models import KernelFactsDict
|
||||
from napalm_device_types.kernel_models import KernelFactsDict
|
||||
from napalm_device_types.livepatch import live_patches, parse_canonical_status
|
||||
|
||||
_BEGIN = "KFACTS_BEGIN"
|
||||
_END = "KFACTS_END"
|
||||
@@ -43,11 +51,23 @@ KERNEL_FACTS_COMMAND = (
|
||||
"if [ -r /boot/config-$r ]; then echo '[config]'; grep '^CONFIG_' /boot/config-$r; "
|
||||
"elif [ -r /proc/config.gz ]; then echo '[config]'; "
|
||||
"zcat /proc/config.gz | grep '^CONFIG_'; fi; "
|
||||
"if [ -d /sys/kernel/livepatch ]; then echo '[livepatch]'; "
|
||||
'for p in /sys/kernel/livepatch/*; do [ -d "$p" ] && '
|
||||
'echo "${p##*/} $(cat "$p/enabled") $(cat "$p/transition")"; done; fi; '
|
||||
"if command -v kpatch >/dev/null; then echo '[kpatch]'; kpatch list; fi; "
|
||||
"c=$(command -v canonical-livepatch || ls /snap/bin/canonical-livepatch); "
|
||||
"if [ -n \"$c\" ]; then echo '[canonical_livepatch]'; "
|
||||
"\"$c\" status --format json | tr -d '\\n'; echo; fi; "
|
||||
"} 2>/dev/null | gzip -c | base64; "
|
||||
"printf '%s%s\\n' KFACTS_ END"
|
||||
)
|
||||
|
||||
|
||||
#: Canonical Livepatch's status, as root: the client lives in ``/snap/bin``, outside the
|
||||
#: ``PATH`` sudo keeps. Read-only: ``status`` reads what the daemon holds.
|
||||
LIVEPATCH_STATUS_COMMAND = "/snap/bin/canonical-livepatch status --format json"
|
||||
|
||||
|
||||
def module_name(raw: str) -> str:
|
||||
"""A module as the kernel names it: no path, no ``.ko`` suffix, ``_`` for ``-``.
|
||||
|
||||
@@ -124,6 +144,7 @@ def parse_kernel_facts(output: str) -> KernelFactsDict:
|
||||
"builtin": names("builtin"),
|
||||
"available": names("available"),
|
||||
"config": _config(sections["config"]) if "config" in sections else None,
|
||||
"live_patches": live_patches(sections),
|
||||
}
|
||||
|
||||
|
||||
@@ -144,6 +165,9 @@ class KernelFactsMixin:
|
||||
"""Run *command* on the host with ``sh`` and return what it printed."""
|
||||
...
|
||||
|
||||
#: Optional: a driver that can gain root supplies
|
||||
#: ``_run_livepatch_status_command(command) -> str``, which runs *command* as root.
|
||||
|
||||
def get_kernel_facts(self) -> KernelFactsDict:
|
||||
"""
|
||||
Returns what the running kernel has built and loaded.
|
||||
@@ -166,6 +190,31 @@ class KernelFactsMixin:
|
||||
"config": {"CONFIG_TIPC": "m", "CONFIG_HZ": "250"},
|
||||
}
|
||||
|
||||
* live_patches (dict) - loaded (``/sys/kernel/livepatch``, None without live
|
||||
patching), kpatch (``kpatch list``) and canonical (Canonical Livepatch's
|
||||
status for the running kernel, with the CVEs it fixes); each None when not read
|
||||
|
||||
:raises ValueError: if the host's output carried no intact report.
|
||||
"""
|
||||
return parse_kernel_facts(self._run_kernel_facts_command(KERNEL_FACTS_COMMAND))
|
||||
facts = parse_kernel_facts(self._run_kernel_facts_command(KERNEL_FACTS_COMMAND))
|
||||
return self._with_canonical_as_root(facts)
|
||||
|
||||
def _with_canonical_as_root(self, facts: KernelFactsDict) -> KernelFactsDict:
|
||||
"""*facts* with Canonical's status read as root where it did not read without.
|
||||
|
||||
Only where the client was found (its section printed) and gave no status, and
|
||||
only by a driver that can gain root. A refusal leaves it unread.
|
||||
"""
|
||||
patches = facts.get("live_patches")
|
||||
run = getattr(self, "_run_livepatch_status_command", None)
|
||||
if patches is None or not patches["canonical_installed"] or not callable(run):
|
||||
return facts
|
||||
if patches["canonical"] is not None:
|
||||
return facts
|
||||
try:
|
||||
status = run(LIVEPATCH_STATUS_COMMAND)
|
||||
except Exception: # noqa: BLE001 - root refused or the client failed
|
||||
# Not read: ``canonical`` stays None, as without a driver that gains root.
|
||||
return facts
|
||||
patches["canonical"] = parse_canonical_status(status)
|
||||
return facts
|
||||
@@ -0,0 +1,34 @@
|
||||
"""The shape of the kernel facts (``KernelFactsMixin.get_kernel_facts``).
|
||||
|
||||
A module of its own rather than in :mod:`napalm_device_types.models`, which re-exports
|
||||
it: the reading grew its live patches (NetOrk/netork#2701), and ``models`` is at its
|
||||
recorded size.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from typing import NotRequired
|
||||
|
||||
from typing_extensions import TypedDict
|
||||
|
||||
from napalm_device_types.livepatch import LivePatchesDict
|
||||
|
||||
|
||||
class KernelFactsDict(TypedDict):
|
||||
"""What the running kernel has built and loaded (``KernelFactsMixin.get_kernel_facts``).
|
||||
|
||||
``None`` means *could not be read*; an empty list means *read, and there is
|
||||
nothing*. The difference is what lets a consumer say "this module cannot be
|
||||
loaded on this kernel" rather than "we did not look".
|
||||
|
||||
Module names are normalised by :func:`napalm_device_types.kernel.module_name`:
|
||||
no path, no ``.ko`` suffix, ``-`` folded to ``_``.
|
||||
"""
|
||||
|
||||
release: str # uname -r
|
||||
loaded: list[str] | None # /proc/modules
|
||||
builtin: list[str] | None # modules.builtin -- compiled into the kernel image
|
||||
available: list[str] | None # modules.dep -- shipped as loadable modules
|
||||
config: dict[str, str] | None # build configuration, set options only; quotes stripped
|
||||
#: The live patches the kernel carries (NetOrk/netork#2701, ``livepatch``).
|
||||
live_patches: NotRequired[LivePatchesDict]
|
||||
@@ -0,0 +1,201 @@
|
||||
"""The live patches a running Linux kernel carries, as the kernel and the vendors' tools say it.
|
||||
|
||||
A live patch replaces kernel functions while the kernel runs: it fixes a CVE without a
|
||||
new release, and without the reboot a new release needs (NetOrk/netork#2701). Three
|
||||
places say which are in, each read by the kernel facts (:mod:`napalm_device_types.kernel`):
|
||||
|
||||
- **The kernel itself:** ``/sys/kernel/livepatch/<patch>/enabled`` for every patch
|
||||
loaded, whoever built it (kpatch, Canonical, SUSE's kGraft successor), and
|
||||
``transition`` while it is still being applied. No package needed.
|
||||
- **kpatch** (the Red Hat family): ``kpatch list`` names the patch modules loaded, with
|
||||
whether each is enabled, and those installed for each kernel.
|
||||
- **Canonical Livepatch** (Ubuntu Pro): ``canonical-livepatch status --format json``,
|
||||
the daemon's last state -- the kernel it is for, whether a patch is applied, and the
|
||||
CVEs it fixes. ``status`` reads what the daemon holds; netOrk never runs ``refresh``,
|
||||
which is what calls Canonical.
|
||||
|
||||
Parsing only: what a patch means for a CVE is the consumer's call. **Not read is None**:
|
||||
a kernel built without live patching has no ``/sys/kernel/livepatch`` and ``loaded`` is
|
||||
None; a host without kpatch or Canonical's client has ``kpatch`` / ``canonical`` None.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import json
|
||||
import re
|
||||
from collections.abc import Iterable, Mapping
|
||||
from typing import Any
|
||||
|
||||
from typing_extensions import TypedDict
|
||||
|
||||
_CVE = re.compile(r"\bcve-(\d{4})-(\d{4,})\b", re.IGNORECASE)
|
||||
#: ``5.15.0-91.101-generic`` (Canonical's) is ``5.15.0-91-generic`` (``uname -r``).
|
||||
_CANONICAL_KERNEL = re.compile(r"^(\d+\.\d+\.\d+-\d+)\.[^-]+(-.+)$")
|
||||
_KPATCH_LOADED = re.compile(r"^(\S+)\s+\[(enabled|disabled)\]$")
|
||||
_KPATCH_INSTALLED = re.compile(r"^(\S+)\s+\((\S+)\)$")
|
||||
|
||||
|
||||
class LoadedLivePatchDict(TypedDict):
|
||||
"""One directory under ``/sys/kernel/livepatch``."""
|
||||
|
||||
name: str
|
||||
enabled: bool | None
|
||||
#: Still being applied to (or taken off) every task.
|
||||
transition: bool | None
|
||||
|
||||
|
||||
class KpatchModuleDict(TypedDict, total=False):
|
||||
name: str
|
||||
enabled: bool # loaded ones
|
||||
kernel: str # installed ones: the kernel they are built for
|
||||
|
||||
|
||||
class KpatchDict(TypedDict):
|
||||
loaded: list[KpatchModuleDict]
|
||||
installed: list[KpatchModuleDict]
|
||||
|
||||
|
||||
class LivepatchFixDict(TypedDict):
|
||||
cve: str # upper case, "CVE-2023-1077"
|
||||
patched: bool
|
||||
|
||||
|
||||
class CanonicalLivepatchDict(TypedDict):
|
||||
"""``canonical-livepatch status`` for the running kernel. None in a field: not said."""
|
||||
|
||||
kernel: str | None # as Canonical writes it: "5.15.0-91.101-generic"
|
||||
running: bool | None
|
||||
state: str | None # "applied", "nothing-to-apply", "unapplied", "apply-failed", ...
|
||||
check_state: str | None # "checked", "needs-check", "check-failed", ...
|
||||
version: str | None
|
||||
fixes: list[LivepatchFixDict]
|
||||
|
||||
|
||||
class LivePatchesDict(TypedDict):
|
||||
#: ``/sys/kernel/livepatch``; None: the kernel has no live patching.
|
||||
loaded: list[LoadedLivePatchDict] | None
|
||||
#: ``kpatch list``; None: kpatch is not installed.
|
||||
kpatch: KpatchDict | None
|
||||
#: ``canonical-livepatch status``; None: not installed, or its status not read.
|
||||
canonical: CanonicalLivepatchDict | None
|
||||
#: Canonical's client is on the host (``canonical`` None then: its status unread).
|
||||
canonical_installed: bool
|
||||
|
||||
|
||||
def _flag(word: str | None) -> bool | None:
|
||||
return {"1": True, "0": False}.get(word or "")
|
||||
|
||||
|
||||
def parse_sysfs_livepatches(lines: Iterable[str]) -> list[LoadedLivePatchDict]:
|
||||
"""``<name> <enabled> <transition>`` per loaded patch, as the command prints them."""
|
||||
patches: list[LoadedLivePatchDict] = []
|
||||
for line in lines:
|
||||
words = line.split()
|
||||
if not words:
|
||||
continue
|
||||
patches.append(
|
||||
{
|
||||
"name": words[0],
|
||||
"enabled": _flag(words[1] if len(words) > 1 else None),
|
||||
"transition": _flag(words[2] if len(words) > 2 else None),
|
||||
}
|
||||
)
|
||||
return patches
|
||||
|
||||
|
||||
def parse_kpatch_list(lines: Iterable[str]) -> KpatchDict:
|
||||
"""``kpatch list``: the loaded modules with their state, the installed ones by kernel."""
|
||||
found: KpatchDict = {"loaded": [], "installed": []}
|
||||
for line in (raw.strip() for raw in lines):
|
||||
loaded = _KPATCH_LOADED.match(line)
|
||||
if loaded:
|
||||
found["loaded"].append({"name": loaded[1], "enabled": loaded[2] == "enabled"})
|
||||
continue
|
||||
installed = _KPATCH_INSTALLED.match(line)
|
||||
if installed:
|
||||
found["installed"].append({"name": installed[1], "kernel": installed[2]})
|
||||
return found
|
||||
|
||||
|
||||
def canonical_release(kernel: str | None) -> str | None:
|
||||
"""Canonical's name of a kernel as ``uname -r`` names it: without the upload number."""
|
||||
if kernel is None:
|
||||
return None
|
||||
match = _CANONICAL_KERNEL.match(kernel)
|
||||
return f"{match[1]}{match[2]}" if match else kernel
|
||||
|
||||
|
||||
def _get(data: Mapping[str, Any], key: str) -> Any:
|
||||
"""*key* in either case: the client wrote ``Status``, later ``status``."""
|
||||
for name, value in data.items():
|
||||
if name.lower() == key.lower():
|
||||
return value
|
||||
return None
|
||||
|
||||
|
||||
def _text(value: object) -> str | None:
|
||||
return value if isinstance(value, str) and value else None
|
||||
|
||||
|
||||
def _cve(text: str) -> str | None:
|
||||
match = _CVE.search(text)
|
||||
return f"CVE-{match[1]}-{match[2]}" if match else None
|
||||
|
||||
|
||||
def _fixes(value: object) -> list[LivepatchFixDict]:
|
||||
"""The 10.x client's list of fixes, or the 9.x client's text of ``* cve-...`` lines."""
|
||||
if isinstance(value, str):
|
||||
return [{"cve": cve, "patched": True} for line in value.splitlines() if (cve := _cve(line))]
|
||||
fixes: list[LivepatchFixDict] = []
|
||||
for fix in value if isinstance(value, list) else []:
|
||||
if not isinstance(fix, Mapping):
|
||||
continue
|
||||
cve = _cve(str(_get(fix, "Name") or ""))
|
||||
if cve:
|
||||
fixes.append({"cve": cve, "patched": _get(fix, "Patched") is True})
|
||||
return fixes
|
||||
|
||||
|
||||
def _running_entry(entries: list[Any]) -> Mapping[str, Any] | None:
|
||||
"""The status of the running kernel: the one marked running, else the only one."""
|
||||
mappings = [e for e in entries if isinstance(e, Mapping)]
|
||||
running = [e for e in mappings if _get(e, "Running") is True]
|
||||
if running:
|
||||
return running[0]
|
||||
return mappings[0] if len(mappings) == 1 else None
|
||||
|
||||
|
||||
def parse_canonical_status(text: str) -> CanonicalLivepatchDict | None:
|
||||
"""``canonical-livepatch status --format json``; None when it carries no status."""
|
||||
try:
|
||||
data = json.loads(text)
|
||||
except ValueError:
|
||||
return None
|
||||
entries = _get(data, "Status") if isinstance(data, Mapping) else None
|
||||
entry = _running_entry(entries) if isinstance(entries, list) else None
|
||||
if entry is None:
|
||||
return None
|
||||
patch = _get(entry, "Livepatch")
|
||||
patch = patch if isinstance(patch, Mapping) else {}
|
||||
running = _get(entry, "Running")
|
||||
return {
|
||||
"kernel": _text(_get(entry, "Kernel")),
|
||||
"running": running if isinstance(running, bool) else None,
|
||||
"state": _text(_get(patch, "State")),
|
||||
"check_state": _text(_get(patch, "CheckState")),
|
||||
"version": _text(_get(patch, "Version")),
|
||||
"fixes": _fixes(_get(patch, "Fixes")),
|
||||
}
|
||||
|
||||
|
||||
def live_patches(sections: Mapping[str, list[str]]) -> LivePatchesDict:
|
||||
"""The three readings from the kernel facts' sections."""
|
||||
canonical = sections.get("canonical_livepatch")
|
||||
return {
|
||||
"loaded": parse_sysfs_livepatches(sections["livepatch"])
|
||||
if "livepatch" in sections
|
||||
else None,
|
||||
"kpatch": parse_kpatch_list(sections["kpatch"]) if "kpatch" in sections else None,
|
||||
"canonical": parse_canonical_status("".join(canonical)) if canonical else None,
|
||||
"canonical_installed": canonical is not None,
|
||||
}
|
||||
@@ -0,0 +1,452 @@
|
||||
"""Every account a person can log in with on a Linux host, and how it is used (NetOrk/netork#2707).
|
||||
|
||||
An access review asks who can get into the systems people actually log in to. On a
|
||||
host that is every account with a shell, not only the ones an application created:
|
||||
|
||||
- **The accounts:** ``/etc/passwd``, root and UID 1000 on, with a shell that lets them
|
||||
in (not ``nologin`` or ``false``; :func:`login_capable`). Only the name, UID, home and
|
||||
shell cross: the comment field is a person's name. Accounts from a directory (SSSD,
|
||||
an AD join) are not in ``/etc/passwd`` and are not read: the directory reviews them.
|
||||
- **The last login,** from every source the host has -- ``lastlog2`` (util-linux 2.40
|
||||
on), the legacy ``lastlog``, ``wtmpdb last`` and ``last`` (wtmp) -- the newest of them
|
||||
wins, with the tool that told it. A host upgraded to lastlog2 keeps an old lastlog
|
||||
file, a desktop login reaches wtmp and not lastlog: no single source is the whole story.
|
||||
- **Lock and expiry,** from ``passwd -S`` (the password set, locked or empty) and
|
||||
``chage -l`` (password change, password and account expiry), as root. An account is
|
||||
``locked`` when its password is locked or it expired -- ``usermod -L -e 1`` does both.
|
||||
- **The failed attempts since the last login,** a number per account: from ``lastb``
|
||||
(btmp; the newest :data:`FAILED_LOGINS_READ` per account) where the host keeps it,
|
||||
else from ``pam_faillock``'s tally, which a successful login resets. Root only.
|
||||
|
||||
One fixed command, read-only, the same on every Linux host; ``LC_ALL=C`` keeps the tools'
|
||||
dates in one format. **Not read is None, never "no":** read as the login user, the lock,
|
||||
the expiry and the failures are ``None``, not "unlocked" or "none failed".
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import re
|
||||
from collections.abc import Iterable
|
||||
from datetime import UTC, date, datetime
|
||||
from shlex import quote
|
||||
from typing import TYPE_CHECKING, TypedDict
|
||||
|
||||
from napalm_device_types.terminal import strip_terminal_codes
|
||||
|
||||
_BEGIN = "LOGINS_BEGIN"
|
||||
_END = "LOGINS_END"
|
||||
|
||||
#: The failed attempts ``lastb`` hands over per account, newest first: a host on the
|
||||
#: internet collects millions in btmp. A count that reaches it is "at least".
|
||||
FAILED_LOGINS_READ = 1000
|
||||
|
||||
#: Root, and people: UID 1000 on, without the overflow UID ``nobody`` has.
|
||||
_FIRST_PERSON_UID = 1000
|
||||
_NOBODY_UID = 65534
|
||||
_NO_LOGIN_SHELLS = frozenset({"nologin", "false"})
|
||||
|
||||
#: The awk filter for a login-capable ``/etc/passwd`` line; :func:`login_capable` again.
|
||||
_CAPABLE = f"($3==0||$3>={_FIRST_PERSON_UID})&&$3!={_NOBODY_UID}&&$7!~/(^|\\/)(nologin|false)$/"
|
||||
#: Keeps the lines of the accounts in ``$u``, the first *n* of each.
|
||||
_KEEP = 'awk -v u=" $u " -v n={n} \'index(u, " " $1 " ") && c[$1]++ < n\''
|
||||
|
||||
#: One line, POSIX ``sh``, read-only, no stdin (a sudo password must not reach a tool).
|
||||
#: The frame markers are printed in two halves so that a transport which echoes the
|
||||
#: command does not show them early. ``passwd``, ``chage`` and ``faillock`` live in
|
||||
#: ``/usr/sbin`` on some systems, outside a login user's ``PATH``.
|
||||
LOGIN_ACCOUNTS_COMMAND = (
|
||||
"exec </dev/null; PATH=$PATH:/usr/sbin:/sbin; LC_ALL=C; export LC_ALL; "
|
||||
f"u=$(awk -F: '{_CAPABLE}{{print $1}}' /etc/passwd 2>/dev/null | tr '\\n' ' '); "
|
||||
'h() { command -v "$1" >/dev/null 2>&1; }; '
|
||||
"printf '%s%s\\n' LOGINS_ BEGIN; "
|
||||
"echo '[uid]'; id -u; echo '[now]'; date -u +%Y-%m-%d; "
|
||||
f'echo \'[passwd]\'; awk -F: \'{_CAPABLE}{{print $1":"$3":"$6":"$7}}\' /etc/passwd; '
|
||||
f"if h lastlog2; then echo '[lastlog2]'; lastlog2 2>/dev/null | {_KEEP.format(n=1)}; fi; "
|
||||
f"if h lastlog; then echo '[lastlog]'; lastlog 2>/dev/null | {_KEEP.format(n=1)}; fi; "
|
||||
"if h wtmpdb && wtmpdb last --time-format iso -n 1 >/dev/null 2>&1; then echo '[wtmpdb]'; "
|
||||
f"wtmpdb last --time-format iso 2>/dev/null | {_KEEP.format(n=1)}; fi; "
|
||||
"if h last && last --time-format iso -n 1 >/dev/null 2>&1; then echo '[wtmp]'; "
|
||||
f"last --time-format iso -w 2>/dev/null | {_KEEP.format(n=1)}; fi; "
|
||||
"if h lastb && lastb --time-format iso -n 1 >/dev/null 2>&1; then echo '[lastb]'; "
|
||||
f"lastb --time-format iso -w 2>/dev/null | {_KEEP.format(n=FAILED_LOGINS_READ)}; fi; "
|
||||
'for n in $u; do echo "[passwd_status $n]"; passwd -S "$n" 2>/dev/null; '
|
||||
'echo "[chage $n]"; chage -l "$n" 2>/dev/null; '
|
||||
'if h faillock; then echo "[faillock $n]"; faillock --user "$n" 2>/dev/null; fi; done; '
|
||||
"printf '%s%s\\n' LOGINS_ END"
|
||||
)
|
||||
|
||||
#: The tools a last login can come from, in the order they are named.
|
||||
LOGIN_SOURCES = ("lastlog2", "lastlog", "wtmpdb", "wtmp")
|
||||
|
||||
_SECTION = re.compile(r"^\[([a-z0-9_]+)(?: (\S+))?\]$")
|
||||
#: ``%a %b %e %H:%M:%S %z %Y``, lastlog's and lastlog2's date, at the end of a line.
|
||||
_LASTLOG_DATE = re.compile(r"\s(\w{3} \w{3} +\d{1,2} \d{2}:\d{2}:\d{2}(?: [+-]\d{4})? \d{4})$")
|
||||
_ISO = re.compile(r"^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}")
|
||||
#: A row of a ``faillock`` tally starts with its date.
|
||||
_ISO_DATE = re.compile(r"^\d{4}-\d{2}-\d{2} ")
|
||||
#: The states of an account's password, as the reading names them. Named, not literals in
|
||||
#: a comparison: a state word is no password, but a scanner reading ``password == "..."``
|
||||
#: takes it for one (bandit B105).
|
||||
STATE_SET, STATE_LOCKED, STATE_NONE = "set", "locked", "none"
|
||||
#: ``passwd -S``'s second word: shadow's and libuser's.
|
||||
_PASSWORD_STATES = {
|
||||
"P": STATE_SET,
|
||||
"PS": STATE_SET,
|
||||
"L": STATE_LOCKED,
|
||||
"LK": STATE_LOCKED,
|
||||
"NP": STATE_NONE,
|
||||
}
|
||||
_NEVER = "never"
|
||||
_MUST_CHANGE = "password must be changed"
|
||||
|
||||
_Sections = dict[tuple[str, str | None], list[str]]
|
||||
|
||||
|
||||
class LoginAccountDict(TypedDict):
|
||||
"""One login-capable account. ``None`` in a field: could not be read."""
|
||||
|
||||
name: str
|
||||
uid: int
|
||||
home: str
|
||||
shell: str
|
||||
#: The newest login any source knows, ISO 8601 in UTC; None: never, or not read
|
||||
#: (``login_sources`` empty).
|
||||
last_login: str | None
|
||||
last_login_from: str | None # the remote host; None for a console login
|
||||
last_login_port: str | None # the terminal: "pts/0", "tty1", ":0"
|
||||
last_login_source: str | None # one of LOGIN_SOURCES
|
||||
password: str | None # "set", "locked" or "none" (passwd -S)
|
||||
password_changed: str | None # ISO date; None: never set, or not read
|
||||
password_expires: str | None # ISO date, "never" or "must_change"
|
||||
account_expires: str | None # ISO date or "never"
|
||||
#: The password locked, or the account expired on the host's date.
|
||||
locked: bool | None
|
||||
#: Failed attempts since the last login (lastb), or in the tally (faillock).
|
||||
failed_logins: int | None
|
||||
#: The count reached FAILED_LOGINS_READ: there may be more.
|
||||
failed_logins_capped: bool
|
||||
|
||||
|
||||
class LoginAccountsDict(TypedDict):
|
||||
"""What :meth:`LoginAccountsMixin.get_login_accounts` read."""
|
||||
|
||||
accounts: list[LoginAccountDict]
|
||||
#: The sources of the last logins the host has, of LOGIN_SOURCES; empty: none.
|
||||
login_sources: list[str]
|
||||
#: "lastb" or "faillock"; None: neither could be read.
|
||||
failed_logins_source: str | None
|
||||
#: Read as root: the lock, the expiry and the failures are known.
|
||||
privileged: bool
|
||||
|
||||
|
||||
class _Login(TypedDict):
|
||||
at: datetime
|
||||
port: str | None
|
||||
host: str | None
|
||||
source: str
|
||||
|
||||
|
||||
def login_capable(uid: int, shell: str) -> bool:
|
||||
"""Whether an account with *uid* and *shell* is one a person logs in with: root, or
|
||||
UID 1000 on (not ``nobody``'s), and a shell that is not ``nologin`` or ``false``.
|
||||
An empty shell is ``/bin/sh``."""
|
||||
if uid != 0 and (uid < _FIRST_PERSON_UID or uid == _NOBODY_UID):
|
||||
return False
|
||||
return shell.rsplit("/", 1)[-1] not in _NO_LOGIN_SHELLS
|
||||
|
||||
|
||||
def _sections(output: str) -> _Sections:
|
||||
lines = [line.rstrip() for line in strip_terminal_codes(output).splitlines()]
|
||||
stripped = [line.strip() for line in lines]
|
||||
try:
|
||||
start = stripped.index(_BEGIN)
|
||||
end = stripped.index(_END, start)
|
||||
except ValueError:
|
||||
raise ValueError("no intact login report in the output") from None
|
||||
sections: _Sections = {}
|
||||
current: list[str] = []
|
||||
for line in lines[start + 1 : end]:
|
||||
header = _SECTION.match(line.strip())
|
||||
if header:
|
||||
current = sections.setdefault((header.group(1), header.group(2)), [])
|
||||
elif line.strip():
|
||||
current.append(line)
|
||||
return sections
|
||||
|
||||
|
||||
def _first(sections: _Sections, key: str, arg: str | None = None) -> str | None:
|
||||
lines = sections.get((key, arg))
|
||||
return lines[0].strip() if lines else None
|
||||
|
||||
|
||||
def _accounts(sections: _Sections) -> list[tuple[str, int, str, str]]:
|
||||
accounts = []
|
||||
for line in sections.get(("passwd", None), []):
|
||||
fields = line.strip().split(":")
|
||||
if len(fields) != 4 or not fields[1].isdigit():
|
||||
continue
|
||||
name, uid, home, shell = fields[0], int(fields[1]), fields[2], fields[3]
|
||||
if login_capable(uid, shell):
|
||||
accounts.append((name, uid, home, shell))
|
||||
return accounts
|
||||
|
||||
|
||||
def _where(middle: list[str]) -> tuple[str | None, str | None]:
|
||||
"""The terminal and the remote host between a line's name and its date."""
|
||||
port = middle[0] if middle else None
|
||||
host = middle[1] if len(middle) > 1 else None
|
||||
return port, host
|
||||
|
||||
|
||||
def _lastlog_line(line: str, source: str) -> tuple[str, _Login] | None:
|
||||
"""A ``lastlog``/``lastlog2`` line; None for "Never logged in" or a header."""
|
||||
found = _LASTLOG_DATE.search(line)
|
||||
if not found:
|
||||
return None
|
||||
text = " ".join(found.group(1).split())
|
||||
try:
|
||||
if re.search(r" [+-]\d{4} ", text):
|
||||
at = datetime.strptime(text, "%a %b %d %H:%M:%S %z %Y")
|
||||
else:
|
||||
at = datetime.strptime(text, "%a %b %d %H:%M:%S %Y").replace(tzinfo=UTC)
|
||||
except ValueError:
|
||||
return None
|
||||
words = line[: found.start()].split()
|
||||
port, host = _where(words[1:])
|
||||
return words[0], {"at": at, "port": port, "host": host, "source": source}
|
||||
|
||||
|
||||
def _iso_line(line: str, source: str) -> tuple[str, _Login] | None:
|
||||
"""A ``last``/``lastb``/``wtmpdb last`` line in ``--time-format iso``."""
|
||||
words = line.split()
|
||||
for index, word in enumerate(words[1:], start=1):
|
||||
if _ISO.match(word):
|
||||
try:
|
||||
at = datetime.fromisoformat(word)
|
||||
except ValueError:
|
||||
return None
|
||||
if at.tzinfo is None:
|
||||
at = at.replace(tzinfo=UTC)
|
||||
port, host = _where(words[1:index])
|
||||
return words[0], {"at": at, "port": port, "host": host, "source": source}
|
||||
return None
|
||||
|
||||
|
||||
def _source_logins(sections: _Sections, source: str) -> Iterable[tuple[str, _Login]]:
|
||||
parse = _lastlog_line if source in ("lastlog2", "lastlog") else _iso_line
|
||||
for line in sections.get((source, None), []):
|
||||
parsed = parse(line, source)
|
||||
if parsed is not None:
|
||||
yield parsed
|
||||
|
||||
|
||||
def _last_logins(sections: _Sections, sources: list[str]) -> dict[str, _Login]:
|
||||
"""Each account's newest login over every source read."""
|
||||
newest: dict[str, _Login] = {}
|
||||
for source in sources:
|
||||
for name, login in _source_logins(sections, source):
|
||||
if name not in newest or login["at"] > newest[name]["at"]:
|
||||
newest[name] = login
|
||||
return newest
|
||||
|
||||
|
||||
def _chage_date(value: str) -> str | None:
|
||||
try:
|
||||
return datetime.strptime(value, "%b %d, %Y").date().isoformat()
|
||||
except ValueError:
|
||||
return None
|
||||
|
||||
|
||||
def _chage(lines: list[str]) -> dict[str, str]:
|
||||
fields = {}
|
||||
for line in lines:
|
||||
key, sep, value = line.partition(":")
|
||||
if sep:
|
||||
fields[" ".join(key.split()).lower()] = value.strip()
|
||||
return fields
|
||||
|
||||
|
||||
def _expiry(value: str | None, *, must_change: bool = False) -> str | None:
|
||||
"""A chage date as ISO, "never", "must_change"; None when it does not read as one."""
|
||||
if value is None:
|
||||
return None
|
||||
if value == _NEVER:
|
||||
return _NEVER
|
||||
if value == _MUST_CHANGE:
|
||||
return "must_change" if must_change else None
|
||||
return _chage_date(value)
|
||||
|
||||
|
||||
def _password(sections: _Sections, name: str) -> str | None:
|
||||
words = (_first(sections, "passwd_status", name) or "").split()
|
||||
if len(words) < 2 or words[0] != name:
|
||||
return None
|
||||
return _PASSWORD_STATES.get(words[1])
|
||||
|
||||
|
||||
def _expired(account_expires: str | None, today: date | None) -> bool | None:
|
||||
"""Whether the account expired on the host's date; pam_unix refuses it from that day."""
|
||||
if account_expires is None:
|
||||
return None
|
||||
if account_expires == _NEVER:
|
||||
return False
|
||||
return None if today is None else date.fromisoformat(account_expires) <= today
|
||||
|
||||
|
||||
def _locked(password: str | None, account_expires: str | None, today: date | None) -> bool | None:
|
||||
"""Locked when either says so, open when both say not, else unknown."""
|
||||
password_locked = None if password is None else password == STATE_LOCKED
|
||||
expired = _expired(account_expires, today)
|
||||
if password_locked or expired:
|
||||
return True
|
||||
if password_locked is False and expired is False:
|
||||
return False
|
||||
return None
|
||||
|
||||
|
||||
def _today(sections: _Sections) -> date | None:
|
||||
try:
|
||||
return date.fromisoformat(_first(sections, "now") or "")
|
||||
except ValueError:
|
||||
return None
|
||||
|
||||
|
||||
def _faillock(lines: list[str] | None) -> int | None:
|
||||
"""The valid failures in a ``faillock --user`` tally; None without its table."""
|
||||
if not lines or not any(line.split()[:1] == ["When"] for line in lines):
|
||||
return None
|
||||
return sum(1 for line in lines if _ISO_DATE.match(line.strip()) and line.split()[-1] == "V")
|
||||
|
||||
|
||||
def _btmp(sections: _Sections) -> dict[str, list[datetime]]:
|
||||
failures: dict[str, list[datetime]] = {}
|
||||
for name, login in _source_logins(sections, "lastb"):
|
||||
failures.setdefault(name, []).append(login["at"])
|
||||
return failures
|
||||
|
||||
|
||||
def _failures(
|
||||
sections: _Sections, name: str, last: _Login | None, btmp: dict[str, list[datetime]] | None
|
||||
) -> tuple[int | None, bool]:
|
||||
"""Failed attempts since *last* and whether the count is capped: lastb first."""
|
||||
if btmp is not None:
|
||||
seen = btmp.get(name, [])
|
||||
count = sum(1 for at in seen if last is None or at > last["at"])
|
||||
return count, count >= FAILED_LOGINS_READ
|
||||
return _faillock(sections.get(("faillock", name))), False
|
||||
|
||||
|
||||
def _failed_source(sections: _Sections, names: list[str]) -> str | None:
|
||||
if ("lastb", None) in sections:
|
||||
return "lastb"
|
||||
if any(_faillock(sections.get(("faillock", name))) is not None for name in names):
|
||||
return "faillock"
|
||||
return None
|
||||
|
||||
|
||||
def _account(
|
||||
sections: _Sections,
|
||||
entry: tuple[str, int, str, str],
|
||||
last: _Login | None,
|
||||
btmp: dict[str, list[datetime]] | None,
|
||||
) -> LoginAccountDict:
|
||||
name, uid, home, shell = entry
|
||||
chage = _chage(sections.get(("chage", name), []))
|
||||
password = _password(sections, name)
|
||||
account_expires = _expiry(chage.get("account expires"))
|
||||
failed, capped = _failures(sections, name, last, btmp)
|
||||
return {
|
||||
"name": name,
|
||||
"uid": uid,
|
||||
"home": home,
|
||||
"shell": shell,
|
||||
"last_login": None if last is None else last["at"].astimezone(UTC).isoformat(),
|
||||
"last_login_from": None if last is None else last["host"],
|
||||
"last_login_port": None if last is None else last["port"],
|
||||
"last_login_source": None if last is None else last["source"],
|
||||
"password": password,
|
||||
"password_changed": _chage_date(chage.get("last password change", "")),
|
||||
"password_expires": _expiry(chage.get("password expires"), must_change=True),
|
||||
"account_expires": account_expires,
|
||||
"locked": _locked(password, account_expires, _today(sections)),
|
||||
"failed_logins": failed,
|
||||
"failed_logins_capped": capped,
|
||||
}
|
||||
|
||||
|
||||
def parse_login_accounts(output: str) -> LoginAccountsDict:
|
||||
"""Parse what :data:`LOGIN_ACCOUNTS_COMMAND` printed.
|
||||
|
||||
:raises ValueError: when the output carries no intact report.
|
||||
"""
|
||||
sections = _sections(output)
|
||||
entries = _accounts(sections)
|
||||
sources = [source for source in LOGIN_SOURCES if (source, None) in sections]
|
||||
logins = _last_logins(sections, sources)
|
||||
btmp = _btmp(sections) if ("lastb", None) in sections else None
|
||||
return {
|
||||
"accounts": [_account(sections, e, logins.get(e[0]), btmp) for e in entries],
|
||||
"login_sources": sources,
|
||||
"failed_logins_source": _failed_source(sections, [e[0] for e in entries]),
|
||||
"privileged": _first(sections, "uid") == "0",
|
||||
}
|
||||
|
||||
|
||||
class LoginAccountsMixin:
|
||||
"""Adds :meth:`get_login_accounts` to a driver that can run a command on a Linux host.
|
||||
|
||||
The template form (README, "Function classes"): the command and its parse are the
|
||||
same everywhere, and a driver supplies only :meth:`_run_login_accounts_command` --
|
||||
how a command reaches its host, and how it gains root there. Mixed in by the drivers
|
||||
that can, so ``hasattr(driver, "get_login_accounts")`` stays a truthful answer.
|
||||
"""
|
||||
|
||||
if TYPE_CHECKING: # pragma: no cover - declared for type checkers only
|
||||
|
||||
def _run_login_accounts_command(self, command: str, *, privileged: bool) -> str:
|
||||
"""Run *command* on the host and return what it printed; as root when
|
||||
*privileged*. The command is a single ``sh -c`` invocation; it reads no stdin."""
|
||||
...
|
||||
|
||||
def get_login_accounts(self) -> LoginAccountsDict:
|
||||
"""
|
||||
Returns every account on the host a person can log in with, and how it is used.
|
||||
|
||||
* accounts (list) - root and UID 1000 on with a login shell, in ``/etc/passwd``'s
|
||||
order: name, uid, home, shell; last_login (ISO, UTC), last_login_from,
|
||||
last_login_port and last_login_source; password ("set", "locked", "none"),
|
||||
password_changed, password_expires and account_expires (ISO date, "never",
|
||||
"must_change"), locked; failed_logins since the last login and
|
||||
failed_logins_capped
|
||||
* login_sources (list) - which of lastlog2, lastlog, wtmpdb, wtmp the host has
|
||||
* failed_logins_source (str or None) - "lastb" or "faillock"
|
||||
* privileged (bool) - read as root
|
||||
|
||||
``None`` in a field means not read. Read as root first; where root is refused, as
|
||||
the login user: the last logins only.
|
||||
|
||||
Example::
|
||||
|
||||
{
|
||||
"accounts": [{"name": "alice", "uid": 1000, "home": "/home/alice",
|
||||
"shell": "/bin/bash",
|
||||
"last_login": "2026-11-27T21:01:02+00:00",
|
||||
"last_login_from": "192.0.2.10", "last_login_port": "pts/0",
|
||||
"last_login_source": "lastlog", "password": "set",
|
||||
"password_changed": "2026-11-01",
|
||||
"password_expires": "never", "account_expires": "never",
|
||||
"locked": False, "failed_logins": 2,
|
||||
"failed_logins_capped": False}],
|
||||
"login_sources": ["lastlog", "wtmp"],
|
||||
"failed_logins_source": "lastb",
|
||||
"privileged": True,
|
||||
}
|
||||
|
||||
:raises ValueError: if neither reading carried an intact report.
|
||||
"""
|
||||
command = f"sh -c {quote(LOGIN_ACCOUNTS_COMMAND)}"
|
||||
try:
|
||||
return parse_login_accounts(self._run_login_accounts_command(command, privileged=True))
|
||||
except ValueError:
|
||||
pass
|
||||
return parse_login_accounts(self._run_login_accounts_command(command, privileged=False))
|
||||
@@ -21,6 +21,7 @@ from napalm_device_types.access_point_models import SSIDBridgeDict as SSIDBridge
|
||||
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.kernel_models import KernelFactsDict as KernelFactsDict
|
||||
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
|
||||
@@ -273,24 +274,6 @@ class NATTranslationDict(TypedDict):
|
||||
age: float
|
||||
|
||||
|
||||
class KernelFactsDict(TypedDict):
|
||||
"""What the running kernel has built and loaded (``KernelFactsMixin.get_kernel_facts``).
|
||||
|
||||
``None`` means *could not be read*; an empty list means *read, and there is
|
||||
nothing*. The difference is what lets a consumer say "this module cannot be
|
||||
loaded on this kernel" rather than "we did not look".
|
||||
|
||||
Module names are normalised by :func:`napalm_device_types.kernel.module_name`:
|
||||
no path, no ``.ko`` suffix, ``-`` folded to ``_``.
|
||||
"""
|
||||
|
||||
release: str # uname -r
|
||||
loaded: list[str] | None # /proc/modules
|
||||
builtin: list[str] | None # modules.builtin -- compiled into the kernel image
|
||||
available: list[str] | None # modules.dep -- shipped as loadable modules
|
||||
config: dict[str, str] | None # build configuration, set options only; quotes stripped
|
||||
|
||||
|
||||
class ListeningSocketDict(TypedDict):
|
||||
"""A TCP socket that listens, or a UDP socket that is bound, on the host.
|
||||
|
||||
|
||||
+1
-1
@@ -4,7 +4,7 @@ build-backend = "setuptools.build_meta"
|
||||
|
||||
[project]
|
||||
name = "napalm-device-types"
|
||||
version = "4.50.0"
|
||||
version = "4.53.0"
|
||||
description = "Abstract device-type base classes for NAPALM drivers"
|
||||
readme = "README.md"
|
||||
requires-python = ">=3.12"
|
||||
|
||||
@@ -31,7 +31,7 @@
|
||||
},
|
||||
"mypy_relaxed": [],
|
||||
"python_file_lines": {
|
||||
"napalm_device_types/models.py": 1353
|
||||
"napalm_device_types/models.py": 1336
|
||||
},
|
||||
"untyped_public": []
|
||||
}
|
||||
@@ -0,0 +1,476 @@
|
||||
"""install_cpu_microcode: the CPU vendor's microcode on a host that runs on its own CPU.
|
||||
|
||||
A CPU vulnerability the kernel reports ``Vulnerable: ... no microcode`` closes with the
|
||||
microcode the CPU's vendor ships, which the distribution packages and the initramfs
|
||||
loads at the next boot (NetOrk/netork#2706). A guest loads none: its host does. Debian
|
||||
keeps the packages in ``non-free-firmware`` (``non-free`` up to bullseye), a component
|
||||
a Proxmox VE install does not enable; the fix adds it to Debian's own sources.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import base64
|
||||
import shlex
|
||||
from typing import Any
|
||||
|
||||
import pytest
|
||||
|
||||
from napalm_device_types import OSDriver
|
||||
from napalm_device_types.apt_releases import AptReleaseMixin
|
||||
from napalm_device_types.cpu_microcode import (
|
||||
CpuMicrocodeMixin,
|
||||
add_component,
|
||||
firmware_component,
|
||||
microcode_package,
|
||||
)
|
||||
from napalm_device_types.fixes import EnsurePackageMixin
|
||||
|
||||
|
||||
class TestThePackage:
|
||||
@pytest.mark.parametrize(
|
||||
"os_ids, vendor, package",
|
||||
[
|
||||
(["debian"], "GenuineIntel", "intel-microcode"),
|
||||
(["debian"], "AuthenticAMD", "amd64-microcode"),
|
||||
(["ubuntu", "debian"], "GenuineIntel", "intel-microcode"),
|
||||
(["linuxmint", "ubuntu", "debian"], "AuthenticAMD", "amd64-microcode"),
|
||||
(["almalinux", "rhel", "centos", "fedora"], "GenuineIntel", "microcode_ctl"),
|
||||
(["rocky", "rhel", "centos", "fedora"], "AuthenticAMD", "linux-firmware"),
|
||||
(["fedora"], "GenuineIntel", "microcode_ctl"),
|
||||
(["opensuse-leap", "suse", "opensuse"], "GenuineIntel", "ucode-intel"),
|
||||
(["opensuse-tumbleweed"], "AuthenticAMD", "ucode-amd"),
|
||||
(["sles"], "GenuineIntel", "ucode-intel"),
|
||||
],
|
||||
)
|
||||
def test_by_distribution_and_vendor(self, os_ids, vendor, package):
|
||||
assert microcode_package(os_ids, vendor) == package
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
"os_ids, vendor",
|
||||
[
|
||||
(["arch"], "GenuineIntel"), # a boot loader entry loads it: not ours to write
|
||||
(["alpine"], "AuthenticAMD"),
|
||||
(["qts"], "GenuineIntel"),
|
||||
(["debian"], "HygonGenuine"),
|
||||
(["debian"], None),
|
||||
(None, "GenuineIntel"),
|
||||
([], "GenuineIntel"),
|
||||
],
|
||||
)
|
||||
def test_none_where_no_package_loads_it(self, os_ids, vendor):
|
||||
assert microcode_package(os_ids, vendor) is None
|
||||
|
||||
|
||||
class TestTheComponent:
|
||||
@pytest.mark.parametrize(
|
||||
"codename, component",
|
||||
[
|
||||
("jessie", "non-free"),
|
||||
("stretch", "non-free"),
|
||||
("buster", "non-free"),
|
||||
("bullseye", "non-free"),
|
||||
("bookworm", "non-free-firmware"),
|
||||
("trixie", "non-free-firmware"),
|
||||
("forky", "non-free-firmware"),
|
||||
],
|
||||
)
|
||||
def test_non_free_firmware_from_bookworm_on(self, codename, component):
|
||||
assert firmware_component(codename) == component
|
||||
|
||||
|
||||
PVE_DEB822 = """\
|
||||
Types: deb
|
||||
URIs: http://deb.debian.org/debian/
|
||||
Suites: trixie trixie-updates
|
||||
Components: main contrib
|
||||
Signed-By: /usr/share/keyrings/debian-archive-keyring.gpg
|
||||
|
||||
# The security updates.
|
||||
Types: deb
|
||||
URIs: http://security.debian.org/debian-security/
|
||||
Suites: trixie-security
|
||||
Components: main
|
||||
contrib
|
||||
Signed-By: /usr/share/keyrings/debian-archive-keyring.gpg
|
||||
|
||||
Types: deb
|
||||
URIs: http://deb.debian.org/debian/
|
||||
Suites: trixie-backports
|
||||
Components: main
|
||||
Enabled: no
|
||||
"""
|
||||
|
||||
|
||||
class TestAddComponentDeb822:
|
||||
def test_every_enabled_debian_paragraph_gets_it(self):
|
||||
new, count = add_component(PVE_DEB822, "non-free-firmware", deb822=True)
|
||||
|
||||
assert count == 2
|
||||
assert "Components: main contrib non-free-firmware\n" in new
|
||||
assert "Components: main\n contrib non-free-firmware\n" in new
|
||||
# The disabled paragraph stays as it was.
|
||||
assert new.rstrip().endswith("Components: main\nEnabled: no")
|
||||
assert "# The security updates." in new
|
||||
|
||||
def test_already_there_is_left(self):
|
||||
text = "Types: deb\nURIs: https://deb.debian.org/debian\nSuites: bookworm\n" + (
|
||||
"Components: main non-free-firmware\n"
|
||||
)
|
||||
|
||||
assert add_component(text, "non-free-firmware", deb822=True) == (text, 0)
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
"uri",
|
||||
[
|
||||
"http://download.proxmox.com/debian/pve",
|
||||
"https://download.docker.com/linux/debian",
|
||||
"http://debian.example.org/debian",
|
||||
"http://notdebian.org/debian",
|
||||
],
|
||||
)
|
||||
def test_a_source_that_is_not_debians_is_left(self, uri):
|
||||
text = f"Types: deb\nURIs: {uri}\nSuites: trixie\nComponents: main\n"
|
||||
|
||||
assert add_component(text, "non-free-firmware", deb822=True) == (text, 0)
|
||||
|
||||
def test_a_mirror_of_debian_org_counts(self):
|
||||
text = (
|
||||
"Types: deb\nURIs: http://ftp.de.debian.org/debian\nSuites: trixie\nComponents: main\n"
|
||||
)
|
||||
|
||||
new, count = add_component(text, "non-free-firmware", deb822=True)
|
||||
|
||||
assert count == 1
|
||||
assert "Components: main non-free-firmware" in new
|
||||
|
||||
def test_a_paragraph_without_main_is_left(self):
|
||||
"""``pve-no-subscription`` is not ``main``; nor is a third-party ``stable``."""
|
||||
text = (
|
||||
"Types: deb\nURIs: http://deb.debian.org/debian\nSuites: trixie\nComponents: contrib\n"
|
||||
)
|
||||
|
||||
assert add_component(text, "non-free-firmware", deb822=True)[1] == 0
|
||||
|
||||
def test_a_paragraph_with_another_vendors_uri_beside_debians_is_left(self):
|
||||
text = (
|
||||
"Types: deb\nURIs: http://deb.debian.org/debian http://mirror.example.com/debian\n"
|
||||
"Suites: trixie\nComponents: main\n"
|
||||
)
|
||||
|
||||
assert add_component(text, "non-free-firmware", deb822=True)[1] == 0
|
||||
|
||||
|
||||
class TestAddComponentList:
|
||||
def test_a_debian_line_gets_it_and_its_comment_stays(self):
|
||||
text = (
|
||||
"deb http://ftp.debian.org/debian bookworm main contrib # the archive\n"
|
||||
"deb [arch=amd64 signed-by=/k.gpg] http://security.debian.org bookworm-security main\n"
|
||||
"# deb http://deb.debian.org/debian bookworm-backports main\n"
|
||||
"deb http://download.proxmox.com/debian/pve bookworm pve-no-subscription\n"
|
||||
"deb http://deb.debian.org/debian bookworm-updates main non-free-firmware\n"
|
||||
)
|
||||
|
||||
new, count = add_component(text, "non-free-firmware", deb822=False)
|
||||
|
||||
assert count == 2
|
||||
assert new.splitlines() == [
|
||||
"deb http://ftp.debian.org/debian bookworm main contrib non-free-firmware # the archive",
|
||||
"deb [arch=amd64 signed-by=/k.gpg] http://security.debian.org bookworm-security main "
|
||||
"non-free-firmware",
|
||||
"# deb http://deb.debian.org/debian bookworm-backports main",
|
||||
"deb http://download.proxmox.com/debian/pve bookworm pve-no-subscription",
|
||||
"deb http://deb.debian.org/debian bookworm-updates main non-free-firmware",
|
||||
]
|
||||
|
||||
def test_bullseye_takes_non_free(self):
|
||||
text = "deb http://deb.debian.org/debian bullseye main\n"
|
||||
|
||||
assert add_component(text, "non-free", deb822=False) == (
|
||||
"deb http://deb.debian.org/debian bullseye main non-free\n",
|
||||
1,
|
||||
)
|
||||
|
||||
def test_a_uri_that_does_not_parse_is_not_debians(self):
|
||||
text = "deb http://[::1/debian trixie main\n"
|
||||
|
||||
assert add_component(text, "non-free-firmware", deb822=False)[1] == 0
|
||||
|
||||
def test_deb_src_too(self):
|
||||
text = "deb-src http://deb.debian.org/debian trixie main\n"
|
||||
|
||||
assert add_component(text, "non-free-firmware", deb822=False)[1] == 1
|
||||
|
||||
|
||||
def _hardening(**overrides: Any) -> dict[str, Any]:
|
||||
reading: dict[str, Any] = {
|
||||
"os_ids": ["debian"],
|
||||
"virtualization": "none",
|
||||
"cpu_vendor": "GenuineIntel",
|
||||
}
|
||||
reading.update(overrides)
|
||||
return reading
|
||||
|
||||
|
||||
_SOURCES = "/etc/apt/sources.list.d/debian.sources"
|
||||
_PVE_LIST = "/etc/apt/sources.list.d/pve-no-subscription.list"
|
||||
_PVE_LIST_TEXT = "deb http://download.proxmox.com/debian/pve trixie pve-no-subscription\n"
|
||||
|
||||
|
||||
class _Host(OSDriver, CpuMicrocodeMixin, EnsurePackageMixin, AptReleaseMixin):
|
||||
"""A Debian host with apt: its files, its packages, and what it was asked."""
|
||||
|
||||
def __init__(self, hardening: dict[str, Any], *, installed: tuple[str, ...] = ()) -> None:
|
||||
self.hardening = hardening
|
||||
self.installed = list(installed)
|
||||
self.files = {_SOURCES: PVE_DEB822, _PVE_LIST: _PVE_LIST_TEXT}
|
||||
self.written: dict[str, str] = {}
|
||||
self.refreshed = 0
|
||||
self.os_release = "ID=debian\nVERSION_CODENAME=trixie\n"
|
||||
|
||||
def get_hardening(self) -> Any:
|
||||
return self.hardening
|
||||
|
||||
def get_packages(self) -> Any:
|
||||
return [{"name": n, "installed": True} for n in self.installed]
|
||||
|
||||
def install_package(self, name: str, version: str = "") -> None:
|
||||
self.installed.append(name)
|
||||
|
||||
def refresh_available_updates(self) -> dict[str, Any]:
|
||||
self.refreshed += 1
|
||||
return {"success": True, "output": "Hit:1 http://deb.debian.org/debian trixie InRelease"}
|
||||
|
||||
def _run_apt_command(self, command: str) -> str:
|
||||
if command.startswith("base64 "):
|
||||
path = shlex.split(command)[1]
|
||||
return base64.b64encode(self.files[path].encode()).decode()
|
||||
body = "".join(
|
||||
f"@@file {path}\n" + "".join(f"|{line}\n" for line in text.split("\n"))
|
||||
for path, text in self.files.items()
|
||||
)
|
||||
os_release = "".join(f"|{line}\n" for line in self.os_release.splitlines())
|
||||
return f"ARELEASE_BEGIN\n@@os\n{os_release}{body}ARELEASE_END\n"
|
||||
|
||||
def _write_apt_file(self, path: str, content: str) -> Any:
|
||||
self.files[path] = content
|
||||
self.written[path] = content
|
||||
return {"ok": True, "output": f"wrote {path}"}
|
||||
|
||||
|
||||
class TestTheFix:
|
||||
def test_proxmox_ve_without_the_component_gets_it_then_the_package(self):
|
||||
host = _Host(_hardening())
|
||||
|
||||
result = host.install_cpu_microcode()
|
||||
|
||||
assert result["success"] is True
|
||||
assert [s["step"] for s in result["steps"]] == ["read", "sources", "install"]
|
||||
assert result["package"] == "intel-microcode"
|
||||
assert result["sources_changed"] is True
|
||||
assert list(host.written) == [_SOURCES]
|
||||
assert "Components: main contrib non-free-firmware" in host.files[_SOURCES]
|
||||
assert host.files[_PVE_LIST] == _PVE_LIST_TEXT
|
||||
assert host.refreshed == 1
|
||||
assert host.installed == ["intel-microcode"]
|
||||
assert result["output"].splitlines()[-1].endswith("loads at the next boot")
|
||||
|
||||
def test_sources_that_carry_it_are_not_written(self):
|
||||
host = _Host(_hardening())
|
||||
host.files[_SOURCES] = add_component(PVE_DEB822, "non-free-firmware", deb822=True)[0]
|
||||
|
||||
result = host.install_cpu_microcode()
|
||||
|
||||
assert result["success"] is True
|
||||
assert result["sources_changed"] is False
|
||||
assert host.written == {} and host.refreshed == 0
|
||||
assert "already carry non-free-firmware" in result["steps"][1]["output"]
|
||||
|
||||
def test_installed_already_touches_nothing(self):
|
||||
host = _Host(_hardening(), installed=("intel-microcode",))
|
||||
|
||||
result = host.install_cpu_microcode()
|
||||
|
||||
assert result["success"] is True
|
||||
assert host.written == {} and host.refreshed == 0
|
||||
assert host.installed == ["intel-microcode"]
|
||||
assert "already installed" in result["steps"][2]["output"]
|
||||
|
||||
def test_bullseye_adds_non_free(self):
|
||||
host = _Host(_hardening(cpu_vendor="AuthenticAMD"))
|
||||
host.os_release = "ID=debian\nVERSION_CODENAME=bullseye\n"
|
||||
host.files = {"/etc/apt/sources.list": "deb http://deb.debian.org/debian bullseye main\n"}
|
||||
|
||||
result = host.install_cpu_microcode()
|
||||
|
||||
assert result["success"] is True
|
||||
assert result["package"] == "amd64-microcode"
|
||||
assert host.files["/etc/apt/sources.list"] == (
|
||||
"deb http://deb.debian.org/debian bullseye main non-free\n"
|
||||
)
|
||||
|
||||
def test_ubuntu_needs_no_sources(self):
|
||||
host = _Host(_hardening(os_ids=["ubuntu", "debian"]))
|
||||
|
||||
result = host.install_cpu_microcode()
|
||||
|
||||
assert result["success"] is True
|
||||
assert host.written == {} and host.refreshed == 0
|
||||
assert host.installed == ["intel-microcode"]
|
||||
|
||||
def test_enterprise_linux_installs_from_its_own_sources(self):
|
||||
host = _Host(_hardening(os_ids=["almalinux", "rhel", "centos", "fedora"]))
|
||||
|
||||
result = host.install_cpu_microcode()
|
||||
|
||||
assert result["success"] is True
|
||||
assert host.installed == ["microcode_ctl"]
|
||||
assert host.written == {}
|
||||
|
||||
@pytest.mark.parametrize("virtualization", ["kvm", "vm", "lxc"])
|
||||
def test_a_guest_is_refused(self, virtualization):
|
||||
host = _Host(_hardening(virtualization=virtualization))
|
||||
|
||||
result = host.install_cpu_microcode()
|
||||
|
||||
assert result["success"] is False
|
||||
assert [s["step"] for s in result["steps"]] == ["read"]
|
||||
assert "its host does" in result["output"]
|
||||
assert host.installed == [] and host.written == {}
|
||||
|
||||
def test_unknown_virtualization_is_refused(self):
|
||||
result = _Host(_hardening(virtualization=None)).install_cpu_microcode()
|
||||
|
||||
assert result["success"] is False
|
||||
assert "could not tell whether the host is virtual" in result["output"]
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
"overrides, said",
|
||||
[
|
||||
({"cpu_vendor": None}, "CPU vendor"),
|
||||
({"cpu_vendor": "HygonGenuine"}, "HygonGenuine"),
|
||||
({"os_ids": ["arch"]}, "arch"),
|
||||
],
|
||||
)
|
||||
def test_no_package_says_why(self, overrides, said):
|
||||
result = _Host(_hardening(**overrides)).install_cpu_microcode()
|
||||
|
||||
assert result["success"] is False
|
||||
assert result["package"] is None
|
||||
assert said in result["output"]
|
||||
|
||||
def test_a_failed_index_refresh_fails_the_fix(self):
|
||||
host = _Host(_hardening())
|
||||
host.refresh_available_updates = lambda: {"success": False, "output": "E: 404"} # type: ignore[method-assign]
|
||||
|
||||
result = host.install_cpu_microcode()
|
||||
|
||||
assert result["success"] is False
|
||||
assert [s["step"] for s in result["steps"]] == ["read", "sources"]
|
||||
assert "E: 404" in result["output"]
|
||||
assert host.installed == []
|
||||
|
||||
def test_a_driver_may_load_the_index_its_own_way(self):
|
||||
"""Proxmox's refresh only starts a task: its driver waits for apt itself."""
|
||||
host = _Host(_hardening())
|
||||
ran: list[str] = []
|
||||
host._reload_package_index = lambda: (
|
||||
ran.append("apt-get update")
|
||||
or { # type: ignore[method-assign]
|
||||
"ok": True,
|
||||
"output": "apt-get update done",
|
||||
}
|
||||
)
|
||||
|
||||
result = host.install_cpu_microcode()
|
||||
|
||||
assert result["success"] is True
|
||||
assert ran == ["apt-get update"] and host.refreshed == 0
|
||||
assert "apt-get update done" in result["steps"][1]["output"]
|
||||
|
||||
def test_a_failed_write_fails_the_fix(self):
|
||||
host = _Host(_hardening())
|
||||
host._write_apt_file = lambda path, content: {"ok": False, "output": "denied"} # type: ignore[method-assign]
|
||||
|
||||
result = host.install_cpu_microcode()
|
||||
|
||||
assert result["success"] is False
|
||||
assert "denied" in result["output"]
|
||||
assert host.installed == []
|
||||
|
||||
def test_a_reading_that_fails_fails_the_fix(self):
|
||||
host = _Host(_hardening())
|
||||
|
||||
def broken() -> Any:
|
||||
raise ValueError("no intact hardening report in the output")
|
||||
|
||||
host.get_hardening = broken # type: ignore[method-assign]
|
||||
|
||||
result = host.install_cpu_microcode()
|
||||
|
||||
assert result["success"] is False
|
||||
assert "no intact hardening report" in result["output"]
|
||||
|
||||
def test_not_an_apt_host_fails_the_sources(self):
|
||||
host = _Host(_hardening())
|
||||
host.get_apt_source_releases = lambda: None # type: ignore[method-assign]
|
||||
|
||||
result = host.install_cpu_microcode()
|
||||
|
||||
assert result["success"] is False
|
||||
assert "not an apt host" in result["output"]
|
||||
|
||||
def test_a_listed_source_the_rewrite_leaves_writes_nothing(self):
|
||||
"""A paragraph that names Debian's archive beside another vendor's mirror: apt
|
||||
lists the Debian URI, the rewrite leaves the paragraph alone."""
|
||||
host = _Host(_hardening())
|
||||
host.files = {
|
||||
_SOURCES: "Types: deb\nURIs: http://deb.debian.org/debian http://m.example.com/d\n"
|
||||
"Suites: trixie\nComponents: main\n"
|
||||
}
|
||||
|
||||
result = host.install_cpu_microcode()
|
||||
|
||||
assert result["success"] is True
|
||||
assert result["sources_changed"] is False
|
||||
assert host.written == {} and host.refreshed == 0
|
||||
assert "carries non-free-firmware already" in result["steps"][1]["output"]
|
||||
|
||||
def test_a_failed_install_fails_the_fix(self):
|
||||
host = _Host(_hardening(os_ids=["ubuntu", "debian"]))
|
||||
|
||||
def refuse(name: str, version: str = "") -> Any:
|
||||
raise RuntimeError("E: Unable to locate package intel-microcode")
|
||||
|
||||
host.install_package = refuse # type: ignore[method-assign]
|
||||
|
||||
result = host.install_cpu_microcode()
|
||||
|
||||
assert result["success"] is False
|
||||
assert "Unable to locate package" in result["steps"][-1]["output"]
|
||||
|
||||
def test_an_ensure_package_without_steps_fails(self):
|
||||
host = _Host(_hardening(os_ids=["ubuntu", "debian"]))
|
||||
host.ensure_package = lambda name: {"success": False, "steps": [], "output": ""} # type: ignore[method-assign]
|
||||
|
||||
result = host.install_cpu_microcode()
|
||||
|
||||
assert result["success"] is False
|
||||
assert "intel-microcode not installed" in result["output"]
|
||||
|
||||
def test_not_on_any_role_base(self):
|
||||
from napalm_device_types import DeviceTypeDriver
|
||||
|
||||
assert not hasattr(DeviceTypeDriver, "install_cpu_microcode")
|
||||
|
||||
|
||||
def test_exported_from_the_package():
|
||||
import napalm_device_types as ndt
|
||||
|
||||
for name in (
|
||||
"CpuMicrocodeMixin",
|
||||
"CpuMicrocodeFixDict",
|
||||
"microcode_package",
|
||||
"firmware_component",
|
||||
"add_component",
|
||||
):
|
||||
assert hasattr(ndt, name), name
|
||||
@@ -43,6 +43,9 @@ ALMA_9 = [
|
||||
"BHI: Not affected\n"
|
||||
"/sys/devices/system/cpu/vulnerabilities/mmio_stale_data:Unknown: No mitigations",
|
||||
),
|
||||
("virtualization", "kvm"),
|
||||
("cpu_hypervisor", "1"),
|
||||
("cpu_vendor", "vendor_id\t: AuthenticAMD"),
|
||||
]
|
||||
|
||||
AA_STATUS = {
|
||||
@@ -124,6 +127,8 @@ class TestTheFixtures:
|
||||
"mitigations": "auto",
|
||||
"nosmt": False,
|
||||
"os_ids": ["almalinux", "rhel", "centos", "fedora"],
|
||||
"virtualization": "kvm",
|
||||
"cpu_vendor": "AuthenticAMD",
|
||||
}
|
||||
|
||||
def test_ubuntu_24_04_apparmor_with_its_profiles(self):
|
||||
@@ -170,6 +175,8 @@ class TestNotReadIsNone:
|
||||
"mitigations": None,
|
||||
"nosmt": None,
|
||||
"os_ids": None,
|
||||
"virtualization": None,
|
||||
"cpu_vendor": None,
|
||||
}
|
||||
|
||||
def test_an_empty_vulnerabilities_directory_is_read_and_empty(self):
|
||||
@@ -303,6 +310,43 @@ class TestCommandLine:
|
||||
assert (reading["mitigations"], reading["nosmt"]) == (mitigations, nosmt)
|
||||
|
||||
|
||||
class TestVirtualization:
|
||||
"""Whether the host runs on its own hardware: ``systemd-detect-virt`` where it is
|
||||
installed, else the ``hypervisor`` CPU flag a hypervisor sets for its guests."""
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
"sections, virtualization",
|
||||
[
|
||||
([("virtualization", "none"), ("cpu_hypervisor", "0")], "none"),
|
||||
([("virtualization", "kvm"), ("cpu_hypervisor", "1")], "kvm"),
|
||||
([("virtualization", "lxc"), ("cpu_hypervisor", "0")], "lxc"),
|
||||
([("virtualization", "VMware")], "vmware"),
|
||||
([("cpu_hypervisor", "1")], "vm"),
|
||||
([("cpu_hypervisor", "0")], "none"),
|
||||
([("virtualization", ""), ("cpu_hypervisor", "1")], "vm"),
|
||||
([("cpu_hypervisor", "nonsense")], None),
|
||||
([], None),
|
||||
],
|
||||
)
|
||||
def test_detect_virt_first_then_the_cpu_flag(self, sections, virtualization):
|
||||
assert parse_hardening(_wire(sections))["virtualization"] == virtualization
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
"line, vendor",
|
||||
[
|
||||
("vendor_id\t: GenuineIntel", "GenuineIntel"),
|
||||
("vendor_id : AuthenticAMD", "AuthenticAMD"),
|
||||
("vendor_id\t:", None),
|
||||
],
|
||||
)
|
||||
def test_the_cpu_vendor(self, line, vendor):
|
||||
assert parse_hardening(_wire([("cpu_vendor", line)]))["cpu_vendor"] == vendor
|
||||
|
||||
def test_no_vendor_line_is_unread(self):
|
||||
"""An ARM CPU's ``/proc/cpuinfo`` has no ``vendor_id``."""
|
||||
assert parse_hardening(_wire([("cpu_vendor", "")]))["cpu_vendor"] is None
|
||||
|
||||
|
||||
class TestCryptoPolicy:
|
||||
def test_a_subpolicy_is_kept(self):
|
||||
reading = parse_hardening(_wire([("crypto_policy", "LEGACY:AD-SUPPORT"), ("fips", "1")]))
|
||||
@@ -389,3 +433,4 @@ class TestTheCommand:
|
||||
|
||||
assert reading["cmdline"] is not None
|
||||
assert reading["mitigations"] is not None
|
||||
assert reading["virtualization"] is not None
|
||||
@@ -0,0 +1,321 @@
|
||||
"""get_kernel_facts' live patches: what the running kernel has patched in while it runs.
|
||||
|
||||
A live patch fixes a kernel CVE without a new release, so a consumer that judges the
|
||||
running release alone reports the CVE open and a reboot as worth it (NetOrk/netork#2701).
|
||||
The kernel facts read three things, each where it is kept: the loaded patches in
|
||||
``/sys/kernel/livepatch`` (every distribution), ``kpatch list`` where kpatch is
|
||||
installed, and ``canonical-livepatch status --format json`` -- the daemon's last state,
|
||||
which names the CVEs each patch fixes. Canonical's status may need root: a driver that
|
||||
can gain it supplies ``_run_livepatch_status_command``.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import base64
|
||||
import gzip
|
||||
import json
|
||||
|
||||
import pytest
|
||||
|
||||
from napalm_device_types.kernel import (
|
||||
KERNEL_FACTS_COMMAND,
|
||||
LIVEPATCH_STATUS_COMMAND,
|
||||
KernelFactsMixin,
|
||||
parse_kernel_facts,
|
||||
)
|
||||
from napalm_device_types.livepatch import (
|
||||
canonical_release,
|
||||
parse_canonical_status,
|
||||
parse_kpatch_list,
|
||||
parse_sysfs_livepatches,
|
||||
)
|
||||
|
||||
#: Ubuntu 22.04 with Livepatch applied: the client of the 10.x series, as the Ubuntu
|
||||
#: Pro client reads it (``Status`` -> ``Livepatch`` -> ``Fixes``).
|
||||
CANONICAL = {
|
||||
"client-version": "10.8.3",
|
||||
"architecture": "x86_64",
|
||||
"cpu-model": "Intel(R) Xeon(R) CPU",
|
||||
"last-check": "2026-11-28T09:12:44Z",
|
||||
"boot-time": "2026-11-01T07:00:00Z",
|
||||
"uptime": "2312h12m44s",
|
||||
"Status": [
|
||||
{
|
||||
"Kernel": "5.15.0-91.101-generic",
|
||||
"Running": True,
|
||||
"Livepatch": {
|
||||
"CheckState": "checked",
|
||||
"State": "applied",
|
||||
"Version": "101.1",
|
||||
"Fixes": [
|
||||
{
|
||||
"Name": "cve-2023-1077",
|
||||
"Description": "sched: ...",
|
||||
"Bug": "",
|
||||
"Patched": True,
|
||||
},
|
||||
{
|
||||
"Name": "cve-2023-3090",
|
||||
"Description": "ipvlan: ...",
|
||||
"Bug": "",
|
||||
"Patched": True,
|
||||
},
|
||||
{
|
||||
"Name": "cve-2023-3389",
|
||||
"Description": "io_uring: ...",
|
||||
"Bug": "",
|
||||
"Patched": False,
|
||||
},
|
||||
{"Name": "lp-2023-1", "Description": "not a CVE", "Bug": "", "Patched": True},
|
||||
],
|
||||
},
|
||||
"Supported": "supported",
|
||||
}
|
||||
],
|
||||
"tier": "updates",
|
||||
}
|
||||
|
||||
#: The 9.x client wrote its fixes as one text, a ``* cve-...`` line each.
|
||||
CANONICAL_9 = {
|
||||
"Status": [
|
||||
{
|
||||
"Kernel": "5.4.0-42.46-generic",
|
||||
"Running": True,
|
||||
"Livepatch": {
|
||||
"CheckState": "checked",
|
||||
"State": "applied",
|
||||
"Version": "70.1",
|
||||
"Fixes": "* cve-2020-11935\n* cve-2020-15780 (bug 1883337)\n",
|
||||
},
|
||||
}
|
||||
]
|
||||
}
|
||||
|
||||
REPORT = """[release]
|
||||
5.15.0-91-generic
|
||||
[loaded]
|
||||
lkp_Ubuntu_5_15_0_91_101_generic_101
|
||||
[livepatch]
|
||||
lkp_Ubuntu_5_15_0_91_101_generic_101 1 0
|
||||
[canonical_livepatch]
|
||||
{json}
|
||||
"""
|
||||
|
||||
|
||||
def _wire(report: str) -> str:
|
||||
payload = base64.encodebytes(gzip.compress(report.encode())).decode()
|
||||
return f"KFACTS_BEGIN\n{payload}KFACTS_END\n"
|
||||
|
||||
|
||||
class TestSysfs:
|
||||
def test_each_loaded_patch_enabled_or_not(self):
|
||||
lines = ["livepatch_cve_2024_1 1 0", "kpatch_5_14_0_427 0 1", ""]
|
||||
|
||||
assert parse_sysfs_livepatches(lines) == [
|
||||
{"name": "livepatch_cve_2024_1", "enabled": True, "transition": False},
|
||||
{"name": "kpatch_5_14_0_427", "enabled": False, "transition": True},
|
||||
]
|
||||
|
||||
def test_an_unreadable_flag_is_none(self):
|
||||
assert parse_sysfs_livepatches(["lkp_x"]) == [
|
||||
{"name": "lkp_x", "enabled": None, "transition": None}
|
||||
]
|
||||
|
||||
|
||||
class TestKpatch:
|
||||
def test_loaded_and_installed_modules(self):
|
||||
text = [
|
||||
"Loaded patch modules:",
|
||||
"kpatch_5_14_0_427_13_1 [enabled]",
|
||||
"kpatch_cumulative_old [disabled]",
|
||||
"",
|
||||
"Installed patch modules:",
|
||||
"kpatch_5_14_0_427_13_1 (5.14.0-427.13.1.el9_4.x86_64)",
|
||||
"kpatch_5_14_0_362 (5.14.0-362.8.1.el9_3.x86_64)",
|
||||
]
|
||||
|
||||
assert parse_kpatch_list(text) == {
|
||||
"loaded": [
|
||||
{"name": "kpatch_5_14_0_427_13_1", "enabled": True},
|
||||
{"name": "kpatch_cumulative_old", "enabled": False},
|
||||
],
|
||||
"installed": [
|
||||
{"name": "kpatch_5_14_0_427_13_1", "kernel": "5.14.0-427.13.1.el9_4.x86_64"},
|
||||
{"name": "kpatch_5_14_0_362", "kernel": "5.14.0-362.8.1.el9_3.x86_64"},
|
||||
],
|
||||
}
|
||||
|
||||
def test_nothing_loaded(self):
|
||||
assert parse_kpatch_list(["Loaded patch modules:", "", "Installed patch modules:"]) == {
|
||||
"loaded": [],
|
||||
"installed": [],
|
||||
}
|
||||
|
||||
|
||||
class TestCanonical:
|
||||
def test_the_running_kernels_status_and_its_cves(self):
|
||||
status = parse_canonical_status(json.dumps(CANONICAL))
|
||||
|
||||
assert status == {
|
||||
"kernel": "5.15.0-91.101-generic",
|
||||
"running": True,
|
||||
"state": "applied",
|
||||
"check_state": "checked",
|
||||
"version": "101.1",
|
||||
"fixes": [
|
||||
{"cve": "CVE-2023-1077", "patched": True},
|
||||
{"cve": "CVE-2023-3090", "patched": True},
|
||||
{"cve": "CVE-2023-3389", "patched": False},
|
||||
],
|
||||
}
|
||||
|
||||
def test_the_9_x_clients_text_of_fixes(self):
|
||||
status = parse_canonical_status(json.dumps(CANONICAL_9))
|
||||
|
||||
assert status is not None
|
||||
assert status["fixes"] == [
|
||||
{"cve": "CVE-2020-11935", "patched": True},
|
||||
{"cve": "CVE-2020-15780", "patched": True},
|
||||
]
|
||||
|
||||
def test_keys_in_either_case(self):
|
||||
lowered = json.loads(
|
||||
json.dumps(CANONICAL).replace('"Status"', '"status"').replace('"State"', '"state"')
|
||||
)
|
||||
|
||||
assert parse_canonical_status(json.dumps(lowered))["state"] == "applied"
|
||||
|
||||
def test_the_entry_of_the_running_kernel(self):
|
||||
other = {
|
||||
"Kernel": "5.15.0-88.98-generic",
|
||||
"Running": False,
|
||||
"Livepatch": {"State": "applied", "Fixes": []},
|
||||
}
|
||||
data = {"Status": [other, CANONICAL["Status"][0]]}
|
||||
|
||||
assert parse_canonical_status(json.dumps(data))["kernel"] == "5.15.0-91.101-generic"
|
||||
|
||||
@pytest.mark.parametrize("text", ["", "error: must be root", "{}", '{"Status": []}', "[1, 2]"])
|
||||
def test_no_status_is_none(self, text):
|
||||
assert parse_canonical_status(text) is None
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
"kernel, release",
|
||||
[
|
||||
("5.15.0-91.101-generic", "5.15.0-91-generic"),
|
||||
("6.8.0-49.49~22.04.1-generic", "6.8.0-49-generic"),
|
||||
("5.4.0-1045.47-aws", "5.4.0-1045-aws"),
|
||||
("6.8.0-49-generic", "6.8.0-49-generic"),
|
||||
(None, None),
|
||||
],
|
||||
)
|
||||
def test_its_kernel_as_uname_names_it(self, kernel, release):
|
||||
assert canonical_release(kernel) == release
|
||||
|
||||
|
||||
class TestInTheKernelFacts:
|
||||
def test_read_with_the_kernel_facts(self):
|
||||
facts = parse_kernel_facts(_wire(REPORT.format(json=json.dumps(CANONICAL))))
|
||||
patches = facts["live_patches"]
|
||||
|
||||
assert patches["loaded"] == [
|
||||
{"name": "lkp_Ubuntu_5_15_0_91_101_generic_101", "enabled": True, "transition": False}
|
||||
]
|
||||
assert patches["kpatch"] is None
|
||||
assert patches["canonical"]["state"] == "applied"
|
||||
|
||||
def test_a_kernel_without_live_patching_has_none_loaded(self):
|
||||
"""No ``/sys/kernel/livepatch``: the kernel was built without it, nothing is loaded."""
|
||||
facts = parse_kernel_facts(_wire("[release]\n6.1.0-25-amd64\n"))
|
||||
|
||||
assert facts["live_patches"] == {
|
||||
"loaded": None,
|
||||
"kpatch": None,
|
||||
"canonical": None,
|
||||
"canonical_installed": False,
|
||||
}
|
||||
|
||||
def test_an_empty_directory_is_none_loaded(self):
|
||||
facts = parse_kernel_facts(_wire("[release]\n6.1.0-25-amd64\n[livepatch]\n"))
|
||||
|
||||
assert facts["live_patches"]["loaded"] == []
|
||||
|
||||
|
||||
class _Driver(KernelFactsMixin):
|
||||
def __init__(self, report: str, status: str | None = None):
|
||||
self.report = report
|
||||
self.status = status
|
||||
self.asked: list[str] = []
|
||||
|
||||
def _run_kernel_facts_command(self, command: str) -> str:
|
||||
return _wire(self.report)
|
||||
|
||||
|
||||
class _RootDriver(_Driver):
|
||||
def _run_livepatch_status_command(self, command: str) -> str:
|
||||
self.asked.append(command)
|
||||
return self.status or ""
|
||||
|
||||
|
||||
class TestCanonicalAsRoot:
|
||||
"""``canonical-livepatch status`` may refuse a user who is not root: where the
|
||||
kernel facts found the client but no status, a driver that can gain root asks again."""
|
||||
|
||||
UNREAD = "[release]\n5.15.0-91-generic\n[livepatch]\n[canonical_livepatch]\n"
|
||||
|
||||
def test_asked_again_as_root(self):
|
||||
driver = _RootDriver(self.UNREAD, json.dumps(CANONICAL))
|
||||
|
||||
facts = driver.get_kernel_facts()
|
||||
|
||||
assert driver.asked == [LIVEPATCH_STATUS_COMMAND]
|
||||
assert facts["live_patches"]["canonical"]["version"] == "101.1"
|
||||
|
||||
def test_not_asked_when_read_already(self):
|
||||
driver = _RootDriver(REPORT.format(json=json.dumps(CANONICAL)))
|
||||
|
||||
driver.get_kernel_facts()
|
||||
|
||||
assert driver.asked == []
|
||||
|
||||
def test_not_asked_without_the_client(self):
|
||||
driver = _RootDriver("[release]\n6.1.0\n")
|
||||
|
||||
driver.get_kernel_facts()
|
||||
|
||||
assert driver.asked == []
|
||||
|
||||
def test_a_driver_without_root_leaves_it_unread(self):
|
||||
facts = _Driver(self.UNREAD).get_kernel_facts()
|
||||
|
||||
assert facts["live_patches"]["canonical"] is None
|
||||
assert facts["live_patches"]["canonical_installed"] is True
|
||||
|
||||
def test_a_failed_root_read_leaves_it_unread(self):
|
||||
class Failing(_RootDriver):
|
||||
def _run_livepatch_status_command(self, command: str) -> str:
|
||||
raise RuntimeError("sudo: a password is required")
|
||||
|
||||
assert Failing(self.UNREAD).get_kernel_facts()["live_patches"]["canonical"] is None
|
||||
|
||||
|
||||
class TestTheCommands:
|
||||
def test_the_kernel_facts_read_the_live_patches(self):
|
||||
assert "/sys/kernel/livepatch" in KERNEL_FACTS_COMMAND
|
||||
assert "kpatch list" in KERNEL_FACTS_COMMAND
|
||||
assert "status --format json" in KERNEL_FACTS_COMMAND
|
||||
|
||||
def test_they_ask_canonical_nothing(self):
|
||||
"""``status`` reads the daemon's last state; ``refresh`` would call Canonical."""
|
||||
for command in (KERNEL_FACTS_COMMAND, LIVEPATCH_STATUS_COMMAND):
|
||||
for verb in (
|
||||
"refresh",
|
||||
"livepatch enable",
|
||||
"livepatch disable",
|
||||
"kpatch load",
|
||||
"kpatch unload",
|
||||
"kpatch install",
|
||||
"kpatch uninstall",
|
||||
):
|
||||
assert verb not in command
|
||||
assert LIVEPATCH_STATUS_COMMAND.endswith("status --format json")
|
||||
@@ -0,0 +1,483 @@
|
||||
"""get_login_accounts: every account on a Linux host a person can log in with (NetOrk/netork#2707).
|
||||
|
||||
The accounts come from ``/etc/passwd`` (root and UID 1000 on, with a shell that lets
|
||||
them in), their last login from whichever of ``lastlog2``, ``lastlog``, ``wtmpdb last``
|
||||
and ``last`` the host has, their lock and expiry from ``passwd -S`` and ``chage -l``,
|
||||
and the failed attempts since their last login from ``lastb`` or ``faillock``. The
|
||||
last three need root; read as the login user they are ``None``, never "unlocked" or
|
||||
"no failures".
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import os
|
||||
import subprocess
|
||||
|
||||
import pytest
|
||||
|
||||
from napalm_device_types import OSDriver
|
||||
from napalm_device_types.login_accounts import (
|
||||
FAILED_LOGINS_READ,
|
||||
LOGIN_ACCOUNTS_COMMAND,
|
||||
LoginAccountsMixin,
|
||||
login_capable,
|
||||
parse_login_accounts,
|
||||
)
|
||||
|
||||
PASSWD = (
|
||||
"root:0:/root:/bin/bash\n"
|
||||
"alice:1000:/home/alice:/bin/bash\n"
|
||||
"bob:1001:/home/bob:/usr/bin/zsh\n"
|
||||
"deploy:1002:/srv/deploy:/bin/sh"
|
||||
)
|
||||
|
||||
#: Debian 12 as root: the legacy lastlog, wtmp through ``last``, btmp through ``lastb``,
|
||||
#: Debian's ``passwd -S``. alice logs in over SSH, bob never did, deploy is locked by
|
||||
#: netOrk (``usermod -L -e 1``).
|
||||
DEBIAN_12 = [
|
||||
("uid", "0"),
|
||||
("now", "2026-11-28"),
|
||||
("passwd", PASSWD),
|
||||
(
|
||||
"lastlog",
|
||||
"Username Port From Latest\n"
|
||||
"root tty1 Mon Oct 5 09:12:44 +0200 2026\n"
|
||||
"alice pts/0 192.0.2.10 Fri Nov 27 22:01:02 +0100 2026\n"
|
||||
"bob **Never logged in**\n"
|
||||
"deploy pts/1 198.51.100.7 Sat Aug 1 10:00:00 +0200 2026",
|
||||
),
|
||||
(
|
||||
"wtmp",
|
||||
"alice pts/0 192.0.2.10 2026-11-27T22:01:02+01:00 - 2026-11-27T23:00:00+01:00 (00:59)\n"
|
||||
"root tty1 2026-10-05T09:12:44+02:00 - 2026-10-05T09:20:00+02:00 (00:07)",
|
||||
),
|
||||
(
|
||||
"lastb",
|
||||
"alice ssh:notty 203.0.113.5 2026-11-28T01:02:03+01:00 - 2026-11-28T01:02:03+01:00 (00:00)\n"
|
||||
"alice ssh:notty 203.0.113.5 2026-11-28T01:02:01+01:00 - 2026-11-28T01:02:01+01:00 (00:00)\n"
|
||||
"alice ssh:notty 203.0.113.5 2026-11-26T08:00:00+01:00 - 2026-11-26T08:00:00+01:00 (00:00)\n"
|
||||
"root ssh:notty 203.0.113.9 2026-11-20T03:00:00+01:00 - 2026-11-20T03:00:00+01:00 (00:00)\n"
|
||||
"root ssh:notty 203.0.113.9 2026-11-19T03:00:00+01:00 - 2026-11-19T03:00:00+01:00 (00:00)",
|
||||
),
|
||||
("passwd_status root", "root P 2026-01-15 0 99999 7 -1"),
|
||||
(
|
||||
"chage root",
|
||||
"Last password change\t\t\t\t\t: Jan 15, 2026\n"
|
||||
"Password expires\t\t\t\t\t: never\n"
|
||||
"Password inactive\t\t\t\t\t: never\n"
|
||||
"Account expires\t\t\t\t\t\t: never\n"
|
||||
"Minimum number of days between password change\t\t: 0\n"
|
||||
"Maximum number of days between password change\t\t: 99999\n"
|
||||
"Number of days of warning before password expires\t: 7",
|
||||
),
|
||||
("passwd_status alice", "alice P 11/01/2026 0 90 7 -1"),
|
||||
(
|
||||
"chage alice",
|
||||
"Last password change\t\t\t\t\t: Nov 01, 2026\n"
|
||||
"Password expires\t\t\t\t\t: Jan 30, 2027\n"
|
||||
"Password inactive\t\t\t\t\t: never\n"
|
||||
"Account expires\t\t\t\t\t\t: Dec 31, 2026",
|
||||
),
|
||||
("passwd_status bob", "bob NP 2026-11-01 0 99999 7 -1"),
|
||||
(
|
||||
"chage bob",
|
||||
"Last password change\t\t\t\t\t: password must be changed\n"
|
||||
"Password expires\t\t\t\t\t: password must be changed\n"
|
||||
"Password inactive\t\t\t\t\t: password must be changed\n"
|
||||
"Account expires\t\t\t\t\t\t: never",
|
||||
),
|
||||
("passwd_status deploy", "deploy L 2026-08-01 0 99999 7 -1"),
|
||||
(
|
||||
"chage deploy",
|
||||
"Last password change\t\t\t\t\t: Aug 01, 2026\n"
|
||||
"Password expires\t\t\t\t\t: never\n"
|
||||
"Password inactive\t\t\t\t\t: never\n"
|
||||
"Account expires\t\t\t\t\t\t: Jan 02, 1970",
|
||||
),
|
||||
]
|
||||
|
||||
#: Debian 13 as root: lastlog2 and wtmpdb, no btmp; pam_faillock counts failures.
|
||||
DEBIAN_13 = [
|
||||
("uid", "0"),
|
||||
("now", "2026-11-28"),
|
||||
("passwd", "root:0:/root:/bin/bash\nalice:1000:/home/alice:/bin/bash"),
|
||||
(
|
||||
"lastlog2",
|
||||
"Username Port From Latest\n"
|
||||
"alice pts/2 2001:db8::5 Thu Nov 26 18:30:00 +0100 2026\n"
|
||||
"root **Never logged in**",
|
||||
),
|
||||
(
|
||||
"wtmpdb",
|
||||
"alice pts/3 2001:db8::6 2026-11-27T07:15:00+01:00 - 2026-11-27T07:20:00+01:00 (00:05)",
|
||||
),
|
||||
("passwd_status root", "root L 2026-11-01 0 99999 7 -1"),
|
||||
("chage root", "Account expires\t\t\t\t\t\t: never"),
|
||||
(
|
||||
"faillock root",
|
||||
"root:\nWhen Type Source Valid",
|
||||
),
|
||||
("passwd_status alice", "alice P 2026-11-01 0 99999 7 -1"),
|
||||
("chage alice", "Account expires\t\t\t\t\t\t: never"),
|
||||
(
|
||||
"faillock alice",
|
||||
"alice:\n"
|
||||
"When Type Source Valid\n"
|
||||
"2026-11-28 01:02:03 RHOST 203.0.113.5 V\n"
|
||||
"2026-11-28 01:02:09 RHOST 203.0.113.5 V\n"
|
||||
"2026-11-27 23:00:00 TTY tty2 I",
|
||||
),
|
||||
]
|
||||
|
||||
#: AlmaLinux 9 as root: libuser's ``passwd -S`` with its comment.
|
||||
ALMA_9 = [
|
||||
("uid", "0"),
|
||||
("now", "2026-11-28"),
|
||||
("passwd", "alice:1000:/home/alice:/bin/bash"),
|
||||
(
|
||||
"lastlog",
|
||||
"Username Port From Latest\n"
|
||||
"alice pts/0 192.0.2.10 Fri Nov 27 22:01:02 +0100 2026",
|
||||
),
|
||||
("passwd_status alice", "alice LK 2026-11-01 0 99999 7 -1 (Password locked.)"),
|
||||
("chage alice", "Account expires\t\t\t\t\t\t: never"),
|
||||
]
|
||||
|
||||
#: The same Debian host read as the login user: no root, so no lock, expiry or failures.
|
||||
AS_LOGIN_USER = [
|
||||
("uid", "1000"),
|
||||
("now", "2026-11-28"),
|
||||
("passwd", PASSWD),
|
||||
(
|
||||
"lastlog",
|
||||
"Username Port From Latest\n"
|
||||
"alice pts/0 192.0.2.10 Fri Nov 27 22:01:02 +0100 2026",
|
||||
),
|
||||
("passwd_status root", ""),
|
||||
("chage root", ""),
|
||||
("faillock root", ""),
|
||||
("passwd_status alice", ""),
|
||||
("chage alice", "Account expires\t\t\t\t\t\t: never"),
|
||||
("faillock alice", ""),
|
||||
]
|
||||
|
||||
|
||||
def _wire(sections: list[tuple[str, str]], *, noise: str = "") -> str:
|
||||
"""The report as the command prints it, framed."""
|
||||
body = "".join(f"[{name}]\n{text}\n" for name, text in sections)
|
||||
return f"{noise}LOGINS_BEGIN\n{body}LOGINS_END\n"
|
||||
|
||||
|
||||
def _by_name(reading):
|
||||
return {account["name"]: account for account in reading["accounts"]}
|
||||
|
||||
|
||||
class TestDebian12:
|
||||
def test_every_login_capable_account_in_passwd_order(self):
|
||||
reading = parse_login_accounts(_wire(DEBIAN_12))
|
||||
|
||||
assert [a["name"] for a in reading["accounts"]] == ["root", "alice", "bob", "deploy"]
|
||||
assert reading["privileged"] is True
|
||||
assert reading["login_sources"] == ["lastlog", "wtmp"]
|
||||
assert reading["failed_logins_source"] == "lastb"
|
||||
|
||||
def test_the_last_login_with_where_it_came_from(self):
|
||||
alice = _by_name(parse_login_accounts(_wire(DEBIAN_12)))["alice"]
|
||||
|
||||
assert alice["uid"] == 1000
|
||||
assert alice["home"] == "/home/alice"
|
||||
assert alice["shell"] == "/bin/bash"
|
||||
assert alice["last_login"] == "2026-11-27T21:01:02+00:00"
|
||||
assert alice["last_login_from"] == "192.0.2.10"
|
||||
assert alice["last_login_port"] == "pts/0"
|
||||
assert alice["last_login_source"] == "lastlog"
|
||||
|
||||
def test_never_logged_in(self):
|
||||
bob = _by_name(parse_login_accounts(_wire(DEBIAN_12)))["bob"]
|
||||
|
||||
assert bob["last_login"] is None
|
||||
assert bob["last_login_source"] is None
|
||||
|
||||
def test_a_console_login_has_a_port_and_no_host(self):
|
||||
root = _by_name(parse_login_accounts(_wire(DEBIAN_12)))["root"]
|
||||
|
||||
assert root["last_login"] == "2026-10-05T07:12:44+00:00"
|
||||
assert (root["last_login_port"], root["last_login_from"]) == ("tty1", None)
|
||||
|
||||
def test_password_and_expiry(self):
|
||||
accounts = _by_name(parse_login_accounts(_wire(DEBIAN_12)))
|
||||
|
||||
assert accounts["alice"]["password"] == "set"
|
||||
assert accounts["alice"]["password_changed"] == "2026-11-01"
|
||||
assert accounts["alice"]["password_expires"] == "2027-01-30"
|
||||
assert accounts["alice"]["account_expires"] == "2026-12-31"
|
||||
assert accounts["alice"]["locked"] is False
|
||||
assert accounts["root"]["password_expires"] == "never"
|
||||
assert accounts["root"]["account_expires"] == "never"
|
||||
|
||||
def test_no_password_that_must_be_changed(self):
|
||||
bob = _by_name(parse_login_accounts(_wire(DEBIAN_12)))["bob"]
|
||||
|
||||
assert bob["password"] == "none"
|
||||
assert bob["password_changed"] is None
|
||||
assert bob["password_expires"] == "must_change"
|
||||
assert bob["locked"] is False
|
||||
|
||||
def test_locked_as_netork_locks_an_account(self):
|
||||
"""``usermod -L -e 1``: the password locked and the account expired in 1970."""
|
||||
deploy = _by_name(parse_login_accounts(_wire(DEBIAN_12)))["deploy"]
|
||||
|
||||
assert deploy["password"] == "locked"
|
||||
assert deploy["account_expires"] == "1970-01-02"
|
||||
assert deploy["locked"] is True
|
||||
|
||||
def test_failed_logins_since_the_last_one_that_worked(self):
|
||||
accounts = _by_name(parse_login_accounts(_wire(DEBIAN_12)))
|
||||
|
||||
# alice's last login was 2026-11-27 22:01; two failures came after it.
|
||||
assert accounts["alice"]["failed_logins"] == 2
|
||||
# root last logged in on 2026-10-05: both failures are later.
|
||||
assert accounts["root"]["failed_logins"] == 2
|
||||
# No line in btmp: none, and btmp was read.
|
||||
assert accounts["bob"]["failed_logins"] == 0
|
||||
assert accounts["alice"]["failed_logins_capped"] is False
|
||||
|
||||
|
||||
class TestDebian13:
|
||||
def test_the_newest_login_over_every_source(self):
|
||||
"""lastlog2 saw alice on the 26th, wtmpdb on the 27th: the 27th is her last login."""
|
||||
reading = parse_login_accounts(_wire(DEBIAN_13))
|
||||
alice = _by_name(reading)["alice"]
|
||||
|
||||
assert reading["login_sources"] == ["lastlog2", "wtmpdb"]
|
||||
assert alice["last_login"] == "2026-11-27T06:15:00+00:00"
|
||||
assert alice["last_login_source"] == "wtmpdb"
|
||||
assert alice["last_login_from"] == "2001:db8::6"
|
||||
|
||||
def test_faillock_counts_its_valid_failures(self):
|
||||
reading = parse_login_accounts(_wire(DEBIAN_13))
|
||||
accounts = _by_name(reading)
|
||||
|
||||
assert reading["failed_logins_source"] == "faillock"
|
||||
assert accounts["alice"]["failed_logins"] == 2
|
||||
assert accounts["root"]["failed_logins"] == 0
|
||||
|
||||
def test_a_locked_password_locks_the_account(self):
|
||||
root = _by_name(parse_login_accounts(_wire(DEBIAN_13)))["root"]
|
||||
|
||||
assert (root["password"], root["locked"]) == ("locked", True)
|
||||
|
||||
|
||||
class TestAlma9:
|
||||
def test_libusers_status_words(self):
|
||||
alice = _by_name(parse_login_accounts(_wire(ALMA_9)))["alice"]
|
||||
|
||||
assert alice["password"] == "locked"
|
||||
assert alice["locked"] is True
|
||||
|
||||
def test_without_lastb_or_faillock_failures_are_unread(self):
|
||||
reading = parse_login_accounts(_wire(ALMA_9))
|
||||
|
||||
assert reading["failed_logins_source"] is None
|
||||
assert _by_name(reading)["alice"]["failed_logins"] is None
|
||||
|
||||
|
||||
class TestAsTheLoginUser:
|
||||
def test_what_needs_root_is_none(self):
|
||||
reading = parse_login_accounts(_wire(AS_LOGIN_USER))
|
||||
root = _by_name(reading)["root"]
|
||||
|
||||
assert reading["privileged"] is False
|
||||
assert reading["failed_logins_source"] is None
|
||||
assert root["password"] is None
|
||||
assert root["password_expires"] is None
|
||||
assert root["account_expires"] is None
|
||||
assert root["locked"] is None
|
||||
assert root["failed_logins"] is None
|
||||
|
||||
def test_the_last_login_is_still_read(self):
|
||||
alice = _by_name(parse_login_accounts(_wire(AS_LOGIN_USER)))["alice"]
|
||||
|
||||
assert alice["last_login"] == "2026-11-27T21:01:02+00:00"
|
||||
# Its own chage is readable without root.
|
||||
assert alice["account_expires"] == "never"
|
||||
|
||||
|
||||
class TestNotReadIsNone:
|
||||
def test_no_login_source_is_not_never(self):
|
||||
"""A host without any of the tools: the last login is unread, not "never"."""
|
||||
reading = parse_login_accounts(
|
||||
_wire([("uid", "0"), ("now", "2026-11-28"), ("passwd", PASSWD)])
|
||||
)
|
||||
|
||||
assert reading["login_sources"] == []
|
||||
assert all(a["last_login"] is None for a in reading["accounts"])
|
||||
|
||||
def test_output_without_the_frame_raises(self):
|
||||
with pytest.raises(ValueError):
|
||||
parse_login_accounts("sudo: a password is required\n")
|
||||
|
||||
def test_whatever_surrounds_the_frame_is_ignored(self):
|
||||
noise = "Last login: today\nprintf '%s%s\\n' LOGINS_ BEGIN; ...\n"
|
||||
|
||||
assert len(parse_login_accounts(_wire(DEBIAN_12, noise=noise))["accounts"]) == 4
|
||||
|
||||
def test_a_line_none_of_the_formats_knows_is_left_out(self):
|
||||
reading = parse_login_accounts(
|
||||
_wire(
|
||||
[
|
||||
("uid", "0"),
|
||||
("passwd", "alice:1000:/home/alice:/bin/bash\nbroken line"),
|
||||
("lastlog", "alice pts/0 somewhere yesterday"),
|
||||
("wtmp", "alice pts/0 nowhere\nwtmp begins 2026-01-01T00:00:00+00:00"),
|
||||
("passwd_status alice", "alice"),
|
||||
("chage alice", "Account expires : sometime"),
|
||||
]
|
||||
)
|
||||
)
|
||||
alice = _by_name(reading)["alice"]
|
||||
|
||||
assert [a["name"] for a in reading["accounts"]] == ["alice"]
|
||||
assert alice["last_login"] is None
|
||||
assert alice["password"] is None
|
||||
assert alice["account_expires"] is None
|
||||
assert alice["locked"] is None
|
||||
|
||||
|
||||
class TestFailedLogins:
|
||||
def test_without_a_last_login_every_failure_counts(self):
|
||||
reading = parse_login_accounts(
|
||||
_wire(
|
||||
[
|
||||
("uid", "0"),
|
||||
("passwd", "bob:1001:/home/bob:/bin/bash"),
|
||||
(
|
||||
"lastb",
|
||||
"bob ssh:notty 203.0.113.5 2026-11-28T01:02:03+01:00 - 2026-11-28T01:02:03+01:00 (00:00)",
|
||||
),
|
||||
]
|
||||
)
|
||||
)
|
||||
|
||||
assert _by_name(reading)["bob"]["failed_logins"] == 1
|
||||
|
||||
def test_a_full_read_is_capped(self):
|
||||
"""The command keeps the newest :data:`FAILED_LOGINS_READ` per account: a count
|
||||
that reaches it is "at least"."""
|
||||
line = "alice ssh:notty 203.0.113.5 2026-11-28T01:02:03+01:00 - 2026-11-28T01:02:03+01:00 (00:00)"
|
||||
reading = parse_login_accounts(
|
||||
_wire(
|
||||
[
|
||||
("uid", "0"),
|
||||
("passwd", "alice:1000:/home/alice:/bin/bash"),
|
||||
("lastb", "\n".join([line] * FAILED_LOGINS_READ)),
|
||||
]
|
||||
)
|
||||
)
|
||||
alice = _by_name(reading)["alice"]
|
||||
|
||||
assert alice["failed_logins"] == FAILED_LOGINS_READ
|
||||
assert alice["failed_logins_capped"] is True
|
||||
|
||||
|
||||
class TestLoginCapable:
|
||||
@pytest.mark.parametrize(
|
||||
"uid, shell, capable",
|
||||
[
|
||||
(0, "/bin/bash", True),
|
||||
(1000, "/bin/sh", True),
|
||||
(1000, "", True),
|
||||
(999, "/bin/bash", False),
|
||||
(65534, "/bin/sh", False),
|
||||
(1000, "/usr/sbin/nologin", False),
|
||||
(1000, "/sbin/nologin", False),
|
||||
(1000, "/bin/false", False),
|
||||
(1000, "/usr/bin/false", False),
|
||||
],
|
||||
)
|
||||
def test_root_and_people_with_a_shell(self, uid, shell, capable):
|
||||
assert login_capable(uid, shell) is capable
|
||||
|
||||
def test_a_service_account_in_passwd_is_left_out(self):
|
||||
reading = parse_login_accounts(
|
||||
_wire(
|
||||
[
|
||||
("uid", "0"),
|
||||
(
|
||||
"passwd",
|
||||
"root:0:/root:/bin/bash\n"
|
||||
"netork:900:/var/lib/netork:/bin/bash\n"
|
||||
"nobody:65534:/nonexistent:/usr/sbin/nologin\n"
|
||||
"svc:1003:/srv/svc:/usr/sbin/nologin",
|
||||
),
|
||||
]
|
||||
)
|
||||
)
|
||||
|
||||
assert [a["name"] for a in reading["accounts"]] == ["root"]
|
||||
|
||||
|
||||
class _Driver(OSDriver, LoginAccountsMixin):
|
||||
def __init__(self, outputs):
|
||||
self.outputs = list(outputs)
|
||||
self.calls: list[tuple[str, bool]] = []
|
||||
|
||||
def _run_login_accounts_command(self, command: str, *, privileged: bool) -> str:
|
||||
self.calls.append((command, privileged))
|
||||
return self.outputs.pop(0)
|
||||
|
||||
|
||||
class TestTheMixin:
|
||||
def test_read_as_root_first(self):
|
||||
driver = _Driver([_wire(DEBIAN_12)])
|
||||
|
||||
reading = driver.get_login_accounts()
|
||||
|
||||
assert driver.calls[0][1] is True
|
||||
assert reading["privileged"] is True
|
||||
|
||||
def test_root_refused_reads_as_the_login_user(self):
|
||||
driver = _Driver(["sudo: a password is required\n", _wire(AS_LOGIN_USER)])
|
||||
|
||||
reading = driver.get_login_accounts()
|
||||
|
||||
assert [privileged for _, privileged in driver.calls] == [True, False]
|
||||
assert reading["privileged"] is False
|
||||
|
||||
def test_the_command_goes_to_sh(self):
|
||||
driver = _Driver([_wire(ALMA_9)])
|
||||
|
||||
driver.get_login_accounts()
|
||||
|
||||
assert driver.calls[0][0].startswith("sh -c ")
|
||||
|
||||
|
||||
class TestTheCommand:
|
||||
def test_the_frame_is_not_in_the_command_itself(self):
|
||||
assert "LOGINS_BEGIN" not in LOGIN_ACCOUNTS_COMMAND
|
||||
assert "LOGINS_END" not in LOGIN_ACCOUNTS_COMMAND
|
||||
|
||||
def test_it_changes_nothing(self):
|
||||
for verb in ("usermod", "passwd -l", "chage -E", "--reset", "lastlog2 -C", " > ", ">>"):
|
||||
assert verb not in LOGIN_ACCOUNTS_COMMAND
|
||||
|
||||
def test_it_reads_no_stdin_and_sends_no_password_hash(self):
|
||||
"""A sudo password on stdin must not reach a tool; the hashes in ``/etc/shadow``
|
||||
are never read: ``passwd -S`` and ``chage -l`` say what is needed."""
|
||||
assert LOGIN_ACCOUNTS_COMMAND.startswith("exec </dev/null; ")
|
||||
assert "shadow" not in LOGIN_ACCOUNTS_COMMAND
|
||||
|
||||
def test_no_gecos_field_leaves_the_host(self):
|
||||
"""The fifth field of ``/etc/passwd`` is a person's name; only name, uid, home and
|
||||
shell are printed."""
|
||||
assert '{print $1":"$3":"$6":"$7}' in LOGIN_ACCOUNTS_COMMAND
|
||||
|
||||
@pytest.mark.skipif(os.uname().sysname != "Linux", reason="reads a Linux host")
|
||||
def test_it_runs_and_parses_on_this_host(self):
|
||||
out = subprocess.run(
|
||||
["sh", "-c", LOGIN_ACCOUNTS_COMMAND], capture_output=True, text=True, timeout=60
|
||||
).stdout
|
||||
|
||||
reading = parse_login_accounts(out)
|
||||
|
||||
assert isinstance(reading["accounts"], list)
|
||||
Reference in new issue
Block a user