From 62bbc7df49a0bc4a7ebed55973a2acb25a1e5655 Mon Sep 17 00:00:00 2001 From: Christian Manivong Date: Tue, 1 Dec 2026 12:47:25 +0100 Subject: [PATCH 01/23] feat(posture): the security posture as the hardening reading (NetOrk/netork#2893) 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. --- CHANGELOG.md | 9 + README.md | 31 ++ napalm_windows/posture.py | 353 +++++++++++++++++++ napalm_windows/windows.py | 3 +- tests/fixtures/synthetic/posture_client.json | 1 + tests/fixtures/synthetic/posture_server.json | 1 + tests/test_posture.py | 330 +++++++++++++++++ tools/harvest.py | 3 +- 8 files changed, 729 insertions(+), 2 deletions(-) create mode 100644 napalm_windows/posture.py create mode 100644 tests/fixtures/synthetic/posture_client.json create mode 100644 tests/fixtures/synthetic/posture_server.json create mode 100644 tests/test_posture.py diff --git a/CHANGELOG.md b/CHANGELOG.md index 23eb7c0..42c232d 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -7,6 +7,15 @@ All notable changes to this driver. The format follows ## [Unreleased] ### Added +- The security posture as napalm-device-types' hardening reading (NetOrk/netork#2893): + `get_hardening()` reads, in one script, whether Secure Boot is on (or unsupported on a + BIOS boot), the TPM, BitLocker's protection per volume, Microsoft Defender (real-time + protection, its running mode, the signatures' age), whether each firewall profile is on, + and virtualization-based security. Each part is read on its own: a part that fails, or a + cmdlet the host does not have, is reported as not read, and a server without the + BitLocker feature as not installed. BitLocker is read through `Win32_EncryptableVolume`, + never `Get-BitLockerVolume`, so no recovery password or key protector is read. Nothing on + the host is changed. - Restarting and shutting the host down (NetOrk/netork#2841): `reboot_host()` and `shutdown_host()` from napalm-device-types' `HostRebootMixin` and `HostShutdownMixin` run `Restart-Computer` and `Stop-Computer` over the PSRP connection, neither with diff --git a/README.md b/README.md index cae0cc4..10263cc 100644 --- a/README.md +++ b/README.md @@ -42,6 +42,7 @@ handshake once. | `get_scheduled_jobs` | `Get-ScheduledTask` + `Get-ScheduledTaskInfo`, one script; `\Microsoft\*` is `platform`, other tasks `admin`, the root task an application wrote `application`; time zone mapped to IANA for the common zones | | `manage_scheduled_job` | `Enable-`/`Disable-ScheduledTask`, `Start-ScheduledTask` (returns once started; the result shows in the next reading) | | `put_scheduled_job` / `delete_scheduled_job` | `Register-ScheduledTask -Xml -Force` in the root folder, `Unregister-ScheduledTask`; an application's tasks only | +| `get_hardening` | The security posture: `Confirm-SecureBootUEFI`, `Win32_Tpm`, `Win32_EncryptableVolume` (BitLocker, never `Get-BitLockerVolume`), `Get-MpComputerStatus`, `Get-NetFirewallProfile -PolicyStore ActiveStore`, `Win32_DeviceGuard`. See *Security posture* | | `get_time_sync` / `configure_time_sync` | w32time's registry values (group policy first), `w32tm /query /status`, the registry's `TimeZoneInformation`; writes `NtpServer`/`Type` + `w32tm /config /update`, `Set-TimeZone`. See *Time sync* | `running_kernel` carries the full build including the update revision @@ -97,6 +98,36 @@ napalm-device-types' `TimeSyncMixin`; both the servers and the zone are written. zone with summer time switched off reads as `None`; writing the zone switches it back on. +### Security posture + +`get_hardening` fills the posture keys of napalm-device-types' `HardeningDict` +(NetOrk/netork#2893); what only a Linux kernel reports (security modules, crypto policy, +CPU vulnerabilities, command line) is `None`. One read-only script; each part is caught on +its own, and a part that failed, or a cmdlet the host lacks (probed with `Get-Command`), +is `None`: not read, never off. Most parts need an administrator. + +* **Secure Boot:** `Confirm-SecureBootUEFI`; on a BIOS boot it throws + `PlatformNotSupportedException`, which reads `unsupported`, not `off`. +* **TPM:** `Win32_Tpm` (`root\cimv2\Security\MicrosoftTpm`): present, enabled, activated, + owned, the specification's version and the manufacturer's ID. +* **BitLocker:** `Win32_EncryptableVolume` (`root\cimv2\Security\MicrosoftVolumeEncryption`) + for each volume with a drive letter: protection (`on`, `off` -- also while suspended -- + or `unknown`), conversion status and cipher; the OS volume is `system`. Never + `Get-BitLockerVolume`, whose objects carry the key protectors and recovery passwords: + the class's properties hold no secret. Where the class is missing the BitLocker feature + is not installed (Windows Server's default), reported as `installed: false`. +* **Defender:** `Get-MpComputerStatus`: engine and service, real-time protection, the + running mode (`Passive Mode`, `EDR Block Mode`: another product protects the host), the + signatures' date, age and version, tamper protection. Missing on Server Core without + the feature, and throwing where Defender is switched off for another product: `None`, + since no other product is judged. +* **Firewall profiles:** `Get-NetFirewallProfile -PolicyStore ActiveStore`, each profile on + or off after group policy. The rules are the host firewall reading's. +* **VBS:** `Win32_DeviceGuard` (`root\Microsoft\Windows\DeviceGuard`): off, configured or + running, and the services it runs (`credential_guard`, `hvci`, ...). + +Nothing is changed on the host: no signature update, no scan, no setting. + Not yet: packages, Windows Update, health metrics, Hyper-V. See netork#300 for the plan. diff --git a/napalm_windows/posture.py b/napalm_windows/posture.py new file mode 100644 index 0000000..a5f8821 --- /dev/null +++ b/napalm_windows/posture.py @@ -0,0 +1,353 @@ +"""A Windows host's security posture as the hardening reading (NetOrk/netork#2893). + +:class:`WindowsPostureMixin` gives the driver napalm-device-types' ``get_hardening``, +filled with the posture keys of ``HardeningDict``; what only a Linux kernel has (the +security modules, the crypto policy, the CPU vulnerabilities, the command line) is +``None``. One script, read-only, six parts, each caught on its own so one that fails +leaves the others standing; a part that failed, or a cmdlet the host lacks, is ``None``: +not read, never "off". + +- **Secure Boot:** ``Confirm-SecureBootUEFI``. On a BIOS boot it throws + ``PlatformNotSupportedException``, which is ``unsupported``, not off. +- **TPM:** ``Win32_Tpm`` in ``root\\cimv2\\Security\\MicrosoftTpm``; no instance is no TPM. +- **BitLocker:** ``Win32_EncryptableVolume`` in + ``root\\cimv2\\Security\\MicrosoftVolumeEncryption``: protection, conversion status, + cipher and volume type, per volume with a drive letter. Never ``Get-BitLockerVolume``, + whose objects carry the key protectors with their recovery passwords: the CIM class's + properties carry no secret. Where the class is missing, the BitLocker feature is not + installed (Windows Server's default): ``installed`` False, not an error. +- **Defender:** ``Get-MpComputerStatus``: the service and the engine, real-time + protection, the running mode (``Passive Mode`` and ``EDR Block Mode`` when another + product protects the host), the signatures' date, age and version, tamper protection. + Missing on Server Core without the Defender feature; it throws where Defender is + switched off for another product. Both are ``None``: no product is judged here. +- **Firewall profiles:** ``Get-NetFirewallProfile -PolicyStore ActiveStore``, the + effective state of each profile after group policy. On or off only: the rules are + the host firewall reading's. +- **VBS:** ``Win32_DeviceGuard`` in ``root\\Microsoft\\Windows\\DeviceGuard``: whether + virtualization-based security runs, and which of its services. + +The cmdlets are probed with ``Get-Command`` first, so a missing one is not read rather +than an error. Most parts need an administrator; as another user they fail on their own. +""" + +from __future__ import annotations + +import json +import logging +from typing import TYPE_CHECKING, Any + +from napalm_device_types.hardening import ( + AntimalwareDict, + AntimalwareMode, + DiskEncryptionDict, + EncryptedVolumeDict, + FirewallProfileDict, + HardeningDict, + SecureBootState, + TpmDict, + VbsDict, + VbsStatus, + VolumeProtection, +) + +from napalm_windows._powershell import _as_list + +logger = logging.getLogger(__name__) + +_PS_POSTURE = r""" +$ErrorActionPreference = 'Stop' +function Has([string]$name) { [bool](Get-Command -Name $name -ErrorAction SilentlyContinue) } +function Unix($when) { + if ($when) { [int64]([datetimeoffset]$when).ToUnixTimeSeconds() } else { $null } +} +$errors = [ordered]@{} +$secureBoot = $null +if (Has 'Confirm-SecureBootUEFI') { + try { $secureBoot = [string][bool](Confirm-SecureBootUEFI) } + catch { + if ($_.Exception -is [System.PlatformNotSupportedException] -or + [string]$_.FullyQualifiedErrorId -like '*PlatformNotSupported*') { + $secureBoot = 'unsupported' + } else { $errors.secure_boot = [string]$_.Exception.Message } + } +} +$tpm = $null +try { + $t = Get-CimInstance -Namespace 'root\cimv2\Security\MicrosoftTpm' -ClassName Win32_Tpm | + Select-Object -First 1 + if ($t) { + $tpm = [pscustomobject]@{ + present = $true + enabled = $t.IsEnabled_InitialValue + activated = $t.IsActivated_InitialValue + owned = $t.IsOwned_InitialValue + spec_version = [string]$t.SpecVersion + manufacturer = [string]$t.ManufacturerIdTxt + } + } else { $tpm = [pscustomobject]@{ present = $false } } +} catch { $errors.tpm = [string]$_.Exception.Message } +$bitlocker = $null +$bde = 'root\cimv2\Security\MicrosoftVolumeEncryption' +$probe = @{ + Namespace = $bde; ClassName = 'Win32_EncryptableVolume'; ErrorAction = 'SilentlyContinue' +} +try { + if (Get-CimClass @probe) { + $bitlocker = [pscustomobject]@{ + installed = $true + volumes = @(Get-CimInstance -Namespace $bde -ClassName Win32_EncryptableVolume | + ForEach-Object { + [pscustomobject]@{ + drive = $_.DriveLetter + volume_type = [string]$_.VolumeType + protection = [string]$_.ProtectionStatus + conversion = [string]$_.ConversionStatus + method = [string]$_.EncryptionMethod + } + }) + } + } else { $bitlocker = [pscustomobject]@{ installed = $false; volumes = @() } } +} catch { $errors.bitlocker = [string]$_.Exception.Message } +$defender = $null +if (Has 'Get-MpComputerStatus') { + try { + $mp = Get-MpComputerStatus + $defender = [pscustomobject]@{ + am_service = $mp.AMServiceEnabled + antivirus = $mp.AntivirusEnabled + real_time = $mp.RealTimeProtectionEnabled + running_mode = [string]$mp.AMRunningMode + signature_updated = Unix $mp.AntivirusSignatureLastUpdated + signature_age = $mp.AntivirusSignatureAge + signature_version = [string]$mp.AntivirusSignatureVersion + tamper_protected = $mp.IsTamperProtected + } + } catch { $errors.defender = [string]$_.Exception.Message } +} +$firewall = $null +if (Has 'Get-NetFirewallProfile') { + try { + $firewall = @(Get-NetFirewallProfile -PolicyStore ActiveStore | ForEach-Object { + [pscustomobject]@{ name = [string]$_.Name; enabled = [string]$_.Enabled } + }) + } catch { $errors.firewall = [string]$_.Exception.Message } +} +$vbs = $null +try { + $dg = Get-CimInstance -Namespace 'root\Microsoft\Windows\DeviceGuard' ` + -ClassName Win32_DeviceGuard | Select-Object -First 1 + if ($dg) { + $vbs = [pscustomobject]@{ + status = [string]$dg.VirtualizationBasedSecurityStatus + running = @($dg.SecurityServicesRunning | ForEach-Object { [string]$_ }) + } + } +} catch { $errors.vbs = [string]$_.Exception.Message } +[pscustomobject]@{ + system_drive = $env:SystemDrive + secure_boot = $secureBoot + tpm = $tpm + bitlocker = $bitlocker + defender = $defender + firewall = $firewall + vbs = $vbs + errors = $errors +} | ConvertTo-Json -Compress -Depth 5 +""" + +_SECURE_BOOT: dict[str, SecureBootState] = { + "true": "on", + "false": "off", + "unsupported": "unsupported", +} +#: Win32_EncryptableVolume.ProtectionStatus +_PROTECTION: dict[str, VolumeProtection] = {"0": "off", "1": "on", "2": "unknown"} +#: Win32_EncryptableVolume.ConversionStatus +_CONVERSION = { + "0": "fully_decrypted", + "1": "fully_encrypted", + "2": "encrypting", + "3": "decrypting", + "4": "encryption_paused", + "5": "decryption_paused", +} +#: Win32_EncryptableVolume.EncryptionMethod; 0 is none. +_CIPHER = { + "1": "aes_128_diffuser", + "2": "aes_256_diffuser", + "3": "aes_128", + "4": "aes_256", + "5": "hardware", + "6": "xts_aes_128", + "7": "xts_aes_256", +} +#: Win32_EncryptableVolume.VolumeType: the volume the OS runs from. +_OS_VOLUME = "0" +#: MSFT_MpComputerStatus.AMRunningMode +_MODES: dict[str, AntimalwareMode] = { + "normal": "active", + "passive mode": "passive", + "passive": "passive", + "edr block mode": "edr_block", + "sxs passive mode": "sxs_passive", +} +#: Win32_DeviceGuard.VirtualizationBasedSecurityStatus +_VBS_STATUS: dict[str, VbsStatus] = {"0": "off", "1": "configured", "2": "running"} +#: Win32_DeviceGuard.SecurityServicesRunning; 0 is none. +_VBS_SERVICES = { + "1": "credential_guard", + "2": "hvci", + "3": "system_guard", + "4": "smm_firmware_measurement", + "5": "kernel_shadow_stacks", + "6": "kernel_shadow_stacks_audit", + "7": "hypervisor_paging_translation", +} +_GPO_BOOLEAN = {"true": True, "false": False} + + +def _text(value: Any) -> str | None: + text = str(value).strip() if value is not None else "" + return text or None + + +def _flag(value: Any) -> bool | None: + return value if isinstance(value, bool) else None + + +def _number(value: Any) -> int | None: + return int(value) if isinstance(value, int | float) and not isinstance(value, bool) else None + + +def _secure_boot(value: Any) -> SecureBootState | None: + return _SECURE_BOOT.get(str(value).lower()) if value is not None else None + + +def _tpm_version(spec: Any) -> str | None: + """``SpecVersion`` is ``"2.0, 0, 1.59"``: the specification's version comes first.""" + return _text(str(spec or "").split(",", 1)[0]) + + +def _tpm(raw: Any) -> TpmDict | None: + if not isinstance(raw, dict): + return None + return { + "present": bool(raw.get("present")), + "enabled": _flag(raw.get("enabled")), + "activated": _flag(raw.get("activated")), + "owned": _flag(raw.get("owned")), + "version": _tpm_version(raw.get("spec_version")), + "manufacturer": _text(raw.get("manufacturer")), + } + + +def _volume(raw: dict[str, Any], system_drive: str) -> EncryptedVolumeDict | None: + drive = _text(raw.get("drive")) + if drive is None: + return None # a recovery or boot partition: nothing is stored on it + return { + "volume": drive, + "system": str(raw.get("volume_type")) == _OS_VOLUME or drive.upper() == system_drive, + "protection": _PROTECTION.get(str(raw.get("protection")), "unknown"), + "status": _CONVERSION.get(str(raw.get("conversion"))), + "method": _CIPHER.get(str(raw.get("method"))), + } + + +def _disk_encryption(raw: Any, system_drive: str) -> DiskEncryptionDict | None: + if not isinstance(raw, dict): + return None + volumes = [ + volume + for item in _as_list(raw.get("volumes")) + if isinstance(item, dict) and (volume := _volume(item, system_drive)) is not None + ] + return {"provider": "bitlocker", "installed": bool(raw.get("installed")), "volumes": volumes} + + +def _antimalware(raw: Any) -> AntimalwareDict | None: + if not isinstance(raw, dict): + return None + service, engine = _flag(raw.get("am_service")), _flag(raw.get("antivirus")) + return { + "product": "Microsoft Defender Antivirus", + "enabled": False if service is False else engine, + "real_time": _flag(raw.get("real_time")), + "mode": _MODES.get(str(raw.get("running_mode") or "").strip().lower()), + "signatures_updated": _number(raw.get("signature_updated")), + "signature_age_days": _number(raw.get("signature_age")), + "signature_version": _text(raw.get("signature_version")), + "tamper_protected": _flag(raw.get("tamper_protected")), + } + + +def _firewall_profiles(raw: Any) -> list[FirewallProfileDict] | None: + if raw is None: + return None + return [ + { + "name": str(item.get("name") or "").lower(), + "enabled": _GPO_BOOLEAN.get(str(item.get("enabled")).lower()), + } + for item in _as_list(raw) + if isinstance(item, dict) + ] + + +def _vbs(raw: Any) -> VbsDict | None: + if not isinstance(raw, dict): + return None + running = [str(code) for code in _as_list(raw.get("running")) if str(code) != "0"] + return { + "status": _VBS_STATUS.get(str(raw.get("status"))), + "running": [_VBS_SERVICES.get(code, f"service_{code}") for code in running], + } + + +def parse_posture(raw: dict[str, Any]) -> HardeningDict: + """The hardening reading from what :data:`_PS_POSTURE` emitted.""" + for part, error in (raw.get("errors") or {}).items(): + logger.info("posture: %s not read: %s", part, error) + system_drive = str(raw.get("system_drive") or "C:").upper() + reading: HardeningDict = { + "lsm": None, + "selinux": None, + "apparmor": None, + "crypto_policy": None, + "fips": None, + "cpu_vulnerabilities": None, + "cmdline": None, + "mitigations": None, + "nosmt": None, + "os_ids": None, + "virtualization": None, + "cpu_vendor": None, + "secure_boot": _secure_boot(raw.get("secure_boot")), + "tpm": _tpm(raw.get("tpm")), + "disk_encryption": _disk_encryption(raw.get("bitlocker"), system_drive), + "antimalware": _antimalware(raw.get("defender")), + "firewall_profiles": _firewall_profiles(raw.get("firewall")), + "vbs": _vbs(raw.get("vbs")), + } + return reading + + +class WindowsPostureMixin: + """``get_hardening`` for a Windows host: its security posture; the driver carries the script.""" + + if TYPE_CHECKING: # pragma: no cover - declared for type checkers only + + def _run_raw(self, script: str) -> str: ... + + def get_hardening(self) -> HardeningDict: + """Secure Boot, the TPM, BitLocker per volume, Defender, the firewall's profiles and + virtualization-based security, in one round trip; see the module. + + :raises ValueError: when the reading came back empty. + """ + out = self._run_raw(_PS_POSTURE).strip() + raw = json.loads(out) if out else None + if not isinstance(raw, dict): + raise ValueError("the posture reading came back empty") + return parse_posture(raw) diff --git a/napalm_windows/windows.py b/napalm_windows/windows.py index fbd26dd..4170037 100644 --- a/napalm_windows/windows.py +++ b/napalm_windows/windows.py @@ -27,6 +27,7 @@ from napalm_device_types import FingerprintRule, OSDriver, PortSpec from napalm_device_types.models import ListeningSocketDict, ListeningSocketsDict, ServiceDict from napalm_windows._powershell import _as_list, _ps_quote +from napalm_windows.posture import WindowsPostureMixin from napalm_windows.scheduled_tasks import WindowsScheduledJobsMixin from napalm_windows.time_sync import WindowsTimeSyncMixin from napalm_windows.transport import PowerShellError, PsrpTransport @@ -261,7 +262,7 @@ def _is_noise_route(destination: str) -> bool: # --------------------------------------------------------------------------- -class WindowsDriver(WindowsScheduledJobsMixin, WindowsTimeSyncMixin, OSDriver): +class WindowsDriver(WindowsScheduledJobsMixin, WindowsTimeSyncMixin, WindowsPostureMixin, OSDriver): """NAPALM driver for Windows Server 2016+ and Windows 10/11. ``optional_args``: diff --git a/tests/fixtures/synthetic/posture_client.json b/tests/fixtures/synthetic/posture_client.json new file mode 100644 index 0000000..135acca --- /dev/null +++ b/tests/fixtures/synthetic/posture_client.json @@ -0,0 +1 @@ +{"system_drive":"C:","secure_boot":"True","tpm":{"present":true,"enabled":true,"activated":true,"owned":true,"spec_version":"2.0, 0, 1.59","manufacturer":"INTC"},"bitlocker":{"installed":true,"volumes":[{"drive":"C:","volume_type":"0","protection":"1","conversion":"1","method":"6"},{"drive":"D:","volume_type":"1","protection":"0","conversion":"0","method":"0"}]},"defender":{"am_service":true,"antivirus":true,"real_time":true,"running_mode":"Normal","signature_updated":1764547200,"signature_age":0,"signature_version":"1.443.512.0","tamper_protected":true},"firewall":[{"name":"Domain","enabled":"True"},{"name":"Private","enabled":"True"},{"name":"Public","enabled":"True"}],"vbs":{"status":"2","running":["1","2"]},"errors":{}} diff --git a/tests/fixtures/synthetic/posture_server.json b/tests/fixtures/synthetic/posture_server.json new file mode 100644 index 0000000..e3dc1da --- /dev/null +++ b/tests/fixtures/synthetic/posture_server.json @@ -0,0 +1 @@ +{"system_drive":"C:","secure_boot":"unsupported","tpm":{"present":false},"bitlocker":{"installed":false,"volumes":[]},"defender":{"am_service":true,"antivirus":true,"real_time":false,"running_mode":"Passive Mode","signature_updated":1763942400,"signature_age":7,"signature_version":"1.443.300.0","tamper_protected":false},"firewall":[{"name":"Domain","enabled":"True"},{"name":"Private","enabled":"False"},{"name":"Public","enabled":"True"}],"vbs":{"status":"0","running":["0"]},"errors":{}} diff --git a/tests/test_posture.py b/tests/test_posture.py new file mode 100644 index 0000000..ae1cd30 --- /dev/null +++ b/tests/test_posture.py @@ -0,0 +1,330 @@ +"""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)) diff --git a/tools/harvest.py b/tools/harvest.py index 38de2f4..0101a00 100644 --- a/tools/harvest.py +++ b/tools/harvest.py @@ -14,7 +14,7 @@ import argparse import getpass import pathlib -from napalm_windows import WindowsDriver, scheduled_tasks, time_sync +from napalm_windows import WindowsDriver, posture, scheduled_tasks, time_sync from napalm_windows import windows as mod SCRIPTS = { @@ -27,6 +27,7 @@ SCRIPTS = { "listening": mod._PS_LISTENING, "scheduled_tasks": scheduled_tasks._PS_SCHEDULED_TASKS, "time_sync": time_sync._PS_TIME_SYNC, + "posture": posture._PS_POSTURE, } OUT = pathlib.Path(__file__).parent / "harvest-out" -- 2.54.1 From 8ed5e0ed87f7924cd2502c53371cdad4d29c2e00 Mon Sep 17 00:00:00 2001 From: Christian Manivong Date: Tue, 1 Dec 2026 12:47:57 +0100 Subject: [PATCH 02/23] feat(identity): the SMBIOS identity from the CIM classes (NetOrk/netork#2888) --- napalm_windows/host_basics.py | 14 +++ napalm_windows/system_identity.py | 86 +++++++++++++++++ napalm_windows/windows.py | 5 +- tests/fixtures/synthetic/system_identity.json | 1 + tests/test_system_identity.py | 93 +++++++++++++++++++ 5 files changed, 198 insertions(+), 1 deletion(-) create mode 100644 napalm_windows/host_basics.py create mode 100644 napalm_windows/system_identity.py create mode 100644 tests/fixtures/synthetic/system_identity.json create mode 100644 tests/test_system_identity.py diff --git a/napalm_windows/host_basics.py b/napalm_windows/host_basics.py new file mode 100644 index 0000000..694e6d0 --- /dev/null +++ b/napalm_windows/host_basics.py @@ -0,0 +1,14 @@ +"""What every host reports about itself, gathered for the driver (NetOrk/netork#2888-#2891). + +One mixin made of one module per reading, so the driver names a single base: + +* :mod:`napalm_windows.system_identity` -- ``get_system_identity`` +""" + +from __future__ import annotations + +from napalm_windows.system_identity import WindowsSystemIdentityMixin + + +class WindowsHostBasicsMixin(WindowsSystemIdentityMixin): + """The readings napalm-linux has as a matter of course; each module documents its own.""" diff --git a/napalm_windows/system_identity.py b/napalm_windows/system_identity.py new file mode 100644 index 0000000..f2c85a6 --- /dev/null +++ b/napalm_windows/system_identity.py @@ -0,0 +1,86 @@ +"""The SMBIOS identity of a Windows host: what ties it to its BMC (NetOrk/netork#2888). + +:class:`WindowsSystemIdentityMixin` gives the driver ``get_system_identity`` with the +shape and the placeholder rules of napalm-device-types' ``SystemIdentityMixin``, which +reads Linux' DMI files. Windows reads the same SMBIOS tables through its CIM classes, +in one script of its own -- not folded into ``get_facts``, so a class only the identity +needs cannot fail the facts: + +* ``Win32_ComputerSystemProduct``: ``UUID`` (the system UUID, which Windows decodes from + SMBIOS 2.6+ the way dmidecode does) and ``IdentifyingNumber`` (the product serial); +* ``Win32_BaseBoard``: ``SerialNumber``, of the first board; +* ``Win32_BIOS``: ``Manufacturer``, ``SMBIOSBIOSVersion`` and ``ReleaseDate``. CIM gives + the date as midnight UTC; it travels as Unix time and is read as that UTC day. + +Vendor placeholders ("To be filled by O.E.M.", all-F UUIDs) read as empty +(``clean_system_identity``). +""" + +from __future__ import annotations + +import json +from datetime import UTC, datetime +from typing import TYPE_CHECKING, Any + +from napalm_device_types import clean_system_identity +from napalm_device_types.system_identity import SystemIdentityDict + +_PS_SYSTEM_IDENTITY = r""" +$ErrorActionPreference = 'Stop' +$product = Get-CimInstance -ClassName Win32_ComputerSystemProduct +$board = @(Get-CimInstance -ClassName Win32_BaseBoard) | Select-Object -First 1 +$bios = Get-CimInstance -ClassName Win32_BIOS +[pscustomobject]@{ + uuid = [string]$product.UUID + product_serial = [string]$product.IdentifyingNumber + board_serial = if ($board) { [string]$board.SerialNumber } else { $null } + bios_vendor = [string]$bios.Manufacturer + bios_version = [string]$bios.SMBIOSBIOSVersion + bios_date = if ($bios.ReleaseDate) { + ([DateTimeOffset]$bios.ReleaseDate).ToUnixTimeSeconds() + } else { $null } +} | ConvertTo-Json -Compress +""" + + +def _text(raw: dict[str, Any], key: str) -> str: + return str(raw.get(key) or "") + + +def _utc_day(value: Any) -> str: + """Unix time as its UTC day, ``YYYY-MM-DD``; empty for none.""" + if not isinstance(value, int | float) or isinstance(value, bool): + return "" + return datetime.fromtimestamp(value, UTC).date().isoformat() + + +def parse_system_identity(raw: dict[str, Any]) -> SystemIdentityDict: + """``_PS_SYSTEM_IDENTITY``'s JSON as napalm-device-types' identity, placeholders empty.""" + return clean_system_identity( + system_uuid=_text(raw, "uuid"), + product_serial=_text(raw, "product_serial"), + board_serial=_text(raw, "board_serial"), + bios_vendor=_text(raw, "bios_vendor"), + bios_version=_text(raw, "bios_version"), + bios_date=_utc_day(raw.get("bios_date")), + ) + + +class WindowsSystemIdentityMixin: + """``get_system_identity`` from the CIM classes; the driver carries the script.""" + + if TYPE_CHECKING: # pragma: no cover - declared for type checkers only + + def _run_raw(self, script: str) -> str: ... + + def get_system_identity(self) -> SystemIdentityDict: + """The host's SMBIOS identity and system firmware, each value empty when unknown + or a vendor placeholder; see the module. + + :raises ValueError: when the reading came back empty. + """ + out = self._run_raw(_PS_SYSTEM_IDENTITY).strip() + raw = json.loads(out) if out else None + if not isinstance(raw, dict): + raise ValueError("the system identity reading came back empty") + return parse_system_identity(raw) diff --git a/napalm_windows/windows.py b/napalm_windows/windows.py index fbd26dd..fb7e465 100644 --- a/napalm_windows/windows.py +++ b/napalm_windows/windows.py @@ -27,6 +27,7 @@ from napalm_device_types import FingerprintRule, OSDriver, PortSpec from napalm_device_types.models import ListeningSocketDict, ListeningSocketsDict, ServiceDict from napalm_windows._powershell import _as_list, _ps_quote +from napalm_windows.host_basics import WindowsHostBasicsMixin from napalm_windows.scheduled_tasks import WindowsScheduledJobsMixin from napalm_windows.time_sync import WindowsTimeSyncMixin from napalm_windows.transport import PowerShellError, PsrpTransport @@ -261,7 +262,9 @@ def _is_noise_route(destination: str) -> bool: # --------------------------------------------------------------------------- -class WindowsDriver(WindowsScheduledJobsMixin, WindowsTimeSyncMixin, OSDriver): +class WindowsDriver( + WindowsHostBasicsMixin, WindowsScheduledJobsMixin, WindowsTimeSyncMixin, OSDriver +): """NAPALM driver for Windows Server 2016+ and Windows 10/11. ``optional_args``: diff --git a/tests/fixtures/synthetic/system_identity.json b/tests/fixtures/synthetic/system_identity.json new file mode 100644 index 0000000..a953853 --- /dev/null +++ b/tests/fixtures/synthetic/system_identity.json @@ -0,0 +1 @@ +{"uuid":"4C4C4544-0042-3510-8051-B4C04F4D3732","product_serial":"4B5QM72","board_serial":".4B5QM72.CNCMS0012345AB.","bios_vendor":"Dell Inc.","bios_version":"2.19.0","bios_date":1692057600} diff --git a/tests/test_system_identity.py b/tests/test_system_identity.py new file mode 100644 index 0000000..424b02f --- /dev/null +++ b/tests/test_system_identity.py @@ -0,0 +1,93 @@ +"""The SMBIOS identity on Windows: CIM classes instead of the DMI files (NetOrk/netork#2888). + +One script reads ``Win32_ComputerSystemProduct``, ``Win32_BaseBoard`` and ``Win32_BIOS``; +a fake transport answers it from tests/fixtures/synthetic/system_identity.json, a Dell +server as the classes describe it. The placeholders are napalm-device-types' own +(``clean_system_identity``). +""" + +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 system_identity as mod + +FIXTURE = Path(__file__).parent / "fixtures" / "synthetic" / "system_identity.json" + + +class FakeTransport: + def __init__(self, answer: str) -> None: + self.answer = answer + self.sent: list[str] = [] + self.is_open = True + + def run(self, script: str) -> str: + self.sent.append(script) + return self.answer + + +def _driver(**changes: Any) -> WindowsDriver: + d = WindowsDriver("win01", "admin", "secret") + d._transport = FakeTransport(json.dumps({**json.loads(FIXTURE.read_text()), **changes})) + return d + + +def test_reads_the_identity_and_the_firmware(): + assert _driver().get_system_identity() == { + "system_uuid": "4c4c4544-0042-3510-8051-b4c04f4d3732", + "product_serial": "4B5QM72", + "board_serial": ".4B5QM72.CNCMS0012345AB.", + "bios_vendor": "Dell Inc.", + "bios_version": "2.19.0", + "bios_date": "2023-08-15", + } + + +def test_one_script_reads_the_three_classes(): + d = _driver() + d.get_system_identity() + (script,) = d._transport.sent # type: ignore[union-attr] + assert script == mod._PS_SYSTEM_IDENTITY + for cls in ("Win32_ComputerSystemProduct", "Win32_BaseBoard", "Win32_BIOS"): + assert cls in script + + +@pytest.mark.parametrize( + ("field", "value"), + [ + ("product_serial", "To be filled by O.E.M."), + ("board_serial", "Default string"), + ("uuid", "FFFFFFFF-FFFF-FFFF-FFFF-FFFFFFFFFFFF"), + ("uuid", "03000200-0400-0500-0006-000700080009"), + ("bios_vendor", "To be filled by O.E.M."), + ], +) +def test_oem_placeholders_read_as_empty(field, value): + identity = _driver(**{field: value}).get_system_identity() + key = {"uuid": "system_uuid"}.get(field, field) + assert identity[key] == "" # type: ignore[literal-required] + + +@pytest.mark.parametrize("field", ["uuid", "product_serial", "board_serial", "bios_date"]) +def test_a_value_the_host_did_not_give_reads_as_empty(field): + # A VM without a base board, a firmware without a release date: null in the JSON. + identity = _driver(**{field: None}).get_system_identity() + key = {"uuid": "system_uuid"}.get(field, field) + assert identity[key] == "" # type: ignore[literal-required] + + +def test_the_release_date_is_the_utc_day(): + # CIM gives the SMBIOS date as midnight UTC; the script sends it as Unix time. + assert _driver(bios_date=1692057600 + 86399).get_system_identity()["bios_date"] == "2023-08-15" + + +def test_an_empty_answer_is_no_reading(): + d = WindowsDriver("win01", "admin", "secret") + d._transport = FakeTransport("") + with pytest.raises(ValueError): + d.get_system_identity() -- 2.54.1 From a97e59c1e2d4442748a44385626da40494212b2d Mon Sep 17 00:00:00 2001 From: Christian Manivong Date: Tue, 1 Dec 2026 12:49:17 +0100 Subject: [PATCH 03/23] feat(processes): running processes from Win32_Process and Get-Process (NetOrk/netork#2889) --- napalm_windows/_reading.py | 18 +++ napalm_windows/host_basics.py | 4 +- napalm_windows/processes.py | 159 ++++++++++++++++++++++++ napalm_windows/system_identity.py | 11 +- tests/fixtures/synthetic/processes.json | 1 + tests/test_processes.py | 125 +++++++++++++++++++ 6 files changed, 311 insertions(+), 7 deletions(-) create mode 100644 napalm_windows/_reading.py create mode 100644 napalm_windows/processes.py create mode 100644 tests/fixtures/synthetic/processes.json create mode 100644 tests/test_processes.py diff --git a/napalm_windows/_reading.py b/napalm_windows/_reading.py new file mode 100644 index 0000000..8d5daba --- /dev/null +++ b/napalm_windows/_reading.py @@ -0,0 +1,18 @@ +"""One reading script's JSON object, which the host readings of this driver share.""" + +from __future__ import annotations + +import json +from typing import Any + + +def json_object(out: str, what: str) -> dict[str, Any]: + """*out*, a script's ``ConvertTo-Json`` of one object, parsed. + + :raises ValueError: when it is empty or no object, naming *what* was read. + """ + out = out.strip() + raw = json.loads(out) if out else None + if not isinstance(raw, dict): + raise ValueError(f"the {what} reading came back empty") + return raw diff --git a/napalm_windows/host_basics.py b/napalm_windows/host_basics.py index 694e6d0..c520468 100644 --- a/napalm_windows/host_basics.py +++ b/napalm_windows/host_basics.py @@ -3,12 +3,14 @@ One mixin made of one module per reading, so the driver names a single base: * :mod:`napalm_windows.system_identity` -- ``get_system_identity`` +* :mod:`napalm_windows.processes` -- ``get_processes`` """ from __future__ import annotations +from napalm_windows.processes import WindowsProcessesMixin from napalm_windows.system_identity import WindowsSystemIdentityMixin -class WindowsHostBasicsMixin(WindowsSystemIdentityMixin): +class WindowsHostBasicsMixin(WindowsSystemIdentityMixin, WindowsProcessesMixin): """The readings napalm-linux has as a matter of course; each module documents its own.""" diff --git a/napalm_windows/processes.py b/napalm_windows/processes.py new file mode 100644 index 0000000..b607e0c --- /dev/null +++ b/napalm_windows/processes.py @@ -0,0 +1,159 @@ +"""Running processes on Windows, shaped like ``ps`` output (NetOrk/netork#2889). + +:class:`WindowsProcessesMixin` gives the driver napalm-device-types' ``get_processes`` +(``ProcessDict``). One script reads two sources and the join happens here: + +* ``Win32_Process``: PID, parent, command line, start (``CreationDate``), the CPU time + (``KernelModeTime`` + ``UserModeTime``, in 100 ns), ``WorkingSetSize`` and + ``VirtualSize``. Read first: it is the list. +* ``Get-Process -IncludeUserName``: the owner, one call for all processes instead of a + ``GetOwner()`` per process. It needs an elevated session, which netOrk's WinRM + administrator has; without one the script falls back to ``Get-Process`` and the owner + is unknown (empty). + +A process is reported only when both saw it with the same start: one that exited between +the two reads is dropped rather than half-filled, and a PID reused in between is another +process. PID 0, the System Idle Process, is no process and is left out, as ``ps`` leaves +it out. + +The values follow ``ps``: ``cpu`` is the CPU time over the time since the start, per +logical processor, so 0-100; ``memory`` the working set over the visible memory; +``vsz`` and ``rss`` in KiB; ``started`` as ``lstart`` prints it, in the host's local +time. Windows has no controlling terminal and no process state of that kind: ``tty`` +and ``state`` are empty. A process without a readable command line (``System``, +protected processes) shows its image name. Command lines are reported as the host +gives them, as ``ps`` does on Linux. +""" + +from __future__ import annotations + +from datetime import UTC, datetime, timedelta +from typing import TYPE_CHECKING, Any + +from napalm_device_types.models import ProcessDict + +from napalm_windows._powershell import _as_list +from napalm_windows._reading import json_object + +_PS_PROCESSES = r""" +$ErrorActionPreference = 'Stop' +function Unix($t) { if ($t) { ([DateTimeOffset]$t).ToUnixTimeSeconds() } else { $null } } +function Offset($t) { if ($t) { [int]([DateTimeOffset]$t).Offset.TotalMinutes } else { 0 } } +$os = Get-CimInstance -ClassName Win32_OperatingSystem +$cs = Get-CimInstance -ClassName Win32_ComputerSystem +$processes = @(Get-CimInstance -ClassName Win32_Process | ForEach-Object { + [pscustomobject]@{ + pid = [int]$_.ProcessId + ppid = [int]$_.ParentProcessId + name = [string]$_.Name + command = [string]$_.CommandLine + started = Unix $_.CreationDate + offset = Offset $_.CreationDate + cpu = [int64]$_.KernelModeTime + [int64]$_.UserModeTime + ws = [int64]$_.WorkingSetSize + vsz = [int64]$_.VirtualSize + } +}) +try { $running = @(Get-Process -IncludeUserName) } catch { $running = @(Get-Process) } +$owners = @($running | ForEach-Object { + $start = $null + try { $start = Unix $_.StartTime } catch { } + [pscustomobject]@{ pid = [int]$_.Id; user = [string]$_.UserName; started = $start } +}) +ConvertTo-Json -Compress -Depth 3 -InputObject ([pscustomobject]@{ + now = [DateTimeOffset]::UtcNow.ToUnixTimeSeconds() + cores = [int]$cs.NumberOfLogicalProcessors + memory_kib = [int64]$os.TotalVisibleMemorySize + processes = $processes + owners = $owners +}) +""" + +#: How far the two sources' starts of one process may differ: they round differently. +_SAME_START = 2 +_DAYS = ("Mon", "Tue", "Wed", "Thu", "Fri", "Sat", "Sun") +_MONTHS = ("Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec") + + +def _lstart(started: int | None, offset_minutes: int) -> str: + """Unix time in the host's local time, as ``ps -o lstart`` prints it in the C locale.""" + if started is None: + return "" + t = datetime.fromtimestamp(started, UTC) + timedelta(minutes=offset_minutes) + return f"{_DAYS[t.weekday()]} {_MONTHS[t.month - 1]} {t.day:2d} {t:%H:%M:%S} {t.year}" + + +class _Host: + """What the reading says about the host as a whole.""" + + def __init__(self, raw: dict[str, Any]) -> None: + self.now = int(raw.get("now") or 0) + self.cores = max(int(raw.get("cores") or 1), 1) + self.memory_kib = int(raw.get("memory_kib") or 0) + + def cpu(self, cpu_100ns: int, started: int | None) -> float: + if started is None: + return 0.0 + elapsed = max(self.now - started, 1) + return round(min(cpu_100ns / 10_000_000 / elapsed / self.cores * 100, 100.0), 1) + + def memory(self, rss_kib: int) -> float: + return round(rss_kib * 100 / self.memory_kib, 1) if self.memory_kib else 0.0 + + +def _started(entry: dict[str, Any]) -> int | None: + value = entry.get("started") + return int(value) if value is not None else None + + +def _same_process(entry: dict[str, Any], owner: dict[str, Any]) -> bool: + """False when ``Get-Process`` saw another start under this PID: it was reused.""" + ours, theirs = _started(entry), _started(owner) + return ours is None or theirs is None or abs(ours - theirs) <= _SAME_START + + +def _process(entry: dict[str, Any], owner: dict[str, Any], host: _Host) -> ProcessDict: + started = _started(entry) + rss = int(entry.get("ws") or 0) // 1024 + return { + "pid": int(entry["pid"]), + "ppid": int(entry.get("ppid") or 0), + "user": str(owner.get("user") or ""), + "cpu": host.cpu(int(entry.get("cpu") or 0), started), + "memory": host.memory(rss), + "vsz": int(entry.get("vsz") or 0) // 1024, + "rss": rss, + "tty": "", + "state": "", + "started": _lstart(started, int(entry.get("offset") or 0)), + "command": str(entry.get("command") or entry.get("name") or ""), + } + + +def parse_processes(raw: dict[str, Any]) -> list[ProcessDict]: + """``_PS_PROCESSES``'s JSON as ``ProcessDict``s by PID; see the module for the join.""" + host = _Host(raw) + owners = {int(o["pid"]): o for o in _as_list(raw.get("owners"))} + processes = [] + for entry in _as_list(raw.get("processes")): + owner = owners.get(int(entry["pid"])) + if not entry["pid"] or owner is None or not _same_process(entry, owner): + continue + processes.append(_process(entry, owner, host)) + return sorted(processes, key=lambda p: p["pid"]) + + +class WindowsProcessesMixin: + """``get_processes`` from ``Win32_Process`` and ``Get-Process``; the driver carries + the script.""" + + if TYPE_CHECKING: # pragma: no cover - declared for type checkers only + + def _run_raw(self, script: str) -> str: ... + + def get_processes(self) -> list[ProcessDict]: + """A snapshot of the running processes, shaped like ``ps``; see the module. + + :raises ValueError: when the reading came back empty. + """ + return parse_processes(json_object(self._run_raw(_PS_PROCESSES), "process")) diff --git a/napalm_windows/system_identity.py b/napalm_windows/system_identity.py index f2c85a6..aeb6827 100644 --- a/napalm_windows/system_identity.py +++ b/napalm_windows/system_identity.py @@ -18,13 +18,14 @@ Vendor placeholders ("To be filled by O.E.M.", all-F UUIDs) read as empty from __future__ import annotations -import json from datetime import UTC, datetime from typing import TYPE_CHECKING, Any from napalm_device_types import clean_system_identity from napalm_device_types.system_identity import SystemIdentityDict +from napalm_windows._reading import json_object + _PS_SYSTEM_IDENTITY = r""" $ErrorActionPreference = 'Stop' $product = Get-CimInstance -ClassName Win32_ComputerSystemProduct @@ -79,8 +80,6 @@ class WindowsSystemIdentityMixin: :raises ValueError: when the reading came back empty. """ - out = self._run_raw(_PS_SYSTEM_IDENTITY).strip() - raw = json.loads(out) if out else None - if not isinstance(raw, dict): - raise ValueError("the system identity reading came back empty") - return parse_system_identity(raw) + return parse_system_identity( + json_object(self._run_raw(_PS_SYSTEM_IDENTITY), "system identity") + ) diff --git a/tests/fixtures/synthetic/processes.json b/tests/fixtures/synthetic/processes.json new file mode 100644 index 0000000..f7eeb34 --- /dev/null +++ b/tests/fixtures/synthetic/processes.json @@ -0,0 +1 @@ +{"now":1764590400,"cores":4,"memory_kib":8388608,"processes":[{"pid":0,"ppid":0,"name":"System Idle Process","command":"","started":null,"offset":0,"cpu":4000000000000,"ws":8192,"vsz":8192},{"pid":4,"ppid":0,"name":"System","command":"","started":null,"offset":0,"cpu":12000000000,"ws":143360,"vsz":3997696},{"pid":812,"ppid":640,"name":"svchost.exe","command":"C:\\Windows\\system32\\svchost.exe -k DcomLaunch -p","started":1764504000,"offset":60,"cpu":3456000000,"ws":31457280,"vsz":2203318222848},{"pid":4312,"ppid":3988,"name":"powershell.exe","command":"\"C:\\Windows\\System32\\WindowsPowerShell\\v1.0\\powershell.exe\" -NoLogo","started":1764589800,"offset":60,"cpu":1200000000,"ws":104857600,"vsz":2203500000000},{"pid":5120,"ppid":812,"name":"WmiPrvSE.exe","command":"C:\\Windows\\system32\\wbem\\wmiprvse.exe","started":1764590395,"offset":60,"cpu":1000000,"ws":10485760,"vsz":2203400000000},{"pid":6000,"ppid":812,"name":"conhost.exe","command":"\\??\\C:\\Windows\\system32\\conhost.exe 0x4","started":1764590370,"offset":60,"cpu":0,"ws":4194304,"vsz":2203300000000}],"owners":[{"pid":0,"user":null,"started":null},{"pid":4,"user":"NT AUTHORITY\\SYSTEM","started":null},{"pid":812,"user":"NT AUTHORITY\\SYSTEM","started":1764504000},{"pid":4312,"user":"WIN01\\admin","started":1764589800},{"pid":6000,"user":"WIN01\\admin","started":1764590398},{"pid":7777,"user":"WIN01\\admin","started":1764590399}]} diff --git a/tests/test_processes.py b/tests/test_processes.py new file mode 100644 index 0000000..60a3881 --- /dev/null +++ b/tests/test_processes.py @@ -0,0 +1,125 @@ +"""Processes on Windows: ``Win32_Process`` joined with ``Get-Process`` (NetOrk/netork#2889). + +One script reads both; a fake transport answers it from +tests/fixtures/synthetic/processes.json. ``Win32_Process`` gives the parent, the command +line, the start and the CPU and memory counters, ``Get-Process -IncludeUserName`` the +owner. The fixture holds the cases the join decides: + +* 0, the System Idle Process: no process, left out as ``ps`` leaves it out; +* 5120, gone by the time ``Get-Process`` ran: dropped, not half-filled; +* 6000, a PID ``Get-Process`` reports with another start: a new process under a PID + that was reused between the two reads, dropped; +* 7777, started after ``Win32_Process`` was read: not part of the reading. +""" + +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 processes as mod + +FIXTURE = Path(__file__).parent / "fixtures" / "synthetic" / "processes.json" + + +class FakeTransport: + def __init__(self, answer: str) -> None: + self.answer = answer + self.sent: list[str] = [] + self.is_open = True + + def run(self, script: str) -> str: + self.sent.append(script) + return self.answer + + +def _reading() -> dict[str, Any]: + return json.loads(FIXTURE.read_text()) + + +def _driver(reading: dict[str, Any] | None = None) -> WindowsDriver: + d = WindowsDriver("win01", "admin", "secret") + d._transport = FakeTransport(json.dumps(reading if reading is not None else _reading())) + return d + + +def _by_pid(reading: dict[str, Any] | None = None) -> dict[int, Any]: + return {p["pid"]: p for p in _driver(reading).get_processes()} + + +def test_the_join_keeps_the_processes_both_reads_saw(): + assert sorted(_by_pid()) == [4, 812, 4312] + + +def test_a_process_reads_like_ps(): + assert _by_pid()[4312] == { + "pid": 4312, + "ppid": 3988, + "user": "WIN01\\admin", + # 120 CPU seconds in 600 s on 4 logical processors + "cpu": 5.0, + # 100 MiB of 8 GiB + "memory": 1.2, + "vsz": 2203500000000 // 1024, + "rss": 102400, + "tty": "", + "state": "", + # 11:50 UTC, an hour east of it + "started": "Mon Dec 1 12:50:00 2025", + "command": '"C:\\Windows\\System32\\WindowsPowerShell\\v1.0\\powershell.exe" -NoLogo', + } + + +def test_a_process_without_a_command_line_shows_its_name(): + system = _by_pid()[4] + assert system["command"] == "System" + assert system["started"] == "" + assert system["cpu"] == 0.0 + + +def test_a_start_one_second_apart_is_the_same_process(): + # Get-Process and CIM round the start differently. + reading = _reading() + reading["owners"][2]["started"] += 1 + assert 812 in _by_pid(reading) + + +def test_without_elevation_the_owner_is_unknown(): + # Get-Process -IncludeUserName needs an elevated session; the script falls back. + reading = _reading() + for owner in reading["owners"]: + owner.pop("user") + assert {p["user"] for p in _by_pid(reading).values()} == {""} + + +def test_cpu_stays_within_a_hundred_percent(): + reading = _reading() + reading["processes"][3]["cpu"] = 10**13 + assert _by_pid(reading)[4312]["cpu"] == 100.0 + + +def test_a_single_process_survives_powershells_unwrapping(): + reading = _reading() + reading["processes"] = reading["processes"][2] + reading["owners"] = reading["owners"][2] + assert sorted(_by_pid(reading)) == [812] + + +def test_one_script_reads_both_sources(): + d = _driver() + d.get_processes() + (script,) = d._transport.sent # type: ignore[union-attr] + assert script == mod._PS_PROCESSES + assert "Win32_Process" in script + assert "Get-Process -IncludeUserName" in script + + +def test_an_empty_answer_is_no_reading(): + d = WindowsDriver("win01", "admin", "secret") + d._transport = FakeTransport("") + with pytest.raises(ValueError): + d.get_processes() -- 2.54.1 From 0bbeebb7a78324da1ebfdc990a62be954c8c60ba Mon Sep 17 00:00:00 2001 From: Christian Manivong Date: Tue, 1 Dec 2026 12:49:37 +0100 Subject: [PATCH 04/23] feat(repairs): SFC, DISM and Defender runs through HostRepairMixin (NetOrk/netork#2899) verify_system_files (sfc /verifyonly), check_component_store (DISM /ScanHealth /English), update_antimalware_signatures (Update-MpSignature) and scan_antimalware (Start-MpScan, quick or full), each one bounded PSRP call streamed line by line through PsrpTransport.run_streaming. Native tools run as a process read in their own encoding (sfc: UTF-16), and NULs of UTF-16 read byte by byte are dropped. The exit code decides; a missing tool or Defender says it is not available. sfc /scannow and DISM /RestoreHealth stay undefined until a real host was tested. tools/harvest.py --runs records the runs' output. --- CHANGELOG.md | 9 + README.md | 31 ++ napalm_windows/repairs.py | 258 +++++++++++++++ napalm_windows/transport.py | 50 +++ napalm_windows/windows.py | 3 +- tests/fixtures/synthetic/README.md | 4 + .../synthetic/defender_quick_scan.txt | 5 + .../synthetic/defender_signature_update.txt | 3 + tests/fixtures/synthetic/dism_scanhealth.txt | 10 + .../synthetic/dism_scanhealth_failed.txt | 14 + tests/fixtures/synthetic/sfc_verifyonly.txt | 10 + tests/test_repairs.py | 305 ++++++++++++++++++ tests/test_transport.py | 108 +++++++ tools/harvest.py | 34 +- 14 files changed, 841 insertions(+), 3 deletions(-) create mode 100644 napalm_windows/repairs.py create mode 100644 tests/fixtures/synthetic/defender_quick_scan.txt create mode 100644 tests/fixtures/synthetic/defender_signature_update.txt create mode 100644 tests/fixtures/synthetic/dism_scanhealth.txt create mode 100644 tests/fixtures/synthetic/dism_scanhealth_failed.txt create mode 100644 tests/fixtures/synthetic/sfc_verifyonly.txt create mode 100644 tests/test_repairs.py diff --git a/CHANGELOG.md b/CHANGELOG.md index 23eb7c0..c680b34 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -7,6 +7,15 @@ All notable changes to this driver. The format follows ## [Unreleased] ### Added +- Repair runs (NetOrk/netork#2899), napalm-device-types' `HostRepairMixin`: checking the + system files (`sfc /verifyonly`) and the component store (`DISM /ScanHealth`), updating + Microsoft Defender's signatures and running a quick or full Defender scan. Each streams + the tool's output line by line as the host prints it and ends with the tool's exit + code; a failure names the tool's last lines. A host without Defender says so instead of + failing with an error. Repairing the system files or the component store is not offered + yet: both wait for a test on a real host. `PsrpTransport.run_streaming(script, + on_output, limit=...)` runs a long script, passing each output line on as it arrives and + stopping it past its limit. - Restarting and shutting the host down (NetOrk/netork#2841): `reboot_host()` and `shutdown_host()` from napalm-device-types' `HostRebootMixin` and `HostShutdownMixin` run `Restart-Computer` and `Stop-Computer` over the PSRP connection, neither with diff --git a/README.md b/README.md index cae0cc4..c423927 100644 --- a/README.md +++ b/README.md @@ -43,6 +43,7 @@ handshake once. | `manage_scheduled_job` | `Enable-`/`Disable-ScheduledTask`, `Start-ScheduledTask` (returns once started; the result shows in the next reading) | | `put_scheduled_job` / `delete_scheduled_job` | `Register-ScheduledTask -Xml -Force` in the root folder, `Unregister-ScheduledTask`; an application's tasks only | | `get_time_sync` / `configure_time_sync` | w32time's registry values (group policy first), `w32tm /query /status`, the registry's `TimeZoneInformation`; writes `NtpServer`/`Type` + `w32tm /config /update`, `Set-TimeZone`. See *Time sync* | +| `verify_system_files`, `check_component_store`, `update_antimalware_signatures`, `scan_antimalware` | `sfc /verifyonly`, `DISM /Online /Cleanup-Image /ScanHealth /English`, `Update-MpSignature`, `Start-MpScan`; streamed runs, see *Repair runs* | `running_kernel` carries the full build including the update revision (`10.0.20348.2340`): Windows ships fixes as UBR bumps, which is what CVE @@ -100,6 +101,36 @@ napalm-device-types' `TimeSyncMixin`; both the servers and the zone are written. Not yet: packages, Windows Update, health metrics, Hyper-V. See netork#300 for the plan. +### Repair runs + +napalm-device-types' `HostRepairMixin` (NetOrk/netork#2899): a fixed catalog of runs, one +method each, so an application can start these and nothing else. + +| Run | Tool | Limit | +|---|---|---| +| `verify_system_files` | `sfc /verifyonly` (changes nothing) | 1 h | +| `check_component_store` | `DISM /Online /Cleanup-Image /ScanHealth /English` (changes nothing) | 1 h | +| `update_antimalware_signatures` | `Update-MpSignature`, with the signature version before and after | 15 min | +| `scan_antimalware(quick=True)` | `Start-MpScan -ScanType QuickScan` (`FullScan` with `quick=False`), with what it detected | 1 h (4 h) | + +* **Not offered yet:** `repair_system_files` (`sfc /scannow`), which may fail to start the + repair service (TrustedInstaller) in a remote session, and `repair_component_store` + (`DISM /RestoreHealth`), which needs a repair source WSUS-managed hosts often lack + (`0x800f081f`). Both wait for a test on a real host. +* **Transport:** one bounded PSRP call per run (`PsrpTransport.run_streaming`): each line + reaches the caller's `log` as the host prints it, and a run past its limit is stopped. + The tools run as the connection's administrator; the SYSTEM scheduled task is where a + tool would move should a real host show it needs SYSTEM. +* **Output:** `sfc` writes UTF-16 to a redirected stdout and is read as such; DISM runs + with `/English` in the OEM code page. Text that still arrives as UTF-16 read byte by byte + loses its NULs. The exit code decides: 0 succeeds, any other fails with the tool's last + lines (an HRESULT in hex). A check that finds damage can still end with 0: the verdict is + in its output, `sfc`'s in the host's language. +* **Defender** runs only where `Get-Command` finds its cmdlets; elsewhere (another + antivirus, a Server without the feature) the run fails with "not available on this + host". A scan's detections are handled as Defender is set to handle them. +* None of them restarts the host or creates a restore point. + ## Preparing a host WinRM is on by default on Windows Server; on Windows 10/11 run diff --git a/napalm_windows/repairs.py b/napalm_windows/repairs.py new file mode 100644 index 0000000..f521975 --- /dev/null +++ b/napalm_windows/repairs.py @@ -0,0 +1,258 @@ +"""Repair runs on Windows: SFC, DISM and Microsoft Defender (NetOrk/netork#2899). + +:class:`WindowsRepairsMixin` implements the runs of napalm-device-types' +:class:`~napalm_device_types.host_repairs.HostRepairMixin` this driver can do: + +================================== =============================================== +``verify_system_files`` ``sfc /verifyonly`` +``check_component_store`` ``DISM /Online /Cleanup-Image /ScanHealth`` +``update_antimalware_signatures`` ``Update-MpSignature`` +``scan_antimalware`` ``Start-MpScan -ScanType QuickScan|FullScan`` +================================== =============================================== + +The two repairs, ``sfc /scannow`` and ``DISM /RestoreHealth``, are not defined, so the +driver does not offer them: in a remote session ``sfc /scannow`` may fail to start the +repair service (TrustedInstaller), and ``RestoreHealth`` needs a repair source that +WSUS-managed hosts often lack. Both wait for a test on a real host. + +**One bounded PSRP call per run.** Each run is one script streamed over the open +connection (``PsrpTransport.run_streaming``): its lines reach ``log`` as the host +prints them, and a run still going after its limit is stopped. The tools run as the +connection's administrator, not through a SYSTEM scheduled task; should a real host +show that a tool needs SYSTEM, the task building block of +:mod:`napalm_windows.scheduled_tasks` is where it would move. + +**Native tools** start as a process whose output is read line by line in the encoding +the tool writes: ``sfc`` writes UTF-16 to a redirected stdout, read as such; DISM +writes the OEM code page and runs with ``/English``, so its words are the same on +every host. Should text still arrive as UTF-16 read byte by byte, :func:`tool_lines` +drops the NULs between the characters. A tool missing from the host says +``napalm-not-available:``; every script ends with ``napalm-exit-code:``. +Neither line reaches ``log``. The exit code decides (``tool_outcome``): 0 succeeds, any +other fails with the tool's last lines. A check that finds damage may still end with 0; +the verdict is in its output. + +**Defender** runs only where ``Get-Command`` finds its cmdlets, so a host with another +antivirus (or Server without the feature) fails with "not available", not an error. +The signature update names the version before and after; a scan names what it +detected since it started, handled as Defender is set to handle it. + +Nothing here restarts the host or creates a restore point. +""" + +from __future__ import annotations + +import re +from typing import TYPE_CHECKING + +from napalm.base.exceptions import ConnectionClosedException +from napalm_device_types import HostRepairMixin, HostRepairResultDict, tool_outcome +from napalm_device_types.host_repairs import LineLog + +from napalm_windows.transport import PowerShellError + +if TYPE_CHECKING: # pragma: no cover - for type checkers only + from napalm_windows.transport import PsrpTransport + +#: The longest each run may take, in seconds. +SFC_LIMIT = 3600 +DISM_LIMIT = 3600 +SIGNATURE_LIMIT = 900 +QUICK_SCAN_LIMIT = 3600 +FULL_SCAN_LIMIT = 4 * 3600 + +_EXIT = "napalm-exit-code:" +_MISSING = "napalm-not-available:" +_LINE_BREAKS = re.compile(r"\r\n|\r|\n") + +# A native tool as a process, its stdout read line by line in the tool's encoding and +# written to the pipeline as it comes, its stderr after it. No console is involved, so +# nothing depends on the remote session's console code page. +_PS_NATIVE = r""" +$ErrorActionPreference = 'Stop' +function Invoke-NativeTool([string]$Path, [string]$Arguments, [System.Text.Encoding]$Encoding) { + if (-not (Test-Path -LiteralPath $Path -PathType Leaf)) { + 'napalm-not-available:' + (Split-Path -Leaf $Path) + return + } + $info = New-Object System.Diagnostics.ProcessStartInfo + $info.FileName = $Path + $info.Arguments = $Arguments + $info.UseShellExecute = $false + $info.CreateNoWindow = $true + $info.RedirectStandardOutput = $true + $info.RedirectStandardError = $true + $info.StandardOutputEncoding = $Encoding + $info.StandardErrorEncoding = $Encoding + $process = [System.Diagnostics.Process]::Start($info) + $errors = $process.StandardError.ReadToEndAsync() + while ($null -ne ($line = $process.StandardOutput.ReadLine())) { $line } + $process.WaitForExit() + $errors.Result -split "`r?`n" | Where-Object { $_ } + 'napalm-exit-code:' + $process.ExitCode +} +""" + +_PS_SFC_VERIFY = ( + _PS_NATIVE + + r""" +$sfc = Join-Path $env:SystemRoot 'System32\sfc.exe' +Invoke-NativeTool $sfc '/verifyonly' ([System.Text.Encoding]::Unicode) +""" +) + +_PS_DISM_SCAN = ( + _PS_NATIVE + + r""" +$page = [System.Globalization.CultureInfo]::CurrentCulture.TextInfo.OEMCodePage +$dism = Join-Path $env:SystemRoot 'System32\Dism.exe' +$arguments = '/Online /Cleanup-Image /ScanHealth /English' +Invoke-NativeTool $dism $arguments ([System.Text.Encoding]::GetEncoding($page)) +""" +) + +_PS_SIGNATURE_UPDATE = r""" +$ErrorActionPreference = 'Stop' +if (-not (Get-Command -Name Update-MpSignature -ErrorAction SilentlyContinue)) { + 'napalm-not-available:Microsoft Defender Antivirus' + return +} +function Get-SignatureLine([string]$When) { + try { + $status = Get-MpComputerStatus + $at = ([datetime]$status.AntivirusSignatureLastUpdated).ToUniversalTime() + $at = $at.ToString('yyyy-MM-dd HH:mm') + $When + ': ' + [string]$status.AntivirusSignatureVersion + ', updated ' + $at + ' UTC' + } catch { + $When + ': not readable (' + $_.Exception.Message + ')' + } +} +Get-SignatureLine 'Signatures before' +$code = 0 +try { Update-MpSignature } catch { 'Update-MpSignature failed: ' + $_.Exception.Message; $code = 1 } +Get-SignatureLine 'Signatures after' +'napalm-exit-code:' + $code +""" + +# Start-MpScan returns when the scan ended. What it detected since it started is read +# from Defender's detections, by threat name and whether Defender's action went through. +_PS_SCAN = r""" +$ErrorActionPreference = 'Stop' +if (-not (Get-Command -Name Start-MpScan -ErrorAction SilentlyContinue)) { + 'napalm-not-available:Microsoft Defender Antivirus' + return +} +$start = Get-Date +'Scan started: {scan_type}' +$code = 0 +try { + Start-MpScan -ScanType {scan_type} +} catch { + 'Start-MpScan failed: ' + $_.Exception.Message + $code = 1 +} +'Scan ended.' +$found = @() +try { + $found = @(Get-MpThreatDetection | Where-Object { $_.InitialDetectionTime -ge $start }) +} catch { } +'Threats detected: ' + $found.Count +foreach ($detection in $found) { + $name = [string]$detection.ThreatID + try { $name = [string](Get-MpThreat -ThreatID $detection.ThreatID).ThreatName } catch { } + $action = if ($detection.ActionSuccess) { 'succeeded' } else { 'not completed' } + ' ' + $name + ': action ' + $action +} +'napalm-exit-code:' + $code +""" +_PS_QUICK_SCAN = _PS_SCAN.replace("{scan_type}", "QuickScan") +_PS_FULL_SCAN = _PS_SCAN.replace("{scan_type}", "FullScan") + + +def tool_lines(item: str) -> list[str]: + """One output object of a run as lines: without NULs (UTF-16 read byte by byte) or a + byte order mark, split at every line break -- progress ends its lines with a bare + carriage return -- trailing spaces and blank lines dropped.""" + text = item.replace("\x00", "").replace("", "") + return [line.rstrip() for line in _LINE_BREAKS.split(text) if line.strip()] + + +def _exit_code(text: str) -> int | None: + try: + return int(text.strip()) + except ValueError: + return None + + +class _ToolRun: + """What a run's script printed, its exit code and a missing tool, as it arrives.""" + + def __init__(self, log: LineLog | None) -> None: + self.log = log + self.lines: list[str] = [] + self.exit_code: int | None = None + self.missing: str | None = None + + def take(self, item: str) -> None: + for line in tool_lines(item): + if line.startswith(_EXIT): + self.exit_code = _exit_code(line.removeprefix(_EXIT)) + elif line.startswith(_MISSING): + self.missing = line.removeprefix(_MISSING).strip() + else: + self.lines.append(line) + if self.log is not None: + self.log(line) + + def outcome(self, tool: str) -> HostRepairResultDict: + if self.missing is not None: + return { + "success": False, + "output": "\n".join(self.lines), + "exit_code": None, + "error": f"{self.missing} is not available on this host", + } + return tool_outcome(self.lines, self.exit_code, tool=tool) + + def cut_off(self, tool: str, why: str) -> HostRepairResultDict: + return tool_outcome([*self.lines, why], None, tool=tool) + + +class WindowsRepairsMixin(HostRepairMixin): + """SFC, DISM and Defender runs for :class:`~napalm_windows.windows.WindowsDriver`.""" + + if TYPE_CHECKING: # pragma: no cover - declared for type checkers only + _transport: PsrpTransport | None + + def verify_system_files(self, *, log: LineLog | None = None) -> HostRepairResultDict: + """``sfc /verifyonly``: checks the protected system files and changes nothing.""" + return self._tool_run(_PS_SFC_VERIFY, "sfc /verifyonly", SFC_LIMIT, log) + + def check_component_store(self, *, log: LineLog | None = None) -> HostRepairResultDict: + """``DISM /Online /Cleanup-Image /ScanHealth``: scans the component store and + changes nothing; up to half an hour.""" + return self._tool_run(_PS_DISM_SCAN, "DISM /ScanHealth", DISM_LIMIT, log) + + def update_antimalware_signatures(self, *, log: LineLog | None = None) -> HostRepairResultDict: + """``Update-MpSignature``, with the signature version before and after.""" + return self._tool_run(_PS_SIGNATURE_UPDATE, "Update-MpSignature", SIGNATURE_LIMIT, log) + + def scan_antimalware( + self, quick: bool = True, *, log: LineLog | None = None + ) -> HostRepairResultDict: + """``Start-MpScan``, quick or full, with what it detected.""" + if quick: + return self._tool_run(_PS_QUICK_SCAN, "Start-MpScan", QUICK_SCAN_LIMIT, log) + return self._tool_run(_PS_FULL_SCAN, "Start-MpScan", FULL_SCAN_LIMIT, log) + + def _tool_run( + self, script: str, tool: str, limit: float, log: LineLog | None + ) -> HostRepairResultDict: + if self._transport is None: + raise ConnectionClosedException("WinRM connection is not open") + run = _ToolRun(log) + try: + self._transport.run_streaming(script, run.take, limit=limit) + except (TimeoutError, PowerShellError) as exc: + return run.cut_off(tool, str(exc)) + return run.outcome(tool) diff --git a/napalm_windows/transport.py b/napalm_windows/transport.py index 679f0aa..9a4b9af 100644 --- a/napalm_windows/transport.py +++ b/napalm_windows/transport.py @@ -10,15 +10,22 @@ transport (Windows OpenSSH) would implement later. from __future__ import annotations import logging +import time +from collections.abc import Callable import requests from napalm.base.exceptions import ConnectionClosedException, ConnectionException +from pypsrp.complex_objects import PSInvocationState from pypsrp.exceptions import AuthenticationError, WinRMError, WinRMTransportError from pypsrp.powershell import PowerShell, RunspacePool from pypsrp.wsman import WSMan logger = logging.getLogger(__name__) +#: The longest one poll of a streaming script waits for output, so its limit is +#: checked at least this often. +_POLL_SECONDS = 20 + class PowerShellError(Exception): """A script ran but wrote to PowerShell's error stream.""" @@ -104,6 +111,49 @@ class PsrpTransport: raise PowerShellError(message or "PowerShell reported an error") return "\n".join(str(o) for o in output if o is not None) + def run_streaming( + self, script: str, on_output: Callable[[str], None], *, limit: float + ) -> list[str]: + """Run a long script, handing each output object to *on_output* as it arrives. + + For a run that takes minutes: the pipeline is started and polled, each poll + waiting at most ``_POLL_SECONDS`` (and less than a read of the connection), so + output reaches the caller while the host still works. A script still running + after *limit* seconds is stopped (Ctrl+C to the pipeline) and raises + :class:`TimeoutError`. An error the script wrote raises :class:`PowerShellError` + once it ended, after its output was passed on. + + :returns: Every output object, as text, in order. + """ + if self._pool is None: + raise ConnectionClosedException("WinRM connection is not open") + ps = PowerShell(self._pool) + ps.add_script(script) + poll = min(_POLL_SECONDS, max(self.timeout // 2, 1)) + deadline = time.monotonic() + limit + taken, out = 0, [] + ps.begin_invoke() + while ps.state == PSInvocationState.RUNNING: + if time.monotonic() > deadline: + self._stop(ps) + raise TimeoutError(f"The script did not end within {int(limit)} seconds") + ps.poll_invoke(timeout=poll) + arrived, taken = ps.output[taken:], len(ps.output) + for item in arrived: + if item is not None: + out.append(str(item)) + on_output(out[-1]) + if ps.had_errors: + message = "; ".join(str(e) for e in ps.streams.error).strip() + raise PowerShellError(message or "PowerShell reported an error") + return out + + def _stop(self, ps: PowerShell) -> None: + try: + ps.stop() + except Exception: # a pipeline that ended meanwhile has nothing to stop + logger.debug("Stopping a pipeline on %s failed", self.host, exc_info=True) + def run_last(self, script: str) -> bool: """Run a script after which the host may stop answering: a restart, a shutdown. diff --git a/napalm_windows/windows.py b/napalm_windows/windows.py index fbd26dd..032228f 100644 --- a/napalm_windows/windows.py +++ b/napalm_windows/windows.py @@ -27,6 +27,7 @@ from napalm_device_types import FingerprintRule, OSDriver, PortSpec from napalm_device_types.models import ListeningSocketDict, ListeningSocketsDict, ServiceDict from napalm_windows._powershell import _as_list, _ps_quote +from napalm_windows.repairs import WindowsRepairsMixin from napalm_windows.scheduled_tasks import WindowsScheduledJobsMixin from napalm_windows.time_sync import WindowsTimeSyncMixin from napalm_windows.transport import PowerShellError, PsrpTransport @@ -261,7 +262,7 @@ def _is_noise_route(destination: str) -> bool: # --------------------------------------------------------------------------- -class WindowsDriver(WindowsScheduledJobsMixin, WindowsTimeSyncMixin, OSDriver): +class WindowsDriver(WindowsScheduledJobsMixin, WindowsTimeSyncMixin, WindowsRepairsMixin, OSDriver): """NAPALM driver for Windows Server 2016+ and Windows 10/11. ``optional_args``: diff --git a/tests/fixtures/synthetic/README.md b/tests/fixtures/synthetic/README.md index 517ed6a..2a7c90c 100644 --- a/tests/fixtures/synthetic/README.md +++ b/tests/fixtures/synthetic/README.md @@ -8,3 +8,7 @@ and the Python side is tested against it here. What they cannot prove is that the scripts produce this shape on a real host (property names, Windows PowerShell 5.1 serialisation quirks). They are to be replaced by output recorded from a Windows Server and a Windows 11 client. + +The repair runs' fixtures (`*.txt`) are what their scripts stream: one output object +per line, ending in `napalm-exit-code:`. They follow Microsoft's documented output of +`sfc`, `DISM` and the Defender cmdlets; `tools/harvest.py --runs` records the real ones. diff --git a/tests/fixtures/synthetic/defender_quick_scan.txt b/tests/fixtures/synthetic/defender_quick_scan.txt new file mode 100644 index 0000000..9016719 --- /dev/null +++ b/tests/fixtures/synthetic/defender_quick_scan.txt @@ -0,0 +1,5 @@ +Scan started: QuickScan +Scan ended. +Threats detected: 1 + Virus:DOS/EICAR_Test_File: action succeeded +napalm-exit-code:0 diff --git a/tests/fixtures/synthetic/defender_signature_update.txt b/tests/fixtures/synthetic/defender_signature_update.txt new file mode 100644 index 0000000..1dbd43d --- /dev/null +++ b/tests/fixtures/synthetic/defender_signature_update.txt @@ -0,0 +1,3 @@ +Signatures before: 1.401.1234.0, updated 2026-11-27 06:12 UTC +Signatures after: 1.401.1502.0, updated 2026-12-01 08:41 UTC +napalm-exit-code:0 diff --git a/tests/fixtures/synthetic/dism_scanhealth.txt b/tests/fixtures/synthetic/dism_scanhealth.txt new file mode 100644 index 0000000..501b000 --- /dev/null +++ b/tests/fixtures/synthetic/dism_scanhealth.txt @@ -0,0 +1,10 @@ + +Deployment Image Servicing and Management tool +Version: 10.0.20348.681 + +Image Version: 10.0.20348.2340 + +[===== 10.0% ] +[==========================100.0%==========================] No component store corruption detected. +The operation completed successfully. +napalm-exit-code:0 diff --git a/tests/fixtures/synthetic/dism_scanhealth_failed.txt b/tests/fixtures/synthetic/dism_scanhealth_failed.txt new file mode 100644 index 0000000..a40cbd4 --- /dev/null +++ b/tests/fixtures/synthetic/dism_scanhealth_failed.txt @@ -0,0 +1,14 @@ + +Deployment Image Servicing and Management tool +Version: 10.0.20348.681 + +Image Version: 10.0.20348.2340 + + +Error: 0x800f081f + +The source files could not be found. +Use the "Source" option to specify the location of the files that are required to restore the feature. For more information on specifying a source location, see https://go.microsoft.com/fwlink/?LinkId=243077. + +The DISM log file can be found at C:\Windows\Logs\DISM\dism.log +napalm-exit-code:-2146498529 diff --git a/tests/fixtures/synthetic/sfc_verifyonly.txt b/tests/fixtures/synthetic/sfc_verifyonly.txt new file mode 100644 index 0000000..7df8e56 --- /dev/null +++ b/tests/fixtures/synthetic/sfc_verifyonly.txt @@ -0,0 +1,10 @@ + +Beginning system scan. This process will take some time. + +Beginning verification phase of system scan. +Verification 1% complete. +Verification 52% complete. +Verification 100% complete. + +Windows Resource Protection did not find any integrity violations. +napalm-exit-code:0 diff --git a/tests/test_repairs.py b/tests/test_repairs.py new file mode 100644 index 0000000..8332800 --- /dev/null +++ b/tests/test_repairs.py @@ -0,0 +1,305 @@ +"""Repair runs on Windows: SFC, DISM and Microsoft Defender over PowerShell Remoting (NetOrk/netork#2899). + +A fake transport replays what a run's script emits, one output object per line of +tests/fixtures/synthetic/.txt, through ``run_streaming``; the scripts end with a +``napalm-exit-code:`` line, or say ``napalm-not-available:`` where the tool is missing. +The fixtures are written from Microsoft's documented output, not recorded from a host. +""" + +from __future__ import annotations + +from collections.abc import Callable +from pathlib import Path + +import pytest +from napalm.base.exceptions import ConnectionClosedException +from napalm_device_types import HostRepairMixin, offered_host_repairs + +from napalm_windows import WindowsDriver +from napalm_windows import repairs as mod +from napalm_windows.transport import PowerShellError + +FIXTURES = Path(__file__).parent / "fixtures" / "synthetic" + + +def _fixture(name: str) -> list[str]: + return (FIXTURES / name).read_text().split("\n")[:-1] + + +class FakeTransport: + """Replays *items* as the output objects of the next streamed script.""" + + def __init__(self, items: list[str], *, error: Exception | None = None) -> None: + self.items = items + self.error = error + self.scripts: list[str] = [] + self.limits: list[float] = [] + self.is_open = True + + def run_streaming( + self, script: str, on_output: Callable[[str], None], *, limit: float + ) -> list[str]: + self.scripts.append(script) + self.limits.append(limit) + for item in self.items: + on_output(item) + if self.error is not None: + raise self.error + return list(self.items) + + def close(self) -> None: + self.is_open = False + + +def _driver(items: list[str], **kwargs) -> tuple[WindowsDriver, FakeTransport]: + transport = FakeTransport(items, **kwargs) + driver = WindowsDriver("win01", "admin", "secret") + driver._transport = transport # type: ignore[assignment] + return driver, transport + + +class TestCatalog: + def test_the_driver_carries_the_contract(self): + assert issubclass(WindowsDriver, HostRepairMixin) + + def test_offers_the_checks_and_the_antimalware_runs_not_the_repairs(self): + # sfc /scannow and DISM /RestoreHealth wait for a real-host test (#2899). + assert offered_host_repairs(WindowsDriver) == [ + "verify_system_files", + "check_component_store", + "update_antimalware_signatures", + "scan_antimalware", + ] + + +class TestToolLines: + def test_an_object_is_one_line(self): + assert mod.tool_lines("Verification 52% complete.") == ["Verification 52% complete."] + + def test_utf16_text_read_as_bytes_loses_its_nuls(self): + # sfc writes UTF-16 to a redirected stdout; decoded byte by byte, each + # character is followed by a NUL. + raw = "Windows Resource Protection".encode("utf-16-le").decode("latin-1") + assert "\x00" in raw + assert mod.tool_lines(raw) == ["Windows Resource Protection"] + + def test_a_byte_order_mark_is_dropped(self): + assert mod.tool_lines("Beginning system scan.") == ["Beginning system scan."] + + def test_carriage_returns_split_progress_into_lines(self): + assert mod.tool_lines("Verification 1% complete.\rVerification 2% complete.\r\n") == [ + "Verification 1% complete.", + "Verification 2% complete.", + ] + + def test_blank_lines_and_trailing_spaces_go(self): + assert mod.tool_lines(" \r\n\nresult ") == ["result"] + + +class TestVerifySystemFiles: + def test_streams_the_lines_and_succeeds_on_exit_code_zero(self): + driver, transport = _driver(_fixture("sfc_verifyonly.txt")) + seen: list[str] = [] + + result = driver.verify_system_files(log=seen.append) + + assert result["success"] is True + assert result["exit_code"] == 0 + assert seen[0] == "Beginning system scan. This process will take some time." + assert seen[-1] == "Windows Resource Protection did not find any integrity violations." + assert not any(line.startswith("napalm-") for line in seen) + assert result["output"] == "\n".join(seen) + + def test_runs_sfc_verifyonly_decoded_as_utf16(self): + driver, transport = _driver(_fixture("sfc_verifyonly.txt")) + + driver.verify_system_files() + + script = transport.scripts[0] + assert "'/verifyonly'" in script + assert "System32\\sfc.exe" in script + assert "[System.Text.Encoding]::Unicode" in script + assert "/scannow" not in script + assert transport.limits == [mod.SFC_LIMIT] + + def test_utf16_output_with_nuls_reads_as_text(self): + items = [ + line.encode("utf-16-le").decode("latin-1") + for line in _fixture("sfc_verifyonly.txt")[:-1] + ] + ["napalm-exit-code:0"] + driver, _ = _driver(items) + + result = driver.verify_system_files() + + assert "did not find any integrity violations" in result["output"] + assert "\x00" not in result["output"] + + def test_a_non_zero_exit_code_fails_with_the_last_lines(self): + items = [ + "Beginning system scan. This process will take some time.", + "Windows Resource Protection could not start the repair service.", + "napalm-exit-code:1", + ] + driver, _ = _driver(items) + + result = driver.verify_system_files() + + assert result["success"] is False + assert result["exit_code"] == 1 + assert result["error"].endswith("could not start the repair service.") + + def test_a_missing_tool_is_not_available_not_an_error(self): + driver, _ = _driver(["napalm-not-available:sfc.exe"]) + + result = driver.verify_system_files() + + assert result == { + "success": False, + "output": "", + "exit_code": None, + "error": "sfc.exe is not available on this host", + } + + def test_without_log_it_still_returns_the_output(self): + driver, _ = _driver(_fixture("sfc_verifyonly.txt")) + assert "Verification 100% complete." in driver.verify_system_files()["output"] + + +class TestCheckComponentStore: + def test_scans_health_in_english_and_succeeds(self): + driver, transport = _driver(_fixture("dism_scanhealth.txt")) + seen: list[str] = [] + + result = driver.check_component_store(log=seen.append) + + assert result["success"] is True + assert "No component store corruption detected." in seen[-2] + script = transport.scripts[0] + assert "System32\\Dism.exe" in script + assert "'/Online /Cleanup-Image /ScanHealth /English'" in script + assert "RestoreHealth" not in script + assert transport.limits == [mod.DISM_LIMIT] + + def test_an_hresult_exit_code_fails_in_hex(self): + driver, _ = _driver(_fixture("dism_scanhealth_failed.txt")) + + result = driver.check_component_store() + + assert result["success"] is False + assert result["exit_code"] == 0x800F081F + assert result["error"].startswith("DISM /ScanHealth ended with exit code 0x800F081F:") + assert "dism.log" in result["error"] + + +class TestAntimalwareSignatures: + def test_updates_and_reports_the_versions(self): + driver, transport = _driver(_fixture("defender_signature_update.txt")) + seen: list[str] = [] + + result = driver.update_antimalware_signatures(log=seen.append) + + assert result["success"] is True + assert seen == [ + "Signatures before: 1.401.1234.0, updated 2026-11-27 06:12 UTC", + "Signatures after: 1.401.1502.0, updated 2026-12-01 08:41 UTC", + ] + script = transport.scripts[0] + assert "Update-MpSignature" in script + assert "Get-Command -Name Update-MpSignature" in script + assert transport.limits == [mod.SIGNATURE_LIMIT] + + def test_a_host_without_defender_says_so(self): + driver, _ = _driver(["napalm-not-available:Microsoft Defender Antivirus"]) + + result = driver.update_antimalware_signatures() + + assert result["success"] is False + assert result["error"] == "Microsoft Defender Antivirus is not available on this host" + + def test_a_refused_update_fails_with_its_reason(self): + items = [ + "Signatures before: 1.401.1234.0, updated 2026-11-27 06:12 UTC", + "Update-MpSignature failed: Virus and spyware definitions update was completed with errors.", + "Signatures after: 1.401.1234.0, updated 2026-11-27 06:12 UTC", + "napalm-exit-code:1", + ] + driver, _ = _driver(items) + + result = driver.update_antimalware_signatures() + + assert result["success"] is False + assert "completed with errors" in result["error"] + + +class TestScanAntimalware: + def test_a_quick_scan_reports_what_it_found(self): + driver, transport = _driver(_fixture("defender_quick_scan.txt")) + seen: list[str] = [] + + result = driver.scan_antimalware(log=seen.append) + + assert result["success"] is True + assert "Threats detected: 1" in seen + script = transport.scripts[0] + assert "Start-MpScan -ScanType QuickScan" in script + assert transport.limits == [mod.QUICK_SCAN_LIMIT] + + def test_a_full_scan_has_its_own_limit(self): + driver, transport = _driver(["napalm-exit-code:0"]) + + driver.scan_antimalware(quick=False) + + assert "Start-MpScan -ScanType FullScan" in transport.scripts[0] + assert transport.limits == [mod.FULL_SCAN_LIMIT] + + +class TestCutOff: + def test_a_run_past_its_limit_fails_with_what_it_printed(self): + driver, _ = _driver( + ["Beginning system scan.", "Verification 40% complete."], + error=TimeoutError("The script did not end within 3600 seconds"), + ) + + result = driver.verify_system_files() + + assert result["success"] is False + assert result["exit_code"] is None + assert result["error"].startswith("sfc /verifyonly ended without an exit code:") + assert "Verification 40% complete." in result["error"] + assert result["error"].endswith("did not end within 3600 seconds") + + def test_an_error_the_script_wrote_fails_the_run(self): + driver, _ = _driver([], error=PowerShellError("Access is denied.")) + + result = driver.check_component_store() + + assert result["success"] is False + assert result["error"].endswith("Access is denied.") + + def test_an_unreadable_exit_code_is_none(self): + driver, _ = _driver(["done", "napalm-exit-code:"]) + assert driver.verify_system_files()["exit_code"] is None + + def test_a_closed_connection_raises(self): + driver = WindowsDriver("win01", "admin", "secret") + with pytest.raises(ConnectionClosedException): + driver.verify_system_files() + + +@pytest.mark.parametrize( + "script", + [ + mod._PS_SFC_VERIFY, + mod._PS_DISM_SCAN, + mod._PS_SIGNATURE_UPDATE, + mod._PS_QUICK_SCAN, + mod._PS_FULL_SCAN, + ], +) +def test_every_script_follows_the_conventions(script): + assert "$ErrorActionPreference = 'Stop'" in script + assert "napalm-exit-code:" in script + assert "napalm-not-available:" in script + # No restart and no restore point as a side effect of a run (#2899). + for forbidden in ("Restart-Computer", "Checkpoint-Computer", "shutdown"): + assert forbidden not in script diff --git a/tests/test_transport.py b/tests/test_transport.py index 8fcc708..c0b8f89 100644 --- a/tests/test_transport.py +++ b/tests/test_transport.py @@ -11,6 +11,7 @@ from unittest.mock import patch import pytest import requests from napalm.base.exceptions import ConnectionClosedException, ConnectionException +from pypsrp.complex_objects import PSInvocationState from pypsrp.exceptions import AuthenticationError, WinRMError, WinRMTransportError from napalm_windows.transport import PowerShellError, PsrpTransport @@ -166,6 +167,113 @@ class TestRunLast: _transport().run_last("Restart-Computer") +class _Pipeline: + """A PowerShell pipeline whose output arrives over several polls, as pypsrp's + ``begin_invoke``/``poll_invoke`` deliver a long-running script's.""" + + def __init__(self, batches, *, errors=(), never_ends=False): + self.batches = [list(b) for b in batches] + self.output: list = [] + self.state = PSInvocationState.NOT_STARTED + self.had_errors = bool(errors) + self.streams = type("Streams", (), {"error": list(errors)})() + self.never_ends = never_ends + self.polls: list = [] + self.stopped = False + self.script = None + + def add_script(self, script): + self.script = script + + def begin_invoke(self): + self.state = PSInvocationState.RUNNING + + def poll_invoke(self, timeout=None): + self.polls.append(timeout) + if self.batches: + self.output.extend(self.batches.pop(0)) + if not self.batches and not self.never_ends: + self.state = PSInvocationState.COMPLETED + + def stop(self): + self.stopped = True + self.state = PSInvocationState.STOPPED + + +class TestRunStreaming: + """A long-running script: each output line reaches the caller as the host prints it.""" + + def _open(self, psrp, pipeline, **overrides): + psrp["ps"].return_value = pipeline + t = _transport(**overrides) + t.open() + return t + + def test_each_output_object_reaches_the_caller_as_it_arrives(self, psrp): + pipeline = _Pipeline([["one"], [], ["two", None, "three"]]) + t = self._open(psrp, pipeline) + seen: list[str] = [] + + out = t.run_streaming("sfc", seen.append, limit=60) + + assert seen == ["one", "two", "three"] + assert out == ["one", "two", "three"] + assert pipeline.script == "sfc" + + def test_each_poll_waits_less_than_a_read_of_the_connection(self, psrp): + pipeline = _Pipeline([["a"], ["b"]]) + t = self._open(psrp, pipeline, timeout=60) + + t.run_streaming("x", lambda _line: None, limit=600) + + assert pipeline.polls and all(0 < p < 60 for p in pipeline.polls) + + def test_a_short_connection_timeout_still_polls(self, psrp): + pipeline = _Pipeline([["a"]]) + t = self._open(psrp, pipeline, timeout=5) + + t.run_streaming("x", lambda _line: None, limit=600) + + assert pipeline.polls == [2] + + def test_the_error_stream_raises_after_the_output_was_passed_on(self, psrp): + pipeline = _Pipeline([["started"]], errors=["Access is denied."]) + t = self._open(psrp, pipeline) + seen: list[str] = [] + + with pytest.raises(PowerShellError, match="Access is denied"): + t.run_streaming("x", seen.append, limit=60) + assert seen == ["started"] + + def test_a_script_past_its_limit_is_stopped(self, psrp): + pipeline = _Pipeline([["working"]], never_ends=True) + t = self._open(psrp, pipeline) + clock = iter([0.0, 10.0, 70.0, 130.0]) + + with ( + patch("napalm_windows.transport.time.monotonic", lambda: next(clock)), + pytest.raises(TimeoutError, match="60 seconds"), + ): + t.run_streaming("x", lambda _line: None, limit=60) + assert pipeline.stopped is True + + def test_stopping_a_pipeline_that_ended_meanwhile_still_times_out(self, psrp): + pipeline = _Pipeline([["working"]], never_ends=True) + pipeline.stop = lambda: (_ for _ in ()).throw(RuntimeError("not running")) + t = self._open(psrp, pipeline) + clock = iter([0.0, 61.0]) + + with ( + patch("napalm_windows.transport.time.monotonic", lambda: next(clock)), + pytest.raises(TimeoutError), + ): + t.run_streaming("x", lambda _line: None, limit=60) + + def test_before_open_raises_connection_closed(self): + with pytest.raises(ConnectionClosedException): + _transport().run_streaming("x", lambda _line: None, limit=60) + + class TestClose: def test_close_closes_pool_and_connection(self, psrp): t = _transport() diff --git a/tools/harvest.py b/tools/harvest.py index 38de2f4..7cef4df 100644 --- a/tools/harvest.py +++ b/tools/harvest.py @@ -1,11 +1,15 @@ """Record what the driver's PowerShell scripts emit on a real Windows host. - python tools/harvest.py