get_hardening() reads Secure Boot, the TPM, BitLocker per volume, Defender, the firewall profiles' state and virtualization-based security in one script, each part caught on its own and each cmdlet probed with Get-Command first. BitLocker through Win32_EncryptableVolume, never Get-BitLockerVolume: no recovery password or key protector is read.
331 lines
11 KiB
Python
331 lines
11 KiB
Python
"""A Windows host's security posture as napalm-device-types' hardening reading (NetOrk/netork#2893).
|
|
|
|
The reading is one script whose JSON a fake host answers, from
|
|
tests/fixtures/synthetic/posture_client.json (a Windows 11 client with everything on) and
|
|
posture_server.json (a Windows Server VM booted from BIOS, without the BitLocker feature,
|
|
Defender passive beside another product, the Private profile off).
|
|
"""
|
|
|
|
from __future__ import annotations
|
|
|
|
import json
|
|
from pathlib import Path
|
|
from typing import Any
|
|
|
|
import pytest
|
|
|
|
from napalm_windows import WindowsDriver
|
|
from napalm_windows import posture as mod
|
|
|
|
FIXTURES = Path(__file__).parent / "fixtures" / "synthetic"
|
|
LINUX_KEYS = (
|
|
"lsm",
|
|
"selinux",
|
|
"apparmor",
|
|
"crypto_policy",
|
|
"fips",
|
|
"cpu_vulnerabilities",
|
|
"cmdline",
|
|
"mitigations",
|
|
"nosmt",
|
|
"os_ids",
|
|
"virtualization",
|
|
"cpu_vendor",
|
|
)
|
|
|
|
|
|
def _fixture(name: str) -> dict[str, Any]:
|
|
data: dict[str, Any] = json.loads((FIXTURES / f"posture_{name}.json").read_text())
|
|
return data
|
|
|
|
|
|
class FakeHost:
|
|
is_open = True
|
|
|
|
def __init__(self, answer: str) -> None:
|
|
self.answer = answer
|
|
self.sent: list[str] = []
|
|
|
|
def run(self, script: str) -> str:
|
|
self.sent.append(script)
|
|
return self.answer
|
|
|
|
def close(self) -> None:
|
|
self.is_open = False
|
|
|
|
|
|
def _read(raw: dict[str, Any] | str) -> dict[str, Any]:
|
|
host = FakeHost(raw if isinstance(raw, str) else json.dumps(raw))
|
|
driver = WindowsDriver("win01", "admin", "secret")
|
|
driver._transport = host # type: ignore[assignment]
|
|
reading: dict[str, Any] = dict(driver.get_hardening())
|
|
assert host.sent == [mod._PS_POSTURE]
|
|
return reading
|
|
|
|
|
|
def _with(name: str, **changes: Any) -> dict[str, Any]:
|
|
return {**_fixture(name), **changes}
|
|
|
|
|
|
class TestClient:
|
|
def test_everything_on(self):
|
|
reading = _read(_fixture("client"))
|
|
|
|
assert reading["secure_boot"] == "on"
|
|
assert reading["tpm"] == {
|
|
"present": True,
|
|
"enabled": True,
|
|
"activated": True,
|
|
"owned": True,
|
|
"version": "2.0",
|
|
"manufacturer": "INTC",
|
|
}
|
|
assert reading["disk_encryption"] == {
|
|
"provider": "bitlocker",
|
|
"installed": True,
|
|
"volumes": [
|
|
{
|
|
"volume": "C:",
|
|
"system": True,
|
|
"protection": "on",
|
|
"status": "fully_encrypted",
|
|
"method": "xts_aes_128",
|
|
},
|
|
{
|
|
"volume": "D:",
|
|
"system": False,
|
|
"protection": "off",
|
|
"status": "fully_decrypted",
|
|
"method": None,
|
|
},
|
|
],
|
|
}
|
|
assert reading["antimalware"] == {
|
|
"product": "Microsoft Defender Antivirus",
|
|
"enabled": True,
|
|
"real_time": True,
|
|
"mode": "active",
|
|
"signatures_updated": 1764547200,
|
|
"signature_age_days": 0,
|
|
"signature_version": "1.443.512.0",
|
|
"tamper_protected": True,
|
|
}
|
|
assert reading["firewall_profiles"] == [
|
|
{"name": "domain", "enabled": True},
|
|
{"name": "private", "enabled": True},
|
|
{"name": "public", "enabled": True},
|
|
]
|
|
assert reading["vbs"] == {"status": "running", "running": ["credential_guard", "hvci"]}
|
|
|
|
def test_what_only_linux_has_is_not_read(self):
|
|
reading = _read(_fixture("client"))
|
|
|
|
assert all(reading[key] is None for key in LINUX_KEYS)
|
|
|
|
|
|
class TestServer:
|
|
def test_a_bios_boot_has_no_secure_boot_to_switch_on(self):
|
|
assert _read(_fixture("server"))["secure_boot"] == "unsupported"
|
|
|
|
def test_no_tpm(self):
|
|
assert _read(_fixture("server"))["tpm"] == {
|
|
"present": False,
|
|
"enabled": None,
|
|
"activated": None,
|
|
"owned": None,
|
|
"version": None,
|
|
"manufacturer": None,
|
|
}
|
|
|
|
def test_bitlocker_not_installed_is_said_so_not_an_error(self):
|
|
assert _read(_fixture("server"))["disk_encryption"] == {
|
|
"provider": "bitlocker",
|
|
"installed": False,
|
|
"volumes": [],
|
|
}
|
|
|
|
def test_defender_passive_beside_another_product(self):
|
|
antimalware = _read(_fixture("server"))["antimalware"]
|
|
|
|
assert antimalware["mode"] == "passive"
|
|
assert antimalware["real_time"] is False
|
|
assert antimalware["signature_age_days"] == 7
|
|
|
|
def test_a_profile_switched_off(self):
|
|
profiles = _read(_fixture("server"))["firewall_profiles"]
|
|
|
|
assert {"name": "private", "enabled": False} in profiles
|
|
|
|
def test_vbs_off_runs_nothing(self):
|
|
assert _read(_fixture("server"))["vbs"] == {"status": "off", "running": []}
|
|
|
|
|
|
class TestEachPartOnItsOwn:
|
|
@pytest.mark.parametrize(
|
|
("part", "key"),
|
|
[
|
|
("secure_boot", "secure_boot"),
|
|
("tpm", "tpm"),
|
|
("bitlocker", "disk_encryption"),
|
|
("defender", "antimalware"),
|
|
("firewall", "firewall_profiles"),
|
|
("vbs", "vbs"),
|
|
],
|
|
)
|
|
def test_a_part_that_failed_is_not_read_and_the_rest_is(self, part, key):
|
|
raw = _with("client", **{part: None, "errors": {part: "Access denied"}})
|
|
|
|
reading = _read(raw)
|
|
|
|
assert reading[key] is None
|
|
others = {"secure_boot", "tpm", "disk_encryption", "antimalware", "firewall_profiles"}
|
|
assert all(reading[k] is not None for k in others - {key})
|
|
|
|
def test_a_cmdlet_the_host_lacks_is_not_read(self):
|
|
"""Server Core without Defender, a build without the firewall module."""
|
|
reading = _read(_with("client", defender=None, firewall=None, secure_boot=None))
|
|
|
|
assert reading["antimalware"] is None
|
|
assert reading["firewall_profiles"] is None
|
|
assert reading["secure_boot"] is None
|
|
|
|
def test_secure_boot_off(self):
|
|
assert _read(_with("client", secure_boot="False"))["secure_boot"] == "off"
|
|
|
|
def test_a_secure_boot_answer_it_does_not_know_is_not_read(self):
|
|
assert _read(_with("client", secure_boot="maybe"))["secure_boot"] is None
|
|
|
|
|
|
class TestValues:
|
|
def test_one_element_lists_arrive_bare(self):
|
|
"""ConvertTo-Json unwraps a one-element array into its element."""
|
|
raw = _fixture("client")
|
|
raw["bitlocker"]["volumes"] = raw["bitlocker"]["volumes"][0]
|
|
raw["firewall"] = raw["firewall"][0]
|
|
raw["vbs"]["running"] = "2"
|
|
|
|
reading = _read(raw)
|
|
|
|
assert [v["volume"] for v in reading["disk_encryption"]["volumes"]] == ["C:"]
|
|
assert reading["firewall_profiles"] == [{"name": "domain", "enabled": True}]
|
|
assert reading["vbs"]["running"] == ["hvci"]
|
|
|
|
@pytest.mark.parametrize(
|
|
("mode", "word"),
|
|
[
|
|
("Normal", "active"),
|
|
("Passive Mode", "passive"),
|
|
("Passive", "passive"),
|
|
("EDR Block Mode", "edr_block"),
|
|
("SxS Passive Mode", "sxs_passive"),
|
|
("Not running", None),
|
|
(None, None),
|
|
],
|
|
)
|
|
def test_defenders_running_mode(self, mode, word):
|
|
raw = _fixture("client")
|
|
raw["defender"]["running_mode"] = mode
|
|
|
|
assert _read(raw)["antimalware"]["mode"] == word
|
|
|
|
def test_defender_with_its_service_off_scans_nothing(self):
|
|
raw = _fixture("client")
|
|
raw["defender"].update(am_service=False)
|
|
|
|
antimalware = _read(raw)["antimalware"]
|
|
|
|
assert antimalware["enabled"] is False
|
|
|
|
def test_defender_without_signatures_yet(self):
|
|
raw = _fixture("client")
|
|
raw["defender"].update(signature_updated=None, signature_age=None, signature_version="")
|
|
|
|
antimalware = _read(raw)["antimalware"]
|
|
|
|
assert antimalware["signatures_updated"] is None
|
|
assert antimalware["signature_age_days"] is None
|
|
assert antimalware["signature_version"] is None
|
|
|
|
def test_the_os_volume_is_the_system_volume_by_its_type_or_its_letter(self):
|
|
raw = _fixture("client")
|
|
raw["bitlocker"]["volumes"] = [
|
|
{
|
|
"drive": "C:",
|
|
"volume_type": "1",
|
|
"protection": "2",
|
|
"conversion": "4",
|
|
"method": "7",
|
|
},
|
|
{
|
|
"drive": "E:",
|
|
"volume_type": "0",
|
|
"protection": "0",
|
|
"conversion": "2",
|
|
"method": "4",
|
|
},
|
|
{
|
|
"drive": None,
|
|
"volume_type": "1",
|
|
"protection": "0",
|
|
"conversion": "0",
|
|
"method": "0",
|
|
},
|
|
]
|
|
|
|
volumes = _read(raw)["disk_encryption"]["volumes"]
|
|
|
|
assert [(v["volume"], v["system"]) for v in volumes] == [("C:", True), ("E:", True)]
|
|
assert volumes[0]["protection"] == "unknown"
|
|
assert volumes[0]["status"] == "encryption_paused"
|
|
assert volumes[0]["method"] == "xts_aes_256"
|
|
assert volumes[1]["status"] == "encrypting"
|
|
assert volumes[1]["method"] == "aes_256"
|
|
|
|
def test_numbers_it_does_not_know_are_not_guessed(self):
|
|
raw = _fixture("client")
|
|
raw["bitlocker"]["volumes"] = [
|
|
{"drive": "C:", "volume_type": "0", "protection": "9", "conversion": "9", "method": "x"}
|
|
]
|
|
raw["vbs"] = {"status": "7", "running": ["9"]}
|
|
raw["tpm"]["spec_version"] = ""
|
|
|
|
reading = _read(raw)
|
|
|
|
volume = reading["disk_encryption"]["volumes"][0]
|
|
assert (volume["protection"], volume["status"], volume["method"]) == ("unknown", None, None)
|
|
assert reading["vbs"] == {"status": None, "running": ["service_9"]}
|
|
assert reading["tpm"]["version"] is None
|
|
|
|
def test_a_firewall_profile_not_configured_is_not_read(self):
|
|
raw = _with("client", firewall=[{"name": "Public", "enabled": "NotConfigured"}])
|
|
|
|
assert _read(raw)["firewall_profiles"] == [{"name": "public", "enabled": None}]
|
|
|
|
def test_an_empty_answer_raises(self):
|
|
with pytest.raises(ValueError, match="came back empty"):
|
|
_read("")
|
|
|
|
|
|
class TestTheScript:
|
|
def test_it_never_touches_a_key(self):
|
|
"""Get-BitLockerVolume returns the key protectors, recovery passwords among them;
|
|
the CIM class's properties carry none."""
|
|
for word in ("Get-BitLockerVolume", "KeyProtector", "RecoveryPassword", "manage-bde"):
|
|
assert word not in mod._PS_POSTURE
|
|
|
|
def test_it_changes_nothing(self):
|
|
for verb in ("Set-", "Enable-", "Disable-", "Update-MpSignature", "Start-MpScan"):
|
|
assert verb not in mod._PS_POSTURE
|
|
|
|
def test_it_probes_the_cmdlets_first(self):
|
|
for cmdlet in ("Confirm-SecureBootUEFI", "Get-MpComputerStatus", "Get-NetFirewallProfile"):
|
|
assert f"Has '{cmdlet}'" in mod._PS_POSTURE
|
|
|
|
def test_it_stops_on_errors_and_catches_each_part(self):
|
|
assert "$ErrorActionPreference = 'Stop'" in mod._PS_POSTURE
|
|
assert mod._PS_POSTURE.count("catch") >= 6
|
|
|
|
|
|
def test_the_driver_reads_the_hardening():
|
|
assert callable(getattr(WindowsDriver, "get_hardening", None))
|