Files
napalm-device-types/tests/test_hardening.py
T
christianmanivong 594cc5e486
driver / lint (pull_request) Successful in 17s
driver / standard (pull_request) Successful in 19s
driver / types (pull_request) Successful in 1m1s
driver / test (3.13) (pull_request) Successful in 1m12s
driver / test (3.12) (pull_request) Successful in 1m19s
driver / lowest (pull_request) Successful in 39s
driver / build (pull_request) Successful in 29s
driver / security (pull_request) Successful in 1m0s
CI / driver (pull_request) Successful in 2m31s
driver / publish (pull_request) Skipped
refactor(hardening): the SELinux part as three small questions (NetOrk/netork#2706)
_selinux_configured, _selinux_running and _selinux_seen, each on its own, so
_selinux stays within napalm-standard's complexity limit. The parse is
unchanged.
2026-11-27 01:45:12 +01:00

392 lines
15 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 TestSelinuxParts:
"""The three questions the SELinux part answers, each on its own (napalm-standard's
complexity limit): the mode it boots in, the mode it runs in, and whether the
host has SELinux at all."""
def test_the_configured_mode_is_the_last_selinux_line(self):
from napalm_device_types.hardening import _selinux_configured
lines = ["SELINUXTYPE=targeted", 'SELINUX="Permissive"']
assert _selinux_configured({"selinux_config": lines}) == "permissive"
assert _selinux_configured({"selinux_config": ["SELINUX="]}) is None
assert _selinux_configured({}) is None
@pytest.mark.parametrize(
"sections, mode",
[
({"selinux": ["Enforcing"]}, "enforcing"),
({"selinux": ["something else"], "selinux_enforce": ["0"]}, "permissive"),
({"selinux_enforce": ["1"]}, "enforcing"),
({"selinux_enforce": ["2"]}, None),
({}, None),
],
)
def test_the_running_mode_getenforce_first(self, sections, mode):
from napalm_device_types.hardening import _selinux_running
assert _selinux_running(sections) == mode
@pytest.mark.parametrize(
"sections, lsm, seen",
[
({}, ["capability", "selinux"], True),
({"selinux_config": []}, None, True),
({}, ["capability", "apparmor"], False),
({}, None, False),
],
)
def test_whether_the_host_has_it(self, sections, lsm, seen):
from napalm_device_types.hardening import _selinux_seen
assert _selinux_seen(sections, lsm, None) is seen
assert _selinux_seen(sections, lsm, "enforcing") is True
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