diff --git a/CHANGELOG.md b/CHANGELOG.md index 06b46fb..68a8e71 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -7,6 +7,22 @@ recorded here; their history is the git log. ## [Unreleased] +### Added +- `HardeningMixin.get_hardening()`: how a Linux host is hardened, read with one fixed, + read-only command (NetOrk/netork#2706). The active security modules + (`/sys/kernel/security/lsm`), SELinux's mode (`getenforce`, else + `/sys/fs/selinux/enforce`) and its configured mode (`SELINUX=` in `/etc/selinux/config`), + AppArmor's switch and, as root, its profiles per mode (`aa-status --json`), the crypto + policy (`update-crypto-policies --show`) and FIPS mode (`/proc/sys/crypto/fips_enabled`), + the kernel's text for each file under `/sys/devices/system/cpu/vulnerabilities`, the + kernel command line with `mitigations=` (`auto` when not given) and `nosmt`, and + `ID`/`ID_LIKE` from `/etc/os-release`. Read as root first; where root is refused, as the + login user, without the profile counts. Anything not read is `None`, never "off". A + driver supplies `_run_hardening_command(command, *, privileged)`. +- `parse_hardening`, `HARDENING_COMMAND`, `cpu_vulnerability_state` (`not_affected`, + `mitigated`, `vulnerable` or `unknown`, from the kernel's words), and the + `HardeningDict`, `SelinuxDict` and `AppArmorDict` shapes (in `hardening`). + ## [4.46.0] - 2026-11-26 ### Fixed diff --git a/README.md b/README.md index 8fc1e3f..ce723be 100644 --- a/README.md +++ b/README.md @@ -160,6 +160,17 @@ everywhere, so the command and its parse are concrete here and a driver supplies `_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. +`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 +(`/sys/kernel/security/lsm`), SELinux's mode (`getenforce`) and the mode it boots in +(`/etc/selinux/config`), AppArmor's switch and its profiles per mode (`aa-status --json`, +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 +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". + `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 diff --git a/napalm_device_types/__init__.py b/napalm_device_types/__init__.py index f64ca2f..c85022e 100644 --- a/napalm_device_types/__init__.py +++ b/napalm_device_types/__init__.py @@ -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", diff --git a/napalm_device_types/hardening.py b/napalm_device_types/hardening.py new file mode 100644 index 0000000..e6b1572 --- /dev/null +++ b/napalm_device_types/hardening.py @@ -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)) diff --git a/tests/test_hardening.py b/tests/test_hardening.py new file mode 100644 index 0000000..03c98d1 --- /dev/null +++ b/tests/test_hardening.py @@ -0,0 +1,347 @@ +"""get_hardening: how a Linux host is hardened, as the kernel and the host's tools say it. + +The security modules in force (``/sys/kernel/security/lsm``, SELinux's mode, AppArmor's +profiles), the system-wide crypto policy and FIPS mode, what the kernel reports for each +known CPU vulnerability, and the command line it booted with (NetOrk/netork#2706). One +read-only command, the same on every Linux host, so it lives here once and a driver only +carries it across. Root only adds AppArmor's profile counts. +""" + +from __future__ import annotations + +import json +import os +import subprocess + +import pytest + +from napalm_device_types import OSDriver +from napalm_device_types.hardening import ( + HARDENING_COMMAND, + HardeningMixin, + cpu_vulnerability_state, + parse_hardening, +) + +#: AlmaLinux 9 on a KVM guest: SELinux enforcing, the DEFAULT policy, no FIPS. +ALMA_9 = [ + ("lsm", "lockdown,capability,yama,selinux,bpf"), + ("cmdline", "BOOT_IMAGE=(hd0,gpt2)/vmlinuz-5.14.0-503.el9.x86_64 root=/dev/vda4 ro"), + ("fips", "0"), + ("os", 'ID="almalinux"\nID_LIKE="rhel centos fedora"'), + ("selinux", "Enforcing"), + ("selinux_config", "SELINUX=enforcing"), + ("crypto_policy", "DEFAULT"), + ( + "cpu_vulnerabilities", + "/sys/devices/system/cpu/vulnerabilities/meltdown:Not affected\n" + "/sys/devices/system/cpu/vulnerabilities/spec_rstack_overflow:Mitigation: Safe RET\n" + "/sys/devices/system/cpu/vulnerabilities/spectre_v1:Mitigation: usercopy/swapgs " + "barriers and __user pointer sanitization\n" + "/sys/devices/system/cpu/vulnerabilities/spectre_v2:Mitigation: Retpolines; IBPB: " + "conditional; IBRS_FW; STIBP: always-on; RSB filling; PBRSB-eIBRS: Not affected; " + "BHI: Not affected\n" + "/sys/devices/system/cpu/vulnerabilities/mmio_stale_data:Unknown: No mitigations", + ), +] + +AA_STATUS = { + "version": "2", + "profiles": { + "/snap/snapd/21759/usr/lib/snapd/snap-confine": "enforce", + "lsb_release": "enforce", + "rsyslogd": "enforce", + "unprivileged_userns": "enforce", + "ubuntu_pro_apt_news": "complain", + "Discord": "unconfined", + }, + "processes": { + "/usr/sbin/rsyslogd": [{"profile": "rsyslogd", "pid": "812", "status": "enforce"}] + }, +} + +#: Ubuntu 24.04, read as root: AppArmor with its profiles, no crypto-policies, no SELinux. +UBUNTU_2404 = [ + ("lsm", "lockdown,capability,landlock,yama,apparmor,ima,evm"), + ("cmdline", "BOOT_IMAGE=/vmlinuz-6.8.0-49-generic root=/dev/mapper/vg-root ro quiet splash"), + ("fips", "0"), + ("apparmor_enabled", "Y"), + ("os", "ID=ubuntu\nID_LIKE=debian"), + ( + "cpu_vulnerabilities", + "/sys/devices/system/cpu/vulnerabilities/meltdown:Not affected\n" + "/sys/devices/system/cpu/vulnerabilities/spectre_v2:Mitigation: Enhanced / Automatic " + "IBRS; IBPB: conditional; RSB filling; PBRSB-eIBRS: SW sequence; BHI: BHI_DIS_S", + ), + ("aa_status", json.dumps(AA_STATUS)), +] + +#: Debian 12 booted with mitigations=off. +MITIGATIONS_OFF = [ + ("lsm", "lockdown,capability,landlock,yama,apparmor,tomoyo"), + ("cmdline", "BOOT_IMAGE=/boot/vmlinuz-6.1.0-25-amd64 root=UUID=1b2c ro quiet mitigations=off"), + ("apparmor_enabled", "Y"), + ("os", "ID=debian"), + ( + "cpu_vulnerabilities", + "/sys/devices/system/cpu/vulnerabilities/meltdown:Vulnerable\n" + "/sys/devices/system/cpu/vulnerabilities/mds:Vulnerable; SMT vulnerable\n" + "/sys/devices/system/cpu/vulnerabilities/spectre_v1:Vulnerable: __user pointer " + "sanitization and usercopy barriers only; no swapgs barriers\n" + "/sys/devices/system/cpu/vulnerabilities/spectre_v2:Vulnerable; IBPB: disabled; " + "STIBP: disabled; PBRSB-eIBRS: Vulnerable; BHI: Vulnerable", + ), + ("aa_status", ""), +] + + +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}HARDENING_BEGIN\n{body}HARDENING_END\n" + + +class TestTheFixtures: + def test_alma_9_selinux_enforcing_default_policy(self): + reading = parse_hardening(_wire(ALMA_9)) + + assert reading == { + "lsm": ["lockdown", "capability", "yama", "selinux", "bpf"], + "selinux": {"mode": "enforcing", "configured": "enforcing"}, + "apparmor": None, + "crypto_policy": "DEFAULT", + "fips": False, + "cpu_vulnerabilities": { + "meltdown": "Not affected", + "mmio_stale_data": "Unknown: No mitigations", + "spec_rstack_overflow": "Mitigation: Safe RET", + "spectre_v1": "Mitigation: usercopy/swapgs barriers and __user pointer " + "sanitization", + "spectre_v2": "Mitigation: Retpolines; IBPB: conditional; IBRS_FW; STIBP: " + "always-on; RSB filling; PBRSB-eIBRS: Not affected; BHI: Not affected", + }, + "cmdline": "BOOT_IMAGE=(hd0,gpt2)/vmlinuz-5.14.0-503.el9.x86_64 root=/dev/vda4 ro", + "mitigations": "auto", + "nosmt": False, + "os_ids": ["almalinux", "rhel", "centos", "fedora"], + } + + def test_ubuntu_24_04_apparmor_with_its_profiles(self): + reading = parse_hardening(_wire(UBUNTU_2404)) + + assert reading["selinux"] is None + assert reading["apparmor"] == { + "enabled": True, + "profiles": {"complain": 1, "enforce": 4, "unconfined": 1}, + } + assert reading["crypto_policy"] is None + assert reading["os_ids"] == ["ubuntu", "debian"] + + def test_mitigations_off(self): + reading = parse_hardening(_wire(MITIGATIONS_OFF)) + + assert reading["mitigations"] == "off" + assert reading["nosmt"] is False + assert {cpu_vulnerability_state(v) for v in reading["cpu_vulnerabilities"].values()} == { + "vulnerable" + } + + def test_apparmor_without_root_has_no_profile_counts(self): + """``aa-status`` needs root: without it the profiles are unread, never zero.""" + reading = parse_hardening(_wire(MITIGATIONS_OFF)) + + assert reading["apparmor"] == {"enabled": True, "profiles": None} + + +class TestNotReadIsNone: + def test_a_section_never_printed_is_none(self): + """``None`` is "could not read": an old kernel without the ``lsm`` file, a + host without ``update-crypto-policies``.""" + reading = parse_hardening(_wire([])) + + assert reading == { + "lsm": None, + "selinux": None, + "apparmor": None, + "crypto_policy": None, + "fips": None, + "cpu_vulnerabilities": None, + "cmdline": None, + "mitigations": None, + "nosmt": None, + "os_ids": None, + } + + def test_an_empty_vulnerabilities_directory_is_read_and_empty(self): + reading = parse_hardening(_wire([("cpu_vulnerabilities", "")])) + + assert reading["cpu_vulnerabilities"] == {} + + def test_output_without_the_frame_raises(self): + with pytest.raises(ValueError): + parse_hardening("sudo: a password is required\n") + + def test_whatever_surrounds_the_frame_is_ignored(self): + noise = "Last login: today\nprintf '%s%s\\n' HARDENING_ BEGIN; ...\n" + + assert parse_hardening(_wire(ALMA_9, noise=noise))["crypto_policy"] == "DEFAULT" + + def test_aa_status_output_that_is_not_json_is_unread(self): + reading = parse_hardening( + _wire([("apparmor_enabled", "Y"), ("aa_status", "apparmor not present.")]) + ) + + assert reading["apparmor"] == {"enabled": True, "profiles": None} + + +class TestSelinux: + def test_getenforce_permissive(self): + reading = parse_hardening(_wire([("selinux", "Permissive")])) + + assert reading["selinux"] == {"mode": "permissive", "configured": None} + + def test_disabled_by_getenforce(self): + reading = parse_hardening( + _wire([("selinux", "Disabled"), ("selinux_config", "SELINUX=disabled")]) + ) + + assert reading["selinux"] == {"mode": "disabled", "configured": "disabled"} + + @pytest.mark.parametrize("value, mode", [("1", "enforcing"), ("0", "permissive")]) + def test_without_getenforce_the_enforce_file_answers(self, value, mode): + reading = parse_hardening(_wire([("selinux_enforce", value)])) + + assert reading["selinux"]["mode"] == mode + + def test_configured_but_not_among_the_active_modules_is_disabled(self): + """The policy is installed (``/etc/selinux/config``), the kernel runs without it.""" + reading = parse_hardening( + _wire([("lsm", "capability,yama"), ("selinux_config", 'SELINUX="enforcing"')]) + ) + + assert reading["selinux"] == {"mode": "disabled", "configured": "enforcing"} + + def test_configured_without_a_list_of_modules_is_unknown(self): + reading = parse_hardening(_wire([("selinux_config", "SELINUX=enforcing")])) + + assert reading["selinux"] == {"mode": None, "configured": "enforcing"} + + +class TestAppArmor: + def test_in_the_list_of_modules_without_the_parameter_file(self): + reading = parse_hardening(_wire([("lsm", "capability,apparmor")])) + + assert reading["apparmor"] == {"enabled": True, "profiles": None} + + def test_switched_off(self): + reading = parse_hardening(_wire([("lsm", "capability"), ("apparmor_enabled", "N")])) + + assert reading["apparmor"] == {"enabled": False, "profiles": None} + + +class TestCommandLine: + @pytest.mark.parametrize( + "cmdline, mitigations, nosmt", + [ + ("ro quiet", "auto", False), + ("ro mitigations=off", "off", False), + ("ro mitigations=auto,nosmt", "auto,nosmt", True), + ("ro nosmt", "auto", True), + ("ro nosmt=force", "auto", True), + ("ro mitigations=auto mitigations=off", "off", False), + ], + ) + def test_mitigations_and_smt(self, cmdline, mitigations, nosmt): + """The last ``mitigations=`` wins, as in the kernel; ``nosmt`` comes alone or + with ``mitigations=auto,nosmt``.""" + reading = parse_hardening(_wire([("cmdline", cmdline)])) + + assert (reading["mitigations"], reading["nosmt"]) == (mitigations, nosmt) + + +class TestCryptoPolicy: + def test_a_subpolicy_is_kept(self): + reading = parse_hardening(_wire([("crypto_policy", "LEGACY:AD-SUPPORT"), ("fips", "1")])) + + assert (reading["crypto_policy"], reading["fips"]) == ("LEGACY:AD-SUPPORT", True) + + def test_no_output_is_unread(self): + assert parse_hardening(_wire([("crypto_policy", "")]))["crypto_policy"] is None + + +class TestCpuVulnerabilityState: + @pytest.mark.parametrize( + "text, state", + [ + ("Not affected", "not_affected"), + ("Mitigation: Retpolines; IBPB: conditional", "mitigated"), + ("KVM: Mitigation: VMX disabled", "mitigated"), + ( + "Mitigation: PTE Inversion; VMX: conditional cache flushes, SMT vulnerable", + "mitigated", + ), + ("Vulnerable", "vulnerable"), + ("Vulnerable: Clear CPU buffers attempted, no microcode; SMT vulnerable", "vulnerable"), + ("Processor vulnerable", "vulnerable"), + ("Unknown: Dependent on hypervisor status", "unknown"), + ("", "unknown"), + ], + ) + def test_the_kernels_words(self, text, state): + assert cpu_vulnerability_state(text) == state + + +class _Driver(OSDriver, HardeningMixin): + def __init__(self, outputs): + self.outputs = list(outputs) + self.calls: list[tuple[str, bool]] = [] + + def _run_hardening_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(UBUNTU_2404)]) + + reading = driver.get_hardening() + + assert driver.calls[0][1] is True + assert reading["apparmor"]["profiles"]["enforce"] == 4 + + def test_root_refused_reads_as_the_login_user(self): + driver = _Driver(["sudo: a password is required\n", _wire(MITIGATIONS_OFF)]) + + reading = driver.get_hardening() + + assert [privileged for _, privileged in driver.calls] == [True, False] + assert reading["mitigations"] == "off" + + def test_the_command_goes_to_sh(self): + driver = _Driver([_wire(ALMA_9)]) + + driver.get_hardening() + + assert driver.calls[0][0].startswith("sh -c ") + + +class TestTheCommand: + def test_the_frame_is_not_in_the_command_itself(self): + assert "HARDENING_BEGIN" not in HARDENING_COMMAND + assert "HARDENING_END" not in HARDENING_COMMAND + + def test_it_changes_nothing(self): + for verb in ("setenforce", "--set", "aa-enforce", "aa-complain", " > ", ">>", "sudo"): + assert verb not in HARDENING_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", HARDENING_COMMAND], capture_output=True, text=True, timeout=60 + ).stdout + + reading = parse_hardening(out) + + assert reading["cmdline"] is not None + assert reading["mitigations"] is not None