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

+476
View File
@@ -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
+45
View File
@@ -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