feat(kernel): the live patches the running kernel carries, with the kernel facts (NetOrk/netork#2701)

/sys/kernel/livepatch with each patch's enabled and transition, kpatch
list, and Canonical Livepatch's status for the running kernel with the
CVEs it names. status reads the daemon's last state; refresh is never run.
Where the client is installed and its status needs root, a driver that
supplies _run_livepatch_status_command reads it again as root.
This commit is contained in:
christianmanivong committed 2026-11-28 04:23:17 +01:00
1 parent 14217b6eeb
commit b9b6297815
6 files changed
+597 -2

No files matched your search

+17 -1
View File
@@ -192,7 +192,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 (
@@ -201,6 +206,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,
@@ -573,6 +584,11 @@ __all__ = [
"KernelFactsMixin",
"KERNEL_FACTS_COMMAND",
"parse_kernel_facts",
"LIVEPATCH_STATUS_COMMAND",
"CanonicalLivepatchDict",
"LivePatchesDict",
"canonical_release",
"parse_canonical_status",
"HARDENING_COMMAND",
"HardeningMixin",
"HardeningDict",
+48 -1
View File
@@ -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,6 +33,7 @@ import gzip
import zlib
from typing import TYPE_CHECKING
from napalm_device_types.livepatch import live_patches, parse_canonical_status
from napalm_device_types.models import KernelFactsDict
_BEGIN = "KFACTS_BEGIN"
@@ -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,29 @@ 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:
patches["canonical"] = parse_canonical_status(run(LIVEPATCH_STATUS_COMMAND))
except Exception: # noqa: BLE001 - root refused or the client failed: not read
pass
return facts
+201
View File
@@ -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,
}
+3
View File
@@ -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.livepatch import LivePatchesDict
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
@@ -289,6 +290,8 @@ class KernelFactsDict(TypedDict):
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]
class ListeningSocketDict(TypedDict):