feat(hardening): how a Linux host is hardened, as one read-only reading (NetOrk/netork#2706)

HardeningMixin.get_hardening() reads, with one fixed command: the active
security modules, SELinux's mode and its configured mode, AppArmor's switch
and (as root) its profiles per mode, the crypto policy and FIPS mode, the
kernel's text for each CPU vulnerability, mitigations= and nosmt from the
command line, and the distribution's IDs. Read as root first, as the login
user where root is refused. What was not read is None, never off.
This commit is contained in:
christianmanivong committed 2026-11-26 23:11:57 +01:00
1 parent 5985c87cc8
commit 3cd0e3621a
5 files changed
+713

No files matched your search

+13
View File
@@ -44,6 +44,7 @@ instead of being restated on every role that happens to need it:
* :class:`~napalm_device_types.credential_expiry.CredentialExpiryMixin`
* :class:`~napalm_device_types.dhcp.DhcpServerMixin`
* :class:`~napalm_device_types.firewall_rules.FirewallRuleMixin`
* :class:`~napalm_device_types.hardening.HardeningMixin`
* :class:`~napalm_device_types.health_metrics.HealthMetricsMixin`
* :class:`~napalm_device_types.host_status.HostStatusMixin`
* :class:`~napalm_device_types.host_reboot.HostRebootMixin`
@@ -163,6 +164,13 @@ from napalm_device_types.fixes import (
ZabbixAgentMixin,
run_fix_steps,
)
from napalm_device_types.hardening import (
HARDENING_COMMAND,
HardeningDict,
HardeningMixin,
cpu_vulnerability_state,
parse_hardening,
)
from napalm_device_types.health_metrics import HealthMetricsMixin
from napalm_device_types.host_firewall import (
HostFirewallMixin,
@@ -541,6 +549,11 @@ __all__ = [
"KernelFactsMixin",
"KERNEL_FACTS_COMMAND",
"parse_kernel_facts",
"HARDENING_COMMAND",
"HardeningMixin",
"HardeningDict",
"cpu_vulnerability_state",
"parse_hardening",
"SERVICE_PACKAGES_COMMAND",
"SERVICES_RESTART_COMMAND",
"ServicesRestartMixin",
+326
View File
@@ -0,0 +1,326 @@
"""How a Linux host is hardened, as its kernel and its own tools say it (NetOrk/netork#2706).
Five things, each read where the host itself keeps it:
- **The security modules in force:** ``/sys/kernel/security/lsm`` lists the active
LSMs. SELinux's mode comes from ``getenforce`` (or ``/sys/fs/selinux/enforce``), the
mode it boots in from ``SELINUX=`` in ``/etc/selinux/config``. AppArmor's switch is
``/sys/module/apparmor/parameters/enabled``, its profiles per mode come from
``aa-status --json`` -- the one part that needs root.
- **The crypto policy:** ``update-crypto-policies --show`` (the dnf family; Debian and
Ubuntu have none) and FIPS mode from ``/proc/sys/crypto/fips_enabled``.
- **The CPU vulnerabilities:** each file under ``/sys/devices/system/cpu/vulnerabilities``
holds the kernel's own answer for one of them: ``Not affected``, ``Mitigation: ...``,
``Vulnerable...``, or ``Unknown: ...`` (:func:`cpu_vulnerability_state`).
- **The kernel command line:** ``mitigations=`` (``auto`` when not given, as in the
kernel) and ``nosmt``.
- **The distribution's IDs** (``ID`` and ``ID_LIKE`` from ``/etc/os-release``), so a
consumer can tell an Enterprise Linux host, where SELinux is the distribution's own
module, from one that merely has it installed.
One fixed command, read-only, the same on every Linux host, so it and its parse live
here once and a driver only carries the command across. **Not read is None, never
empty or off:** a section the command did not print -- a file missing, a tool not
installed, root refused -- comes back ``None``, so a consumer never reads "not looked"
as "clean".
"""
from __future__ import annotations
import json
import re
from shlex import quote
from typing import TYPE_CHECKING, Literal, TypedDict
from napalm_device_types.terminal import strip_terminal_codes
_BEGIN = "HARDENING_BEGIN"
_END = "HARDENING_END"
_VULNERABILITIES = "/sys/devices/system/cpu/vulnerabilities"
#: One line, POSIX ``sh``, read-only. The frame markers are printed in two halves so
#: that a transport which echoes the command does not show them early. The tools are in
#: ``/usr/sbin`` on some systems, outside a login user's ``PATH``. ``r`` prints a file
#: under a section header and ends it with a newline: ``/sys/kernel/security/lsm`` has
#: none of its own.
HARDENING_COMMAND = (
"PATH=$PATH:/usr/sbin:/sbin; "
'r() { if [ -r "$2" ]; then echo "[$1]"; cat "$2" 2>/dev/null; echo; fi; }; '
"printf '%s%s\\n' HARDENING_ BEGIN; "
"r lsm /sys/kernel/security/lsm; "
"r cmdline /proc/cmdline; "
"r fips /proc/sys/crypto/fips_enabled; "
"r apparmor_enabled /sys/module/apparmor/parameters/enabled; "
"if [ -r /etc/os-release ]; then echo '[os]'; grep -E '^(ID|ID_LIKE)=' /etc/os-release; fi; "
"if command -v getenforce >/dev/null 2>&1; then echo '[selinux]'; getenforce 2>/dev/null; "
"else r selinux_enforce /sys/fs/selinux/enforce; fi; "
"if [ -r /etc/selinux/config ]; then echo '[selinux_config]'; "
"grep -E '^SELINUX=' /etc/selinux/config; fi; "
"if command -v update-crypto-policies >/dev/null 2>&1; then echo '[crypto_policy]'; "
"update-crypto-policies --show 2>/dev/null; fi; "
f"if [ -d {_VULNERABILITIES} ]; then echo '[cpu_vulnerabilities]'; "
f"grep -H . {_VULNERABILITIES}/* 2>/dev/null; fi; "
"if command -v aa-status >/dev/null 2>&1; then echo '[aa_status]'; "
"aa-status --json 2>/dev/null; echo; fi; "
"printf '%s%s\\n' HARDENING_ END"
)
CpuVulnerabilityState = Literal["not_affected", "mitigated", "vulnerable", "unknown"]
_SELINUX_MODES = frozenset({"enforcing", "permissive", "disabled"})
_ENFORCE_FILE = {"1": "enforcing", "0": "permissive"}
_SECTION = re.compile(r"^\[([a-z_]+)\]$")
class SelinuxDict(TypedDict):
"""SELinux on the host. ``None`` in a field: could not be read."""
mode: str | None # "enforcing", "permissive" or "disabled"
configured: str | None # SELINUX= in /etc/selinux/config: the mode it boots in
class AppArmorDict(TypedDict):
"""AppArmor on the host. ``None`` in a field: could not be read."""
enabled: bool | None # /sys/module/apparmor/parameters/enabled, else the LSM list
#: Loaded profiles per mode ("enforce", "complain", ...), from ``aa-status --json``;
#: None without root, which it needs.
profiles: dict[str, int] | None
class HardeningDict(TypedDict):
"""What :meth:`HardeningMixin.get_hardening` read. ``None``: not read, never "off"."""
lsm: list[str] | None # /sys/kernel/security/lsm, in the kernel's order
selinux: SelinuxDict | None # None: no sign of SELinux on the host
apparmor: AppArmorDict | None # None: no sign of AppArmor on the host
crypto_policy: str | None # update-crypto-policies --show, e.g. "DEFAULT:SHA1"
fips: bool | None # /proc/sys/crypto/fips_enabled
#: File name under /sys/devices/system/cpu/vulnerabilities -> the kernel's text.
cpu_vulnerabilities: dict[str, str] | None
cmdline: str | None # /proc/cmdline
mitigations: str | None # mitigations= on the command line; "auto" when not given
nosmt: bool | None # SMT switched off by the command line
os_ids: list[str] | None # ID, then ID_LIKE, from /etc/os-release, lowercased
def cpu_vulnerability_state(text: str) -> CpuVulnerabilityState:
"""What the kernel's text for one CPU vulnerability says, in one word.
The kernel writes ``Not affected``, ``Mitigation: ...`` (also behind a prefix, as
``KVM: Mitigation: VMX disabled``), ``Vulnerable...`` or ``Processor vulnerable``,
and ``Unknown: ...`` where it cannot tell (a guest that cannot see its host's
microcode). A mitigation that leaves SMT exposed is still the kernel's
``Mitigation``: the text keeps the rest.
"""
lowered = text.strip().lower()
if lowered.startswith("not affected"):
return "not_affected"
if lowered.startswith(("vulnerable", "processor vulnerable")):
return "vulnerable"
if lowered.startswith("mitigation") or ": mitigation" in lowered:
return "mitigated"
return "unknown"
def _sections(output: str) -> dict[str, list[str]]:
lines = [line.strip() for line in strip_terminal_codes(output).splitlines()]
try:
start = lines.index(_BEGIN)
end = lines.index(_END, start)
except ValueError:
raise ValueError("no intact hardening report in the output") from None
sections: dict[str, list[str]] = {}
current: list[str] = []
for line in lines[start + 1 : end]:
header = _SECTION.match(line)
if header:
current = sections.setdefault(header.group(1), [])
elif line:
current.append(line)
return sections
def _first(sections: dict[str, list[str]], key: str) -> str | None:
lines = sections.get(key)
return lines[0] if lines else None
def _unquote(value: str) -> str:
value = value.strip()
return value[1:-1] if len(value) >= 2 and value[0] == value[-1] and value[0] in "\"'" else value
def _lsm(sections: dict[str, list[str]]) -> list[str] | None:
line = _first(sections, "lsm")
if line is None:
return None
return [name.strip() for name in line.split(",") if name.strip()]
def _selinux(sections: dict[str, list[str]], lsm: list[str] | None) -> SelinuxDict | None:
said = (_first(sections, "selinux") or "").lower()
configured = None
for line in sections.get("selinux_config", []):
key, _, value = line.partition("=")
if key.strip() == "SELINUX":
configured = _unquote(value).lower() or None
mode: str | None = said if said in _SELINUX_MODES else None
if mode is None:
mode = _ENFORCE_FILE.get(_first(sections, "selinux_enforce") or "")
seen = mode is not None or "selinux_config" in sections or "selinux" in (lsm or [])
if not seen:
return None
if mode is None and "selinux_config" in sections and lsm is not None and "selinux" not in lsm:
mode = "disabled"
return {"mode": mode, "configured": configured}
def _profiles(sections: dict[str, list[str]]) -> dict[str, int] | None:
text = "".join(sections.get("aa_status", []))
try:
profiles = json.loads(text).get("profiles")
except (ValueError, AttributeError):
return None
if not isinstance(profiles, dict):
return None
counts: dict[str, int] = {}
for mode in profiles.values():
counts[str(mode)] = counts.get(str(mode), 0) + 1
return dict(sorted(counts.items()))
def _apparmor(sections: dict[str, list[str]], lsm: list[str] | None) -> AppArmorDict | None:
switch = _first(sections, "apparmor_enabled")
profiles = _profiles(sections)
in_lsm = "apparmor" in (lsm or [])
if switch is None and profiles is None and not in_lsm:
return None
if switch is not None:
enabled: bool | None = switch.upper().startswith("Y")
else:
enabled = True if in_lsm else None
return {"enabled": enabled, "profiles": profiles}
def _cpu_vulnerabilities(sections: dict[str, list[str]]) -> dict[str, str] | None:
if "cpu_vulnerabilities" not in sections:
return None
found: dict[str, str] = {}
for line in sections["cpu_vulnerabilities"]:
path, sep, text = line.partition(":")
if sep:
found[path.rsplit("/", 1)[-1]] = text.strip()
return dict(sorted(found.items()))
def _command_line(cmdline: str | None) -> tuple[str | None, bool | None]:
"""``mitigations=`` (the last one wins, as in the kernel) and whether SMT is off."""
if cmdline is None:
return None, None
mitigations = "auto"
nosmt = False
for word in cmdline.split():
key, _, value = word.partition("=")
if key == "mitigations":
mitigations = value
elif key == "nosmt":
nosmt = True
return mitigations, nosmt or "nosmt" in mitigations.split(",")
def _os_ids(sections: dict[str, list[str]]) -> list[str] | None:
if "os" not in sections:
return None
values = {}
for line in sections["os"]:
key, _, value = line.partition("=")
values[key.strip()] = _unquote(value)
ids: list[str] = []
for word in f"{values.get('ID', '')} {values.get('ID_LIKE', '')}".lower().split():
if word not in ids:
ids.append(word)
return ids
def parse_hardening(output: str) -> HardeningDict:
"""Parse what :data:`HARDENING_COMMAND` printed.
:raises ValueError: when the output carries no intact report.
"""
sections = _sections(output)
lsm = _lsm(sections)
cmdline = _first(sections, "cmdline")
mitigations, nosmt = _command_line(cmdline)
fips = _first(sections, "fips")
return {
"lsm": lsm,
"selinux": _selinux(sections, lsm),
"apparmor": _apparmor(sections, lsm),
"crypto_policy": _first(sections, "crypto_policy"),
"fips": None if fips is None else fips == "1",
"cpu_vulnerabilities": _cpu_vulnerabilities(sections),
"cmdline": cmdline,
"mitigations": mitigations,
"nosmt": nosmt,
"os_ids": _os_ids(sections),
}
class HardeningMixin:
"""Adds :meth:`get_hardening` to a driver that can run a command on a Linux host.
The template form (README, "Function classes"): the command and its parse are the
same everywhere, and a driver supplies only :meth:`_run_hardening_command` -- how a
command reaches its host, and how it gains root there. Mixed in by the drivers that
can, so ``hasattr(driver, "get_hardening")`` stays a truthful answer.
"""
if TYPE_CHECKING: # pragma: no cover - declared for type checkers only
def _run_hardening_command(self, command: str, *, privileged: bool) -> str:
"""Run *command* on the host and return what it printed; as root when
*privileged*. The command is a single ``sh -c`` invocation; it reads no stdin."""
...
def get_hardening(self) -> HardeningDict:
"""
Returns how the host is hardened: its security modules, crypto policy, CPU
vulnerabilities and kernel command line.
* lsm (list or None) - the active security modules, in the kernel's order
* selinux ({mode, configured} or None) - None without any sign of SELinux
* apparmor ({enabled, profiles} or None) - profiles per mode need root
* crypto_policy (str or None) - ``update-crypto-policies --show``
* fips (bool or None) - FIPS mode
* cpu_vulnerabilities (dict or None) - name -> the kernel's text
* cmdline (str or None), mitigations (str or None), nosmt (bool or None)
* os_ids (list or None) - ``ID`` and ``ID_LIKE`` from ``/etc/os-release``
``None`` means not read. Read as root first, for AppArmor's profiles; where root
is refused, as the login user, without them.
Example::
{
"lsm": ["lockdown", "capability", "yama", "selinux", "bpf"],
"selinux": {"mode": "enforcing", "configured": "enforcing"},
"apparmor": None,
"crypto_policy": "DEFAULT",
"fips": False,
"cpu_vulnerabilities": {"meltdown": "Not affected",
"spectre_v2": "Mitigation: Retpolines; ..."},
"cmdline": "BOOT_IMAGE=... ro",
"mitigations": "auto",
"nosmt": False,
"os_ids": ["almalinux", "rhel", "centos", "fedora"],
}
:raises ValueError: if neither reading carried an intact report.
"""
command = f"sh -c {quote(HARDENING_COMMAND)}"
try:
return parse_hardening(self._run_hardening_command(command, privileged=True))
except ValueError:
pass
return parse_hardening(self._run_hardening_command(command, privileged=False))