feat(hardening): where the OS runs and whose CPU it is, and installing the CPU microcode, 4.53.0 (NetOrk/netork#2838)
driver / standard (pull_request) Successful in 16s
driver / lint (pull_request) Successful in 1m11s
driver / test (3.12) (pull_request) Successful in 1m12s
driver / test (3.13) (pull_request) Successful in 1m5s
driver / lowest (pull_request) Successful in 34s
driver / build (pull_request) Successful in 27s
driver / types (pull_request) Successful in 1m50s
driver / security (pull_request) Successful in 58s
CI / driver (pull_request) Successful in 2m12s
driver / publish (pull_request) Skipped

get_hardening() reads virtualization (systemd-detect-virt, else the cpuinfo
hypervisor flag) and cpu_vendor. CpuMicrocodeMixin.install_cpu_microcode()
refuses a guest, picks the package of the distribution and CPU vendor
(microcode_package), adds Debian's firmware component to Debian's own sources
where it is missing, reloads the index and installs the package; it loads at
the next boot.
This commit is contained in:
christianmanivong committed 2026-11-29 00:06:50 +01:00
1 parent 5faf9a1021
commit 7451fc9dfc
8 files changed
+913 -3

No files matched your search

+12
View File
@@ -156,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,
@@ -597,6 +604,11 @@ __all__ = [
"parse_canonical_status",
"HARDENING_COMMAND",
"HardeningMixin",
"CpuMicrocodeFixDict",
"CpuMicrocodeMixin",
"add_component",
"firmware_component",
"microcode_package",
"HardeningDict",
"cpu_vulnerability_state",
"parse_hardening",
+309
View File
@@ -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",
]
+41 -1
View File
@@ -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.