Files
napalm-device-types/tests/test_hardening.py
T
christianmanivong 3cd0e3621a 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.
2026-11-26 23:11:57 +01:00

348 lines
13 KiB
Python

"""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